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.

265317 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. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  14509. if (numSamples <= 0)
  14510. return true;
  14511. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  14512. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  14513. char tempBuffer [tempBufSize];
  14514. while (numSamples > 0)
  14515. {
  14516. int* left = destSamples[0];
  14517. if (left != 0)
  14518. left += startOffsetInDestBuffer;
  14519. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  14520. if (right != 0)
  14521. right += startOffsetInDestBuffer;
  14522. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  14523. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  14524. if (bytesRead < numThisTime * bytesPerFrame)
  14525. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  14526. if (bitsPerSample == 16)
  14527. {
  14528. if (littleEndian)
  14529. {
  14530. const short* src = (const short*) tempBuffer;
  14531. if (numChannels > 1)
  14532. {
  14533. if (left == 0)
  14534. {
  14535. for (int i = numThisTime; --i >= 0;)
  14536. {
  14537. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14538. ++src;
  14539. }
  14540. }
  14541. else if (right == 0)
  14542. {
  14543. for (int i = numThisTime; --i >= 0;)
  14544. {
  14545. ++src;
  14546. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14547. }
  14548. }
  14549. else
  14550. {
  14551. for (int i = numThisTime; --i >= 0;)
  14552. {
  14553. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14554. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14555. }
  14556. }
  14557. }
  14558. else
  14559. {
  14560. for (int i = numThisTime; --i >= 0;)
  14561. {
  14562. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  14563. }
  14564. }
  14565. }
  14566. else
  14567. {
  14568. const char* src = (const char*) tempBuffer;
  14569. if (numChannels > 1)
  14570. {
  14571. if (left == 0)
  14572. {
  14573. for (int i = numThisTime; --i >= 0;)
  14574. {
  14575. *right++ = bigEndianShort (src) << 16;
  14576. src += 4;
  14577. }
  14578. }
  14579. else if (right == 0)
  14580. {
  14581. for (int i = numThisTime; --i >= 0;)
  14582. {
  14583. src += 2;
  14584. *left++ = bigEndianShort (src) << 16;
  14585. src += 2;
  14586. }
  14587. }
  14588. else
  14589. {
  14590. for (int i = numThisTime; --i >= 0;)
  14591. {
  14592. *left++ = bigEndianShort (src) << 16;
  14593. src += 2;
  14594. *right++ = bigEndianShort (src) << 16;
  14595. src += 2;
  14596. }
  14597. }
  14598. }
  14599. else
  14600. {
  14601. for (int i = numThisTime; --i >= 0;)
  14602. {
  14603. *left++ = bigEndianShort (src) << 16;
  14604. src += 2;
  14605. }
  14606. }
  14607. }
  14608. }
  14609. else if (bitsPerSample == 24)
  14610. {
  14611. const char* src = (const char*)tempBuffer;
  14612. if (littleEndian)
  14613. {
  14614. if (numChannels > 1)
  14615. {
  14616. if (left == 0)
  14617. {
  14618. for (int i = numThisTime; --i >= 0;)
  14619. {
  14620. *right++ = littleEndian24Bit (src) << 8;
  14621. src += 6;
  14622. }
  14623. }
  14624. else if (right == 0)
  14625. {
  14626. for (int i = numThisTime; --i >= 0;)
  14627. {
  14628. src += 3;
  14629. *left++ = littleEndian24Bit (src) << 8;
  14630. src += 3;
  14631. }
  14632. }
  14633. else
  14634. {
  14635. for (int i = numThisTime; --i >= 0;)
  14636. {
  14637. *left++ = littleEndian24Bit (src) << 8;
  14638. src += 3;
  14639. *right++ = littleEndian24Bit (src) << 8;
  14640. src += 3;
  14641. }
  14642. }
  14643. }
  14644. else
  14645. {
  14646. for (int i = numThisTime; --i >= 0;)
  14647. {
  14648. *left++ = littleEndian24Bit (src) << 8;
  14649. src += 3;
  14650. }
  14651. }
  14652. }
  14653. else
  14654. {
  14655. if (numChannels > 1)
  14656. {
  14657. if (left == 0)
  14658. {
  14659. for (int i = numThisTime; --i >= 0;)
  14660. {
  14661. *right++ = bigEndian24Bit (src) << 8;
  14662. src += 6;
  14663. }
  14664. }
  14665. else if (right == 0)
  14666. {
  14667. for (int i = numThisTime; --i >= 0;)
  14668. {
  14669. src += 3;
  14670. *left++ = bigEndian24Bit (src) << 8;
  14671. src += 3;
  14672. }
  14673. }
  14674. else
  14675. {
  14676. for (int i = numThisTime; --i >= 0;)
  14677. {
  14678. *left++ = bigEndian24Bit (src) << 8;
  14679. src += 3;
  14680. *right++ = bigEndian24Bit (src) << 8;
  14681. src += 3;
  14682. }
  14683. }
  14684. }
  14685. else
  14686. {
  14687. for (int i = numThisTime; --i >= 0;)
  14688. {
  14689. *left++ = bigEndian24Bit (src) << 8;
  14690. src += 3;
  14691. }
  14692. }
  14693. }
  14694. }
  14695. else if (bitsPerSample == 32)
  14696. {
  14697. const unsigned int* src = (const unsigned int*) tempBuffer;
  14698. unsigned int* l = (unsigned int*) left;
  14699. unsigned int* r = (unsigned int*) right;
  14700. if (littleEndian)
  14701. {
  14702. if (numChannels > 1)
  14703. {
  14704. if (l == 0)
  14705. {
  14706. for (int i = numThisTime; --i >= 0;)
  14707. {
  14708. ++src;
  14709. *r++ = swapIfBigEndian (*src++);
  14710. }
  14711. }
  14712. else if (r == 0)
  14713. {
  14714. for (int i = numThisTime; --i >= 0;)
  14715. {
  14716. *l++ = swapIfBigEndian (*src++);
  14717. ++src;
  14718. }
  14719. }
  14720. else
  14721. {
  14722. for (int i = numThisTime; --i >= 0;)
  14723. {
  14724. *l++ = swapIfBigEndian (*src++);
  14725. *r++ = swapIfBigEndian (*src++);
  14726. }
  14727. }
  14728. }
  14729. else
  14730. {
  14731. for (int i = numThisTime; --i >= 0;)
  14732. {
  14733. *l++ = swapIfBigEndian (*src++);
  14734. }
  14735. }
  14736. }
  14737. else
  14738. {
  14739. if (numChannels > 1)
  14740. {
  14741. if (l == 0)
  14742. {
  14743. for (int i = numThisTime; --i >= 0;)
  14744. {
  14745. ++src;
  14746. *r++ = swapIfLittleEndian (*src++);
  14747. }
  14748. }
  14749. else if (r == 0)
  14750. {
  14751. for (int i = numThisTime; --i >= 0;)
  14752. {
  14753. *l++ = swapIfLittleEndian (*src++);
  14754. ++src;
  14755. }
  14756. }
  14757. else
  14758. {
  14759. for (int i = numThisTime; --i >= 0;)
  14760. {
  14761. *l++ = swapIfLittleEndian (*src++);
  14762. *r++ = swapIfLittleEndian (*src++);
  14763. }
  14764. }
  14765. }
  14766. else
  14767. {
  14768. for (int i = numThisTime; --i >= 0;)
  14769. {
  14770. *l++ = swapIfLittleEndian (*src++);
  14771. }
  14772. }
  14773. }
  14774. left = (int*) l;
  14775. right = (int*) r;
  14776. }
  14777. else if (bitsPerSample == 8)
  14778. {
  14779. const char* src = (const char*) tempBuffer;
  14780. if (numChannels > 1)
  14781. {
  14782. if (left == 0)
  14783. {
  14784. for (int i = numThisTime; --i >= 0;)
  14785. {
  14786. *right++ = ((int) *src++) << 24;
  14787. ++src;
  14788. }
  14789. }
  14790. else if (right == 0)
  14791. {
  14792. for (int i = numThisTime; --i >= 0;)
  14793. {
  14794. ++src;
  14795. *left++ = ((int) *src++) << 24;
  14796. }
  14797. }
  14798. else
  14799. {
  14800. for (int i = numThisTime; --i >= 0;)
  14801. {
  14802. *left++ = ((int) *src++) << 24;
  14803. *right++ = ((int) *src++) << 24;
  14804. }
  14805. }
  14806. }
  14807. else
  14808. {
  14809. for (int i = numThisTime; --i >= 0;)
  14810. {
  14811. *left++ = ((int) *src++) << 24;
  14812. }
  14813. }
  14814. }
  14815. startOffsetInDestBuffer += numThisTime;
  14816. numSamples -= numThisTime;
  14817. }
  14818. if (numSamples > 0)
  14819. {
  14820. for (int i = numDestChannels; --i >= 0;)
  14821. if (destSamples[i] != 0)
  14822. zeromem (destSamples[i] + startOffsetInDestBuffer,
  14823. sizeof (int) * numSamples);
  14824. }
  14825. return true;
  14826. }
  14827. juce_UseDebuggingNewOperator
  14828. private:
  14829. AiffAudioFormatReader (const AiffAudioFormatReader&);
  14830. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  14831. };
  14832. class AiffAudioFormatWriter : public AudioFormatWriter
  14833. {
  14834. MemoryBlock tempBlock;
  14835. uint32 lengthInSamples, bytesWritten;
  14836. int64 headerPosition;
  14837. bool writeFailed;
  14838. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  14839. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  14840. void writeHeader()
  14841. {
  14842. const bool couldSeekOk = output->setPosition (headerPosition);
  14843. (void) couldSeekOk;
  14844. // if this fails, you've given it an output stream that can't seek! It needs
  14845. // to be able to seek back to write the header
  14846. jassert (couldSeekOk);
  14847. const int headerLen = 54;
  14848. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  14849. audioBytes += (audioBytes & 1);
  14850. output->writeInt (chunkName ("FORM"));
  14851. output->writeIntBigEndian (headerLen + audioBytes - 8);
  14852. output->writeInt (chunkName ("AIFF"));
  14853. output->writeInt (chunkName ("COMM"));
  14854. output->writeIntBigEndian (18);
  14855. output->writeShortBigEndian ((short) numChannels);
  14856. output->writeIntBigEndian (lengthInSamples);
  14857. output->writeShortBigEndian ((short) bitsPerSample);
  14858. uint8 sampleRateBytes[10];
  14859. zeromem (sampleRateBytes, 10);
  14860. if (sampleRate <= 1)
  14861. {
  14862. sampleRateBytes[0] = 0x3f;
  14863. sampleRateBytes[1] = 0xff;
  14864. sampleRateBytes[2] = 0x80;
  14865. }
  14866. else
  14867. {
  14868. int mask = 0x40000000;
  14869. sampleRateBytes[0] = 0x40;
  14870. if (sampleRate >= mask)
  14871. {
  14872. jassertfalse
  14873. sampleRateBytes[1] = 0x1d;
  14874. }
  14875. else
  14876. {
  14877. int n = (int) sampleRate;
  14878. int i;
  14879. for (i = 0; i <= 32 ; ++i)
  14880. {
  14881. if ((n & mask) != 0)
  14882. break;
  14883. mask >>= 1;
  14884. }
  14885. n = n << (i + 1);
  14886. sampleRateBytes[1] = (uint8) (29 - i);
  14887. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  14888. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  14889. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  14890. sampleRateBytes[5] = (uint8) (n & 0xff);
  14891. }
  14892. }
  14893. output->write (sampleRateBytes, 10);
  14894. output->writeInt (chunkName ("SSND"));
  14895. output->writeIntBigEndian (audioBytes + 8);
  14896. output->writeInt (0);
  14897. output->writeInt (0);
  14898. jassert (output->getPosition() == headerLen);
  14899. }
  14900. public:
  14901. AiffAudioFormatWriter (OutputStream* out,
  14902. const double sampleRate_,
  14903. const unsigned int chans,
  14904. const int bits)
  14905. : AudioFormatWriter (out,
  14906. aiffFormatName,
  14907. sampleRate_,
  14908. chans,
  14909. bits),
  14910. lengthInSamples (0),
  14911. bytesWritten (0),
  14912. writeFailed (false)
  14913. {
  14914. headerPosition = out->getPosition();
  14915. writeHeader();
  14916. }
  14917. ~AiffAudioFormatWriter()
  14918. {
  14919. if ((bytesWritten & 1) != 0)
  14920. output->writeByte (0);
  14921. writeHeader();
  14922. }
  14923. bool write (const int** data, int numSamples)
  14924. {
  14925. if (writeFailed)
  14926. return false;
  14927. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  14928. tempBlock.ensureSize (bytes, false);
  14929. char* buffer = (char*) tempBlock.getData();
  14930. const int* left = data[0];
  14931. const int* right = data[1];
  14932. if (right == 0)
  14933. right = left;
  14934. if (bitsPerSample == 16)
  14935. {
  14936. short* b = (short*) buffer;
  14937. if (numChannels > 1)
  14938. {
  14939. for (int i = numSamples; --i >= 0;)
  14940. {
  14941. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14942. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  14943. }
  14944. }
  14945. else
  14946. {
  14947. for (int i = numSamples; --i >= 0;)
  14948. {
  14949. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  14950. }
  14951. }
  14952. }
  14953. else if (bitsPerSample == 24)
  14954. {
  14955. char* b = (char*) buffer;
  14956. if (numChannels > 1)
  14957. {
  14958. for (int i = numSamples; --i >= 0;)
  14959. {
  14960. bigEndian24BitToChars (*left++ >> 8, b);
  14961. b += 3;
  14962. bigEndian24BitToChars (*right++ >> 8, b);
  14963. b += 3;
  14964. }
  14965. }
  14966. else
  14967. {
  14968. for (int i = numSamples; --i >= 0;)
  14969. {
  14970. bigEndian24BitToChars (*left++ >> 8, b);
  14971. b += 3;
  14972. }
  14973. }
  14974. }
  14975. else if (bitsPerSample == 32)
  14976. {
  14977. unsigned int* b = (unsigned int*) buffer;
  14978. if (numChannels > 1)
  14979. {
  14980. for (int i = numSamples; --i >= 0;)
  14981. {
  14982. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14983. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  14984. }
  14985. }
  14986. else
  14987. {
  14988. for (int i = numSamples; --i >= 0;)
  14989. {
  14990. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  14991. }
  14992. }
  14993. }
  14994. else if (bitsPerSample == 8)
  14995. {
  14996. char* b = (char*)buffer;
  14997. if (numChannels > 1)
  14998. {
  14999. for (int i = numSamples; --i >= 0;)
  15000. {
  15001. *b++ = (char) (*left++ >> 24);
  15002. *b++ = (char) (*right++ >> 24);
  15003. }
  15004. }
  15005. else
  15006. {
  15007. for (int i = numSamples; --i >= 0;)
  15008. {
  15009. *b++ = (char) (*left++ >> 24);
  15010. }
  15011. }
  15012. }
  15013. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15014. || ! output->write (buffer, bytes))
  15015. {
  15016. // failed to write to disk, so let's try writing the header.
  15017. // If it's just run out of disk space, then if it does manage
  15018. // to write the header, we'll still have a useable file..
  15019. writeHeader();
  15020. writeFailed = true;
  15021. return false;
  15022. }
  15023. else
  15024. {
  15025. bytesWritten += bytes;
  15026. lengthInSamples += numSamples;
  15027. return true;
  15028. }
  15029. }
  15030. juce_UseDebuggingNewOperator
  15031. };
  15032. AiffAudioFormat::AiffAudioFormat()
  15033. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  15034. {
  15035. }
  15036. AiffAudioFormat::~AiffAudioFormat()
  15037. {
  15038. }
  15039. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  15040. {
  15041. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15042. return Array <int> (rates);
  15043. }
  15044. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  15045. {
  15046. const int depths[] = { 8, 16, 24, 0 };
  15047. return Array <int> (depths);
  15048. }
  15049. bool AiffAudioFormat::canDoStereo()
  15050. {
  15051. return true;
  15052. }
  15053. bool AiffAudioFormat::canDoMono()
  15054. {
  15055. return true;
  15056. }
  15057. #if JUCE_MAC
  15058. bool AiffAudioFormat::canHandleFile (const File& f)
  15059. {
  15060. if (AudioFormat::canHandleFile (f))
  15061. return true;
  15062. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  15063. return type == 'AIFF' || type == 'AIFC'
  15064. || type == 'aiff' || type == 'aifc';
  15065. }
  15066. #endif
  15067. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  15068. const bool deleteStreamIfOpeningFails)
  15069. {
  15070. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  15071. if (w->sampleRate == 0)
  15072. {
  15073. if (! deleteStreamIfOpeningFails)
  15074. w->input = 0;
  15075. deleteAndZero (w);
  15076. }
  15077. return w;
  15078. }
  15079. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  15080. double sampleRate,
  15081. unsigned int chans,
  15082. int bitsPerSample,
  15083. const StringPairArray& /*metadataValues*/,
  15084. int /*qualityOptionIndex*/)
  15085. {
  15086. if (getPossibleBitDepths().contains (bitsPerSample))
  15087. {
  15088. return new AiffAudioFormatWriter (out,
  15089. sampleRate,
  15090. chans,
  15091. bitsPerSample);
  15092. }
  15093. return 0;
  15094. }
  15095. END_JUCE_NAMESPACE
  15096. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  15097. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  15098. BEGIN_JUCE_NAMESPACE
  15099. #if JUCE_MAC
  15100. // Mac version doesn't need any native code because it's all done with files..
  15101. // Windows + Linux versions are in the platform-dependent code sections.
  15102. static void findCDs (OwnedArray<File>& cds)
  15103. {
  15104. File volumes ("/Volumes");
  15105. volumes.findChildFiles (cds, File::findDirectories, false);
  15106. for (int i = cds.size(); --i >= 0;)
  15107. if (! cds[i]->getChildFile (".TOC.plist").exists())
  15108. cds.remove (i);
  15109. }
  15110. const StringArray AudioCDReader::getAvailableCDNames()
  15111. {
  15112. OwnedArray<File> cds;
  15113. findCDs (cds);
  15114. StringArray names;
  15115. for (int i = 0; i < cds.size(); ++i)
  15116. names.add (cds[i]->getFileName());
  15117. return names;
  15118. }
  15119. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  15120. {
  15121. OwnedArray<File> cds;
  15122. findCDs (cds);
  15123. if (cds[index] != 0)
  15124. return new AudioCDReader (*cds[index]);
  15125. else
  15126. return 0;
  15127. }
  15128. AudioCDReader::AudioCDReader (const File& volume)
  15129. : AudioFormatReader (0, "CD Audio"),
  15130. volumeDir (volume),
  15131. currentReaderTrack (-1),
  15132. reader (0)
  15133. {
  15134. sampleRate = 44100.0;
  15135. bitsPerSample = 16;
  15136. numChannels = 2;
  15137. usesFloatingPointData = false;
  15138. refreshTrackLengths();
  15139. }
  15140. AudioCDReader::~AudioCDReader()
  15141. {
  15142. if (reader != 0)
  15143. delete reader;
  15144. }
  15145. static int getTrackNumber (const File& file)
  15146. {
  15147. return file.getFileName()
  15148. .initialSectionContainingOnly (T("0123456789"))
  15149. .getIntValue();
  15150. }
  15151. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  15152. {
  15153. const int firstTrack = getTrackNumber (*first);
  15154. const int secondTrack = getTrackNumber (*second);
  15155. jassert (firstTrack > 0 && secondTrack > 0);
  15156. return firstTrack - secondTrack;
  15157. }
  15158. void AudioCDReader::refreshTrackLengths()
  15159. {
  15160. tracks.clear();
  15161. trackStartSamples.clear();
  15162. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  15163. tracks.sort (*this);
  15164. AiffAudioFormat format;
  15165. int sample = 0;
  15166. for (int i = 0; i < tracks.size(); ++i)
  15167. {
  15168. trackStartSamples.add (sample);
  15169. FileInputStream* const in = tracks[i]->createInputStream();
  15170. if (in != 0)
  15171. {
  15172. AudioFormatReader* const r = format.createReaderFor (in, true);
  15173. if (r != 0)
  15174. {
  15175. sample += r->lengthInSamples;
  15176. delete r;
  15177. }
  15178. }
  15179. }
  15180. trackStartSamples.add (sample);
  15181. lengthInSamples = sample;
  15182. }
  15183. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15184. int64 startSampleInFile, int numSamples)
  15185. {
  15186. while (numSamples > 0)
  15187. {
  15188. int track = -1;
  15189. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  15190. {
  15191. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  15192. {
  15193. track = i;
  15194. break;
  15195. }
  15196. }
  15197. if (track < 0)
  15198. return false;
  15199. if (track != currentReaderTrack)
  15200. {
  15201. deleteAndZero (reader);
  15202. if (tracks [track] != 0)
  15203. {
  15204. FileInputStream* const in = tracks [track]->createInputStream();
  15205. if (in != 0)
  15206. {
  15207. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  15208. AiffAudioFormat format;
  15209. reader = format.createReaderFor (bin, true);
  15210. if (reader == 0)
  15211. currentReaderTrack = -1;
  15212. else
  15213. currentReaderTrack = track;
  15214. }
  15215. }
  15216. }
  15217. if (reader == 0)
  15218. return false;
  15219. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  15220. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  15221. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  15222. numSamples -= numAvailable;
  15223. startSampleInFile += numAvailable;
  15224. }
  15225. return true;
  15226. }
  15227. bool AudioCDReader::isCDStillPresent() const
  15228. {
  15229. return volumeDir.exists();
  15230. }
  15231. int AudioCDReader::getNumTracks() const
  15232. {
  15233. return tracks.size();
  15234. }
  15235. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  15236. {
  15237. return trackStartSamples [trackNum];
  15238. }
  15239. bool AudioCDReader::isTrackAudio (int trackNum) const
  15240. {
  15241. return tracks [trackNum] != 0;
  15242. }
  15243. void AudioCDReader::enableIndexScanning (bool b)
  15244. {
  15245. // any way to do this on a Mac??
  15246. }
  15247. int AudioCDReader::getLastIndex() const
  15248. {
  15249. return 0;
  15250. }
  15251. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  15252. {
  15253. return Array <int>();
  15254. }
  15255. int AudioCDReader::getCDDBId()
  15256. {
  15257. return 0; //xxx
  15258. }
  15259. #endif
  15260. END_JUCE_NAMESPACE
  15261. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  15262. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  15263. BEGIN_JUCE_NAMESPACE
  15264. AudioFormatReader::AudioFormatReader (InputStream* const in,
  15265. const String& formatName_)
  15266. : sampleRate (0),
  15267. bitsPerSample (0),
  15268. lengthInSamples (0),
  15269. numChannels (0),
  15270. usesFloatingPointData (false),
  15271. input (in),
  15272. formatName (formatName_)
  15273. {
  15274. }
  15275. AudioFormatReader::~AudioFormatReader()
  15276. {
  15277. delete input;
  15278. }
  15279. bool AudioFormatReader::read (int** destSamples,
  15280. int numDestChannels,
  15281. int64 startSampleInSource,
  15282. int numSamplesToRead,
  15283. const bool fillLeftoverChannelsWithCopies)
  15284. {
  15285. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  15286. int startOffsetInDestBuffer = 0;
  15287. if (startSampleInSource < 0)
  15288. {
  15289. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  15290. for (int i = numDestChannels; --i >= 0;)
  15291. if (destSamples[i] != 0)
  15292. zeromem (destSamples[i], sizeof (int) * silence);
  15293. startOffsetInDestBuffer += silence;
  15294. numSamplesToRead -= silence;
  15295. startSampleInSource = 0;
  15296. }
  15297. if (numSamplesToRead <= 0)
  15298. return true;
  15299. if (! readSamples (destSamples, jmin (numChannels, numDestChannels), startOffsetInDestBuffer,
  15300. startSampleInSource, numSamplesToRead))
  15301. return false;
  15302. if (numDestChannels > (int) numChannels)
  15303. {
  15304. if (fillLeftoverChannelsWithCopies)
  15305. {
  15306. int* lastFullChannel = destSamples[0];
  15307. for (int i = numDestChannels; --i > 0;)
  15308. {
  15309. if (destSamples[i] != 0)
  15310. {
  15311. lastFullChannel = destSamples[i];
  15312. break;
  15313. }
  15314. }
  15315. if (lastFullChannel != 0)
  15316. for (int i = numChannels; i < numDestChannels; ++i)
  15317. if (destSamples[i] != 0)
  15318. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  15319. }
  15320. else
  15321. {
  15322. for (int i = numChannels; i < numDestChannels; ++i)
  15323. if (destSamples[i] != 0)
  15324. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  15325. }
  15326. }
  15327. return true;
  15328. }
  15329. static void findMaxMin (const float* src, const int num,
  15330. float& maxVal, float& minVal)
  15331. {
  15332. float mn = src[0];
  15333. float mx = mn;
  15334. for (int i = 1; i < num; ++i)
  15335. {
  15336. const float s = src[i];
  15337. if (s > mx)
  15338. mx = s;
  15339. if (s < mn)
  15340. mn = s;
  15341. }
  15342. maxVal = mx;
  15343. minVal = mn;
  15344. }
  15345. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  15346. int64 numSamples,
  15347. float& lowestLeft, float& highestLeft,
  15348. float& lowestRight, float& highestRight)
  15349. {
  15350. if (numSamples <= 0)
  15351. {
  15352. lowestLeft = 0;
  15353. lowestRight = 0;
  15354. highestLeft = 0;
  15355. highestRight = 0;
  15356. return;
  15357. }
  15358. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  15359. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15360. int* tempBuffer[3];
  15361. tempBuffer[0] = (int*) tempSpace.getData();
  15362. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15363. tempBuffer[2] = 0;
  15364. if (usesFloatingPointData)
  15365. {
  15366. float lmin = 1.0e6;
  15367. float lmax = -lmin;
  15368. float rmin = lmin;
  15369. float rmax = lmax;
  15370. while (numSamples > 0)
  15371. {
  15372. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15373. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15374. numSamples -= numToDo;
  15375. startSampleInFile += numToDo;
  15376. float bufmin, bufmax;
  15377. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  15378. lmin = jmin (lmin, bufmin);
  15379. lmax = jmax (lmax, bufmax);
  15380. if (numChannels > 1)
  15381. {
  15382. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  15383. rmin = jmin (rmin, bufmin);
  15384. rmax = jmax (rmax, bufmax);
  15385. }
  15386. }
  15387. if (numChannels <= 1)
  15388. {
  15389. rmax = lmax;
  15390. rmin = lmin;
  15391. }
  15392. lowestLeft = lmin;
  15393. highestLeft = lmax;
  15394. lowestRight = rmin;
  15395. highestRight = rmax;
  15396. }
  15397. else
  15398. {
  15399. int lmax = INT_MIN;
  15400. int lmin = INT_MAX;
  15401. int rmax = INT_MIN;
  15402. int rmin = INT_MAX;
  15403. while (numSamples > 0)
  15404. {
  15405. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  15406. read ((int**) tempBuffer, 2, startSampleInFile, numToDo, false);
  15407. numSamples -= numToDo;
  15408. startSampleInFile += numToDo;
  15409. for (int j = numChannels; --j >= 0;)
  15410. {
  15411. int bufMax = INT_MIN;
  15412. int bufMin = INT_MAX;
  15413. const int* const b = tempBuffer[j];
  15414. for (int i = 0; i < numToDo; ++i)
  15415. {
  15416. const int samp = b[i];
  15417. if (samp < bufMin)
  15418. bufMin = samp;
  15419. if (samp > bufMax)
  15420. bufMax = samp;
  15421. }
  15422. if (j == 0)
  15423. {
  15424. lmax = jmax (lmax, bufMax);
  15425. lmin = jmin (lmin, bufMin);
  15426. }
  15427. else
  15428. {
  15429. rmax = jmax (rmax, bufMax);
  15430. rmin = jmin (rmin, bufMin);
  15431. }
  15432. }
  15433. }
  15434. if (numChannels <= 1)
  15435. {
  15436. rmax = lmax;
  15437. rmin = lmin;
  15438. }
  15439. lowestLeft = lmin / (float)INT_MAX;
  15440. highestLeft = lmax / (float)INT_MAX;
  15441. lowestRight = rmin / (float)INT_MAX;
  15442. highestRight = rmax / (float)INT_MAX;
  15443. }
  15444. }
  15445. int64 AudioFormatReader::searchForLevel (int64 startSample,
  15446. int64 numSamplesToSearch,
  15447. const double magnitudeRangeMinimum,
  15448. const double magnitudeRangeMaximum,
  15449. const int minimumConsecutiveSamples)
  15450. {
  15451. if (numSamplesToSearch == 0)
  15452. return -1;
  15453. const int bufferSize = 4096;
  15454. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  15455. int* tempBuffer[3];
  15456. tempBuffer[0] = (int*) tempSpace.getData();
  15457. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  15458. tempBuffer[2] = 0;
  15459. int consecutive = 0;
  15460. int64 firstMatchPos = -1;
  15461. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  15462. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  15463. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  15464. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  15465. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  15466. while (numSamplesToSearch != 0)
  15467. {
  15468. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  15469. int64 bufferStart = startSample;
  15470. if (numSamplesToSearch < 0)
  15471. bufferStart -= numThisTime;
  15472. if (bufferStart >= (int) lengthInSamples)
  15473. break;
  15474. read ((int**) tempBuffer, 2, bufferStart, numThisTime, false);
  15475. int num = numThisTime;
  15476. while (--num >= 0)
  15477. {
  15478. if (numSamplesToSearch < 0)
  15479. --startSample;
  15480. bool matches = false;
  15481. const int index = (int) (startSample - bufferStart);
  15482. if (usesFloatingPointData)
  15483. {
  15484. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  15485. if (sample1 >= magnitudeRangeMinimum
  15486. && sample1 <= magnitudeRangeMaximum)
  15487. {
  15488. matches = true;
  15489. }
  15490. else if (numChannels > 1)
  15491. {
  15492. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  15493. matches = (sample2 >= magnitudeRangeMinimum
  15494. && sample2 <= magnitudeRangeMaximum);
  15495. }
  15496. }
  15497. else
  15498. {
  15499. const int sample1 = abs (tempBuffer[0] [index]);
  15500. if (sample1 >= intMagnitudeRangeMinimum
  15501. && sample1 <= intMagnitudeRangeMaximum)
  15502. {
  15503. matches = true;
  15504. }
  15505. else if (numChannels > 1)
  15506. {
  15507. const int sample2 = abs (tempBuffer[1][index]);
  15508. matches = (sample2 >= intMagnitudeRangeMinimum
  15509. && sample2 <= intMagnitudeRangeMaximum);
  15510. }
  15511. }
  15512. if (matches)
  15513. {
  15514. if (firstMatchPos < 0)
  15515. firstMatchPos = startSample;
  15516. if (++consecutive >= minimumConsecutiveSamples)
  15517. {
  15518. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  15519. return -1;
  15520. return firstMatchPos;
  15521. }
  15522. }
  15523. else
  15524. {
  15525. consecutive = 0;
  15526. firstMatchPos = -1;
  15527. }
  15528. if (numSamplesToSearch > 0)
  15529. ++startSample;
  15530. }
  15531. if (numSamplesToSearch > 0)
  15532. numSamplesToSearch -= numThisTime;
  15533. else
  15534. numSamplesToSearch += numThisTime;
  15535. }
  15536. return -1;
  15537. }
  15538. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  15539. const String& formatName_,
  15540. const double rate,
  15541. const unsigned int numChannels_,
  15542. const unsigned int bitsPerSample_)
  15543. : sampleRate (rate),
  15544. numChannels (numChannels_),
  15545. bitsPerSample (bitsPerSample_),
  15546. usesFloatingPointData (false),
  15547. output (out),
  15548. formatName (formatName_)
  15549. {
  15550. }
  15551. AudioFormatWriter::~AudioFormatWriter()
  15552. {
  15553. delete output;
  15554. }
  15555. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  15556. int64 startSample,
  15557. int64 numSamplesToRead)
  15558. {
  15559. const int bufferSize = 16384;
  15560. const int maxChans = 128;
  15561. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  15562. int* buffers [maxChans];
  15563. for (int i = maxChans; --i >= 0;)
  15564. buffers[i] = 0;
  15565. if (numSamplesToRead < 0)
  15566. numSamplesToRead = reader.lengthInSamples;
  15567. while (numSamplesToRead > 0)
  15568. {
  15569. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  15570. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  15571. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15572. if (! reader.read (buffers, maxChans, startSample, numToDo, false))
  15573. return false;
  15574. if (reader.usesFloatingPointData != isFloatingPoint())
  15575. {
  15576. int** bufferChan = buffers;
  15577. while (*bufferChan != 0)
  15578. {
  15579. int* b = *bufferChan++;
  15580. if (isFloatingPoint())
  15581. {
  15582. // int -> float
  15583. const double factor = 1.0 / INT_MAX;
  15584. for (int i = 0; i < numToDo; ++i)
  15585. ((float*)b)[i] = (float) (factor * b[i]);
  15586. }
  15587. else
  15588. {
  15589. // float -> int
  15590. for (int i = 0; i < numToDo; ++i)
  15591. {
  15592. const double samp = *(const float*) b;
  15593. if (samp <= -1.0)
  15594. *b++ = INT_MIN;
  15595. else if (samp >= 1.0)
  15596. *b++ = INT_MAX;
  15597. else
  15598. *b++ = roundDoubleToInt (INT_MAX * samp);
  15599. }
  15600. }
  15601. }
  15602. }
  15603. if (! write ((const int**) buffers, numToDo))
  15604. return false;
  15605. numSamplesToRead -= numToDo;
  15606. startSample += numToDo;
  15607. }
  15608. return true;
  15609. }
  15610. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  15611. int numSamplesToRead,
  15612. const int samplesPerBlock)
  15613. {
  15614. const int maxChans = 128;
  15615. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  15616. int* buffers [maxChans];
  15617. while (numSamplesToRead > 0)
  15618. {
  15619. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  15620. AudioSourceChannelInfo info;
  15621. info.buffer = &tempBuffer;
  15622. info.startSample = 0;
  15623. info.numSamples = numToDo;
  15624. info.clearActiveBufferRegion();
  15625. source.getNextAudioBlock (info);
  15626. int i;
  15627. for (i = maxChans; --i >= 0;)
  15628. buffers[i] = 0;
  15629. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  15630. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  15631. if (! isFloatingPoint())
  15632. {
  15633. int** bufferChan = buffers;
  15634. while (*bufferChan != 0)
  15635. {
  15636. int* b = *bufferChan++;
  15637. // float -> int
  15638. for (int j = numToDo; --j >= 0;)
  15639. {
  15640. const double samp = *(const float*) b;
  15641. if (samp <= -1.0)
  15642. *b++ = INT_MIN;
  15643. else if (samp >= 1.0)
  15644. *b++ = INT_MAX;
  15645. else
  15646. *b++ = roundDoubleToInt (INT_MAX * samp);
  15647. }
  15648. }
  15649. }
  15650. if (! write ((const int**) buffers, numToDo))
  15651. return false;
  15652. numSamplesToRead -= numToDo;
  15653. }
  15654. return true;
  15655. }
  15656. AudioFormat::AudioFormat (const String& name,
  15657. const tchar** const extensions)
  15658. : formatName (name),
  15659. fileExtensions (extensions)
  15660. {
  15661. }
  15662. AudioFormat::~AudioFormat()
  15663. {
  15664. }
  15665. const String& AudioFormat::getFormatName() const
  15666. {
  15667. return formatName;
  15668. }
  15669. const StringArray& AudioFormat::getFileExtensions() const
  15670. {
  15671. return fileExtensions;
  15672. }
  15673. bool AudioFormat::canHandleFile (const File& f)
  15674. {
  15675. for (int i = 0; i < fileExtensions.size(); ++i)
  15676. if (f.hasFileExtension (fileExtensions[i]))
  15677. return true;
  15678. return false;
  15679. }
  15680. bool AudioFormat::isCompressed()
  15681. {
  15682. return false;
  15683. }
  15684. const StringArray AudioFormat::getQualityOptions()
  15685. {
  15686. return StringArray();
  15687. }
  15688. END_JUCE_NAMESPACE
  15689. /********* End of inlined file: juce_AudioFormat.cpp *********/
  15690. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  15691. BEGIN_JUCE_NAMESPACE
  15692. AudioFormatManager::AudioFormatManager()
  15693. : knownFormats (4),
  15694. defaultFormatIndex (0)
  15695. {
  15696. }
  15697. AudioFormatManager::~AudioFormatManager()
  15698. {
  15699. clearFormats();
  15700. clearSingletonInstance();
  15701. }
  15702. juce_ImplementSingleton (AudioFormatManager);
  15703. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  15704. const bool makeThisTheDefaultFormat)
  15705. {
  15706. jassert (newFormat != 0);
  15707. if (newFormat != 0)
  15708. {
  15709. #ifdef JUCE_DEBUG
  15710. for (int i = getNumKnownFormats(); --i >= 0;)
  15711. {
  15712. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  15713. {
  15714. jassertfalse // trying to add the same format twice!
  15715. }
  15716. }
  15717. #endif
  15718. if (makeThisTheDefaultFormat)
  15719. defaultFormatIndex = knownFormats.size();
  15720. knownFormats.add (newFormat);
  15721. }
  15722. }
  15723. void AudioFormatManager::registerBasicFormats()
  15724. {
  15725. #if JUCE_MAC
  15726. registerFormat (new AiffAudioFormat(), true);
  15727. registerFormat (new WavAudioFormat(), false);
  15728. #else
  15729. registerFormat (new WavAudioFormat(), true);
  15730. registerFormat (new AiffAudioFormat(), false);
  15731. #endif
  15732. #if JUCE_USE_FLAC
  15733. registerFormat (new FlacAudioFormat(), false);
  15734. #endif
  15735. #if JUCE_USE_OGGVORBIS
  15736. registerFormat (new OggVorbisAudioFormat(), false);
  15737. #endif
  15738. }
  15739. void AudioFormatManager::clearFormats()
  15740. {
  15741. for (int i = getNumKnownFormats(); --i >= 0;)
  15742. {
  15743. AudioFormat* const af = getKnownFormat(i);
  15744. delete af;
  15745. }
  15746. knownFormats.clear();
  15747. defaultFormatIndex = 0;
  15748. }
  15749. int AudioFormatManager::getNumKnownFormats() const
  15750. {
  15751. return knownFormats.size();
  15752. }
  15753. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  15754. {
  15755. return (AudioFormat*) knownFormats [index];
  15756. }
  15757. AudioFormat* AudioFormatManager::getDefaultFormat() const
  15758. {
  15759. return getKnownFormat (defaultFormatIndex);
  15760. }
  15761. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  15762. {
  15763. String e (fileExtension);
  15764. if (! e.startsWithChar (T('.')))
  15765. e = T(".") + e;
  15766. for (int i = 0; i < getNumKnownFormats(); ++i)
  15767. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  15768. return getKnownFormat(i);
  15769. return 0;
  15770. }
  15771. const String AudioFormatManager::getWildcardForAllFormats() const
  15772. {
  15773. StringArray allExtensions;
  15774. int i;
  15775. for (i = 0; i < getNumKnownFormats(); ++i)
  15776. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  15777. allExtensions.trim();
  15778. allExtensions.removeEmptyStrings();
  15779. String s;
  15780. for (i = 0; i < allExtensions.size(); ++i)
  15781. {
  15782. s << T('*');
  15783. if (! allExtensions[i].startsWithChar (T('.')))
  15784. s << T('.');
  15785. s << allExtensions[i];
  15786. if (i < allExtensions.size() - 1)
  15787. s << T(';');
  15788. }
  15789. return s;
  15790. }
  15791. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  15792. {
  15793. // you need to actually register some formats before the manager can
  15794. // use them to open a file!
  15795. jassert (knownFormats.size() > 0);
  15796. for (int i = 0; i < getNumKnownFormats(); ++i)
  15797. {
  15798. AudioFormat* const af = getKnownFormat(i);
  15799. if (af->canHandleFile (file))
  15800. {
  15801. InputStream* const in = file.createInputStream();
  15802. if (in != 0)
  15803. {
  15804. AudioFormatReader* const r = af->createReaderFor (in, true);
  15805. if (r != 0)
  15806. return r;
  15807. }
  15808. }
  15809. }
  15810. return 0;
  15811. }
  15812. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  15813. {
  15814. // you need to actually register some formats before the manager can
  15815. // use them to open a file!
  15816. jassert (knownFormats.size() > 0);
  15817. if (in != 0)
  15818. {
  15819. const int64 originalStreamPos = in->getPosition();
  15820. for (int i = 0; i < getNumKnownFormats(); ++i)
  15821. {
  15822. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  15823. if (r != 0)
  15824. return r;
  15825. in->setPosition (originalStreamPos);
  15826. // the stream that is passed-in must be capable of being repositioned so
  15827. // that all the formats can have a go at opening it.
  15828. jassert (in->getPosition() == originalStreamPos);
  15829. }
  15830. delete in;
  15831. }
  15832. return 0;
  15833. }
  15834. END_JUCE_NAMESPACE
  15835. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  15836. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  15837. BEGIN_JUCE_NAMESPACE
  15838. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  15839. const int64 startSample_,
  15840. const int64 length_,
  15841. const bool deleteSourceWhenDeleted_)
  15842. : AudioFormatReader (0, source_->getFormatName()),
  15843. source (source_),
  15844. startSample (startSample_),
  15845. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  15846. {
  15847. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  15848. sampleRate = source->sampleRate;
  15849. bitsPerSample = source->bitsPerSample;
  15850. lengthInSamples = length;
  15851. numChannels = source->numChannels;
  15852. usesFloatingPointData = source->usesFloatingPointData;
  15853. }
  15854. AudioSubsectionReader::~AudioSubsectionReader()
  15855. {
  15856. if (deleteSourceWhenDeleted)
  15857. delete source;
  15858. }
  15859. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  15860. int64 startSampleInFile, int numSamples)
  15861. {
  15862. if (startSampleInFile + numSamples > length)
  15863. {
  15864. for (int i = numDestChannels; --i >= 0;)
  15865. if (destSamples[i] != 0)
  15866. zeromem (destSamples[i], sizeof (int) * numSamples);
  15867. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  15868. if (numSamples <= 0)
  15869. return true;
  15870. }
  15871. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  15872. startSampleInFile + startSample, numSamples);
  15873. }
  15874. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  15875. int64 numSamples,
  15876. float& lowestLeft,
  15877. float& highestLeft,
  15878. float& lowestRight,
  15879. float& highestRight)
  15880. {
  15881. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  15882. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  15883. source->readMaxLevels (startSampleInFile + startSample,
  15884. numSamples,
  15885. lowestLeft,
  15886. highestLeft,
  15887. lowestRight,
  15888. highestRight);
  15889. }
  15890. END_JUCE_NAMESPACE
  15891. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  15892. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  15893. BEGIN_JUCE_NAMESPACE
  15894. const int timeBeforeDeletingReader = 2000;
  15895. struct AudioThumbnailDataFormat
  15896. {
  15897. char thumbnailMagic[4];
  15898. int samplesPerThumbSample;
  15899. int64 totalSamples; // source samples
  15900. int64 numFinishedSamples; // source samples
  15901. int numThumbnailSamples;
  15902. int numChannels;
  15903. int sampleRate;
  15904. char future[16];
  15905. char data[1];
  15906. };
  15907. #if JUCE_BIG_ENDIAN
  15908. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  15909. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  15910. #endif
  15911. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  15912. {
  15913. (void) d;
  15914. #if JUCE_BIG_ENDIAN
  15915. swap (d->samplesPerThumbSample);
  15916. swap (d->totalSamples);
  15917. swap (d->numFinishedSamples);
  15918. swap (d->numThumbnailSamples);
  15919. swap (d->numChannels);
  15920. swap (d->sampleRate);
  15921. #endif
  15922. }
  15923. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  15924. AudioFormatManager& formatManagerToUse_,
  15925. AudioThumbnailCache& cacheToUse)
  15926. : formatManagerToUse (formatManagerToUse_),
  15927. cache (cacheToUse),
  15928. source (0),
  15929. reader (0),
  15930. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  15931. {
  15932. clear();
  15933. }
  15934. AudioThumbnail::~AudioThumbnail()
  15935. {
  15936. cache.removeThumbnail (this);
  15937. const ScopedLock sl (readerLock);
  15938. deleteAndZero (reader);
  15939. delete source;
  15940. }
  15941. void AudioThumbnail::setSource (InputSource* const newSource)
  15942. {
  15943. cache.removeThumbnail (this);
  15944. timerCallback(); // stops the timer and deletes the reader
  15945. delete source;
  15946. source = newSource;
  15947. clear();
  15948. if (newSource != 0
  15949. && ! (cache.loadThumb (*this, newSource->hashCode())
  15950. && isFullyLoaded()))
  15951. {
  15952. {
  15953. const ScopedLock sl (readerLock);
  15954. reader = createReader();
  15955. }
  15956. if (reader != 0)
  15957. {
  15958. initialiseFromAudioFile (*reader);
  15959. cache.addThumbnail (this);
  15960. }
  15961. }
  15962. sendChangeMessage (this);
  15963. }
  15964. bool AudioThumbnail::useTimeSlice()
  15965. {
  15966. const ScopedLock sl (readerLock);
  15967. if (isFullyLoaded())
  15968. {
  15969. if (reader != 0)
  15970. startTimer (timeBeforeDeletingReader);
  15971. cache.removeThumbnail (this);
  15972. return false;
  15973. }
  15974. if (reader == 0)
  15975. reader = createReader();
  15976. if (reader != 0)
  15977. {
  15978. readNextBlockFromAudioFile (*reader);
  15979. stopTimer();
  15980. sendChangeMessage (this);
  15981. const bool justFinished = isFullyLoaded();
  15982. if (justFinished)
  15983. cache.storeThumb (*this, source->hashCode());
  15984. return ! justFinished;
  15985. }
  15986. return false;
  15987. }
  15988. AudioFormatReader* AudioThumbnail::createReader() const
  15989. {
  15990. if (source != 0)
  15991. {
  15992. InputStream* const audioFileStream = source->createInputStream();
  15993. if (audioFileStream != 0)
  15994. return formatManagerToUse.createReaderFor (audioFileStream);
  15995. }
  15996. return 0;
  15997. }
  15998. void AudioThumbnail::timerCallback()
  15999. {
  16000. stopTimer();
  16001. const ScopedLock sl (readerLock);
  16002. deleteAndZero (reader);
  16003. }
  16004. void AudioThumbnail::clear()
  16005. {
  16006. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  16007. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16008. d->thumbnailMagic[0] = 'j';
  16009. d->thumbnailMagic[1] = 'a';
  16010. d->thumbnailMagic[2] = 't';
  16011. d->thumbnailMagic[3] = 'm';
  16012. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  16013. d->totalSamples = 0;
  16014. d->numFinishedSamples = 0;
  16015. d->numThumbnailSamples = 0;
  16016. d->numChannels = 0;
  16017. d->sampleRate = 0;
  16018. numSamplesCached = 0;
  16019. cacheNeedsRefilling = true;
  16020. }
  16021. void AudioThumbnail::loadFrom (InputStream& input)
  16022. {
  16023. data.setSize (0);
  16024. input.readIntoMemoryBlock (data);
  16025. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16026. swapEndiannessIfNeeded (d);
  16027. if (! (d->thumbnailMagic[0] == 'j'
  16028. && d->thumbnailMagic[1] == 'a'
  16029. && d->thumbnailMagic[2] == 't'
  16030. && d->thumbnailMagic[3] == 'm'))
  16031. {
  16032. clear();
  16033. }
  16034. numSamplesCached = 0;
  16035. cacheNeedsRefilling = true;
  16036. }
  16037. void AudioThumbnail::saveTo (OutputStream& output) const
  16038. {
  16039. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16040. swapEndiannessIfNeeded (d);
  16041. output.write (data.getData(), data.getSize());
  16042. swapEndiannessIfNeeded (d);
  16043. }
  16044. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  16045. {
  16046. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  16047. d->totalSamples = reader.lengthInSamples;
  16048. d->numChannels = jmin (2, reader.numChannels);
  16049. d->numFinishedSamples = 0;
  16050. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  16051. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  16052. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  16053. d = (AudioThumbnailDataFormat*) data.getData();
  16054. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  16055. return d->totalSamples > 0;
  16056. }
  16057. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  16058. {
  16059. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16060. if (d->numFinishedSamples < d->totalSamples)
  16061. {
  16062. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  16063. generateSection (reader,
  16064. d->numFinishedSamples,
  16065. numToDo);
  16066. d->numFinishedSamples += numToDo;
  16067. }
  16068. cacheNeedsRefilling = true;
  16069. return (d->numFinishedSamples < d->totalSamples);
  16070. }
  16071. int AudioThumbnail::getNumChannels() const throw()
  16072. {
  16073. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16074. jassert (d != 0);
  16075. return d->numChannels;
  16076. }
  16077. double AudioThumbnail::getTotalLength() const throw()
  16078. {
  16079. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16080. jassert (d != 0);
  16081. if (d->sampleRate > 0)
  16082. return d->totalSamples / (double)d->sampleRate;
  16083. else
  16084. return 0.0;
  16085. }
  16086. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  16087. int64 startSample,
  16088. int numSamples)
  16089. {
  16090. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16091. jassert (d != 0);
  16092. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  16093. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  16094. char* l = getChannelData (0);
  16095. char* r = getChannelData (1);
  16096. for (int i = firstDataPos; i < lastDataPos; ++i)
  16097. {
  16098. const int sourceStart = i * d->samplesPerThumbSample;
  16099. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  16100. float lowestLeft, highestLeft, lowestRight, highestRight;
  16101. reader.readMaxLevels (sourceStart,
  16102. sourceEnd - sourceStart,
  16103. lowestLeft,
  16104. highestLeft,
  16105. lowestRight,
  16106. highestRight);
  16107. int n = i * 2;
  16108. if (r != 0)
  16109. {
  16110. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16111. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  16112. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16113. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  16114. }
  16115. else
  16116. {
  16117. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  16118. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  16119. }
  16120. }
  16121. }
  16122. char* AudioThumbnail::getChannelData (int channel) const
  16123. {
  16124. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  16125. jassert (d != 0);
  16126. if (channel >= 0 && channel < d->numChannels)
  16127. return d->data + (channel * 2 * d->numThumbnailSamples);
  16128. return 0;
  16129. }
  16130. bool AudioThumbnail::isFullyLoaded() const throw()
  16131. {
  16132. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16133. jassert (d != 0);
  16134. return d->numFinishedSamples >= d->totalSamples;
  16135. }
  16136. void AudioThumbnail::refillCache (const int numSamples,
  16137. double startTime,
  16138. const double timePerPixel)
  16139. {
  16140. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  16141. jassert (d != 0);
  16142. if (numSamples <= 0
  16143. || timePerPixel <= 0.0
  16144. || d->sampleRate <= 0)
  16145. {
  16146. numSamplesCached = 0;
  16147. cacheNeedsRefilling = true;
  16148. return;
  16149. }
  16150. if (numSamples == numSamplesCached
  16151. && numChannelsCached == d->numChannels
  16152. && startTime == cachedStart
  16153. && timePerPixel == cachedTimePerPixel
  16154. && ! cacheNeedsRefilling)
  16155. {
  16156. return;
  16157. }
  16158. numSamplesCached = numSamples;
  16159. numChannelsCached = d->numChannels;
  16160. cachedStart = startTime;
  16161. cachedTimePerPixel = timePerPixel;
  16162. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  16163. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  16164. const ScopedLock sl (readerLock);
  16165. cacheNeedsRefilling = false;
  16166. if (needExtraDetail && reader == 0)
  16167. reader = createReader();
  16168. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  16169. {
  16170. startTimer (timeBeforeDeletingReader);
  16171. char* cacheData = (char*) cachedLevels.getData();
  16172. int sample = roundDoubleToInt (startTime * d->sampleRate);
  16173. for (int i = numSamples; --i >= 0;)
  16174. {
  16175. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  16176. if (sample >= 0)
  16177. {
  16178. if (sample >= reader->lengthInSamples)
  16179. break;
  16180. float lmin, lmax, rmin, rmax;
  16181. reader->readMaxLevels (sample,
  16182. jmax (1, nextSample - sample),
  16183. lmin, lmax, rmin, rmax);
  16184. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  16185. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  16186. if (numChannelsCached > 1)
  16187. {
  16188. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  16189. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  16190. }
  16191. cacheData += 2 * numChannelsCached;
  16192. }
  16193. startTime += timePerPixel;
  16194. sample = nextSample;
  16195. }
  16196. }
  16197. else
  16198. {
  16199. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  16200. {
  16201. char* const data = getChannelData (channelNum);
  16202. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  16203. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  16204. startTime = cachedStart;
  16205. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  16206. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  16207. for (int i = numSamples; --i >= 0;)
  16208. {
  16209. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  16210. if (sample >= 0 && data != 0)
  16211. {
  16212. char mx = -128;
  16213. char mn = 127;
  16214. while (sample <= nextSample)
  16215. {
  16216. if (sample >= numFinished)
  16217. break;
  16218. const int n = sample << 1;
  16219. const char sampMin = data [n];
  16220. const char sampMax = data [n + 1];
  16221. if (sampMin < mn)
  16222. mn = sampMin;
  16223. if (sampMax > mx)
  16224. mx = sampMax;
  16225. ++sample;
  16226. }
  16227. if (mn <= mx)
  16228. {
  16229. cacheData[0] = mn;
  16230. cacheData[1] = mx;
  16231. }
  16232. else
  16233. {
  16234. cacheData[0] = 1;
  16235. cacheData[1] = 0;
  16236. }
  16237. }
  16238. else
  16239. {
  16240. cacheData[0] = 1;
  16241. cacheData[1] = 0;
  16242. }
  16243. cacheData += numChannelsCached * 2;
  16244. startTime += timePerPixel;
  16245. sample = nextSample;
  16246. }
  16247. }
  16248. }
  16249. }
  16250. void AudioThumbnail::drawChannel (Graphics& g,
  16251. int x, int y, int w, int h,
  16252. double startTime,
  16253. double endTime,
  16254. int channelNum,
  16255. const float verticalZoomFactor)
  16256. {
  16257. refillCache (w, startTime, (endTime - startTime) / w);
  16258. if (numSamplesCached >= w
  16259. && channelNum >= 0
  16260. && channelNum < numChannelsCached)
  16261. {
  16262. const float topY = (float) y;
  16263. const float bottomY = topY + h;
  16264. const float midY = topY + h * 0.5f;
  16265. const float vscale = verticalZoomFactor * h / 256.0f;
  16266. const Rectangle clip (g.getClipBounds());
  16267. const int skipLeft = jlimit (0, w, clip.getX() - x);
  16268. w -= skipLeft;
  16269. x += skipLeft;
  16270. const char* cacheData = ((const char*) cachedLevels.getData())
  16271. + (channelNum << 1)
  16272. + skipLeft * (numChannelsCached << 1);
  16273. while (--w >= 0)
  16274. {
  16275. const char mn = cacheData[0];
  16276. const char mx = cacheData[1];
  16277. cacheData += numChannelsCached << 1;
  16278. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  16279. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  16280. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  16281. ++x;
  16282. if (x >= clip.getRight())
  16283. break;
  16284. }
  16285. }
  16286. }
  16287. END_JUCE_NAMESPACE
  16288. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  16289. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  16290. BEGIN_JUCE_NAMESPACE
  16291. struct ThumbnailCacheEntry
  16292. {
  16293. int64 hash;
  16294. uint32 lastUsed;
  16295. MemoryBlock data;
  16296. juce_UseDebuggingNewOperator
  16297. };
  16298. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  16299. : TimeSliceThread (T("thumb cache")),
  16300. maxNumThumbsToStore (maxNumThumbsToStore_)
  16301. {
  16302. startThread (2);
  16303. }
  16304. AudioThumbnailCache::~AudioThumbnailCache()
  16305. {
  16306. }
  16307. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  16308. {
  16309. for (int i = thumbs.size(); --i >= 0;)
  16310. {
  16311. if (thumbs[i]->hash == hashCode)
  16312. {
  16313. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  16314. thumbs[i]->data.getSize(),
  16315. false);
  16316. thumb.loadFrom (in);
  16317. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  16318. return true;
  16319. }
  16320. }
  16321. return false;
  16322. }
  16323. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  16324. const int64 hashCode)
  16325. {
  16326. MemoryOutputStream out;
  16327. thumb.saveTo (out);
  16328. ThumbnailCacheEntry* te = 0;
  16329. for (int i = thumbs.size(); --i >= 0;)
  16330. {
  16331. if (thumbs[i]->hash == hashCode)
  16332. {
  16333. te = thumbs[i];
  16334. break;
  16335. }
  16336. }
  16337. if (te == 0)
  16338. {
  16339. te = new ThumbnailCacheEntry();
  16340. te->hash = hashCode;
  16341. if (thumbs.size() < maxNumThumbsToStore)
  16342. {
  16343. thumbs.add (te);
  16344. }
  16345. else
  16346. {
  16347. int oldest = 0;
  16348. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  16349. int i;
  16350. for (i = thumbs.size(); --i >= 0;)
  16351. if (thumbs[i]->lastUsed < oldestTime)
  16352. oldest = i;
  16353. thumbs.set (i, te);
  16354. }
  16355. }
  16356. te->lastUsed = Time::getMillisecondCounter();
  16357. te->data.setSize (0);
  16358. te->data.append (out.getData(), out.getDataSize());
  16359. }
  16360. void AudioThumbnailCache::clear()
  16361. {
  16362. thumbs.clear();
  16363. }
  16364. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  16365. {
  16366. addTimeSliceClient (thumb);
  16367. }
  16368. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  16369. {
  16370. removeTimeSliceClient (thumb);
  16371. }
  16372. END_JUCE_NAMESPACE
  16373. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  16374. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16375. #if JUCE_QUICKTIME
  16376. #if ! defined (_WIN32)
  16377. #include <QuickTime/Movies.h>
  16378. #include <QuickTime/QTML.h>
  16379. #include <QuickTime/QuickTimeComponents.h>
  16380. #include <QuickTime/MediaHandlers.h>
  16381. #include <QuickTime/ImageCodec.h>
  16382. #else
  16383. #ifdef _MSC_VER
  16384. #pragma warning (push)
  16385. #pragma warning (disable : 4100)
  16386. #endif
  16387. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  16388. add its header directory to your include path.
  16389. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  16390. flag in juce_Config.h
  16391. */
  16392. #include <Movies.h>
  16393. #include <QTML.h>
  16394. #include <QuickTimeComponents.h>
  16395. #include <MediaHandlers.h>
  16396. #include <ImageCodec.h>
  16397. #ifdef _MSC_VER
  16398. #pragma warning (pop)
  16399. #endif
  16400. #endif
  16401. #if ! (JUCE_MAC && JUCE_64BIT)
  16402. BEGIN_JUCE_NAMESPACE
  16403. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  16404. #define quickTimeFormatName TRANS("QuickTime file")
  16405. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  16406. class QTAudioReader : public AudioFormatReader
  16407. {
  16408. public:
  16409. QTAudioReader (InputStream* const input_, const int trackNum_)
  16410. : AudioFormatReader (input_, quickTimeFormatName),
  16411. ok (false),
  16412. movie (0),
  16413. trackNum (trackNum_),
  16414. extractor (0),
  16415. lastSampleRead (0),
  16416. lastThreadId (0),
  16417. dataHandle (0)
  16418. {
  16419. bufferList = (AudioBufferList*) juce_calloc (256);
  16420. #ifdef WIN32
  16421. if (InitializeQTML (0) != noErr)
  16422. return;
  16423. #endif
  16424. if (EnterMovies() != noErr)
  16425. return;
  16426. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  16427. if (! opened)
  16428. return;
  16429. {
  16430. const int numTracks = GetMovieTrackCount (movie);
  16431. int trackCount = 0;
  16432. for (int i = 1; i <= numTracks; ++i)
  16433. {
  16434. track = GetMovieIndTrack (movie, i);
  16435. media = GetTrackMedia (track);
  16436. OSType mediaType;
  16437. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  16438. if (mediaType == SoundMediaType
  16439. && trackCount++ == trackNum_)
  16440. {
  16441. ok = true;
  16442. break;
  16443. }
  16444. }
  16445. }
  16446. if (! ok)
  16447. return;
  16448. ok = false;
  16449. lengthInSamples = GetMediaDecodeDuration (media);
  16450. usesFloatingPointData = false;
  16451. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  16452. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  16453. / GetMediaTimeScale (media);
  16454. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  16455. unsigned long output_layout_size;
  16456. err = MovieAudioExtractionGetPropertyInfo (extractor,
  16457. kQTPropertyClass_MovieAudioExtraction_Audio,
  16458. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16459. 0, &output_layout_size, 0);
  16460. if (err != noErr)
  16461. return;
  16462. AudioChannelLayout* const qt_audio_channel_layout
  16463. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  16464. err = MovieAudioExtractionGetProperty (extractor,
  16465. kQTPropertyClass_MovieAudioExtraction_Audio,
  16466. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16467. output_layout_size, qt_audio_channel_layout, 0);
  16468. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  16469. err = MovieAudioExtractionSetProperty (extractor,
  16470. kQTPropertyClass_MovieAudioExtraction_Audio,
  16471. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  16472. sizeof (qt_audio_channel_layout),
  16473. qt_audio_channel_layout);
  16474. juce_free (qt_audio_channel_layout);
  16475. err = MovieAudioExtractionGetProperty (extractor,
  16476. kQTPropertyClass_MovieAudioExtraction_Audio,
  16477. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16478. sizeof (inputStreamDesc),
  16479. &inputStreamDesc, 0);
  16480. if (err != noErr)
  16481. return;
  16482. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  16483. | kAudioFormatFlagIsPacked
  16484. | kAudioFormatFlagsNativeEndian;
  16485. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  16486. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  16487. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  16488. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  16489. err = MovieAudioExtractionSetProperty (extractor,
  16490. kQTPropertyClass_MovieAudioExtraction_Audio,
  16491. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  16492. sizeof (inputStreamDesc),
  16493. &inputStreamDesc);
  16494. if (err != noErr)
  16495. return;
  16496. Boolean allChannelsDiscrete = false;
  16497. err = MovieAudioExtractionSetProperty (extractor,
  16498. kQTPropertyClass_MovieAudioExtraction_Movie,
  16499. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  16500. sizeof (allChannelsDiscrete),
  16501. &allChannelsDiscrete);
  16502. if (err != noErr)
  16503. return;
  16504. bufferList->mNumberBuffers = 1;
  16505. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  16506. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  16507. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  16508. sampleRate = inputStreamDesc.mSampleRate;
  16509. bitsPerSample = 16;
  16510. numChannels = inputStreamDesc.mChannelsPerFrame;
  16511. detachThread();
  16512. ok = true;
  16513. }
  16514. ~QTAudioReader()
  16515. {
  16516. if (dataHandle != 0)
  16517. DisposeHandle (dataHandle);
  16518. if (extractor != 0)
  16519. {
  16520. MovieAudioExtractionEnd (extractor);
  16521. extractor = 0;
  16522. }
  16523. checkThreadIsAttached();
  16524. DisposeMovie (movie);
  16525. juce_free (bufferList->mBuffers[0].mData);
  16526. juce_free (bufferList);
  16527. #if JUCE_MAC
  16528. ExitMoviesOnThread ();
  16529. #endif
  16530. }
  16531. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16532. int64 startSampleInFile, int numSamples)
  16533. {
  16534. checkThreadIsAttached();
  16535. while (numSamples > 0)
  16536. {
  16537. if (! loadFrame ((int) startSampleInFile))
  16538. return false;
  16539. const int numToDo = jmin (numSamples, samplesPerFrame);
  16540. for (int j = numDestChannels; --j >= 0;)
  16541. {
  16542. if (destSamples[j] != 0)
  16543. {
  16544. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  16545. for (int i = 0; i < numToDo; ++i)
  16546. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  16547. }
  16548. }
  16549. startOffsetInDestBuffer += numToDo;
  16550. startSampleInFile += numToDo;
  16551. numSamples -= numToDo;
  16552. }
  16553. detachThread();
  16554. return true;
  16555. }
  16556. bool loadFrame (const int sampleNum)
  16557. {
  16558. if (lastSampleRead != sampleNum)
  16559. {
  16560. TimeRecord time;
  16561. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  16562. time.base = 0;
  16563. time.value.hi = 0;
  16564. time.value.lo = (UInt32) sampleNum;
  16565. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  16566. kQTPropertyClass_MovieAudioExtraction_Movie,
  16567. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  16568. sizeof (time), &time);
  16569. if (err != noErr)
  16570. return false;
  16571. }
  16572. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  16573. UInt32 outFlags = 0;
  16574. UInt32 actualNumSamples = samplesPerFrame;
  16575. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  16576. bufferList, &outFlags);
  16577. lastSampleRead = sampleNum + samplesPerFrame;
  16578. return err == noErr;
  16579. }
  16580. juce_UseDebuggingNewOperator
  16581. bool ok;
  16582. private:
  16583. Movie movie;
  16584. Media media;
  16585. Track track;
  16586. const int trackNum;
  16587. double trackUnitsPerFrame;
  16588. int samplesPerFrame;
  16589. int lastSampleRead;
  16590. Thread::ThreadID lastThreadId;
  16591. MovieAudioExtractionRef extractor;
  16592. AudioStreamBasicDescription inputStreamDesc;
  16593. AudioBufferList* bufferList;
  16594. Handle dataHandle;
  16595. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  16596. {
  16597. input->setPosition (offset);
  16598. input->read (dataPtr, size);
  16599. return noErr;
  16600. }
  16601. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  16602. {
  16603. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  16604. }*/
  16605. void checkThreadIsAttached()
  16606. {
  16607. #if JUCE_MAC
  16608. if (Thread::getCurrentThreadId() != lastThreadId)
  16609. EnterMoviesOnThread (0);
  16610. AttachMovieToCurrentThread (movie);
  16611. #endif
  16612. }
  16613. void detachThread()
  16614. {
  16615. #if JUCE_MAC
  16616. DetachMovieFromCurrentThread (movie);
  16617. #endif
  16618. }
  16619. };
  16620. QuickTimeAudioFormat::QuickTimeAudioFormat()
  16621. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  16622. {
  16623. }
  16624. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  16625. {
  16626. }
  16627. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  16628. {
  16629. return Array<int>();
  16630. }
  16631. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  16632. {
  16633. return Array<int>();
  16634. }
  16635. bool QuickTimeAudioFormat::canDoStereo()
  16636. {
  16637. return true;
  16638. }
  16639. bool QuickTimeAudioFormat::canDoMono()
  16640. {
  16641. return true;
  16642. }
  16643. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  16644. const bool deleteStreamIfOpeningFails)
  16645. {
  16646. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  16647. if (! r->ok)
  16648. {
  16649. if (! deleteStreamIfOpeningFails)
  16650. r->input = 0;
  16651. deleteAndZero (r);
  16652. }
  16653. return r;
  16654. }
  16655. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  16656. double /*sampleRateToUse*/,
  16657. unsigned int /*numberOfChannels*/,
  16658. int /*bitsPerSample*/,
  16659. const StringPairArray& /*metadataValues*/,
  16660. int /*qualityOptionIndex*/)
  16661. {
  16662. jassertfalse // not yet implemented!
  16663. return 0;
  16664. }
  16665. END_JUCE_NAMESPACE
  16666. #endif
  16667. #endif
  16668. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  16669. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  16670. BEGIN_JUCE_NAMESPACE
  16671. #define wavFormatName TRANS("WAV file")
  16672. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  16673. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  16674. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  16675. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  16676. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  16677. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  16678. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  16679. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  16680. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  16681. const String& originator,
  16682. const String& originatorRef,
  16683. const Time& date,
  16684. const int64 timeReferenceSamples,
  16685. const String& codingHistory)
  16686. {
  16687. StringPairArray m;
  16688. m.set (bwavDescription, description);
  16689. m.set (bwavOriginator, originator);
  16690. m.set (bwavOriginatorRef, originatorRef);
  16691. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  16692. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  16693. m.set (bwavTimeReference, String (timeReferenceSamples));
  16694. m.set (bwavCodingHistory, codingHistory);
  16695. return m;
  16696. }
  16697. #if JUCE_MSVC
  16698. #pragma pack (push, 1)
  16699. #define PACKED
  16700. #elif defined (JUCE_GCC)
  16701. #define PACKED __attribute__((packed))
  16702. #else
  16703. #define PACKED
  16704. #endif
  16705. struct BWAVChunk
  16706. {
  16707. uint8 description [256];
  16708. uint8 originator [32];
  16709. uint8 originatorRef [32];
  16710. uint8 originationDate [10];
  16711. uint8 originationTime [8];
  16712. uint32 timeRefLow;
  16713. uint32 timeRefHigh;
  16714. uint16 version;
  16715. uint8 umid[64];
  16716. uint8 reserved[190];
  16717. uint8 codingHistory[1];
  16718. void copyTo (StringPairArray& values) const
  16719. {
  16720. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  16721. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  16722. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  16723. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  16724. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  16725. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  16726. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  16727. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  16728. values.set (WavAudioFormat::bwavTimeReference, String (time));
  16729. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  16730. }
  16731. static MemoryBlock createFrom (const StringPairArray& values)
  16732. {
  16733. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (0) - 1;
  16734. MemoryBlock data ((sizeNeeded + 3) & ~3);
  16735. data.fillWith (0);
  16736. BWAVChunk* b = (BWAVChunk*) data.getData();
  16737. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  16738. // as they get called in the right order..
  16739. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  16740. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  16741. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  16742. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  16743. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  16744. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  16745. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  16746. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  16747. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory);
  16748. if (b->description[0] != 0
  16749. || b->originator[0] != 0
  16750. || b->originationDate[0] != 0
  16751. || b->originationTime[0] != 0
  16752. || b->codingHistory[0] != 0
  16753. || time != 0)
  16754. {
  16755. return data;
  16756. }
  16757. return MemoryBlock();
  16758. }
  16759. } PACKED;
  16760. struct SMPLChunk
  16761. {
  16762. struct SampleLoop
  16763. {
  16764. uint32 identifier;
  16765. uint32 type;
  16766. uint32 start;
  16767. uint32 end;
  16768. uint32 fraction;
  16769. uint32 playCount;
  16770. } PACKED;
  16771. uint32 manufacturer;
  16772. uint32 product;
  16773. uint32 samplePeriod;
  16774. uint32 midiUnityNote;
  16775. uint32 midiPitchFraction;
  16776. uint32 smpteFormat;
  16777. uint32 smpteOffset;
  16778. uint32 numSampleLoops;
  16779. uint32 samplerData;
  16780. SampleLoop loops[1];
  16781. void copyTo (StringPairArray& values, const int totalSize) const
  16782. {
  16783. values.set (T("Manufacturer"), String (swapIfBigEndian (manufacturer)));
  16784. values.set (T("Product"), String (swapIfBigEndian (product)));
  16785. values.set (T("SamplePeriod"), String (swapIfBigEndian (samplePeriod)));
  16786. values.set (T("MidiUnityNote"), String (swapIfBigEndian (midiUnityNote)));
  16787. values.set (T("MidiPitchFraction"), String (swapIfBigEndian (midiPitchFraction)));
  16788. values.set (T("SmpteFormat"), String (swapIfBigEndian (smpteFormat)));
  16789. values.set (T("SmpteOffset"), String (swapIfBigEndian (smpteOffset)));
  16790. values.set (T("NumSampleLoops"), String (swapIfBigEndian (numSampleLoops)));
  16791. values.set (T("SamplerData"), String (swapIfBigEndian (samplerData)));
  16792. for (uint32 i = 0; i < numSampleLoops; ++i)
  16793. {
  16794. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  16795. break;
  16796. values.set (String::formatted (T("Loop%dIdentifier"), i), String (swapIfBigEndian (loops[i].identifier)));
  16797. values.set (String::formatted (T("Loop%dType"), i), String (swapIfBigEndian (loops[i].type)));
  16798. values.set (String::formatted (T("Loop%dStart"), i), String (swapIfBigEndian (loops[i].start)));
  16799. values.set (String::formatted (T("Loop%dEnd"), i), String (swapIfBigEndian (loops[i].end)));
  16800. values.set (String::formatted (T("Loop%dFraction"), i), String (swapIfBigEndian (loops[i].fraction)));
  16801. values.set (String::formatted (T("Loop%dPlayCount"), i), String (swapIfBigEndian (loops[i].playCount)));
  16802. }
  16803. }
  16804. } PACKED;
  16805. #if JUCE_MSVC
  16806. #pragma pack (pop)
  16807. #endif
  16808. #undef PACKED
  16809. #undef chunkName
  16810. #define chunkName(a) ((int) littleEndianInt(a))
  16811. class WavAudioFormatReader : public AudioFormatReader
  16812. {
  16813. int bytesPerFrame;
  16814. int64 dataChunkStart, dataLength;
  16815. WavAudioFormatReader (const WavAudioFormatReader&);
  16816. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  16817. public:
  16818. int64 bwavChunkStart, bwavSize;
  16819. WavAudioFormatReader (InputStream* const in)
  16820. : AudioFormatReader (in, wavFormatName),
  16821. dataLength (0),
  16822. bwavChunkStart (0),
  16823. bwavSize (0)
  16824. {
  16825. if (input->readInt() == chunkName ("RIFF"))
  16826. {
  16827. const uint32 len = (uint32) input->readInt();
  16828. const int64 end = input->getPosition() + len;
  16829. bool hasGotType = false;
  16830. bool hasGotData = false;
  16831. if (input->readInt() == chunkName ("WAVE"))
  16832. {
  16833. while (input->getPosition() < end
  16834. && ! input->isExhausted())
  16835. {
  16836. const int chunkType = input->readInt();
  16837. uint32 length = (uint32) input->readInt();
  16838. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  16839. if (chunkType == chunkName ("fmt "))
  16840. {
  16841. // read the format chunk
  16842. const short format = input->readShort();
  16843. const short numChans = input->readShort();
  16844. sampleRate = input->readInt();
  16845. const int bytesPerSec = input->readInt();
  16846. numChannels = numChans;
  16847. bytesPerFrame = bytesPerSec / (int)sampleRate;
  16848. bitsPerSample = 8 * bytesPerFrame / numChans;
  16849. if (format == 3)
  16850. usesFloatingPointData = true;
  16851. else if (format != 1)
  16852. bytesPerFrame = 0;
  16853. hasGotType = true;
  16854. }
  16855. else if (chunkType == chunkName ("data"))
  16856. {
  16857. // get the data chunk's position
  16858. dataLength = length;
  16859. dataChunkStart = input->getPosition();
  16860. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  16861. hasGotData = true;
  16862. }
  16863. else if (chunkType == chunkName ("bext"))
  16864. {
  16865. bwavChunkStart = input->getPosition();
  16866. bwavSize = length;
  16867. // Broadcast-wav extension chunk..
  16868. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  16869. input->read (bwav, length);
  16870. bwav->copyTo (metadataValues);
  16871. juce_free (bwav);
  16872. }
  16873. else if (chunkType == chunkName ("smpl"))
  16874. {
  16875. SMPLChunk* const smpl = (SMPLChunk*) juce_calloc (jmax (length + 1, (int) sizeof (SMPLChunk)));
  16876. input->read (smpl, length);
  16877. smpl->copyTo (metadataValues, length);
  16878. juce_free (smpl);
  16879. }
  16880. else if (chunkEnd <= input->getPosition())
  16881. {
  16882. break;
  16883. }
  16884. input->setPosition (chunkEnd);
  16885. }
  16886. }
  16887. }
  16888. }
  16889. ~WavAudioFormatReader()
  16890. {
  16891. }
  16892. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16893. int64 startSampleInFile, int numSamples)
  16894. {
  16895. numSamples = (int) jmin ((int64) numSamples, lengthInSamples - startSampleInFile);
  16896. if (numSamples <= 0)
  16897. return true;
  16898. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16899. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16900. char tempBuffer [tempBufSize];
  16901. while (numSamples > 0)
  16902. {
  16903. int* left = destSamples[0];
  16904. if (left != 0)
  16905. left += startOffsetInDestBuffer;
  16906. int* right = numDestChannels > 1 ? destSamples[1] : 0;
  16907. if (right != 0)
  16908. right += startOffsetInDestBuffer;
  16909. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16910. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16911. if (bytesRead < numThisTime * bytesPerFrame)
  16912. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16913. if (bitsPerSample == 16)
  16914. {
  16915. const short* src = (const short*) tempBuffer;
  16916. if (numChannels > 1)
  16917. {
  16918. if (left == 0)
  16919. {
  16920. for (int i = numThisTime; --i >= 0;)
  16921. {
  16922. ++src;
  16923. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16924. }
  16925. }
  16926. else if (right == 0)
  16927. {
  16928. for (int i = numThisTime; --i >= 0;)
  16929. {
  16930. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16931. ++src;
  16932. }
  16933. }
  16934. else
  16935. {
  16936. for (int i = numThisTime; --i >= 0;)
  16937. {
  16938. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16939. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16940. }
  16941. }
  16942. }
  16943. else
  16944. {
  16945. for (int i = numThisTime; --i >= 0;)
  16946. {
  16947. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  16948. }
  16949. }
  16950. }
  16951. else if (bitsPerSample == 24)
  16952. {
  16953. const char* src = (const char*) tempBuffer;
  16954. if (numChannels > 1)
  16955. {
  16956. if (left == 0)
  16957. {
  16958. for (int i = numThisTime; --i >= 0;)
  16959. {
  16960. src += 3;
  16961. *right++ = littleEndian24Bit (src) << 8;
  16962. src += 3;
  16963. }
  16964. }
  16965. else if (right == 0)
  16966. {
  16967. for (int i = numThisTime; --i >= 0;)
  16968. {
  16969. *left++ = littleEndian24Bit (src) << 8;
  16970. src += 6;
  16971. }
  16972. }
  16973. else
  16974. {
  16975. for (int i = 0; i < numThisTime; ++i)
  16976. {
  16977. *left++ = littleEndian24Bit (src) << 8;
  16978. src += 3;
  16979. *right++ = littleEndian24Bit (src) << 8;
  16980. src += 3;
  16981. }
  16982. }
  16983. }
  16984. else
  16985. {
  16986. for (int i = 0; i < numThisTime; ++i)
  16987. {
  16988. *left++ = littleEndian24Bit (src) << 8;
  16989. src += 3;
  16990. }
  16991. }
  16992. }
  16993. else if (bitsPerSample == 32)
  16994. {
  16995. const unsigned int* src = (const unsigned int*) tempBuffer;
  16996. unsigned int* l = (unsigned int*) left;
  16997. unsigned int* r = (unsigned int*) right;
  16998. if (numChannels > 1)
  16999. {
  17000. if (l == 0)
  17001. {
  17002. for (int i = numThisTime; --i >= 0;)
  17003. {
  17004. ++src;
  17005. *r++ = swapIfBigEndian (*src++);
  17006. }
  17007. }
  17008. else if (r == 0)
  17009. {
  17010. for (int i = numThisTime; --i >= 0;)
  17011. {
  17012. *l++ = swapIfBigEndian (*src++);
  17013. ++src;
  17014. }
  17015. }
  17016. else
  17017. {
  17018. for (int i = numThisTime; --i >= 0;)
  17019. {
  17020. *l++ = swapIfBigEndian (*src++);
  17021. *r++ = swapIfBigEndian (*src++);
  17022. }
  17023. }
  17024. }
  17025. else
  17026. {
  17027. for (int i = numThisTime; --i >= 0;)
  17028. {
  17029. *l++ = swapIfBigEndian (*src++);
  17030. }
  17031. }
  17032. left = (int*)l;
  17033. right = (int*)r;
  17034. }
  17035. else if (bitsPerSample == 8)
  17036. {
  17037. const unsigned char* src = (const unsigned char*) tempBuffer;
  17038. if (numChannels > 1)
  17039. {
  17040. if (left == 0)
  17041. {
  17042. for (int i = numThisTime; --i >= 0;)
  17043. {
  17044. ++src;
  17045. *right++ = ((int) *src++ - 128) << 24;
  17046. }
  17047. }
  17048. else if (right == 0)
  17049. {
  17050. for (int i = numThisTime; --i >= 0;)
  17051. {
  17052. *left++ = ((int) *src++ - 128) << 24;
  17053. ++src;
  17054. }
  17055. }
  17056. else
  17057. {
  17058. for (int i = numThisTime; --i >= 0;)
  17059. {
  17060. *left++ = ((int) *src++ - 128) << 24;
  17061. *right++ = ((int) *src++ - 128) << 24;
  17062. }
  17063. }
  17064. }
  17065. else
  17066. {
  17067. for (int i = numThisTime; --i >= 0;)
  17068. {
  17069. *left++ = ((int)*src++ - 128) << 24;
  17070. }
  17071. }
  17072. }
  17073. startOffsetInDestBuffer += numThisTime;
  17074. numSamples -= numThisTime;
  17075. }
  17076. if (numSamples > 0)
  17077. {
  17078. for (int i = numDestChannels; --i >= 0;)
  17079. if (destSamples[i] != 0)
  17080. zeromem (destSamples[i] + startOffsetInDestBuffer,
  17081. sizeof (int) * numSamples);
  17082. }
  17083. return true;
  17084. }
  17085. juce_UseDebuggingNewOperator
  17086. };
  17087. class WavAudioFormatWriter : public AudioFormatWriter
  17088. {
  17089. MemoryBlock tempBlock, bwavChunk;
  17090. uint32 lengthInSamples, bytesWritten;
  17091. int64 headerPosition;
  17092. bool writeFailed;
  17093. WavAudioFormatWriter (const WavAudioFormatWriter&);
  17094. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  17095. void writeHeader()
  17096. {
  17097. const bool seekedOk = output->setPosition (headerPosition);
  17098. (void) seekedOk;
  17099. // if this fails, you've given it an output stream that can't seek! It needs
  17100. // to be able to seek back to write the header
  17101. jassert (seekedOk);
  17102. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  17103. output->writeInt (chunkName ("RIFF"));
  17104. output->writeInt (lengthInSamples * bytesPerFrame
  17105. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  17106. output->writeInt (chunkName ("WAVE"));
  17107. output->writeInt (chunkName ("fmt "));
  17108. output->writeInt (16);
  17109. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  17110. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  17111. output->writeShort ((short) numChannels);
  17112. output->writeInt ((int) sampleRate);
  17113. output->writeInt (bytesPerFrame * (int) sampleRate);
  17114. output->writeShort ((short) bytesPerFrame);
  17115. output->writeShort ((short) bitsPerSample);
  17116. if (bwavChunk.getSize() > 0)
  17117. {
  17118. output->writeInt (chunkName ("bext"));
  17119. output->writeInt (bwavChunk.getSize());
  17120. output->write (bwavChunk.getData(), bwavChunk.getSize());
  17121. }
  17122. output->writeInt (chunkName ("data"));
  17123. output->writeInt (lengthInSamples * bytesPerFrame);
  17124. usesFloatingPointData = (bitsPerSample == 32);
  17125. }
  17126. public:
  17127. WavAudioFormatWriter (OutputStream* const out,
  17128. const double sampleRate,
  17129. const unsigned int numChannels_,
  17130. const int bits,
  17131. const StringPairArray& metadataValues)
  17132. : AudioFormatWriter (out,
  17133. wavFormatName,
  17134. sampleRate,
  17135. numChannels_,
  17136. bits),
  17137. lengthInSamples (0),
  17138. bytesWritten (0),
  17139. writeFailed (false)
  17140. {
  17141. if (metadataValues.size() > 0)
  17142. bwavChunk = BWAVChunk::createFrom (metadataValues);
  17143. headerPosition = out->getPosition();
  17144. writeHeader();
  17145. }
  17146. ~WavAudioFormatWriter()
  17147. {
  17148. writeHeader();
  17149. }
  17150. bool write (const int** data, int numSamples)
  17151. {
  17152. if (writeFailed)
  17153. return false;
  17154. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  17155. tempBlock.ensureSize (bytes, false);
  17156. char* buffer = (char*) tempBlock.getData();
  17157. const int* left = data[0];
  17158. const int* right = data[1];
  17159. if (right == 0)
  17160. right = left;
  17161. if (bitsPerSample == 16)
  17162. {
  17163. short* b = (short*) buffer;
  17164. if (numChannels > 1)
  17165. {
  17166. for (int i = numSamples; --i >= 0;)
  17167. {
  17168. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17169. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  17170. }
  17171. }
  17172. else
  17173. {
  17174. for (int i = numSamples; --i >= 0;)
  17175. {
  17176. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  17177. }
  17178. }
  17179. }
  17180. else if (bitsPerSample == 24)
  17181. {
  17182. char* b = (char*) buffer;
  17183. if (numChannels > 1)
  17184. {
  17185. for (int i = numSamples; --i >= 0;)
  17186. {
  17187. littleEndian24BitToChars ((*left++) >> 8, b);
  17188. b += 3;
  17189. littleEndian24BitToChars ((*right++) >> 8, b);
  17190. b += 3;
  17191. }
  17192. }
  17193. else
  17194. {
  17195. for (int i = numSamples; --i >= 0;)
  17196. {
  17197. littleEndian24BitToChars ((*left++) >> 8, b);
  17198. b += 3;
  17199. }
  17200. }
  17201. }
  17202. else if (bitsPerSample == 32)
  17203. {
  17204. unsigned int* b = (unsigned int*) buffer;
  17205. if (numChannels > 1)
  17206. {
  17207. for (int i = numSamples; --i >= 0;)
  17208. {
  17209. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17210. *b++ = swapIfBigEndian ((unsigned int) *right++);
  17211. }
  17212. }
  17213. else
  17214. {
  17215. for (int i = numSamples; --i >= 0;)
  17216. {
  17217. *b++ = swapIfBigEndian ((unsigned int) *left++);
  17218. }
  17219. }
  17220. }
  17221. else if (bitsPerSample == 8)
  17222. {
  17223. unsigned char* b = (unsigned char*) buffer;
  17224. if (numChannels > 1)
  17225. {
  17226. for (int i = numSamples; --i >= 0;)
  17227. {
  17228. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17229. *b++ = (unsigned char) (128 + (*right++ >> 24));
  17230. }
  17231. }
  17232. else
  17233. {
  17234. for (int i = numSamples; --i >= 0;)
  17235. {
  17236. *b++ = (unsigned char) (128 + (*left++ >> 24));
  17237. }
  17238. }
  17239. }
  17240. if (bytesWritten + bytes >= (uint32) 0xfff00000
  17241. || ! output->write (buffer, bytes))
  17242. {
  17243. // failed to write to disk, so let's try writing the header.
  17244. // If it's just run out of disk space, then if it does manage
  17245. // to write the header, we'll still have a useable file..
  17246. writeHeader();
  17247. writeFailed = true;
  17248. return false;
  17249. }
  17250. else
  17251. {
  17252. bytesWritten += bytes;
  17253. lengthInSamples += numSamples;
  17254. return true;
  17255. }
  17256. }
  17257. juce_UseDebuggingNewOperator
  17258. };
  17259. WavAudioFormat::WavAudioFormat()
  17260. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  17261. {
  17262. }
  17263. WavAudioFormat::~WavAudioFormat()
  17264. {
  17265. }
  17266. const Array <int> WavAudioFormat::getPossibleSampleRates()
  17267. {
  17268. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  17269. return Array <int> (rates);
  17270. }
  17271. const Array <int> WavAudioFormat::getPossibleBitDepths()
  17272. {
  17273. const int depths[] = { 8, 16, 24, 32, 0 };
  17274. return Array <int> (depths);
  17275. }
  17276. bool WavAudioFormat::canDoStereo()
  17277. {
  17278. return true;
  17279. }
  17280. bool WavAudioFormat::canDoMono()
  17281. {
  17282. return true;
  17283. }
  17284. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  17285. const bool deleteStreamIfOpeningFails)
  17286. {
  17287. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  17288. if (r->sampleRate == 0)
  17289. {
  17290. if (! deleteStreamIfOpeningFails)
  17291. r->input = 0;
  17292. deleteAndZero (r);
  17293. }
  17294. return r;
  17295. }
  17296. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  17297. double sampleRate,
  17298. unsigned int numChannels,
  17299. int bitsPerSample,
  17300. const StringPairArray& metadataValues,
  17301. int /*qualityOptionIndex*/)
  17302. {
  17303. if (getPossibleBitDepths().contains (bitsPerSample))
  17304. {
  17305. return new WavAudioFormatWriter (out,
  17306. sampleRate,
  17307. numChannels,
  17308. bitsPerSample,
  17309. metadataValues);
  17310. }
  17311. return 0;
  17312. }
  17313. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  17314. {
  17315. bool ok = false;
  17316. WavAudioFormat wav;
  17317. const File dest (file.getNonexistentSibling());
  17318. OutputStream* outStream = dest.createOutputStream();
  17319. if (outStream != 0)
  17320. {
  17321. AudioFormatReader* reader = wav.createReaderFor (file.createInputStream(), true);
  17322. if (reader != 0)
  17323. {
  17324. AudioFormatWriter* writer = wav.createWriterFor (outStream, reader->sampleRate,
  17325. reader->numChannels, reader->bitsPerSample,
  17326. metadata, 0);
  17327. if (writer != 0)
  17328. {
  17329. ok = writer->writeFromAudioReader (*reader, 0, -1);
  17330. outStream = 0;
  17331. delete writer;
  17332. }
  17333. delete reader;
  17334. }
  17335. delete outStream;
  17336. }
  17337. if (ok)
  17338. ok = dest.moveFileTo (file);
  17339. if (! ok)
  17340. dest.deleteFile();
  17341. return ok;
  17342. }
  17343. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  17344. {
  17345. WavAudioFormatReader* reader = (WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true);
  17346. if (reader != 0)
  17347. {
  17348. const int64 bwavPos = reader->bwavChunkStart;
  17349. const int64 bwavSize = reader->bwavSize;
  17350. delete reader;
  17351. if (bwavSize > 0)
  17352. {
  17353. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  17354. if (chunk.getSize() <= bwavSize)
  17355. {
  17356. // the new one will fit in the space available, so write it directly..
  17357. const int64 oldSize = wavFile.getSize();
  17358. FileOutputStream* out = wavFile.createOutputStream();
  17359. out->setPosition (bwavPos);
  17360. out->write (chunk.getData(), chunk.getSize());
  17361. out->setPosition (oldSize);
  17362. delete out;
  17363. jassert (wavFile.getSize() == oldSize);
  17364. return true;
  17365. }
  17366. }
  17367. }
  17368. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  17369. }
  17370. END_JUCE_NAMESPACE
  17371. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  17372. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17373. BEGIN_JUCE_NAMESPACE
  17374. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  17375. const bool deleteReaderWhenThisIsDeleted)
  17376. : reader (reader_),
  17377. deleteReader (deleteReaderWhenThisIsDeleted),
  17378. nextPlayPos (0),
  17379. looping (false)
  17380. {
  17381. jassert (reader != 0);
  17382. }
  17383. AudioFormatReaderSource::~AudioFormatReaderSource()
  17384. {
  17385. releaseResources();
  17386. if (deleteReader)
  17387. delete reader;
  17388. }
  17389. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  17390. {
  17391. nextPlayPos = newPosition;
  17392. }
  17393. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  17394. {
  17395. looping = shouldLoop;
  17396. }
  17397. int AudioFormatReaderSource::getNextReadPosition() const
  17398. {
  17399. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  17400. : nextPlayPos;
  17401. }
  17402. int AudioFormatReaderSource::getTotalLength() const
  17403. {
  17404. return (int) reader->lengthInSamples;
  17405. }
  17406. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17407. double /*sampleRate*/)
  17408. {
  17409. }
  17410. void AudioFormatReaderSource::releaseResources()
  17411. {
  17412. }
  17413. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17414. {
  17415. if (info.numSamples > 0)
  17416. {
  17417. const int start = nextPlayPos;
  17418. if (looping)
  17419. {
  17420. const int newStart = start % (int) reader->lengthInSamples;
  17421. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  17422. if (newEnd > newStart)
  17423. {
  17424. info.buffer->readFromAudioReader (reader,
  17425. info.startSample,
  17426. newEnd - newStart,
  17427. newStart,
  17428. true, true);
  17429. }
  17430. else
  17431. {
  17432. const int endSamps = (int) reader->lengthInSamples - newStart;
  17433. info.buffer->readFromAudioReader (reader,
  17434. info.startSample,
  17435. endSamps,
  17436. newStart,
  17437. true, true);
  17438. info.buffer->readFromAudioReader (reader,
  17439. info.startSample + endSamps,
  17440. newEnd,
  17441. 0,
  17442. true, true);
  17443. }
  17444. nextPlayPos = newEnd;
  17445. }
  17446. else
  17447. {
  17448. info.buffer->readFromAudioReader (reader,
  17449. info.startSample,
  17450. info.numSamples,
  17451. start,
  17452. true, true);
  17453. nextPlayPos += info.numSamples;
  17454. }
  17455. }
  17456. }
  17457. END_JUCE_NAMESPACE
  17458. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  17459. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  17460. BEGIN_JUCE_NAMESPACE
  17461. AudioSourcePlayer::AudioSourcePlayer()
  17462. : source (0),
  17463. sampleRate (0),
  17464. bufferSize (0),
  17465. tempBuffer (2, 8),
  17466. lastGain (1.0f),
  17467. gain (1.0f)
  17468. {
  17469. }
  17470. AudioSourcePlayer::~AudioSourcePlayer()
  17471. {
  17472. setSource (0);
  17473. }
  17474. void AudioSourcePlayer::setSource (AudioSource* newSource)
  17475. {
  17476. if (source != newSource)
  17477. {
  17478. AudioSource* const oldSource = source;
  17479. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  17480. newSource->prepareToPlay (bufferSize, sampleRate);
  17481. {
  17482. const ScopedLock sl (readLock);
  17483. source = newSource;
  17484. }
  17485. if (oldSource != 0)
  17486. oldSource->releaseResources();
  17487. }
  17488. }
  17489. void AudioSourcePlayer::setGain (const float newGain) throw()
  17490. {
  17491. gain = newGain;
  17492. }
  17493. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  17494. int totalNumInputChannels,
  17495. float** outputChannelData,
  17496. int totalNumOutputChannels,
  17497. int numSamples)
  17498. {
  17499. // these should have been prepared by audioDeviceAboutToStart()...
  17500. jassert (sampleRate > 0 && bufferSize > 0);
  17501. const ScopedLock sl (readLock);
  17502. if (source != 0)
  17503. {
  17504. AudioSourceChannelInfo info;
  17505. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  17506. // messy stuff needed to compact the channels down into an array
  17507. // of non-zero pointers..
  17508. for (i = 0; i < totalNumInputChannels; ++i)
  17509. {
  17510. if (inputChannelData[i] != 0)
  17511. {
  17512. inputChans [numInputs++] = inputChannelData[i];
  17513. if (numInputs >= numElementsInArray (inputChans))
  17514. break;
  17515. }
  17516. }
  17517. for (i = 0; i < totalNumOutputChannels; ++i)
  17518. {
  17519. if (outputChannelData[i] != 0)
  17520. {
  17521. outputChans [numOutputs++] = outputChannelData[i];
  17522. if (numOutputs >= numElementsInArray (outputChans))
  17523. break;
  17524. }
  17525. }
  17526. if (numInputs > numOutputs)
  17527. {
  17528. // if there aren't enough output channels for the number of
  17529. // inputs, we need to create some temporary extra ones (can't
  17530. // use the input data in case it gets written to)
  17531. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  17532. false, false, true);
  17533. for (i = 0; i < numOutputs; ++i)
  17534. {
  17535. channels[numActiveChans] = outputChans[i];
  17536. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17537. ++numActiveChans;
  17538. }
  17539. for (i = numOutputs; i < numInputs; ++i)
  17540. {
  17541. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  17542. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17543. ++numActiveChans;
  17544. }
  17545. }
  17546. else
  17547. {
  17548. for (i = 0; i < numInputs; ++i)
  17549. {
  17550. channels[numActiveChans] = outputChans[i];
  17551. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  17552. ++numActiveChans;
  17553. }
  17554. for (i = numInputs; i < numOutputs; ++i)
  17555. {
  17556. channels[numActiveChans] = outputChans[i];
  17557. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  17558. ++numActiveChans;
  17559. }
  17560. }
  17561. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  17562. info.buffer = &buffer;
  17563. info.startSample = 0;
  17564. info.numSamples = numSamples;
  17565. source->getNextAudioBlock (info);
  17566. for (i = info.buffer->getNumChannels(); --i >= 0;)
  17567. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  17568. lastGain = gain;
  17569. }
  17570. else
  17571. {
  17572. for (int i = 0; i < totalNumOutputChannels; ++i)
  17573. if (outputChannelData[i] != 0)
  17574. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17575. }
  17576. }
  17577. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  17578. {
  17579. sampleRate = device->getCurrentSampleRate();
  17580. bufferSize = device->getCurrentBufferSizeSamples();
  17581. zeromem (channels, sizeof (channels));
  17582. if (source != 0)
  17583. source->prepareToPlay (bufferSize, sampleRate);
  17584. }
  17585. void AudioSourcePlayer::audioDeviceStopped()
  17586. {
  17587. if (source != 0)
  17588. source->releaseResources();
  17589. sampleRate = 0.0;
  17590. bufferSize = 0;
  17591. tempBuffer.setSize (2, 8);
  17592. }
  17593. END_JUCE_NAMESPACE
  17594. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  17595. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  17596. BEGIN_JUCE_NAMESPACE
  17597. AudioTransportSource::AudioTransportSource()
  17598. : source (0),
  17599. resamplerSource (0),
  17600. bufferingSource (0),
  17601. positionableSource (0),
  17602. masterSource (0),
  17603. gain (1.0f),
  17604. lastGain (1.0f),
  17605. playing (false),
  17606. stopped (true),
  17607. sampleRate (44100.0),
  17608. sourceSampleRate (0.0),
  17609. blockSize (128),
  17610. readAheadBufferSize (0),
  17611. isPrepared (false),
  17612. inputStreamEOF (false)
  17613. {
  17614. }
  17615. AudioTransportSource::~AudioTransportSource()
  17616. {
  17617. setSource (0);
  17618. releaseResources();
  17619. }
  17620. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  17621. int readAheadBufferSize_,
  17622. double sourceSampleRateToCorrectFor)
  17623. {
  17624. if (source == newSource)
  17625. {
  17626. if (source == 0)
  17627. return;
  17628. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  17629. }
  17630. readAheadBufferSize = readAheadBufferSize_;
  17631. sourceSampleRate = sourceSampleRateToCorrectFor;
  17632. ResamplingAudioSource* newResamplerSource = 0;
  17633. BufferingAudioSource* newBufferingSource = 0;
  17634. PositionableAudioSource* newPositionableSource = 0;
  17635. AudioSource* newMasterSource = 0;
  17636. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  17637. BufferingAudioSource* oldBufferingSource = bufferingSource;
  17638. AudioSource* oldMasterSource = masterSource;
  17639. if (newSource != 0)
  17640. {
  17641. newPositionableSource = newSource;
  17642. if (readAheadBufferSize_ > 0)
  17643. newPositionableSource = newBufferingSource
  17644. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  17645. newPositionableSource->setNextReadPosition (0);
  17646. if (sourceSampleRateToCorrectFor != 0)
  17647. newMasterSource = newResamplerSource
  17648. = new ResamplingAudioSource (newPositionableSource, false);
  17649. else
  17650. newMasterSource = newPositionableSource;
  17651. if (isPrepared)
  17652. {
  17653. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  17654. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17655. newMasterSource->prepareToPlay (blockSize, sampleRate);
  17656. }
  17657. }
  17658. {
  17659. const ScopedLock sl (callbackLock);
  17660. source = newSource;
  17661. resamplerSource = newResamplerSource;
  17662. bufferingSource = newBufferingSource;
  17663. masterSource = newMasterSource;
  17664. positionableSource = newPositionableSource;
  17665. playing = false;
  17666. }
  17667. if (oldMasterSource != 0)
  17668. oldMasterSource->releaseResources();
  17669. delete oldResamplerSource;
  17670. delete oldBufferingSource;
  17671. }
  17672. void AudioTransportSource::start()
  17673. {
  17674. if ((! playing) && masterSource != 0)
  17675. {
  17676. callbackLock.enter();
  17677. playing = true;
  17678. stopped = false;
  17679. inputStreamEOF = false;
  17680. callbackLock.exit();
  17681. sendChangeMessage (this);
  17682. }
  17683. }
  17684. void AudioTransportSource::stop()
  17685. {
  17686. if (playing)
  17687. {
  17688. callbackLock.enter();
  17689. playing = false;
  17690. callbackLock.exit();
  17691. int n = 500;
  17692. while (--n >= 0 && ! stopped)
  17693. Thread::sleep (2);
  17694. sendChangeMessage (this);
  17695. }
  17696. }
  17697. void AudioTransportSource::setPosition (double newPosition)
  17698. {
  17699. if (sampleRate > 0.0)
  17700. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  17701. }
  17702. double AudioTransportSource::getCurrentPosition() const
  17703. {
  17704. if (sampleRate > 0.0)
  17705. return getNextReadPosition() / sampleRate;
  17706. else
  17707. return 0.0;
  17708. }
  17709. void AudioTransportSource::setNextReadPosition (int newPosition)
  17710. {
  17711. if (positionableSource != 0)
  17712. {
  17713. if (sampleRate > 0 && sourceSampleRate > 0)
  17714. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  17715. positionableSource->setNextReadPosition (newPosition);
  17716. }
  17717. }
  17718. int AudioTransportSource::getNextReadPosition() const
  17719. {
  17720. if (positionableSource != 0)
  17721. {
  17722. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17723. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  17724. }
  17725. return 0;
  17726. }
  17727. int AudioTransportSource::getTotalLength() const
  17728. {
  17729. const ScopedLock sl (callbackLock);
  17730. if (positionableSource != 0)
  17731. {
  17732. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  17733. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  17734. }
  17735. return 0;
  17736. }
  17737. bool AudioTransportSource::isLooping() const
  17738. {
  17739. const ScopedLock sl (callbackLock);
  17740. return positionableSource != 0
  17741. && positionableSource->isLooping();
  17742. }
  17743. void AudioTransportSource::setGain (const float newGain) throw()
  17744. {
  17745. gain = newGain;
  17746. }
  17747. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  17748. double sampleRate_)
  17749. {
  17750. const ScopedLock sl (callbackLock);
  17751. sampleRate = sampleRate_;
  17752. blockSize = samplesPerBlockExpected;
  17753. if (masterSource != 0)
  17754. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17755. if (resamplerSource != 0 && sourceSampleRate != 0)
  17756. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  17757. isPrepared = true;
  17758. }
  17759. void AudioTransportSource::releaseResources()
  17760. {
  17761. const ScopedLock sl (callbackLock);
  17762. if (masterSource != 0)
  17763. masterSource->releaseResources();
  17764. isPrepared = false;
  17765. }
  17766. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17767. {
  17768. const ScopedLock sl (callbackLock);
  17769. inputStreamEOF = false;
  17770. if (masterSource != 0 && ! stopped)
  17771. {
  17772. masterSource->getNextAudioBlock (info);
  17773. if (! playing)
  17774. {
  17775. // just stopped playing, so fade out the last block..
  17776. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17777. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  17778. if (info.numSamples > 256)
  17779. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  17780. }
  17781. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  17782. && ! positionableSource->isLooping())
  17783. {
  17784. playing = false;
  17785. inputStreamEOF = true;
  17786. sendChangeMessage (this);
  17787. }
  17788. stopped = ! playing;
  17789. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  17790. {
  17791. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  17792. lastGain, gain);
  17793. }
  17794. }
  17795. else
  17796. {
  17797. info.clearActiveBufferRegion();
  17798. stopped = true;
  17799. }
  17800. lastGain = gain;
  17801. }
  17802. END_JUCE_NAMESPACE
  17803. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  17804. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  17805. BEGIN_JUCE_NAMESPACE
  17806. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  17807. public Thread,
  17808. private Timer
  17809. {
  17810. public:
  17811. SharedBufferingAudioSourceThread()
  17812. : Thread ("Audio Buffer"),
  17813. sources (8)
  17814. {
  17815. }
  17816. ~SharedBufferingAudioSourceThread()
  17817. {
  17818. stopThread (10000);
  17819. clearSingletonInstance();
  17820. }
  17821. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  17822. void addSource (BufferingAudioSource* source)
  17823. {
  17824. const ScopedLock sl (lock);
  17825. if (! sources.contains ((void*) source))
  17826. {
  17827. sources.add ((void*) source);
  17828. startThread();
  17829. stopTimer();
  17830. }
  17831. notify();
  17832. }
  17833. void removeSource (BufferingAudioSource* source)
  17834. {
  17835. const ScopedLock sl (lock);
  17836. sources.removeValue ((void*) source);
  17837. if (sources.size() == 0)
  17838. startTimer (5000);
  17839. }
  17840. private:
  17841. VoidArray sources;
  17842. CriticalSection lock;
  17843. void run()
  17844. {
  17845. while (! threadShouldExit())
  17846. {
  17847. bool busy = false;
  17848. for (int i = sources.size(); --i >= 0;)
  17849. {
  17850. if (threadShouldExit())
  17851. return;
  17852. const ScopedLock sl (lock);
  17853. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  17854. if (b != 0 && b->readNextBufferChunk())
  17855. busy = true;
  17856. }
  17857. if (! busy)
  17858. wait (500);
  17859. }
  17860. }
  17861. void timerCallback()
  17862. {
  17863. stopTimer();
  17864. if (sources.size() == 0)
  17865. deleteInstance();
  17866. }
  17867. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  17868. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  17869. };
  17870. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  17871. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  17872. const bool deleteSourceWhenDeleted_,
  17873. int numberOfSamplesToBuffer_)
  17874. : source (source_),
  17875. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  17876. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  17877. buffer (2, 0),
  17878. bufferValidStart (0),
  17879. bufferValidEnd (0),
  17880. nextPlayPos (0),
  17881. wasSourceLooping (false)
  17882. {
  17883. jassert (source_ != 0);
  17884. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  17885. // not using a larger buffer..
  17886. }
  17887. BufferingAudioSource::~BufferingAudioSource()
  17888. {
  17889. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17890. if (thread != 0)
  17891. thread->removeSource (this);
  17892. if (deleteSourceWhenDeleted)
  17893. delete source;
  17894. }
  17895. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  17896. {
  17897. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  17898. sampleRate = sampleRate_;
  17899. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  17900. buffer.clear();
  17901. bufferValidStart = 0;
  17902. bufferValidEnd = 0;
  17903. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  17904. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  17905. buffer.getNumSamples() / 2))
  17906. {
  17907. SharedBufferingAudioSourceThread::getInstance()->notify();
  17908. Thread::sleep (5);
  17909. }
  17910. }
  17911. void BufferingAudioSource::releaseResources()
  17912. {
  17913. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17914. if (thread != 0)
  17915. thread->removeSource (this);
  17916. buffer.setSize (2, 0);
  17917. source->releaseResources();
  17918. }
  17919. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17920. {
  17921. const ScopedLock sl (bufferStartPosLock);
  17922. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  17923. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  17924. if (validStart == validEnd)
  17925. {
  17926. // total cache miss
  17927. info.clearActiveBufferRegion();
  17928. }
  17929. else
  17930. {
  17931. if (validStart > 0)
  17932. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  17933. if (validEnd < info.numSamples)
  17934. info.buffer->clear (info.startSample + validEnd,
  17935. info.numSamples - validEnd); // partial cache miss at end
  17936. if (validStart < validEnd)
  17937. {
  17938. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  17939. {
  17940. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  17941. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  17942. if (startBufferIndex < endBufferIndex)
  17943. {
  17944. info.buffer->copyFrom (chan, info.startSample + validStart,
  17945. buffer,
  17946. chan, startBufferIndex,
  17947. validEnd - validStart);
  17948. }
  17949. else
  17950. {
  17951. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  17952. info.buffer->copyFrom (chan, info.startSample + validStart,
  17953. buffer,
  17954. chan, startBufferIndex,
  17955. initialSize);
  17956. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  17957. buffer,
  17958. chan, 0,
  17959. (validEnd - validStart) - initialSize);
  17960. }
  17961. }
  17962. }
  17963. nextPlayPos += info.numSamples;
  17964. if (source->isLooping() && nextPlayPos > 0)
  17965. nextPlayPos %= source->getTotalLength();
  17966. }
  17967. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17968. if (thread != 0)
  17969. thread->notify();
  17970. }
  17971. int BufferingAudioSource::getNextReadPosition() const
  17972. {
  17973. return (source->isLooping() && nextPlayPos > 0)
  17974. ? nextPlayPos % source->getTotalLength()
  17975. : nextPlayPos;
  17976. }
  17977. void BufferingAudioSource::setNextReadPosition (int newPosition)
  17978. {
  17979. const ScopedLock sl (bufferStartPosLock);
  17980. nextPlayPos = newPosition;
  17981. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  17982. if (thread != 0)
  17983. thread->notify();
  17984. }
  17985. bool BufferingAudioSource::readNextBufferChunk()
  17986. {
  17987. bufferStartPosLock.enter();
  17988. if (wasSourceLooping != isLooping())
  17989. {
  17990. wasSourceLooping = isLooping();
  17991. bufferValidStart = 0;
  17992. bufferValidEnd = 0;
  17993. }
  17994. int newBVS = jmax (0, nextPlayPos);
  17995. int newBVE = newBVS + buffer.getNumSamples() - 4;
  17996. int sectionToReadStart = 0;
  17997. int sectionToReadEnd = 0;
  17998. const int maxChunkSize = 2048;
  17999. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  18000. {
  18001. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  18002. sectionToReadStart = newBVS;
  18003. sectionToReadEnd = newBVE;
  18004. bufferValidStart = 0;
  18005. bufferValidEnd = 0;
  18006. }
  18007. else if (abs (newBVS - bufferValidStart) > 512
  18008. || abs (newBVE - bufferValidEnd) > 512)
  18009. {
  18010. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  18011. sectionToReadStart = bufferValidEnd;
  18012. sectionToReadEnd = newBVE;
  18013. bufferValidStart = newBVS;
  18014. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  18015. }
  18016. bufferStartPosLock.exit();
  18017. if (sectionToReadStart != sectionToReadEnd)
  18018. {
  18019. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  18020. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  18021. if (bufferIndexStart < bufferIndexEnd)
  18022. {
  18023. readBufferSection (sectionToReadStart,
  18024. sectionToReadEnd - sectionToReadStart,
  18025. bufferIndexStart);
  18026. }
  18027. else
  18028. {
  18029. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  18030. readBufferSection (sectionToReadStart,
  18031. initialSize,
  18032. bufferIndexStart);
  18033. readBufferSection (sectionToReadStart + initialSize,
  18034. (sectionToReadEnd - sectionToReadStart) - initialSize,
  18035. 0);
  18036. }
  18037. const ScopedLock sl2 (bufferStartPosLock);
  18038. bufferValidStart = newBVS;
  18039. bufferValidEnd = newBVE;
  18040. return true;
  18041. }
  18042. else
  18043. {
  18044. return false;
  18045. }
  18046. }
  18047. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  18048. {
  18049. if (source->getNextReadPosition() != start)
  18050. source->setNextReadPosition (start);
  18051. AudioSourceChannelInfo info;
  18052. info.buffer = &buffer;
  18053. info.startSample = bufferOffset;
  18054. info.numSamples = length;
  18055. source->getNextAudioBlock (info);
  18056. }
  18057. END_JUCE_NAMESPACE
  18058. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  18059. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18060. BEGIN_JUCE_NAMESPACE
  18061. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  18062. const bool deleteSourceWhenDeleted_)
  18063. : requiredNumberOfChannels (2),
  18064. source (source_),
  18065. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  18066. buffer (2, 16)
  18067. {
  18068. remappedInfo.buffer = &buffer;
  18069. remappedInfo.startSample = 0;
  18070. }
  18071. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  18072. {
  18073. if (deleteSourceWhenDeleted)
  18074. delete source;
  18075. }
  18076. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  18077. {
  18078. const ScopedLock sl (lock);
  18079. requiredNumberOfChannels = requiredNumberOfChannels_;
  18080. }
  18081. void ChannelRemappingAudioSource::clearAllMappings() throw()
  18082. {
  18083. const ScopedLock sl (lock);
  18084. remappedInputs.clear();
  18085. remappedOutputs.clear();
  18086. }
  18087. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  18088. {
  18089. const ScopedLock sl (lock);
  18090. while (remappedInputs.size() < destIndex)
  18091. remappedInputs.add (-1);
  18092. remappedInputs.set (destIndex, sourceIndex);
  18093. }
  18094. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  18095. {
  18096. const ScopedLock sl (lock);
  18097. while (remappedOutputs.size() < sourceIndex)
  18098. remappedOutputs.add (-1);
  18099. remappedOutputs.set (sourceIndex, destIndex);
  18100. }
  18101. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  18102. {
  18103. const ScopedLock sl (lock);
  18104. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  18105. return remappedInputs.getUnchecked (inputChannelIndex);
  18106. return -1;
  18107. }
  18108. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  18109. {
  18110. const ScopedLock sl (lock);
  18111. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  18112. return remappedOutputs .getUnchecked (outputChannelIndex);
  18113. return -1;
  18114. }
  18115. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18116. {
  18117. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18118. }
  18119. void ChannelRemappingAudioSource::releaseResources()
  18120. {
  18121. source->releaseResources();
  18122. }
  18123. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18124. {
  18125. const ScopedLock sl (lock);
  18126. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  18127. const int numChans = bufferToFill.buffer->getNumChannels();
  18128. int i;
  18129. for (i = 0; i < buffer.getNumChannels(); ++i)
  18130. {
  18131. const int remappedChan = getRemappedInputChannel (i);
  18132. if (remappedChan >= 0 && remappedChan < numChans)
  18133. {
  18134. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  18135. remappedChan,
  18136. bufferToFill.startSample,
  18137. bufferToFill.numSamples);
  18138. }
  18139. else
  18140. {
  18141. buffer.clear (i, 0, bufferToFill.numSamples);
  18142. }
  18143. }
  18144. remappedInfo.numSamples = bufferToFill.numSamples;
  18145. source->getNextAudioBlock (remappedInfo);
  18146. bufferToFill.clearActiveBufferRegion();
  18147. for (i = 0; i < requiredNumberOfChannels; ++i)
  18148. {
  18149. const int remappedChan = getRemappedOutputChannel (i);
  18150. if (remappedChan >= 0 && remappedChan < numChans)
  18151. {
  18152. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  18153. buffer, i, 0, bufferToFill.numSamples);
  18154. }
  18155. }
  18156. }
  18157. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  18158. {
  18159. XmlElement* e = new XmlElement (T("MAPPINGS"));
  18160. String ins, outs;
  18161. int i;
  18162. const ScopedLock sl (lock);
  18163. for (i = 0; i < remappedInputs.size(); ++i)
  18164. ins << remappedInputs.getUnchecked(i) << T(' ');
  18165. for (i = 0; i < remappedOutputs.size(); ++i)
  18166. outs << remappedOutputs.getUnchecked(i) << T(' ');
  18167. e->setAttribute (T("inputs"), ins.trimEnd());
  18168. e->setAttribute (T("outputs"), outs.trimEnd());
  18169. return e;
  18170. }
  18171. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  18172. {
  18173. if (e.hasTagName (T("MAPPINGS")))
  18174. {
  18175. const ScopedLock sl (lock);
  18176. clearAllMappings();
  18177. StringArray ins, outs;
  18178. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  18179. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  18180. int i;
  18181. for (i = 0; i < ins.size(); ++i)
  18182. remappedInputs.add (ins[i].getIntValue());
  18183. for (i = 0; i < outs.size(); ++i)
  18184. remappedOutputs.add (outs[i].getIntValue());
  18185. }
  18186. }
  18187. END_JUCE_NAMESPACE
  18188. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  18189. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18190. BEGIN_JUCE_NAMESPACE
  18191. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  18192. const bool deleteInputWhenDeleted_)
  18193. : input (inputSource),
  18194. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  18195. {
  18196. jassert (inputSource != 0);
  18197. for (int i = 2; --i >= 0;)
  18198. iirFilters.add (new IIRFilter());
  18199. }
  18200. IIRFilterAudioSource::~IIRFilterAudioSource()
  18201. {
  18202. if (deleteInputWhenDeleted)
  18203. delete input;
  18204. }
  18205. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  18206. {
  18207. for (int i = iirFilters.size(); --i >= 0;)
  18208. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  18209. }
  18210. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18211. {
  18212. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18213. for (int i = iirFilters.size(); --i >= 0;)
  18214. iirFilters.getUnchecked(i)->reset();
  18215. }
  18216. void IIRFilterAudioSource::releaseResources()
  18217. {
  18218. input->releaseResources();
  18219. }
  18220. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  18221. {
  18222. input->getNextAudioBlock (bufferToFill);
  18223. const int numChannels = bufferToFill.buffer->getNumChannels();
  18224. while (numChannels > iirFilters.size())
  18225. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  18226. for (int i = 0; i < numChannels; ++i)
  18227. iirFilters.getUnchecked(i)
  18228. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  18229. bufferToFill.numSamples);
  18230. }
  18231. END_JUCE_NAMESPACE
  18232. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  18233. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  18234. BEGIN_JUCE_NAMESPACE
  18235. MixerAudioSource::MixerAudioSource()
  18236. : tempBuffer (2, 0),
  18237. currentSampleRate (0.0),
  18238. bufferSizeExpected (0)
  18239. {
  18240. }
  18241. MixerAudioSource::~MixerAudioSource()
  18242. {
  18243. removeAllInputs();
  18244. }
  18245. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  18246. {
  18247. if (input != 0 && ! inputs.contains (input))
  18248. {
  18249. lock.enter();
  18250. double localRate = currentSampleRate;
  18251. int localBufferSize = bufferSizeExpected;
  18252. lock.exit();
  18253. if (localRate != 0.0)
  18254. input->prepareToPlay (localBufferSize, localRate);
  18255. const ScopedLock sl (lock);
  18256. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  18257. inputs.add (input);
  18258. }
  18259. }
  18260. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  18261. {
  18262. if (input != 0)
  18263. {
  18264. lock.enter();
  18265. const int index = inputs.indexOf ((void*) input);
  18266. if (index >= 0)
  18267. {
  18268. inputsToDelete.shiftBits (index, 1);
  18269. inputs.remove (index);
  18270. }
  18271. lock.exit();
  18272. if (index >= 0)
  18273. {
  18274. input->releaseResources();
  18275. if (deleteInput)
  18276. delete input;
  18277. }
  18278. }
  18279. }
  18280. void MixerAudioSource::removeAllInputs()
  18281. {
  18282. lock.enter();
  18283. VoidArray inputsCopy (inputs);
  18284. BitArray inputsToDeleteCopy (inputsToDelete);
  18285. inputs.clear();
  18286. lock.exit();
  18287. for (int i = inputsCopy.size(); --i >= 0;)
  18288. if (inputsToDeleteCopy[i])
  18289. delete (AudioSource*) inputsCopy[i];
  18290. }
  18291. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  18292. {
  18293. tempBuffer.setSize (2, samplesPerBlockExpected);
  18294. const ScopedLock sl (lock);
  18295. currentSampleRate = sampleRate;
  18296. bufferSizeExpected = samplesPerBlockExpected;
  18297. for (int i = inputs.size(); --i >= 0;)
  18298. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  18299. sampleRate);
  18300. }
  18301. void MixerAudioSource::releaseResources()
  18302. {
  18303. const ScopedLock sl (lock);
  18304. for (int i = inputs.size(); --i >= 0;)
  18305. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  18306. tempBuffer.setSize (2, 0);
  18307. currentSampleRate = 0;
  18308. bufferSizeExpected = 0;
  18309. }
  18310. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18311. {
  18312. const ScopedLock sl (lock);
  18313. if (inputs.size() > 0)
  18314. {
  18315. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  18316. if (inputs.size() > 1)
  18317. {
  18318. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  18319. info.buffer->getNumSamples());
  18320. AudioSourceChannelInfo info2;
  18321. info2.buffer = &tempBuffer;
  18322. info2.numSamples = info.numSamples;
  18323. info2.startSample = 0;
  18324. for (int i = 1; i < inputs.size(); ++i)
  18325. {
  18326. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  18327. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  18328. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  18329. }
  18330. }
  18331. }
  18332. else
  18333. {
  18334. info.clearActiveBufferRegion();
  18335. }
  18336. }
  18337. END_JUCE_NAMESPACE
  18338. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  18339. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  18340. BEGIN_JUCE_NAMESPACE
  18341. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  18342. const bool deleteInputWhenDeleted_)
  18343. : input (inputSource),
  18344. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  18345. ratio (1.0),
  18346. lastRatio (1.0),
  18347. buffer (2, 0),
  18348. sampsInBuffer (0)
  18349. {
  18350. jassert (input != 0);
  18351. }
  18352. ResamplingAudioSource::~ResamplingAudioSource()
  18353. {
  18354. if (deleteInputWhenDeleted)
  18355. delete input;
  18356. }
  18357. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  18358. {
  18359. jassert (samplesInPerOutputSample > 0);
  18360. const ScopedLock sl (ratioLock);
  18361. ratio = jmax (0.0, samplesInPerOutputSample);
  18362. }
  18363. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  18364. double sampleRate)
  18365. {
  18366. const ScopedLock sl (ratioLock);
  18367. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  18368. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  18369. buffer.clear();
  18370. sampsInBuffer = 0;
  18371. bufferPos = 0;
  18372. subSampleOffset = 0.0;
  18373. createLowPass (ratio);
  18374. resetFilters();
  18375. }
  18376. void ResamplingAudioSource::releaseResources()
  18377. {
  18378. input->releaseResources();
  18379. buffer.setSize (2, 0);
  18380. }
  18381. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18382. {
  18383. const ScopedLock sl (ratioLock);
  18384. if (lastRatio != ratio)
  18385. {
  18386. createLowPass (ratio);
  18387. lastRatio = ratio;
  18388. }
  18389. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  18390. int bufferSize = buffer.getNumSamples();
  18391. if (bufferSize < sampsNeeded + 8)
  18392. {
  18393. bufferPos %= bufferSize;
  18394. bufferSize = sampsNeeded + 32;
  18395. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  18396. }
  18397. bufferPos %= bufferSize;
  18398. int endOfBufferPos = bufferPos + sampsInBuffer;
  18399. while (sampsNeeded > sampsInBuffer)
  18400. {
  18401. endOfBufferPos %= bufferSize;
  18402. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  18403. bufferSize - endOfBufferPos);
  18404. AudioSourceChannelInfo readInfo;
  18405. readInfo.buffer = &buffer;
  18406. readInfo.numSamples = numToDo;
  18407. readInfo.startSample = endOfBufferPos;
  18408. input->getNextAudioBlock (readInfo);
  18409. if (ratio > 1.0001)
  18410. {
  18411. // for down-sampling, pre-apply the filter..
  18412. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18413. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  18414. }
  18415. sampsInBuffer += numToDo;
  18416. endOfBufferPos += numToDo;
  18417. }
  18418. float* dl = info.buffer->getSampleData (0, info.startSample);
  18419. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  18420. const float* const bl = buffer.getSampleData (0, 0);
  18421. const float* const br = buffer.getSampleData (1, 0);
  18422. int nextPos = (bufferPos + 1) % bufferSize;
  18423. for (int m = info.numSamples; --m >= 0;)
  18424. {
  18425. const float alpha = (float) subSampleOffset;
  18426. const float invAlpha = 1.0f - alpha;
  18427. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  18428. if (dr != 0)
  18429. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  18430. subSampleOffset += ratio;
  18431. jassert (sampsInBuffer > 0);
  18432. while (subSampleOffset >= 1.0)
  18433. {
  18434. if (++bufferPos >= bufferSize)
  18435. bufferPos = 0;
  18436. --sampsInBuffer;
  18437. nextPos = (bufferPos + 1) % bufferSize;
  18438. subSampleOffset -= 1.0;
  18439. }
  18440. }
  18441. if (ratio < 0.9999)
  18442. {
  18443. // for up-sampling, apply the filter after transposing..
  18444. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18445. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  18446. }
  18447. else if (ratio <= 1.0001)
  18448. {
  18449. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  18450. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  18451. {
  18452. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  18453. FilterState& fs = filterStates[i];
  18454. if (info.numSamples > 1)
  18455. {
  18456. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  18457. }
  18458. else
  18459. {
  18460. fs.y2 = fs.y1;
  18461. fs.x2 = fs.x1;
  18462. }
  18463. fs.y1 = fs.x1 = *endOfBuffer;
  18464. }
  18465. }
  18466. jassert (sampsInBuffer >= 0);
  18467. }
  18468. void ResamplingAudioSource::createLowPass (const double ratio)
  18469. {
  18470. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  18471. : 0.5 * ratio;
  18472. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  18473. const double nSquared = n * n;
  18474. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18475. setFilterCoefficients (c1,
  18476. c1 * 2.0f,
  18477. c1,
  18478. 1.0,
  18479. c1 * 2.0 * (1.0 - nSquared),
  18480. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18481. }
  18482. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  18483. {
  18484. const double a = 1.0 / c4;
  18485. c1 *= a;
  18486. c2 *= a;
  18487. c3 *= a;
  18488. c5 *= a;
  18489. c6 *= a;
  18490. coefficients[0] = c1;
  18491. coefficients[1] = c2;
  18492. coefficients[2] = c3;
  18493. coefficients[3] = c4;
  18494. coefficients[4] = c5;
  18495. coefficients[5] = c6;
  18496. }
  18497. void ResamplingAudioSource::resetFilters()
  18498. {
  18499. zeromem (filterStates, sizeof (filterStates));
  18500. }
  18501. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  18502. {
  18503. while (--num >= 0)
  18504. {
  18505. const double in = *samples;
  18506. double out = coefficients[0] * in
  18507. + coefficients[1] * fs.x1
  18508. + coefficients[2] * fs.x2
  18509. - coefficients[4] * fs.y1
  18510. - coefficients[5] * fs.y2;
  18511. #if JUCE_INTEL
  18512. if (! (out < -1.0e-8 || out > 1.0e-8))
  18513. out = 0;
  18514. #endif
  18515. fs.x2 = fs.x1;
  18516. fs.x1 = in;
  18517. fs.y2 = fs.y1;
  18518. fs.y1 = out;
  18519. *samples++ = (float) out;
  18520. }
  18521. }
  18522. END_JUCE_NAMESPACE
  18523. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  18524. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18525. BEGIN_JUCE_NAMESPACE
  18526. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  18527. : frequency (1000.0),
  18528. sampleRate (44100.0),
  18529. currentPhase (0.0),
  18530. phasePerSample (0.0),
  18531. amplitude (0.5f)
  18532. {
  18533. }
  18534. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  18535. {
  18536. }
  18537. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  18538. {
  18539. amplitude = newAmplitude;
  18540. }
  18541. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  18542. {
  18543. frequency = newFrequencyHz;
  18544. phasePerSample = 0.0;
  18545. }
  18546. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18547. double sampleRate_)
  18548. {
  18549. currentPhase = 0.0;
  18550. phasePerSample = 0.0;
  18551. sampleRate = sampleRate_;
  18552. }
  18553. void ToneGeneratorAudioSource::releaseResources()
  18554. {
  18555. }
  18556. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18557. {
  18558. if (phasePerSample == 0.0)
  18559. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18560. for (int i = 0; i < info.numSamples; ++i)
  18561. {
  18562. const float sample = amplitude * (float) sin (currentPhase);
  18563. currentPhase += phasePerSample;
  18564. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  18565. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  18566. }
  18567. }
  18568. END_JUCE_NAMESPACE
  18569. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  18570. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  18571. BEGIN_JUCE_NAMESPACE
  18572. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18573. : sampleRate (0),
  18574. bufferSize (0),
  18575. useDefaultInputChannels (true),
  18576. useDefaultOutputChannels (true)
  18577. {
  18578. }
  18579. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  18580. {
  18581. return outputDeviceName == other.outputDeviceName
  18582. && inputDeviceName == other.inputDeviceName
  18583. && sampleRate == other.sampleRate
  18584. && bufferSize == other.bufferSize
  18585. && inputChannels == other.inputChannels
  18586. && useDefaultInputChannels == other.useDefaultInputChannels
  18587. && outputChannels == other.outputChannels
  18588. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  18589. }
  18590. AudioDeviceManager::AudioDeviceManager()
  18591. : currentAudioDevice (0),
  18592. numInputChansNeeded (0),
  18593. numOutputChansNeeded (2),
  18594. lastExplicitSettings (0),
  18595. listNeedsScanning (true),
  18596. useInputNames (false),
  18597. inputLevelMeasurementEnabledCount (0),
  18598. inputLevel (0),
  18599. testSound (0),
  18600. tempBuffer (2, 2),
  18601. enabledMidiInputs (4),
  18602. midiCallbacks (4),
  18603. midiCallbackDevices (4),
  18604. defaultMidiOutput (0),
  18605. cpuUsageMs (0),
  18606. timeToCpuScale (0)
  18607. {
  18608. callbackHandler.owner = this;
  18609. }
  18610. AudioDeviceManager::~AudioDeviceManager()
  18611. {
  18612. deleteAndZero (currentAudioDevice);
  18613. deleteAndZero (defaultMidiOutput);
  18614. delete lastExplicitSettings;
  18615. delete testSound;
  18616. }
  18617. void AudioDeviceManager::createDeviceTypesIfNeeded()
  18618. {
  18619. if (availableDeviceTypes.size() == 0)
  18620. {
  18621. createAudioDeviceTypes (availableDeviceTypes);
  18622. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  18623. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  18624. if (availableDeviceTypes.size() > 0)
  18625. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  18626. }
  18627. }
  18628. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  18629. {
  18630. scanDevicesIfNeeded();
  18631. return availableDeviceTypes;
  18632. }
  18633. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  18634. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  18635. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  18636. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  18637. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  18638. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  18639. {
  18640. #if JUCE_WIN32
  18641. #if JUCE_WASAPI
  18642. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  18643. list.add (juce_createAudioIODeviceType_WASAPI());
  18644. #endif
  18645. #if JUCE_DIRECTSOUND
  18646. list.add (juce_createAudioIODeviceType_DirectSound());
  18647. #endif
  18648. #if JUCE_ASIO
  18649. list.add (juce_createAudioIODeviceType_ASIO());
  18650. #endif
  18651. #endif
  18652. #if JUCE_MAC
  18653. list.add (juce_createAudioIODeviceType_CoreAudio());
  18654. #endif
  18655. #if JUCE_LINUX && JUCE_ALSA
  18656. list.add (juce_createAudioIODeviceType_ALSA());
  18657. #endif
  18658. }
  18659. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  18660. const int numOutputChannelsNeeded,
  18661. const XmlElement* const e,
  18662. const bool selectDefaultDeviceOnFailure,
  18663. const String& preferredDefaultDeviceName,
  18664. const AudioDeviceSetup* preferredSetupOptions)
  18665. {
  18666. scanDevicesIfNeeded();
  18667. numInputChansNeeded = numInputChannelsNeeded;
  18668. numOutputChansNeeded = numOutputChannelsNeeded;
  18669. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  18670. {
  18671. delete lastExplicitSettings;
  18672. lastExplicitSettings = new XmlElement (*e);
  18673. String error;
  18674. AudioDeviceSetup setup;
  18675. if (preferredSetupOptions != 0)
  18676. setup = *preferredSetupOptions;
  18677. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  18678. {
  18679. setup.inputDeviceName = setup.outputDeviceName
  18680. = e->getStringAttribute (T("audioDeviceName"));
  18681. }
  18682. else
  18683. {
  18684. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  18685. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  18686. }
  18687. currentDeviceType = e->getStringAttribute (T("deviceType"));
  18688. if (currentDeviceType.isEmpty())
  18689. {
  18690. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  18691. if (type != 0)
  18692. currentDeviceType = type->getTypeName();
  18693. else if (availableDeviceTypes.size() > 0)
  18694. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  18695. }
  18696. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  18697. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  18698. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  18699. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  18700. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  18701. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  18702. error = setAudioDeviceSetup (setup, true);
  18703. midiInsFromXml.clear();
  18704. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  18705. midiInsFromXml.add (c->getStringAttribute (T("name")));
  18706. const StringArray allMidiIns (MidiInput::getDevices());
  18707. for (int i = allMidiIns.size(); --i >= 0;)
  18708. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  18709. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  18710. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  18711. false, preferredDefaultDeviceName);
  18712. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  18713. return error;
  18714. }
  18715. else
  18716. {
  18717. AudioDeviceSetup setup;
  18718. if (preferredSetupOptions != 0)
  18719. {
  18720. setup = *preferredSetupOptions;
  18721. }
  18722. else if (preferredDefaultDeviceName.isNotEmpty())
  18723. {
  18724. for (int j = availableDeviceTypes.size(); --j >= 0;)
  18725. {
  18726. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  18727. StringArray outs (type->getDeviceNames (false));
  18728. int i;
  18729. for (i = 0; i < outs.size(); ++i)
  18730. {
  18731. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  18732. {
  18733. setup.outputDeviceName = outs[i];
  18734. break;
  18735. }
  18736. }
  18737. StringArray ins (type->getDeviceNames (true));
  18738. for (i = 0; i < ins.size(); ++i)
  18739. {
  18740. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  18741. {
  18742. setup.inputDeviceName = ins[i];
  18743. break;
  18744. }
  18745. }
  18746. }
  18747. }
  18748. insertDefaultDeviceNames (setup);
  18749. return setAudioDeviceSetup (setup, false);
  18750. }
  18751. }
  18752. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  18753. {
  18754. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18755. if (type != 0)
  18756. {
  18757. if (setup.outputDeviceName.isEmpty())
  18758. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  18759. if (setup.inputDeviceName.isEmpty())
  18760. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  18761. }
  18762. }
  18763. XmlElement* AudioDeviceManager::createStateXml() const
  18764. {
  18765. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  18766. }
  18767. void AudioDeviceManager::scanDevicesIfNeeded()
  18768. {
  18769. if (listNeedsScanning)
  18770. {
  18771. listNeedsScanning = false;
  18772. createDeviceTypesIfNeeded();
  18773. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18774. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  18775. }
  18776. }
  18777. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  18778. {
  18779. scanDevicesIfNeeded();
  18780. for (int i = availableDeviceTypes.size(); --i >= 0;)
  18781. {
  18782. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  18783. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  18784. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  18785. {
  18786. return type;
  18787. }
  18788. }
  18789. return 0;
  18790. }
  18791. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  18792. {
  18793. setup = currentSetup;
  18794. }
  18795. void AudioDeviceManager::deleteCurrentDevice()
  18796. {
  18797. deleteAndZero (currentAudioDevice);
  18798. currentSetup.inputDeviceName = String::empty;
  18799. currentSetup.outputDeviceName = String::empty;
  18800. }
  18801. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  18802. const bool treatAsChosenDevice)
  18803. {
  18804. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18805. {
  18806. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  18807. && currentDeviceType != type)
  18808. {
  18809. currentDeviceType = type;
  18810. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  18811. insertDefaultDeviceNames (s);
  18812. setAudioDeviceSetup (s, treatAsChosenDevice);
  18813. sendChangeMessage (this);
  18814. break;
  18815. }
  18816. }
  18817. }
  18818. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  18819. {
  18820. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18821. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  18822. return availableDeviceTypes[i];
  18823. return availableDeviceTypes[0];
  18824. }
  18825. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  18826. const bool treatAsChosenDevice)
  18827. {
  18828. jassert (&newSetup != &currentSetup); // this will have no effect
  18829. if (newSetup == currentSetup && currentAudioDevice != 0)
  18830. return String::empty;
  18831. if (! (newSetup == currentSetup))
  18832. sendChangeMessage (this);
  18833. stopDevice();
  18834. String error;
  18835. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  18836. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  18837. && newSetup.outputDeviceName.isEmpty()))
  18838. {
  18839. deleteCurrentDevice();
  18840. if (treatAsChosenDevice)
  18841. updateXml();
  18842. return String::empty;
  18843. }
  18844. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  18845. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  18846. if (currentSetup.inputDeviceName != newInputDeviceName
  18847. || currentSetup.outputDeviceName != newOutputDeviceName
  18848. || currentAudioDevice == 0)
  18849. {
  18850. deleteCurrentDevice();
  18851. scanDevicesIfNeeded();
  18852. if (newOutputDeviceName.isNotEmpty()
  18853. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  18854. {
  18855. return "No such device: " + newOutputDeviceName;
  18856. }
  18857. if (newInputDeviceName.isNotEmpty()
  18858. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  18859. {
  18860. return "No such device: " + newInputDeviceName;
  18861. }
  18862. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  18863. if (currentAudioDevice == 0)
  18864. 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!";
  18865. else
  18866. error = currentAudioDevice->getLastError();
  18867. if (error.isNotEmpty())
  18868. {
  18869. deleteCurrentDevice();
  18870. return error;
  18871. }
  18872. if (newSetup.useDefaultInputChannels)
  18873. {
  18874. inputChannels.clear();
  18875. inputChannels.setRange (0, numInputChansNeeded, true);
  18876. }
  18877. if (newSetup.useDefaultOutputChannels)
  18878. {
  18879. outputChannels.clear();
  18880. outputChannels.setRange (0, numOutputChansNeeded, true);
  18881. }
  18882. if (newInputDeviceName.isEmpty())
  18883. inputChannels.clear();
  18884. if (newOutputDeviceName.isEmpty())
  18885. outputChannels.clear();
  18886. }
  18887. if (! newSetup.useDefaultInputChannels)
  18888. inputChannels = newSetup.inputChannels;
  18889. if (! newSetup.useDefaultOutputChannels)
  18890. outputChannels = newSetup.outputChannels;
  18891. currentSetup = newSetup;
  18892. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  18893. error = currentAudioDevice->open (inputChannels,
  18894. outputChannels,
  18895. currentSetup.sampleRate,
  18896. currentSetup.bufferSize);
  18897. if (error.isEmpty())
  18898. {
  18899. currentDeviceType = currentAudioDevice->getTypeName();
  18900. currentAudioDevice->start (&callbackHandler);
  18901. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  18902. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  18903. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  18904. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  18905. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  18906. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  18907. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  18908. if (treatAsChosenDevice)
  18909. updateXml();
  18910. }
  18911. else
  18912. {
  18913. deleteCurrentDevice();
  18914. }
  18915. return error;
  18916. }
  18917. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  18918. {
  18919. jassert (currentAudioDevice != 0);
  18920. if (rate > 0)
  18921. {
  18922. bool ok = false;
  18923. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18924. {
  18925. const double sr = currentAudioDevice->getSampleRate (i);
  18926. if (sr == rate)
  18927. ok = true;
  18928. }
  18929. if (! ok)
  18930. rate = 0;
  18931. }
  18932. if (rate == 0)
  18933. {
  18934. double lowestAbove44 = 0.0;
  18935. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  18936. {
  18937. const double sr = currentAudioDevice->getSampleRate (i);
  18938. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  18939. lowestAbove44 = sr;
  18940. }
  18941. if (lowestAbove44 == 0.0)
  18942. rate = currentAudioDevice->getSampleRate (0);
  18943. else
  18944. rate = lowestAbove44;
  18945. }
  18946. return rate;
  18947. }
  18948. void AudioDeviceManager::stopDevice()
  18949. {
  18950. if (currentAudioDevice != 0)
  18951. currentAudioDevice->stop();
  18952. deleteAndZero (testSound);
  18953. }
  18954. void AudioDeviceManager::closeAudioDevice()
  18955. {
  18956. stopDevice();
  18957. deleteAndZero (currentAudioDevice);
  18958. }
  18959. void AudioDeviceManager::restartLastAudioDevice()
  18960. {
  18961. if (currentAudioDevice == 0)
  18962. {
  18963. if (currentSetup.inputDeviceName.isEmpty()
  18964. && currentSetup.outputDeviceName.isEmpty())
  18965. {
  18966. // This method will only reload the last device that was running
  18967. // before closeAudioDevice() was called - you need to actually open
  18968. // one first, with setAudioDevice().
  18969. jassertfalse
  18970. return;
  18971. }
  18972. AudioDeviceSetup s (currentSetup);
  18973. setAudioDeviceSetup (s, false);
  18974. }
  18975. }
  18976. void AudioDeviceManager::updateXml()
  18977. {
  18978. delete lastExplicitSettings;
  18979. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  18980. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  18981. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  18982. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  18983. if (currentAudioDevice != 0)
  18984. {
  18985. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  18986. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  18987. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  18988. if (! currentSetup.useDefaultInputChannels)
  18989. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  18990. if (! currentSetup.useDefaultOutputChannels)
  18991. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  18992. }
  18993. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  18994. {
  18995. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  18996. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  18997. lastExplicitSettings->addChildElement (m);
  18998. }
  18999. if (midiInsFromXml.size() > 0)
  19000. {
  19001. // Add any midi devices that have been enabled before, but which aren't currently
  19002. // open because the device has been disconnected.
  19003. const StringArray availableMidiDevices (MidiInput::getDevices());
  19004. for (int i = 0; i < midiInsFromXml.size(); ++i)
  19005. {
  19006. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  19007. {
  19008. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  19009. m->setAttribute (T("name"), midiInsFromXml[i]);
  19010. lastExplicitSettings->addChildElement (m);
  19011. }
  19012. }
  19013. }
  19014. if (defaultMidiOutputName.isNotEmpty())
  19015. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  19016. }
  19017. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  19018. {
  19019. {
  19020. const ScopedLock sl (audioCallbackLock);
  19021. if (callbacks.contains (newCallback))
  19022. return;
  19023. }
  19024. if (currentAudioDevice != 0 && newCallback != 0)
  19025. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  19026. const ScopedLock sl (audioCallbackLock);
  19027. callbacks.add (newCallback);
  19028. }
  19029. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  19030. {
  19031. if (callback != 0)
  19032. {
  19033. bool needsDeinitialising = currentAudioDevice != 0;
  19034. {
  19035. const ScopedLock sl (audioCallbackLock);
  19036. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  19037. callbacks.removeValue (callback);
  19038. }
  19039. if (needsDeinitialising)
  19040. callback->audioDeviceStopped();
  19041. }
  19042. }
  19043. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  19044. int numInputChannels,
  19045. float** outputChannelData,
  19046. int numOutputChannels,
  19047. int numSamples)
  19048. {
  19049. const ScopedLock sl (audioCallbackLock);
  19050. if (inputLevelMeasurementEnabledCount > 0)
  19051. {
  19052. for (int j = 0; j < numSamples; ++j)
  19053. {
  19054. float s = 0;
  19055. for (int i = 0; i < numInputChannels; ++i)
  19056. s += fabsf (inputChannelData[i][j]);
  19057. s /= numInputChannels;
  19058. const double decayFactor = 0.99992;
  19059. if (s > inputLevel)
  19060. inputLevel = s;
  19061. else if (inputLevel > 0.001f)
  19062. inputLevel *= decayFactor;
  19063. else
  19064. inputLevel = 0;
  19065. }
  19066. }
  19067. if (callbacks.size() > 0)
  19068. {
  19069. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  19070. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  19071. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19072. outputChannelData, numOutputChannels, numSamples);
  19073. float** const tempChans = tempBuffer.getArrayOfChannels();
  19074. for (int i = callbacks.size(); --i > 0;)
  19075. {
  19076. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  19077. tempChans, numOutputChannels, numSamples);
  19078. for (int chan = 0; chan < numOutputChannels; ++chan)
  19079. {
  19080. const float* const src = tempChans [chan];
  19081. float* const dst = outputChannelData [chan];
  19082. if (src != 0 && dst != 0)
  19083. for (int j = 0; j < numSamples; ++j)
  19084. dst[j] += src[j];
  19085. }
  19086. }
  19087. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  19088. const double filterAmount = 0.2;
  19089. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  19090. }
  19091. else
  19092. {
  19093. for (int i = 0; i < numOutputChannels; ++i)
  19094. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19095. }
  19096. if (testSound != 0)
  19097. {
  19098. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  19099. const float* const src = testSound->getSampleData (0, testSoundPosition);
  19100. for (int i = 0; i < numOutputChannels; ++i)
  19101. for (int j = 0; j < numSamps; ++j)
  19102. outputChannelData [i][j] += src[j];
  19103. testSoundPosition += numSamps;
  19104. if (testSoundPosition >= testSound->getNumSamples())
  19105. {
  19106. delete testSound;
  19107. testSound = 0;
  19108. }
  19109. }
  19110. }
  19111. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  19112. {
  19113. cpuUsageMs = 0;
  19114. const double sampleRate = device->getCurrentSampleRate();
  19115. const int blockSize = device->getCurrentBufferSizeSamples();
  19116. if (sampleRate > 0.0 && blockSize > 0)
  19117. {
  19118. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  19119. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  19120. }
  19121. {
  19122. const ScopedLock sl (audioCallbackLock);
  19123. for (int i = callbacks.size(); --i >= 0;)
  19124. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  19125. }
  19126. sendChangeMessage (this);
  19127. }
  19128. void AudioDeviceManager::audioDeviceStoppedInt()
  19129. {
  19130. cpuUsageMs = 0;
  19131. timeToCpuScale = 0;
  19132. sendChangeMessage (this);
  19133. const ScopedLock sl (audioCallbackLock);
  19134. for (int i = callbacks.size(); --i >= 0;)
  19135. callbacks.getUnchecked(i)->audioDeviceStopped();
  19136. }
  19137. double AudioDeviceManager::getCpuUsage() const
  19138. {
  19139. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  19140. }
  19141. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  19142. const bool enabled)
  19143. {
  19144. if (enabled != isMidiInputEnabled (name))
  19145. {
  19146. if (enabled)
  19147. {
  19148. const int index = MidiInput::getDevices().indexOf (name);
  19149. if (index >= 0)
  19150. {
  19151. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  19152. if (min != 0)
  19153. {
  19154. enabledMidiInputs.add (min);
  19155. min->start();
  19156. }
  19157. }
  19158. }
  19159. else
  19160. {
  19161. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19162. if (enabledMidiInputs[i]->getName() == name)
  19163. enabledMidiInputs.remove (i);
  19164. }
  19165. updateXml();
  19166. sendChangeMessage (this);
  19167. }
  19168. }
  19169. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  19170. {
  19171. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19172. if (enabledMidiInputs[i]->getName() == name)
  19173. return true;
  19174. return false;
  19175. }
  19176. void AudioDeviceManager::addMidiInputCallback (const String& name,
  19177. MidiInputCallback* callback)
  19178. {
  19179. removeMidiInputCallback (name, callback);
  19180. if (name.isEmpty())
  19181. {
  19182. midiCallbacks.add (callback);
  19183. midiCallbackDevices.add (0);
  19184. }
  19185. else
  19186. {
  19187. for (int i = enabledMidiInputs.size(); --i >= 0;)
  19188. {
  19189. if (enabledMidiInputs[i]->getName() == name)
  19190. {
  19191. const ScopedLock sl (midiCallbackLock);
  19192. midiCallbacks.add (callback);
  19193. midiCallbackDevices.add (enabledMidiInputs[i]);
  19194. break;
  19195. }
  19196. }
  19197. }
  19198. }
  19199. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  19200. MidiInputCallback* /*callback*/)
  19201. {
  19202. const ScopedLock sl (midiCallbackLock);
  19203. for (int i = midiCallbacks.size(); --i >= 0;)
  19204. {
  19205. String devName;
  19206. if (midiCallbackDevices.getUnchecked(i) != 0)
  19207. devName = midiCallbackDevices.getUnchecked(i)->getName();
  19208. if (devName == name)
  19209. {
  19210. midiCallbacks.remove (i);
  19211. midiCallbackDevices.remove (i);
  19212. }
  19213. }
  19214. }
  19215. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  19216. const MidiMessage& message)
  19217. {
  19218. if (! message.isActiveSense())
  19219. {
  19220. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  19221. const ScopedLock sl (midiCallbackLock);
  19222. for (int i = midiCallbackDevices.size(); --i >= 0;)
  19223. {
  19224. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  19225. if (md == source || (md == 0 && isDefaultSource))
  19226. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  19227. }
  19228. }
  19229. }
  19230. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  19231. {
  19232. if (defaultMidiOutputName != deviceName)
  19233. {
  19234. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  19235. {
  19236. const ScopedLock sl (audioCallbackLock);
  19237. oldCallbacks = callbacks;
  19238. callbacks.clear();
  19239. }
  19240. if (currentAudioDevice != 0)
  19241. for (int i = oldCallbacks.size(); --i >= 0;)
  19242. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  19243. deleteAndZero (defaultMidiOutput);
  19244. defaultMidiOutputName = deviceName;
  19245. if (deviceName.isNotEmpty())
  19246. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  19247. if (currentAudioDevice != 0)
  19248. for (int i = oldCallbacks.size(); --i >= 0;)
  19249. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  19250. {
  19251. const ScopedLock sl (audioCallbackLock);
  19252. callbacks = oldCallbacks;
  19253. }
  19254. updateXml();
  19255. sendChangeMessage (this);
  19256. }
  19257. }
  19258. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  19259. int numInputChannels,
  19260. float** outputChannelData,
  19261. int numOutputChannels,
  19262. int numSamples)
  19263. {
  19264. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  19265. }
  19266. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  19267. {
  19268. owner->audioDeviceAboutToStartInt (device);
  19269. }
  19270. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  19271. {
  19272. owner->audioDeviceStoppedInt();
  19273. }
  19274. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  19275. {
  19276. owner->handleIncomingMidiMessageInt (source, message);
  19277. }
  19278. void AudioDeviceManager::playTestSound()
  19279. {
  19280. audioCallbackLock.enter();
  19281. AudioSampleBuffer* oldSound = testSound;
  19282. testSound = 0;
  19283. audioCallbackLock.exit();
  19284. delete oldSound;
  19285. testSoundPosition = 0;
  19286. if (currentAudioDevice != 0)
  19287. {
  19288. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  19289. const int soundLength = (int) sampleRate;
  19290. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  19291. float* samples = newSound->getSampleData (0);
  19292. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  19293. const float amplitude = 0.5f;
  19294. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  19295. for (int i = 0; i < soundLength; ++i)
  19296. samples[i] = amplitude * (float) sin (i * phasePerSample);
  19297. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  19298. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  19299. const ScopedLock sl (audioCallbackLock);
  19300. testSound = newSound;
  19301. }
  19302. }
  19303. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  19304. {
  19305. const ScopedLock sl (audioCallbackLock);
  19306. if (enableMeasurement)
  19307. ++inputLevelMeasurementEnabledCount;
  19308. else
  19309. --inputLevelMeasurementEnabledCount;
  19310. inputLevel = 0;
  19311. }
  19312. double AudioDeviceManager::getCurrentInputLevel() const
  19313. {
  19314. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  19315. return inputLevel;
  19316. }
  19317. END_JUCE_NAMESPACE
  19318. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  19319. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  19320. BEGIN_JUCE_NAMESPACE
  19321. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  19322. : name (deviceName),
  19323. typeName (typeName_)
  19324. {
  19325. }
  19326. AudioIODevice::~AudioIODevice()
  19327. {
  19328. }
  19329. bool AudioIODevice::hasControlPanel() const
  19330. {
  19331. return false;
  19332. }
  19333. bool AudioIODevice::showControlPanel()
  19334. {
  19335. jassertfalse // this should only be called for devices which return true from
  19336. // their hasControlPanel() method.
  19337. return false;
  19338. }
  19339. END_JUCE_NAMESPACE
  19340. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  19341. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  19342. BEGIN_JUCE_NAMESPACE
  19343. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  19344. : typeName (name)
  19345. {
  19346. }
  19347. AudioIODeviceType::~AudioIODeviceType()
  19348. {
  19349. }
  19350. END_JUCE_NAMESPACE
  19351. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  19352. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  19353. BEGIN_JUCE_NAMESPACE
  19354. MidiOutput::MidiOutput() throw()
  19355. : Thread ("midi out"),
  19356. internal (0),
  19357. firstMessage (0)
  19358. {
  19359. }
  19360. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  19361. const int len,
  19362. const double sampleNumber) throw()
  19363. : message (data, len, sampleNumber)
  19364. {
  19365. }
  19366. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  19367. const double millisecondCounterToStartAt,
  19368. double samplesPerSecondForBuffer) throw()
  19369. {
  19370. // You've got to call startBackgroundThread() for this to actually work..
  19371. jassert (isThreadRunning());
  19372. // this needs to be a value in the future - RTFM for this method!
  19373. jassert (millisecondCounterToStartAt > 0);
  19374. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  19375. MidiBuffer::Iterator i (buffer);
  19376. const uint8* data;
  19377. int len, time;
  19378. while (i.getNextEvent (data, len, time))
  19379. {
  19380. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  19381. PendingMessage* const m
  19382. = new PendingMessage (data, len, eventTime);
  19383. const ScopedLock sl (lock);
  19384. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  19385. {
  19386. m->next = firstMessage;
  19387. firstMessage = m;
  19388. }
  19389. else
  19390. {
  19391. PendingMessage* mm = firstMessage;
  19392. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  19393. mm = mm->next;
  19394. m->next = mm->next;
  19395. mm->next = m;
  19396. }
  19397. }
  19398. notify();
  19399. }
  19400. void MidiOutput::clearAllPendingMessages() throw()
  19401. {
  19402. const ScopedLock sl (lock);
  19403. while (firstMessage != 0)
  19404. {
  19405. PendingMessage* const m = firstMessage;
  19406. firstMessage = firstMessage->next;
  19407. delete m;
  19408. }
  19409. }
  19410. void MidiOutput::startBackgroundThread() throw()
  19411. {
  19412. startThread (9);
  19413. }
  19414. void MidiOutput::stopBackgroundThread() throw()
  19415. {
  19416. stopThread (5000);
  19417. }
  19418. void MidiOutput::run()
  19419. {
  19420. while (! threadShouldExit())
  19421. {
  19422. uint32 now = Time::getMillisecondCounter();
  19423. uint32 eventTime = 0;
  19424. uint32 timeToWait = 500;
  19425. lock.enter();
  19426. PendingMessage* message = firstMessage;
  19427. if (message != 0)
  19428. {
  19429. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  19430. if (eventTime > now + 20)
  19431. {
  19432. timeToWait = jmax (10, eventTime - now - 100);
  19433. message = 0;
  19434. }
  19435. else
  19436. {
  19437. firstMessage = message->next;
  19438. }
  19439. }
  19440. lock.exit();
  19441. if (message != 0)
  19442. {
  19443. if (eventTime > now)
  19444. {
  19445. Time::waitForMillisecondCounter (eventTime);
  19446. if (threadShouldExit())
  19447. break;
  19448. }
  19449. if (eventTime > now - 200)
  19450. sendMessageNow (message->message);
  19451. delete message;
  19452. }
  19453. else
  19454. {
  19455. jassert (timeToWait < 1000 * 30);
  19456. wait (timeToWait);
  19457. }
  19458. }
  19459. clearAllPendingMessages();
  19460. }
  19461. END_JUCE_NAMESPACE
  19462. /********* End of inlined file: juce_MidiOutput.cpp *********/
  19463. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  19464. BEGIN_JUCE_NAMESPACE
  19465. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19466. {
  19467. const double maxVal = (double) 0x7fff;
  19468. char* intData = (char*) dest;
  19469. if (dest != (void*) source || destBytesPerSample <= 4)
  19470. {
  19471. for (int i = 0; i < numSamples; ++i)
  19472. {
  19473. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19474. intData += destBytesPerSample;
  19475. }
  19476. }
  19477. else
  19478. {
  19479. intData += destBytesPerSample * numSamples;
  19480. for (int i = numSamples; --i >= 0;)
  19481. {
  19482. intData -= destBytesPerSample;
  19483. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19484. }
  19485. }
  19486. }
  19487. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19488. {
  19489. const double maxVal = (double) 0x7fff;
  19490. char* intData = (char*) dest;
  19491. if (dest != (void*) source || destBytesPerSample <= 4)
  19492. {
  19493. for (int i = 0; i < numSamples; ++i)
  19494. {
  19495. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19496. intData += destBytesPerSample;
  19497. }
  19498. }
  19499. else
  19500. {
  19501. intData += destBytesPerSample * numSamples;
  19502. for (int i = numSamples; --i >= 0;)
  19503. {
  19504. intData -= destBytesPerSample;
  19505. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19506. }
  19507. }
  19508. }
  19509. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19510. {
  19511. const double maxVal = (double) 0x7fffff;
  19512. char* intData = (char*) dest;
  19513. if (dest != (void*) source || destBytesPerSample <= 4)
  19514. {
  19515. for (int i = 0; i < numSamples; ++i)
  19516. {
  19517. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19518. intData += destBytesPerSample;
  19519. }
  19520. }
  19521. else
  19522. {
  19523. intData += destBytesPerSample * numSamples;
  19524. for (int i = numSamples; --i >= 0;)
  19525. {
  19526. intData -= destBytesPerSample;
  19527. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19528. }
  19529. }
  19530. }
  19531. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19532. {
  19533. const double maxVal = (double) 0x7fffff;
  19534. char* intData = (char*) dest;
  19535. if (dest != (void*) source || destBytesPerSample <= 4)
  19536. {
  19537. for (int i = 0; i < numSamples; ++i)
  19538. {
  19539. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19540. intData += destBytesPerSample;
  19541. }
  19542. }
  19543. else
  19544. {
  19545. intData += destBytesPerSample * numSamples;
  19546. for (int i = numSamples; --i >= 0;)
  19547. {
  19548. intData -= destBytesPerSample;
  19549. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  19550. }
  19551. }
  19552. }
  19553. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19554. {
  19555. const double maxVal = (double) 0x7fffffff;
  19556. char* intData = (char*) dest;
  19557. if (dest != (void*) source || destBytesPerSample <= 4)
  19558. {
  19559. for (int i = 0; i < numSamples; ++i)
  19560. {
  19561. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19562. intData += destBytesPerSample;
  19563. }
  19564. }
  19565. else
  19566. {
  19567. intData += destBytesPerSample * numSamples;
  19568. for (int i = numSamples; --i >= 0;)
  19569. {
  19570. intData -= destBytesPerSample;
  19571. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19572. }
  19573. }
  19574. }
  19575. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19576. {
  19577. const double maxVal = (double) 0x7fffffff;
  19578. char* intData = (char*) dest;
  19579. if (dest != (void*) source || destBytesPerSample <= 4)
  19580. {
  19581. for (int i = 0; i < numSamples; ++i)
  19582. {
  19583. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19584. intData += destBytesPerSample;
  19585. }
  19586. }
  19587. else
  19588. {
  19589. intData += destBytesPerSample * numSamples;
  19590. for (int i = numSamples; --i >= 0;)
  19591. {
  19592. intData -= destBytesPerSample;
  19593. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  19594. }
  19595. }
  19596. }
  19597. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19598. {
  19599. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19600. char* d = (char*) dest;
  19601. for (int i = 0; i < numSamples; ++i)
  19602. {
  19603. *(float*)d = source[i];
  19604. #if JUCE_BIG_ENDIAN
  19605. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19606. #endif
  19607. d += destBytesPerSample;
  19608. }
  19609. }
  19610. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  19611. {
  19612. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  19613. char* d = (char*) dest;
  19614. for (int i = 0; i < numSamples; ++i)
  19615. {
  19616. *(float*)d = source[i];
  19617. #if JUCE_LITTLE_ENDIAN
  19618. *(uint32*)d = swapByteOrder (*(uint32*)d);
  19619. #endif
  19620. d += destBytesPerSample;
  19621. }
  19622. }
  19623. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19624. {
  19625. const float scale = 1.0f / 0x7fff;
  19626. const char* intData = (const char*) source;
  19627. if (source != (void*) dest || srcBytesPerSample >= 4)
  19628. {
  19629. for (int i = 0; i < numSamples; ++i)
  19630. {
  19631. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19632. intData += srcBytesPerSample;
  19633. }
  19634. }
  19635. else
  19636. {
  19637. intData += srcBytesPerSample * numSamples;
  19638. for (int i = numSamples; --i >= 0;)
  19639. {
  19640. intData -= srcBytesPerSample;
  19641. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  19642. }
  19643. }
  19644. }
  19645. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19646. {
  19647. const float scale = 1.0f / 0x7fff;
  19648. const char* intData = (const char*) source;
  19649. if (source != (void*) dest || srcBytesPerSample >= 4)
  19650. {
  19651. for (int i = 0; i < numSamples; ++i)
  19652. {
  19653. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19654. intData += srcBytesPerSample;
  19655. }
  19656. }
  19657. else
  19658. {
  19659. intData += srcBytesPerSample * numSamples;
  19660. for (int i = numSamples; --i >= 0;)
  19661. {
  19662. intData -= srcBytesPerSample;
  19663. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  19664. }
  19665. }
  19666. }
  19667. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19668. {
  19669. const float scale = 1.0f / 0x7fffff;
  19670. const char* intData = (const char*) source;
  19671. if (source != (void*) dest || srcBytesPerSample >= 4)
  19672. {
  19673. for (int i = 0; i < numSamples; ++i)
  19674. {
  19675. dest[i] = scale * (short) littleEndian24Bit (intData);
  19676. intData += srcBytesPerSample;
  19677. }
  19678. }
  19679. else
  19680. {
  19681. intData += srcBytesPerSample * numSamples;
  19682. for (int i = numSamples; --i >= 0;)
  19683. {
  19684. intData -= srcBytesPerSample;
  19685. dest[i] = scale * (short) littleEndian24Bit (intData);
  19686. }
  19687. }
  19688. }
  19689. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19690. {
  19691. const float scale = 1.0f / 0x7fffff;
  19692. const char* intData = (const char*) source;
  19693. if (source != (void*) dest || srcBytesPerSample >= 4)
  19694. {
  19695. for (int i = 0; i < numSamples; ++i)
  19696. {
  19697. dest[i] = scale * (short) bigEndian24Bit (intData);
  19698. intData += srcBytesPerSample;
  19699. }
  19700. }
  19701. else
  19702. {
  19703. intData += srcBytesPerSample * numSamples;
  19704. for (int i = numSamples; --i >= 0;)
  19705. {
  19706. intData -= srcBytesPerSample;
  19707. dest[i] = scale * (short) bigEndian24Bit (intData);
  19708. }
  19709. }
  19710. }
  19711. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19712. {
  19713. const float scale = 1.0f / 0x7fffffff;
  19714. const char* intData = (const char*) source;
  19715. if (source != (void*) dest || srcBytesPerSample >= 4)
  19716. {
  19717. for (int i = 0; i < numSamples; ++i)
  19718. {
  19719. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19720. intData += srcBytesPerSample;
  19721. }
  19722. }
  19723. else
  19724. {
  19725. intData += srcBytesPerSample * numSamples;
  19726. for (int i = numSamples; --i >= 0;)
  19727. {
  19728. intData -= srcBytesPerSample;
  19729. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  19730. }
  19731. }
  19732. }
  19733. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19734. {
  19735. const float scale = 1.0f / 0x7fffffff;
  19736. const char* intData = (const char*) source;
  19737. if (source != (void*) dest || srcBytesPerSample >= 4)
  19738. {
  19739. for (int i = 0; i < numSamples; ++i)
  19740. {
  19741. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19742. intData += srcBytesPerSample;
  19743. }
  19744. }
  19745. else
  19746. {
  19747. intData += srcBytesPerSample * numSamples;
  19748. for (int i = numSamples; --i >= 0;)
  19749. {
  19750. intData -= srcBytesPerSample;
  19751. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  19752. }
  19753. }
  19754. }
  19755. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19756. {
  19757. const char* s = (const char*) source;
  19758. for (int i = 0; i < numSamples; ++i)
  19759. {
  19760. dest[i] = *(float*)s;
  19761. #if JUCE_BIG_ENDIAN
  19762. uint32* const d = (uint32*) (dest + i);
  19763. *d = swapByteOrder (*d);
  19764. #endif
  19765. s += srcBytesPerSample;
  19766. }
  19767. }
  19768. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  19769. {
  19770. const char* s = (const char*) source;
  19771. for (int i = 0; i < numSamples; ++i)
  19772. {
  19773. dest[i] = *(float*)s;
  19774. #if JUCE_LITTLE_ENDIAN
  19775. uint32* const d = (uint32*) (dest + i);
  19776. *d = swapByteOrder (*d);
  19777. #endif
  19778. s += srcBytesPerSample;
  19779. }
  19780. }
  19781. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  19782. const float* const source,
  19783. void* const dest,
  19784. const int numSamples)
  19785. {
  19786. switch (destFormat)
  19787. {
  19788. case int16LE:
  19789. convertFloatToInt16LE (source, dest, numSamples);
  19790. break;
  19791. case int16BE:
  19792. convertFloatToInt16BE (source, dest, numSamples);
  19793. break;
  19794. case int24LE:
  19795. convertFloatToInt24LE (source, dest, numSamples);
  19796. break;
  19797. case int24BE:
  19798. convertFloatToInt24BE (source, dest, numSamples);
  19799. break;
  19800. case int32LE:
  19801. convertFloatToInt32LE (source, dest, numSamples);
  19802. break;
  19803. case int32BE:
  19804. convertFloatToInt32BE (source, dest, numSamples);
  19805. break;
  19806. case float32LE:
  19807. convertFloatToFloat32LE (source, dest, numSamples);
  19808. break;
  19809. case float32BE:
  19810. convertFloatToFloat32BE (source, dest, numSamples);
  19811. break;
  19812. default:
  19813. jassertfalse
  19814. break;
  19815. }
  19816. }
  19817. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  19818. const void* const source,
  19819. float* const dest,
  19820. const int numSamples)
  19821. {
  19822. switch (sourceFormat)
  19823. {
  19824. case int16LE:
  19825. convertInt16LEToFloat (source, dest, numSamples);
  19826. break;
  19827. case int16BE:
  19828. convertInt16BEToFloat (source, dest, numSamples);
  19829. break;
  19830. case int24LE:
  19831. convertInt24LEToFloat (source, dest, numSamples);
  19832. break;
  19833. case int24BE:
  19834. convertInt24BEToFloat (source, dest, numSamples);
  19835. break;
  19836. case int32LE:
  19837. convertInt32LEToFloat (source, dest, numSamples);
  19838. break;
  19839. case int32BE:
  19840. convertInt32BEToFloat (source, dest, numSamples);
  19841. break;
  19842. case float32LE:
  19843. convertFloat32LEToFloat (source, dest, numSamples);
  19844. break;
  19845. case float32BE:
  19846. convertFloat32BEToFloat (source, dest, numSamples);
  19847. break;
  19848. default:
  19849. jassertfalse
  19850. break;
  19851. }
  19852. }
  19853. void AudioDataConverters::interleaveSamples (const float** const source,
  19854. float* const dest,
  19855. const int numSamples,
  19856. const int numChannels)
  19857. {
  19858. for (int chan = 0; chan < numChannels; ++chan)
  19859. {
  19860. int i = chan;
  19861. const float* src = source [chan];
  19862. for (int j = 0; j < numSamples; ++j)
  19863. {
  19864. dest [i] = src [j];
  19865. i += numChannels;
  19866. }
  19867. }
  19868. }
  19869. void AudioDataConverters::deinterleaveSamples (const float* const source,
  19870. float** const dest,
  19871. const int numSamples,
  19872. const int numChannels)
  19873. {
  19874. for (int chan = 0; chan < numChannels; ++chan)
  19875. {
  19876. int i = chan;
  19877. float* dst = dest [chan];
  19878. for (int j = 0; j < numSamples; ++j)
  19879. {
  19880. dst [j] = source [i];
  19881. i += numChannels;
  19882. }
  19883. }
  19884. }
  19885. END_JUCE_NAMESPACE
  19886. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  19887. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  19888. BEGIN_JUCE_NAMESPACE
  19889. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  19890. const int numSamples) throw()
  19891. : numChannels (numChannels_),
  19892. size (numSamples)
  19893. {
  19894. jassert (numSamples >= 0);
  19895. jassert (numChannels_ > 0);
  19896. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  19897. allocatedData = (float*) juce_malloc (allocatedBytes);
  19898. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19899. float* chan = allocatedData;
  19900. for (int i = 0; i < numChannels_; ++i)
  19901. {
  19902. channels[i] = chan;
  19903. chan += numSamples;
  19904. }
  19905. channels [numChannels_] = 0;
  19906. }
  19907. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  19908. const int numChannels_,
  19909. const int numSamples) throw()
  19910. : numChannels (numChannels_),
  19911. size (numSamples),
  19912. allocatedBytes (0),
  19913. allocatedData (0)
  19914. {
  19915. jassert (numChannels_ > 0);
  19916. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  19917. if (numChannels_ < numElementsInArray (preallocatedChannelSpace))
  19918. channels = (float**) preallocatedChannelSpace;
  19919. else
  19920. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  19921. for (int i = 0; i < numChannels_; ++i)
  19922. {
  19923. // you have to pass in the same number of valid pointers as numChannels
  19924. jassert (dataToReferTo[i] != 0);
  19925. channels[i] = dataToReferTo[i];
  19926. }
  19927. channels [numChannels_] = 0;
  19928. }
  19929. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  19930. const int numChannels_,
  19931. const int numSamples) throw()
  19932. {
  19933. jassert (numChannels_ > 0);
  19934. juce_free (allocatedData);
  19935. allocatedData = 0;
  19936. allocatedBytes = 0;
  19937. if (numChannels_ > numChannels)
  19938. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  19939. numChannels = numChannels_;
  19940. size = numSamples;
  19941. for (int i = 0; i < numChannels_; ++i)
  19942. {
  19943. // you have to pass in the same number of valid pointers as numChannels
  19944. jassert (dataToReferTo[i] != 0);
  19945. channels[i] = dataToReferTo[i];
  19946. }
  19947. channels [numChannels_] = 0;
  19948. }
  19949. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  19950. : numChannels (other.numChannels),
  19951. size (other.size)
  19952. {
  19953. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  19954. if (other.allocatedData != 0)
  19955. {
  19956. allocatedBytes = numChannels * size * sizeof (float) + 32;
  19957. allocatedData = (float*) juce_malloc (allocatedBytes);
  19958. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  19959. float* chan = allocatedData;
  19960. for (int i = 0; i < numChannels; ++i)
  19961. {
  19962. channels[i] = chan;
  19963. chan += size;
  19964. }
  19965. channels [numChannels] = 0;
  19966. }
  19967. else
  19968. {
  19969. allocatedData = 0;
  19970. allocatedBytes = 0;
  19971. memcpy (channels, other.channels, sizeof (channels));
  19972. }
  19973. }
  19974. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  19975. {
  19976. if (this != &other)
  19977. {
  19978. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  19979. const int numBytes = size * sizeof (float);
  19980. for (int i = 0; i < numChannels; ++i)
  19981. memcpy (channels[i], other.channels[i], numBytes);
  19982. }
  19983. return *this;
  19984. }
  19985. AudioSampleBuffer::~AudioSampleBuffer() throw()
  19986. {
  19987. juce_free (allocatedData);
  19988. if (channels != (float**) preallocatedChannelSpace)
  19989. juce_free (channels);
  19990. }
  19991. void AudioSampleBuffer::setSize (const int newNumChannels,
  19992. const int newNumSamples,
  19993. const bool keepExistingContent,
  19994. const bool clearExtraSpace,
  19995. const bool avoidReallocating) throw()
  19996. {
  19997. jassert (newNumChannels > 0);
  19998. if (newNumSamples != size || newNumChannels != numChannels)
  19999. {
  20000. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  20001. if (keepExistingContent)
  20002. {
  20003. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20004. : (float*) juce_malloc (newTotalBytes);
  20005. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  20006. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  20007. {
  20008. memcpy (newData + i * newNumSamples,
  20009. channels[i],
  20010. sizeToCopy);
  20011. }
  20012. juce_free (allocatedData);
  20013. allocatedData = newData;
  20014. allocatedBytes = newTotalBytes;
  20015. }
  20016. else
  20017. {
  20018. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  20019. {
  20020. if (clearExtraSpace)
  20021. zeromem (allocatedData, newTotalBytes);
  20022. }
  20023. else
  20024. {
  20025. juce_free (allocatedData);
  20026. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  20027. : (float*) juce_malloc (newTotalBytes);
  20028. allocatedBytes = newTotalBytes;
  20029. }
  20030. }
  20031. size = newNumSamples;
  20032. if (newNumChannels > numChannels)
  20033. channels = (float**) juce_realloc (channels, (newNumChannels + 1) * sizeof (float*));
  20034. numChannels = newNumChannels;
  20035. float* chan = allocatedData;
  20036. for (int i = 0; i < newNumChannels; ++i)
  20037. {
  20038. channels[i] = chan;
  20039. chan += size;
  20040. }
  20041. channels [newNumChannels] = 0;
  20042. }
  20043. }
  20044. void AudioSampleBuffer::clear() throw()
  20045. {
  20046. for (int i = 0; i < numChannels; ++i)
  20047. zeromem (channels[i], size * sizeof (float));
  20048. }
  20049. void AudioSampleBuffer::clear (const int startSample,
  20050. const int numSamples) throw()
  20051. {
  20052. jassert (startSample >= 0 && startSample + numSamples <= size);
  20053. for (int i = 0; i < numChannels; ++i)
  20054. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  20055. }
  20056. void AudioSampleBuffer::clear (const int channel,
  20057. const int startSample,
  20058. const int numSamples) throw()
  20059. {
  20060. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20061. jassert (startSample >= 0 && startSample + numSamples <= size);
  20062. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  20063. }
  20064. void AudioSampleBuffer::applyGain (const int channel,
  20065. const int startSample,
  20066. int numSamples,
  20067. const float gain) throw()
  20068. {
  20069. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20070. jassert (startSample >= 0 && startSample + numSamples <= size);
  20071. if (gain != 1.0f)
  20072. {
  20073. float* d = channels [channel] + startSample;
  20074. if (gain == 0.0f)
  20075. {
  20076. zeromem (d, sizeof (float) * numSamples);
  20077. }
  20078. else
  20079. {
  20080. while (--numSamples >= 0)
  20081. *d++ *= gain;
  20082. }
  20083. }
  20084. }
  20085. void AudioSampleBuffer::applyGainRamp (const int channel,
  20086. const int startSample,
  20087. int numSamples,
  20088. float startGain,
  20089. float endGain) throw()
  20090. {
  20091. if (startGain == endGain)
  20092. {
  20093. applyGain (channel, startSample, numSamples, startGain);
  20094. }
  20095. else
  20096. {
  20097. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20098. jassert (startSample >= 0 && startSample + numSamples <= size);
  20099. const float increment = (endGain - startGain) / numSamples;
  20100. float* d = channels [channel] + startSample;
  20101. while (--numSamples >= 0)
  20102. {
  20103. *d++ *= startGain;
  20104. startGain += increment;
  20105. }
  20106. }
  20107. }
  20108. void AudioSampleBuffer::applyGain (const int startSample,
  20109. const int numSamples,
  20110. const float gain) throw()
  20111. {
  20112. for (int i = 0; i < numChannels; ++i)
  20113. applyGain (i, startSample, numSamples, gain);
  20114. }
  20115. void AudioSampleBuffer::addFrom (const int destChannel,
  20116. const int destStartSample,
  20117. const AudioSampleBuffer& source,
  20118. const int sourceChannel,
  20119. const int sourceStartSample,
  20120. int numSamples,
  20121. const float gain) throw()
  20122. {
  20123. jassert (&source != this || sourceChannel != destChannel);
  20124. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20125. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20126. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20127. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20128. if (gain != 0.0f && numSamples > 0)
  20129. {
  20130. float* d = channels [destChannel] + destStartSample;
  20131. const float* s = source.channels [sourceChannel] + sourceStartSample;
  20132. if (gain != 1.0f)
  20133. {
  20134. while (--numSamples >= 0)
  20135. *d++ += gain * *s++;
  20136. }
  20137. else
  20138. {
  20139. while (--numSamples >= 0)
  20140. *d++ += *s++;
  20141. }
  20142. }
  20143. }
  20144. void AudioSampleBuffer::addFrom (const int destChannel,
  20145. const int destStartSample,
  20146. const float* source,
  20147. int numSamples,
  20148. const float gain) throw()
  20149. {
  20150. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20151. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20152. jassert (source != 0);
  20153. if (gain != 0.0f && numSamples > 0)
  20154. {
  20155. float* d = channels [destChannel] + destStartSample;
  20156. if (gain != 1.0f)
  20157. {
  20158. while (--numSamples >= 0)
  20159. *d++ += gain * *source++;
  20160. }
  20161. else
  20162. {
  20163. while (--numSamples >= 0)
  20164. *d++ += *source++;
  20165. }
  20166. }
  20167. }
  20168. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  20169. const int destStartSample,
  20170. const float* source,
  20171. int numSamples,
  20172. float startGain,
  20173. const float endGain) throw()
  20174. {
  20175. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20176. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20177. jassert (source != 0);
  20178. if (startGain == endGain)
  20179. {
  20180. addFrom (destChannel,
  20181. destStartSample,
  20182. source,
  20183. numSamples,
  20184. startGain);
  20185. }
  20186. else
  20187. {
  20188. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20189. {
  20190. const float increment = (endGain - startGain) / numSamples;
  20191. float* d = channels [destChannel] + destStartSample;
  20192. while (--numSamples >= 0)
  20193. {
  20194. *d++ += startGain * *source++;
  20195. startGain += increment;
  20196. }
  20197. }
  20198. }
  20199. }
  20200. void AudioSampleBuffer::copyFrom (const int destChannel,
  20201. const int destStartSample,
  20202. const AudioSampleBuffer& source,
  20203. const int sourceChannel,
  20204. const int sourceStartSample,
  20205. int numSamples) throw()
  20206. {
  20207. jassert (&source != this || sourceChannel != destChannel);
  20208. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20209. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20210. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  20211. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  20212. if (numSamples > 0)
  20213. {
  20214. memcpy (channels [destChannel] + destStartSample,
  20215. source.channels [sourceChannel] + sourceStartSample,
  20216. sizeof (float) * numSamples);
  20217. }
  20218. }
  20219. void AudioSampleBuffer::copyFrom (const int destChannel,
  20220. const int destStartSample,
  20221. const float* source,
  20222. int numSamples) throw()
  20223. {
  20224. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20225. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20226. jassert (source != 0);
  20227. if (numSamples > 0)
  20228. {
  20229. memcpy (channels [destChannel] + destStartSample,
  20230. source,
  20231. sizeof (float) * numSamples);
  20232. }
  20233. }
  20234. void AudioSampleBuffer::copyFrom (const int destChannel,
  20235. const int destStartSample,
  20236. const float* source,
  20237. int numSamples,
  20238. const float gain) throw()
  20239. {
  20240. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20241. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20242. jassert (source != 0);
  20243. if (numSamples > 0 && gain != 0)
  20244. {
  20245. float* d = channels [destChannel] + destStartSample;
  20246. if (gain != 1.0f)
  20247. {
  20248. while (--numSamples >= 0)
  20249. *d++ = gain * *source++;
  20250. }
  20251. else
  20252. {
  20253. memcpy (d, source, sizeof (float) * numSamples);
  20254. }
  20255. }
  20256. }
  20257. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  20258. const int destStartSample,
  20259. const float* source,
  20260. int numSamples,
  20261. float startGain,
  20262. float endGain) throw()
  20263. {
  20264. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  20265. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  20266. jassert (source != 0);
  20267. if (startGain == endGain)
  20268. {
  20269. copyFrom (destChannel,
  20270. destStartSample,
  20271. source,
  20272. numSamples,
  20273. startGain);
  20274. }
  20275. else
  20276. {
  20277. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  20278. {
  20279. const float increment = (endGain - startGain) / numSamples;
  20280. float* d = channels [destChannel] + destStartSample;
  20281. while (--numSamples >= 0)
  20282. {
  20283. *d++ = startGain * *source++;
  20284. startGain += increment;
  20285. }
  20286. }
  20287. }
  20288. }
  20289. void AudioSampleBuffer::findMinMax (const int channel,
  20290. const int startSample,
  20291. int numSamples,
  20292. float& minVal,
  20293. float& maxVal) const throw()
  20294. {
  20295. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20296. jassert (startSample >= 0 && startSample + numSamples <= size);
  20297. if (numSamples <= 0)
  20298. {
  20299. minVal = 0.0f;
  20300. maxVal = 0.0f;
  20301. }
  20302. else
  20303. {
  20304. const float* d = channels [channel] + startSample;
  20305. float mn = *d++;
  20306. float mx = mn;
  20307. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  20308. {
  20309. const float samp = *d++;
  20310. if (samp > mx)
  20311. mx = samp;
  20312. if (samp < mn)
  20313. mn = samp;
  20314. }
  20315. maxVal = mx;
  20316. minVal = mn;
  20317. }
  20318. }
  20319. float AudioSampleBuffer::getMagnitude (const int channel,
  20320. const int startSample,
  20321. const int numSamples) const throw()
  20322. {
  20323. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20324. jassert (startSample >= 0 && startSample + numSamples <= size);
  20325. float mn, mx;
  20326. findMinMax (channel, startSample, numSamples, mn, mx);
  20327. return jmax (mn, -mn, mx, -mx);
  20328. }
  20329. float AudioSampleBuffer::getMagnitude (const int startSample,
  20330. const int numSamples) const throw()
  20331. {
  20332. float mag = 0.0f;
  20333. for (int i = 0; i < numChannels; ++i)
  20334. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  20335. return mag;
  20336. }
  20337. float AudioSampleBuffer::getRMSLevel (const int channel,
  20338. const int startSample,
  20339. const int numSamples) const throw()
  20340. {
  20341. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  20342. jassert (startSample >= 0 && startSample + numSamples <= size);
  20343. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  20344. return 0.0f;
  20345. const float* const data = channels [channel] + startSample;
  20346. double sum = 0.0;
  20347. for (int i = 0; i < numSamples; ++i)
  20348. {
  20349. const float sample = data [i];
  20350. sum += sample * sample;
  20351. }
  20352. return (float) sqrt (sum / numSamples);
  20353. }
  20354. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  20355. const int startSample,
  20356. const int numSamples,
  20357. const int readerStartSample,
  20358. const bool useLeftChan,
  20359. const bool useRightChan) throw()
  20360. {
  20361. jassert (reader != 0);
  20362. jassert (startSample >= 0 && startSample + numSamples <= size);
  20363. if (numSamples > 0)
  20364. {
  20365. int* chans[3];
  20366. if (useLeftChan == useRightChan)
  20367. {
  20368. chans[0] = (int*) getSampleData (0, startSample);
  20369. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  20370. }
  20371. else if (useLeftChan || (reader->numChannels == 1))
  20372. {
  20373. chans[0] = (int*) getSampleData (0, startSample);
  20374. chans[1] = 0;
  20375. }
  20376. else if (useRightChan)
  20377. {
  20378. chans[0] = 0;
  20379. chans[1] = (int*) getSampleData (0, startSample);
  20380. }
  20381. chans[2] = 0;
  20382. reader->read (chans, 2, readerStartSample, numSamples, true);
  20383. if (! reader->usesFloatingPointData)
  20384. {
  20385. for (int j = 0; j < 2; ++j)
  20386. {
  20387. float* const d = (float*) (chans[j]);
  20388. if (d != 0)
  20389. {
  20390. const float multiplier = 1.0f / 0x7fffffff;
  20391. for (int i = 0; i < numSamples; ++i)
  20392. d[i] = *(int*)(d + i) * multiplier;
  20393. }
  20394. }
  20395. }
  20396. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  20397. {
  20398. // if this is a stereo buffer and the source was mono, dupe the first channel..
  20399. memcpy (getSampleData (1, startSample),
  20400. getSampleData (0, startSample),
  20401. sizeof (float) * numSamples);
  20402. }
  20403. }
  20404. }
  20405. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  20406. const int startSample,
  20407. const int numSamples) const throw()
  20408. {
  20409. jassert (startSample >= 0 && startSample + numSamples <= size);
  20410. if (numSamples > 0)
  20411. {
  20412. int* chans [3];
  20413. if (writer->isFloatingPoint())
  20414. {
  20415. chans[0] = (int*) getSampleData (0, startSample);
  20416. if (numChannels > 1)
  20417. chans[1] = (int*) getSampleData (1, startSample);
  20418. else
  20419. chans[1] = 0;
  20420. chans[2] = 0;
  20421. writer->write ((const int**) chans, numSamples);
  20422. }
  20423. else
  20424. {
  20425. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  20426. if (numChannels > 1)
  20427. chans[1] = chans[0] + numSamples;
  20428. else
  20429. chans[1] = 0;
  20430. chans[2] = 0;
  20431. for (int j = 0; j < 2; ++j)
  20432. {
  20433. int* const dest = chans[j];
  20434. if (dest != 0)
  20435. {
  20436. const float* const src = channels [j] + startSample;
  20437. for (int i = 0; i < numSamples; ++i)
  20438. {
  20439. const double samp = src[i];
  20440. if (samp <= -1.0)
  20441. dest[i] = INT_MIN;
  20442. else if (samp >= 1.0)
  20443. dest[i] = INT_MAX;
  20444. else
  20445. dest[i] = roundDoubleToInt (INT_MAX * samp);
  20446. }
  20447. }
  20448. }
  20449. writer->write ((const int**) chans, numSamples);
  20450. juce_free (chans[0]);
  20451. }
  20452. }
  20453. }
  20454. END_JUCE_NAMESPACE
  20455. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  20456. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  20457. BEGIN_JUCE_NAMESPACE
  20458. IIRFilter::IIRFilter() throw()
  20459. : active (false)
  20460. {
  20461. reset();
  20462. }
  20463. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  20464. : active (other.active)
  20465. {
  20466. const ScopedLock sl (other.processLock);
  20467. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20468. reset();
  20469. }
  20470. IIRFilter::~IIRFilter() throw()
  20471. {
  20472. }
  20473. void IIRFilter::reset() throw()
  20474. {
  20475. const ScopedLock sl (processLock);
  20476. x1 = 0;
  20477. x2 = 0;
  20478. y1 = 0;
  20479. y2 = 0;
  20480. }
  20481. float IIRFilter::processSingleSampleRaw (const float in) throw()
  20482. {
  20483. float out = coefficients[0] * in
  20484. + coefficients[1] * x1
  20485. + coefficients[2] * x2
  20486. - coefficients[4] * y1
  20487. - coefficients[5] * y2;
  20488. #if JUCE_INTEL
  20489. if (! (out < -1.0e-8 || out > 1.0e-8))
  20490. out = 0;
  20491. #endif
  20492. x2 = x1;
  20493. x1 = in;
  20494. y2 = y1;
  20495. y1 = out;
  20496. return out;
  20497. }
  20498. void IIRFilter::processSamples (float* const samples,
  20499. const int numSamples) throw()
  20500. {
  20501. const ScopedLock sl (processLock);
  20502. if (active)
  20503. {
  20504. for (int i = 0; i < numSamples; ++i)
  20505. {
  20506. const float in = samples[i];
  20507. float out = coefficients[0] * in
  20508. + coefficients[1] * x1
  20509. + coefficients[2] * x2
  20510. - coefficients[4] * y1
  20511. - coefficients[5] * y2;
  20512. #if JUCE_INTEL
  20513. if (! (out < -1.0e-8 || out > 1.0e-8))
  20514. out = 0;
  20515. #endif
  20516. x2 = x1;
  20517. x1 = in;
  20518. y2 = y1;
  20519. y1 = out;
  20520. samples[i] = out;
  20521. }
  20522. }
  20523. }
  20524. void IIRFilter::makeLowPass (const double sampleRate,
  20525. const double frequency) throw()
  20526. {
  20527. jassert (sampleRate > 0);
  20528. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  20529. const double nSquared = n * n;
  20530. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20531. setCoefficients (c1,
  20532. c1 * 2.0f,
  20533. c1,
  20534. 1.0,
  20535. c1 * 2.0 * (1.0 - nSquared),
  20536. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20537. }
  20538. void IIRFilter::makeHighPass (const double sampleRate,
  20539. const double frequency) throw()
  20540. {
  20541. const double n = tan (double_Pi * frequency / sampleRate);
  20542. const double nSquared = n * n;
  20543. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  20544. setCoefficients (c1,
  20545. c1 * -2.0f,
  20546. c1,
  20547. 1.0,
  20548. c1 * 2.0 * (nSquared - 1.0),
  20549. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  20550. }
  20551. void IIRFilter::makeLowShelf (const double sampleRate,
  20552. const double cutOffFrequency,
  20553. const double Q,
  20554. const float gainFactor) throw()
  20555. {
  20556. jassert (sampleRate > 0);
  20557. jassert (Q > 0);
  20558. const double A = jmax (0.0f, gainFactor);
  20559. const double aminus1 = A - 1.0;
  20560. const double aplus1 = A + 1.0;
  20561. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20562. const double coso = cos (omega);
  20563. const double beta = sin (omega) * sqrt (A) / Q;
  20564. const double aminus1TimesCoso = aminus1 * coso;
  20565. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  20566. A * 2.0 * (aminus1 - aplus1 * coso),
  20567. A * (aplus1 - aminus1TimesCoso - beta),
  20568. aplus1 + aminus1TimesCoso + beta,
  20569. -2.0 * (aminus1 + aplus1 * coso),
  20570. aplus1 + aminus1TimesCoso - beta);
  20571. }
  20572. void IIRFilter::makeHighShelf (const double sampleRate,
  20573. const double cutOffFrequency,
  20574. const double Q,
  20575. const float gainFactor) throw()
  20576. {
  20577. jassert (sampleRate > 0);
  20578. jassert (Q > 0);
  20579. const double A = jmax (0.0f, gainFactor);
  20580. const double aminus1 = A - 1.0;
  20581. const double aplus1 = A + 1.0;
  20582. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  20583. const double coso = cos (omega);
  20584. const double beta = sin (omega) * sqrt (A) / Q;
  20585. const double aminus1TimesCoso = aminus1 * coso;
  20586. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  20587. A * -2.0 * (aminus1 + aplus1 * coso),
  20588. A * (aplus1 + aminus1TimesCoso - beta),
  20589. aplus1 - aminus1TimesCoso + beta,
  20590. 2.0 * (aminus1 - aplus1 * coso),
  20591. aplus1 - aminus1TimesCoso - beta);
  20592. }
  20593. void IIRFilter::makeBandPass (const double sampleRate,
  20594. const double centreFrequency,
  20595. const double Q,
  20596. const float gainFactor) throw()
  20597. {
  20598. jassert (sampleRate > 0);
  20599. jassert (Q > 0);
  20600. const double A = jmax (0.0f, gainFactor);
  20601. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  20602. const double alpha = 0.5 * sin (omega) / Q;
  20603. const double c2 = -2.0 * cos (omega);
  20604. const double alphaTimesA = alpha * A;
  20605. const double alphaOverA = alpha / A;
  20606. setCoefficients (1.0 + alphaTimesA,
  20607. c2,
  20608. 1.0 - alphaTimesA,
  20609. 1.0 + alphaOverA,
  20610. c2,
  20611. 1.0 - alphaOverA);
  20612. }
  20613. void IIRFilter::makeInactive() throw()
  20614. {
  20615. const ScopedLock sl (processLock);
  20616. active = false;
  20617. }
  20618. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  20619. {
  20620. const ScopedLock sl (processLock);
  20621. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  20622. active = other.active;
  20623. }
  20624. void IIRFilter::setCoefficients (double c1,
  20625. double c2,
  20626. double c3,
  20627. double c4,
  20628. double c5,
  20629. double c6) throw()
  20630. {
  20631. const double a = 1.0 / c4;
  20632. c1 *= a;
  20633. c2 *= a;
  20634. c3 *= a;
  20635. c5 *= a;
  20636. c6 *= a;
  20637. const ScopedLock sl (processLock);
  20638. coefficients[0] = (float) c1;
  20639. coefficients[1] = (float) c2;
  20640. coefficients[2] = (float) c3;
  20641. coefficients[3] = (float) c4;
  20642. coefficients[4] = (float) c5;
  20643. coefficients[5] = (float) c6;
  20644. active = true;
  20645. }
  20646. END_JUCE_NAMESPACE
  20647. /********* End of inlined file: juce_IIRFilter.cpp *********/
  20648. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  20649. BEGIN_JUCE_NAMESPACE
  20650. MidiBuffer::MidiBuffer() throw()
  20651. : ArrayAllocationBase <uint8> (32),
  20652. bytesUsed (0)
  20653. {
  20654. }
  20655. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  20656. : ArrayAllocationBase <uint8> (32),
  20657. bytesUsed (0)
  20658. {
  20659. addEvent (message, 0);
  20660. }
  20661. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  20662. : ArrayAllocationBase <uint8> (32),
  20663. bytesUsed (other.bytesUsed)
  20664. {
  20665. ensureAllocatedSize (bytesUsed);
  20666. memcpy (elements, other.elements, bytesUsed);
  20667. }
  20668. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  20669. {
  20670. if (this != &other)
  20671. {
  20672. bytesUsed = other.bytesUsed;
  20673. ensureAllocatedSize (bytesUsed);
  20674. if (bytesUsed > 0)
  20675. memcpy (elements, other.elements, bytesUsed);
  20676. }
  20677. return *this;
  20678. }
  20679. void MidiBuffer::swap (MidiBuffer& other)
  20680. {
  20681. swapVariables <uint8*> (this->elements, other.elements);
  20682. swapVariables <int> (this->numAllocated, other.numAllocated);
  20683. swapVariables <int> (this->bytesUsed, other.bytesUsed);
  20684. }
  20685. MidiBuffer::~MidiBuffer() throw()
  20686. {
  20687. }
  20688. void MidiBuffer::clear() throw()
  20689. {
  20690. bytesUsed = 0;
  20691. }
  20692. void MidiBuffer::clear (const int startSample,
  20693. const int numSamples) throw()
  20694. {
  20695. uint8* const start = findEventAfter (elements, startSample - 1);
  20696. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  20697. if (end > start)
  20698. {
  20699. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  20700. if (bytesToMove > 0)
  20701. memmove (start, end, bytesToMove);
  20702. bytesUsed -= (int) (end - start);
  20703. }
  20704. }
  20705. void MidiBuffer::addEvent (const MidiMessage& m,
  20706. const int sampleNumber) throw()
  20707. {
  20708. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  20709. }
  20710. static int findActualEventLength (const uint8* const data,
  20711. const int maxBytes) throw()
  20712. {
  20713. unsigned int byte = (unsigned int) *data;
  20714. int size = 0;
  20715. if (byte == 0xf0 || byte == 0xf7)
  20716. {
  20717. const uint8* d = data + 1;
  20718. while (d < data + maxBytes)
  20719. if (*d++ == 0xf7)
  20720. break;
  20721. size = (int) (d - data);
  20722. }
  20723. else if (byte == 0xff)
  20724. {
  20725. int n;
  20726. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  20727. size = jmin (maxBytes, n + 2 + bytesLeft);
  20728. }
  20729. else if (byte >= 0x80)
  20730. {
  20731. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  20732. }
  20733. return size;
  20734. }
  20735. void MidiBuffer::addEvent (const uint8* const newData,
  20736. const int maxBytes,
  20737. const int sampleNumber) throw()
  20738. {
  20739. const int numBytes = findActualEventLength (newData, maxBytes);
  20740. if (numBytes > 0)
  20741. {
  20742. ensureAllocatedSize (bytesUsed + numBytes + 6);
  20743. uint8* d = findEventAfter (elements, sampleNumber);
  20744. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  20745. if (bytesToMove > 0)
  20746. memmove (d + numBytes + 6,
  20747. d,
  20748. bytesToMove);
  20749. *(int*) d = sampleNumber;
  20750. d += 4;
  20751. *(uint16*) d = (uint16) numBytes;
  20752. d += 2;
  20753. memcpy (d, newData, numBytes);
  20754. bytesUsed += numBytes + 6;
  20755. }
  20756. }
  20757. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  20758. const int startSample,
  20759. const int numSamples,
  20760. const int sampleDeltaToAdd) throw()
  20761. {
  20762. Iterator i (otherBuffer);
  20763. i.setNextSamplePosition (startSample);
  20764. const uint8* data;
  20765. int size, position;
  20766. while (i.getNextEvent (data, size, position)
  20767. && (position < startSample + numSamples || numSamples < 0))
  20768. {
  20769. addEvent (data, size, position + sampleDeltaToAdd);
  20770. }
  20771. }
  20772. bool MidiBuffer::isEmpty() const throw()
  20773. {
  20774. return bytesUsed == 0;
  20775. }
  20776. int MidiBuffer::getNumEvents() const throw()
  20777. {
  20778. int n = 0;
  20779. const uint8* d = elements;
  20780. const uint8* const end = elements + bytesUsed;
  20781. while (d < end)
  20782. {
  20783. d += 4;
  20784. d += 2 + *(const uint16*) d;
  20785. ++n;
  20786. }
  20787. return n;
  20788. }
  20789. int MidiBuffer::getFirstEventTime() const throw()
  20790. {
  20791. return (bytesUsed > 0) ? *(const int*) elements : 0;
  20792. }
  20793. int MidiBuffer::getLastEventTime() const throw()
  20794. {
  20795. if (bytesUsed == 0)
  20796. return 0;
  20797. const uint8* d = elements;
  20798. const uint8* const endData = d + bytesUsed;
  20799. for (;;)
  20800. {
  20801. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  20802. if (nextOne >= endData)
  20803. return *(const int*) d;
  20804. d = nextOne;
  20805. }
  20806. }
  20807. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  20808. {
  20809. const uint8* const endData = elements + bytesUsed;
  20810. while (d < endData && *(int*) d <= samplePosition)
  20811. {
  20812. d += 4;
  20813. d += 2 + *(uint16*) d;
  20814. }
  20815. return d;
  20816. }
  20817. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  20818. : buffer (buffer),
  20819. data (buffer.elements)
  20820. {
  20821. }
  20822. MidiBuffer::Iterator::~Iterator() throw()
  20823. {
  20824. }
  20825. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  20826. {
  20827. data = buffer.elements;
  20828. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  20829. while (data < dataEnd && *(int*) data < samplePosition)
  20830. {
  20831. data += 4;
  20832. data += 2 + *(uint16*) data;
  20833. }
  20834. }
  20835. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  20836. int& numBytes,
  20837. int& samplePosition) throw()
  20838. {
  20839. if (data >= buffer.elements + buffer.bytesUsed)
  20840. return false;
  20841. samplePosition = *(int*) data;
  20842. data += 4;
  20843. numBytes = *(uint16*) data;
  20844. data += 2;
  20845. midiData = data;
  20846. data += numBytes;
  20847. return true;
  20848. }
  20849. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  20850. int& samplePosition) throw()
  20851. {
  20852. if (data >= buffer.elements + buffer.bytesUsed)
  20853. return false;
  20854. samplePosition = *(int*) data;
  20855. data += 4;
  20856. const int numBytes = *(uint16*) data;
  20857. data += 2;
  20858. result = MidiMessage (data, numBytes, samplePosition);
  20859. data += numBytes;
  20860. return true;
  20861. }
  20862. END_JUCE_NAMESPACE
  20863. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  20864. /********* Start of inlined file: juce_MidiFile.cpp *********/
  20865. BEGIN_JUCE_NAMESPACE
  20866. struct TempoInfo
  20867. {
  20868. double bpm, timestamp;
  20869. };
  20870. struct TimeSigInfo
  20871. {
  20872. int numerator, denominator;
  20873. double timestamp;
  20874. };
  20875. MidiFile::MidiFile() throw()
  20876. : numTracks (0),
  20877. timeFormat ((short)(unsigned short)0xe728)
  20878. {
  20879. }
  20880. MidiFile::~MidiFile() throw()
  20881. {
  20882. clear();
  20883. }
  20884. void MidiFile::clear() throw()
  20885. {
  20886. while (numTracks > 0)
  20887. delete tracks [--numTracks];
  20888. }
  20889. int MidiFile::getNumTracks() const throw()
  20890. {
  20891. return numTracks;
  20892. }
  20893. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  20894. {
  20895. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  20896. }
  20897. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  20898. {
  20899. jassert (numTracks < numElementsInArray (tracks));
  20900. if (numTracks < numElementsInArray (tracks))
  20901. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  20902. }
  20903. short MidiFile::getTimeFormat() const throw()
  20904. {
  20905. return timeFormat;
  20906. }
  20907. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  20908. {
  20909. timeFormat = (short)ticks;
  20910. }
  20911. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  20912. const int subframeResolution) throw()
  20913. {
  20914. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  20915. }
  20916. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  20917. {
  20918. for (int i = numTracks; --i >= 0;)
  20919. {
  20920. const int numEvents = tracks[i]->getNumEvents();
  20921. for (int j = 0; j < numEvents; ++j)
  20922. {
  20923. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20924. if (m.isTempoMetaEvent())
  20925. tempoChangeEvents.addEvent (m);
  20926. }
  20927. }
  20928. }
  20929. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  20930. {
  20931. for (int i = numTracks; --i >= 0;)
  20932. {
  20933. const int numEvents = tracks[i]->getNumEvents();
  20934. for (int j = 0; j < numEvents; ++j)
  20935. {
  20936. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  20937. if (m.isTimeSignatureMetaEvent())
  20938. timeSigEvents.addEvent (m);
  20939. }
  20940. }
  20941. }
  20942. double MidiFile::getLastTimestamp() const
  20943. {
  20944. double t = 0.0;
  20945. for (int i = numTracks; --i >= 0;)
  20946. t = jmax (t, tracks[i]->getEndTime());
  20947. return t;
  20948. }
  20949. static bool parseMidiHeader (const char* &data,
  20950. short& timeFormat,
  20951. short& fileType,
  20952. short& numberOfTracks)
  20953. {
  20954. unsigned int ch = (int) bigEndianInt (data);
  20955. data += 4;
  20956. if (ch != bigEndianInt ("MThd"))
  20957. {
  20958. bool ok = false;
  20959. if (ch == bigEndianInt ("RIFF"))
  20960. {
  20961. for (int i = 0; i < 8; ++i)
  20962. {
  20963. ch = bigEndianInt (data);
  20964. data += 4;
  20965. if (ch == bigEndianInt ("MThd"))
  20966. {
  20967. ok = true;
  20968. break;
  20969. }
  20970. }
  20971. }
  20972. if (! ok)
  20973. return false;
  20974. }
  20975. unsigned int bytesRemaining = bigEndianInt (data);
  20976. data += 4;
  20977. fileType = (short)bigEndianShort (data);
  20978. data += 2;
  20979. numberOfTracks = (short)bigEndianShort (data);
  20980. data += 2;
  20981. timeFormat = (short)bigEndianShort (data);
  20982. data += 2;
  20983. bytesRemaining -= 6;
  20984. data += bytesRemaining;
  20985. return true;
  20986. }
  20987. bool MidiFile::readFrom (InputStream& sourceStream)
  20988. {
  20989. clear();
  20990. MemoryBlock data;
  20991. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  20992. // (put a sanity-check on the file size, as midi files are generally small)
  20993. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  20994. {
  20995. int size = data.getSize();
  20996. const char* d = (char*) data.getData();
  20997. short fileType, expectedTracks;
  20998. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  20999. {
  21000. size -= (int) (d - (char*) data.getData());
  21001. int track = 0;
  21002. while (size > 0 && track < expectedTracks)
  21003. {
  21004. const int chunkType = (int)bigEndianInt (d);
  21005. d += 4;
  21006. const int chunkSize = (int)bigEndianInt (d);
  21007. d += 4;
  21008. if (chunkSize <= 0)
  21009. break;
  21010. if (size < 0)
  21011. return false;
  21012. if (chunkType == (int)bigEndianInt ("MTrk"))
  21013. {
  21014. readNextTrack (d, chunkSize);
  21015. }
  21016. size -= chunkSize + 8;
  21017. d += chunkSize;
  21018. ++track;
  21019. }
  21020. return true;
  21021. }
  21022. }
  21023. return false;
  21024. }
  21025. // a comparator that puts all the note-offs before note-ons that have the same time
  21026. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21027. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21028. {
  21029. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  21030. if (diff == 0)
  21031. {
  21032. if (first->message.isNoteOff() && second->message.isNoteOn())
  21033. return -1;
  21034. else if (first->message.isNoteOn() && second->message.isNoteOff())
  21035. return 1;
  21036. else
  21037. return 0;
  21038. }
  21039. else
  21040. {
  21041. return (diff > 0) ? 1 : -1;
  21042. }
  21043. }
  21044. void MidiFile::readNextTrack (const char* data, int size)
  21045. {
  21046. double time = 0;
  21047. char lastStatusByte = 0;
  21048. MidiMessageSequence result;
  21049. while (size > 0)
  21050. {
  21051. int bytesUsed;
  21052. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  21053. data += bytesUsed;
  21054. size -= bytesUsed;
  21055. time += delay;
  21056. int messSize = 0;
  21057. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  21058. if (messSize <= 0)
  21059. break;
  21060. size -= messSize;
  21061. data += messSize;
  21062. result.addEvent (mm);
  21063. const char firstByte = *(mm.getRawData());
  21064. if ((firstByte & 0xf0) != 0xf0)
  21065. lastStatusByte = firstByte;
  21066. }
  21067. // use a sort that puts all the note-offs before note-ons that have the same time
  21068. result.list.sort (*this, true);
  21069. result.updateMatchedPairs();
  21070. addTrack (result);
  21071. }
  21072. static double convertTicksToSeconds (const double time,
  21073. const MidiMessageSequence& tempoEvents,
  21074. const int timeFormat)
  21075. {
  21076. if (timeFormat > 0)
  21077. {
  21078. int numer = 4, denom = 4;
  21079. double tempoTime = 0.0, correctedTempoTime = 0.0;
  21080. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  21081. double secsPerTick = 0.5 * tickLen;
  21082. const int numEvents = tempoEvents.getNumEvents();
  21083. for (int i = 0; i < numEvents; ++i)
  21084. {
  21085. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  21086. if (time <= m.getTimeStamp())
  21087. break;
  21088. if (timeFormat > 0)
  21089. {
  21090. correctedTempoTime = correctedTempoTime
  21091. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  21092. }
  21093. else
  21094. {
  21095. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21096. }
  21097. tempoTime = m.getTimeStamp();
  21098. if (m.isTempoMetaEvent())
  21099. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  21100. else if (m.isTimeSignatureMetaEvent())
  21101. m.getTimeSignatureInfo (numer, denom);
  21102. while (i + 1 < numEvents)
  21103. {
  21104. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  21105. if (m2.getTimeStamp() == tempoTime)
  21106. {
  21107. ++i;
  21108. if (m2.isTempoMetaEvent())
  21109. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  21110. else if (m2.isTimeSignatureMetaEvent())
  21111. m2.getTimeSignatureInfo (numer, denom);
  21112. }
  21113. else
  21114. {
  21115. break;
  21116. }
  21117. }
  21118. }
  21119. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  21120. }
  21121. else
  21122. {
  21123. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  21124. }
  21125. }
  21126. void MidiFile::convertTimestampTicksToSeconds()
  21127. {
  21128. MidiMessageSequence tempoEvents;
  21129. findAllTempoEvents (tempoEvents);
  21130. findAllTimeSigEvents (tempoEvents);
  21131. for (int i = 0; i < numTracks; ++i)
  21132. {
  21133. MidiMessageSequence& ms = *tracks[i];
  21134. for (int j = ms.getNumEvents(); --j >= 0;)
  21135. {
  21136. MidiMessage& m = ms.getEventPointer(j)->message;
  21137. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  21138. tempoEvents,
  21139. timeFormat));
  21140. }
  21141. }
  21142. }
  21143. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  21144. {
  21145. unsigned int buffer = v & 0x7F;
  21146. while ((v >>= 7) != 0)
  21147. {
  21148. buffer <<= 8;
  21149. buffer |= ((v & 0x7F) | 0x80);
  21150. }
  21151. for (;;)
  21152. {
  21153. out.writeByte ((char) buffer);
  21154. if (buffer & 0x80)
  21155. buffer >>= 8;
  21156. else
  21157. break;
  21158. }
  21159. }
  21160. bool MidiFile::writeTo (OutputStream& out)
  21161. {
  21162. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  21163. out.writeIntBigEndian (6);
  21164. out.writeShortBigEndian (1); // type
  21165. out.writeShortBigEndian (numTracks);
  21166. out.writeShortBigEndian (timeFormat);
  21167. for (int i = 0; i < numTracks; ++i)
  21168. writeTrack (out, i);
  21169. out.flush();
  21170. return true;
  21171. }
  21172. void MidiFile::writeTrack (OutputStream& mainOut,
  21173. const int trackNum)
  21174. {
  21175. MemoryOutputStream out;
  21176. const MidiMessageSequence& ms = *tracks[trackNum];
  21177. int lastTick = 0;
  21178. char lastStatusByte = 0;
  21179. for (int i = 0; i < ms.getNumEvents(); ++i)
  21180. {
  21181. const MidiMessage& mm = ms.getEventPointer(i)->message;
  21182. const int tick = roundDoubleToInt (mm.getTimeStamp());
  21183. const int delta = jmax (0, tick - lastTick);
  21184. writeVariableLengthInt (out, delta);
  21185. lastTick = tick;
  21186. const char statusByte = *(mm.getRawData());
  21187. if ((statusByte == lastStatusByte)
  21188. && ((statusByte & 0xf0) != 0xf0)
  21189. && i > 0
  21190. && mm.getRawDataSize() > 1)
  21191. {
  21192. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  21193. }
  21194. else
  21195. {
  21196. out.write (mm.getRawData(), mm.getRawDataSize());
  21197. }
  21198. lastStatusByte = statusByte;
  21199. }
  21200. out.writeByte (0);
  21201. const MidiMessage m (MidiMessage::endOfTrack());
  21202. out.write (m.getRawData(),
  21203. m.getRawDataSize());
  21204. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  21205. mainOut.writeIntBigEndian (out.getDataSize());
  21206. mainOut.write (out.getData(), out.getDataSize());
  21207. }
  21208. END_JUCE_NAMESPACE
  21209. /********* End of inlined file: juce_MidiFile.cpp *********/
  21210. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  21211. BEGIN_JUCE_NAMESPACE
  21212. MidiKeyboardState::MidiKeyboardState()
  21213. : listeners (2)
  21214. {
  21215. zeromem (noteStates, sizeof (noteStates));
  21216. }
  21217. MidiKeyboardState::~MidiKeyboardState()
  21218. {
  21219. }
  21220. void MidiKeyboardState::reset()
  21221. {
  21222. const ScopedLock sl (lock);
  21223. zeromem (noteStates, sizeof (noteStates));
  21224. eventsToAdd.clear();
  21225. }
  21226. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  21227. {
  21228. jassert (midiChannel >= 0 && midiChannel <= 16);
  21229. return ((unsigned int) n) < 128
  21230. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  21231. }
  21232. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  21233. {
  21234. return ((unsigned int) n) < 128
  21235. && (noteStates[n] & midiChannelMask) != 0;
  21236. }
  21237. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  21238. {
  21239. jassert (midiChannel >= 0 && midiChannel <= 16);
  21240. jassert (((unsigned int) midiNoteNumber) < 128);
  21241. const ScopedLock sl (lock);
  21242. if (((unsigned int) midiNoteNumber) < 128)
  21243. {
  21244. const int timeNow = (int) Time::getMillisecondCounter();
  21245. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  21246. eventsToAdd.clear (0, timeNow - 500);
  21247. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  21248. }
  21249. }
  21250. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  21251. {
  21252. if (((unsigned int) midiNoteNumber) < 128)
  21253. {
  21254. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  21255. for (int i = listeners.size(); --i >= 0;)
  21256. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21257. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  21258. }
  21259. }
  21260. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  21261. {
  21262. const ScopedLock sl (lock);
  21263. if (isNoteOn (midiChannel, midiNoteNumber))
  21264. {
  21265. const int timeNow = (int) Time::getMillisecondCounter();
  21266. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  21267. eventsToAdd.clear (0, timeNow - 500);
  21268. noteOffInternal (midiChannel, midiNoteNumber);
  21269. }
  21270. }
  21271. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  21272. {
  21273. if (isNoteOn (midiChannel, midiNoteNumber))
  21274. {
  21275. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  21276. for (int i = listeners.size(); --i >= 0;)
  21277. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  21278. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  21279. }
  21280. }
  21281. void MidiKeyboardState::allNotesOff (const int midiChannel)
  21282. {
  21283. const ScopedLock sl (lock);
  21284. if (midiChannel <= 0)
  21285. {
  21286. for (int i = 1; i <= 16; ++i)
  21287. allNotesOff (i);
  21288. }
  21289. else
  21290. {
  21291. for (int i = 0; i < 128; ++i)
  21292. noteOff (midiChannel, i);
  21293. }
  21294. }
  21295. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  21296. {
  21297. if (message.isNoteOn())
  21298. {
  21299. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  21300. }
  21301. else if (message.isNoteOff())
  21302. {
  21303. noteOffInternal (message.getChannel(), message.getNoteNumber());
  21304. }
  21305. else if (message.isAllNotesOff())
  21306. {
  21307. for (int i = 0; i < 128; ++i)
  21308. noteOffInternal (message.getChannel(), i);
  21309. }
  21310. }
  21311. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  21312. const int startSample,
  21313. const int numSamples,
  21314. const bool injectIndirectEvents)
  21315. {
  21316. MidiBuffer::Iterator i (buffer);
  21317. MidiMessage message (0xf4, 0.0);
  21318. int time;
  21319. const ScopedLock sl (lock);
  21320. while (i.getNextEvent (message, time))
  21321. processNextMidiEvent (message);
  21322. if (injectIndirectEvents)
  21323. {
  21324. MidiBuffer::Iterator i2 (eventsToAdd);
  21325. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  21326. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  21327. while (i2.getNextEvent (message, time))
  21328. {
  21329. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  21330. buffer.addEvent (message, startSample + pos);
  21331. }
  21332. }
  21333. eventsToAdd.clear();
  21334. }
  21335. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  21336. {
  21337. const ScopedLock sl (lock);
  21338. listeners.addIfNotAlreadyThere (listener);
  21339. }
  21340. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  21341. {
  21342. const ScopedLock sl (lock);
  21343. listeners.removeValue (listener);
  21344. }
  21345. END_JUCE_NAMESPACE
  21346. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  21347. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  21348. BEGIN_JUCE_NAMESPACE
  21349. int MidiMessage::readVariableLengthVal (const uint8* data,
  21350. int& numBytesUsed) throw()
  21351. {
  21352. numBytesUsed = 0;
  21353. int v = 0;
  21354. int i;
  21355. do
  21356. {
  21357. i = (int) *data++;
  21358. if (++numBytesUsed > 6)
  21359. break;
  21360. v = (v << 7) + (i & 0x7f);
  21361. } while (i & 0x80);
  21362. return v;
  21363. }
  21364. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  21365. {
  21366. // this method only works for valid starting bytes of a short midi message
  21367. jassert (firstByte >= 0x80
  21368. && firstByte != 0xf0
  21369. && firstByte != 0xf7);
  21370. static const char messageLengths[] =
  21371. {
  21372. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21373. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21374. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21375. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21376. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21377. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  21378. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  21379. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  21380. };
  21381. return messageLengths [firstByte & 0x7f];
  21382. }
  21383. MidiMessage::MidiMessage (const uint8* const d,
  21384. const int dataSize,
  21385. const double t) throw()
  21386. : timeStamp (t),
  21387. message (0),
  21388. size (dataSize)
  21389. {
  21390. jassert (dataSize > 0);
  21391. if (dataSize <= 4)
  21392. data = (uint8*) &message;
  21393. else
  21394. data = (uint8*) juce_malloc (dataSize);
  21395. memcpy (data, d, dataSize);
  21396. // check that the length matches the data..
  21397. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  21398. }
  21399. MidiMessage::MidiMessage (const int byte1,
  21400. const double t) throw()
  21401. : timeStamp (t),
  21402. data ((uint8*) &message),
  21403. size (1)
  21404. {
  21405. data[0] = (uint8) byte1;
  21406. // check that the length matches the data..
  21407. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  21408. }
  21409. MidiMessage::MidiMessage (const int byte1,
  21410. const int byte2,
  21411. const double t) throw()
  21412. : timeStamp (t),
  21413. data ((uint8*) &message),
  21414. size (2)
  21415. {
  21416. data[0] = (uint8) byte1;
  21417. data[1] = (uint8) byte2;
  21418. // check that the length matches the data..
  21419. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  21420. }
  21421. MidiMessage::MidiMessage (const int byte1,
  21422. const int byte2,
  21423. const int byte3,
  21424. const double t) throw()
  21425. : timeStamp (t),
  21426. data ((uint8*) &message),
  21427. size (3)
  21428. {
  21429. data[0] = (uint8) byte1;
  21430. data[1] = (uint8) byte2;
  21431. data[2] = (uint8) byte3;
  21432. // check that the length matches the data..
  21433. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  21434. }
  21435. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  21436. : timeStamp (other.timeStamp),
  21437. message (other.message),
  21438. size (other.size)
  21439. {
  21440. if (other.data != (uint8*) &other.message)
  21441. {
  21442. data = (uint8*) juce_malloc (size);
  21443. memcpy (data, other.data, size);
  21444. }
  21445. else
  21446. {
  21447. data = (uint8*) &message;
  21448. }
  21449. }
  21450. MidiMessage::MidiMessage (const MidiMessage& other,
  21451. const double newTimeStamp) throw()
  21452. : timeStamp (newTimeStamp),
  21453. message (other.message),
  21454. size (other.size)
  21455. {
  21456. if (other.data != (uint8*) &other.message)
  21457. {
  21458. data = (uint8*) juce_malloc (size);
  21459. memcpy (data, other.data, size);
  21460. }
  21461. else
  21462. {
  21463. data = (uint8*) &message;
  21464. }
  21465. }
  21466. MidiMessage::MidiMessage (const uint8* src,
  21467. int sz,
  21468. int& numBytesUsed,
  21469. const uint8 lastStatusByte,
  21470. double t) throw()
  21471. : timeStamp (t),
  21472. data ((uint8*) &message),
  21473. message (0)
  21474. {
  21475. unsigned int byte = (unsigned int) *src;
  21476. if (byte < 0x80)
  21477. {
  21478. byte = (unsigned int) (uint8) lastStatusByte;
  21479. numBytesUsed = -1;
  21480. }
  21481. else
  21482. {
  21483. numBytesUsed = 0;
  21484. --sz;
  21485. ++src;
  21486. }
  21487. if (byte >= 0x80)
  21488. {
  21489. if (byte == 0xf0)
  21490. {
  21491. const uint8* d = (const uint8*) src;
  21492. while (d < src + sz)
  21493. {
  21494. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  21495. {
  21496. if (*d == 0xf7) // include an 0xf7 if we hit one
  21497. ++d;
  21498. break;
  21499. }
  21500. ++d;
  21501. }
  21502. size = 1 + (int) (d - src);
  21503. data = (uint8*) juce_malloc (size);
  21504. *data = (uint8) byte;
  21505. memcpy (data + 1, src, size - 1);
  21506. }
  21507. else if (byte == 0xff)
  21508. {
  21509. int n;
  21510. const int bytesLeft = readVariableLengthVal (src + 1, n);
  21511. size = jmin (sz + 1, n + 2 + bytesLeft);
  21512. data = (uint8*) juce_malloc (size);
  21513. *data = (uint8) byte;
  21514. memcpy (data + 1, src, size - 1);
  21515. }
  21516. else
  21517. {
  21518. size = getMessageLengthFromFirstByte ((uint8) byte);
  21519. *data = (uint8) byte;
  21520. if (size > 1)
  21521. {
  21522. data[1] = src[0];
  21523. if (size > 2)
  21524. data[2] = src[1];
  21525. }
  21526. }
  21527. numBytesUsed += size;
  21528. }
  21529. else
  21530. {
  21531. message = 0;
  21532. size = 0;
  21533. }
  21534. }
  21535. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  21536. {
  21537. if (this == &other)
  21538. return *this;
  21539. timeStamp = other.timeStamp;
  21540. size = other.size;
  21541. message = other.message;
  21542. if (data != (uint8*) &message)
  21543. juce_free (data);
  21544. if (other.data != (uint8*) &other.message)
  21545. {
  21546. data = (uint8*) juce_malloc (size);
  21547. memcpy (data, other.data, size);
  21548. }
  21549. else
  21550. {
  21551. data = (uint8*) &message;
  21552. }
  21553. return *this;
  21554. }
  21555. MidiMessage::~MidiMessage() throw()
  21556. {
  21557. if (data != (uint8*) &message)
  21558. juce_free (data);
  21559. }
  21560. int MidiMessage::getChannel() const throw()
  21561. {
  21562. if ((data[0] & 0xf0) != 0xf0)
  21563. return (data[0] & 0xf) + 1;
  21564. else
  21565. return 0;
  21566. }
  21567. bool MidiMessage::isForChannel (const int channel) const throw()
  21568. {
  21569. return ((data[0] & 0xf) == channel - 1)
  21570. && ((data[0] & 0xf0) != 0xf0);
  21571. }
  21572. void MidiMessage::setChannel (const int channel) throw()
  21573. {
  21574. if ((data[0] & 0xf0) != (uint8) 0xf0)
  21575. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  21576. | (uint8)(channel - 1));
  21577. }
  21578. bool MidiMessage::isNoteOn() const throw()
  21579. {
  21580. return ((data[0] & 0xf0) == 0x90)
  21581. && (data[2] != 0);
  21582. }
  21583. bool MidiMessage::isNoteOff() const throw()
  21584. {
  21585. return ((data[0] & 0xf0) == 0x80)
  21586. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  21587. }
  21588. bool MidiMessage::isNoteOnOrOff() const throw()
  21589. {
  21590. const int d = data[0] & 0xf0;
  21591. return (d == 0x90) || (d == 0x80);
  21592. }
  21593. int MidiMessage::getNoteNumber() const throw()
  21594. {
  21595. return data[1];
  21596. }
  21597. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  21598. {
  21599. if (isNoteOnOrOff())
  21600. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  21601. }
  21602. uint8 MidiMessage::getVelocity() const throw()
  21603. {
  21604. if (isNoteOnOrOff())
  21605. return data[2];
  21606. else
  21607. return 0;
  21608. }
  21609. float MidiMessage::getFloatVelocity() const throw()
  21610. {
  21611. return getVelocity() * (1.0f / 127.0f);
  21612. }
  21613. void MidiMessage::setVelocity (const float newVelocity) throw()
  21614. {
  21615. if (isNoteOnOrOff())
  21616. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  21617. }
  21618. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  21619. {
  21620. if (isNoteOnOrOff())
  21621. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  21622. }
  21623. bool MidiMessage::isAftertouch() const throw()
  21624. {
  21625. return (data[0] & 0xf0) == 0xa0;
  21626. }
  21627. int MidiMessage::getAfterTouchValue() const throw()
  21628. {
  21629. return data[2];
  21630. }
  21631. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  21632. const int noteNum,
  21633. const int aftertouchValue) throw()
  21634. {
  21635. jassert (channel > 0 && channel <= 16);
  21636. jassert (((unsigned int) noteNum) <= 127);
  21637. jassert (((unsigned int) aftertouchValue) <= 127);
  21638. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  21639. noteNum & 0x7f,
  21640. aftertouchValue & 0x7f);
  21641. }
  21642. bool MidiMessage::isChannelPressure() const throw()
  21643. {
  21644. return (data[0] & 0xf0) == 0xd0;
  21645. }
  21646. int MidiMessage::getChannelPressureValue() const throw()
  21647. {
  21648. jassert (isChannelPressure());
  21649. return data[1];
  21650. }
  21651. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  21652. const int pressure) throw()
  21653. {
  21654. jassert (channel > 0 && channel <= 16);
  21655. jassert (((unsigned int) pressure) <= 127);
  21656. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  21657. pressure & 0x7f);
  21658. }
  21659. bool MidiMessage::isProgramChange() const throw()
  21660. {
  21661. return (data[0] & 0xf0) == 0xc0;
  21662. }
  21663. int MidiMessage::getProgramChangeNumber() const throw()
  21664. {
  21665. return data[1];
  21666. }
  21667. const MidiMessage MidiMessage::programChange (const int channel,
  21668. const int programNumber) throw()
  21669. {
  21670. jassert (channel > 0 && channel <= 16);
  21671. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  21672. programNumber & 0x7f);
  21673. }
  21674. bool MidiMessage::isPitchWheel() const throw()
  21675. {
  21676. return (data[0] & 0xf0) == 0xe0;
  21677. }
  21678. int MidiMessage::getPitchWheelValue() const throw()
  21679. {
  21680. return data[1] | (data[2] << 7);
  21681. }
  21682. const MidiMessage MidiMessage::pitchWheel (const int channel,
  21683. const int position) throw()
  21684. {
  21685. jassert (channel > 0 && channel <= 16);
  21686. jassert (((unsigned int) position) <= 0x3fff);
  21687. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  21688. position & 127,
  21689. (position >> 7) & 127);
  21690. }
  21691. bool MidiMessage::isController() const throw()
  21692. {
  21693. return (data[0] & 0xf0) == 0xb0;
  21694. }
  21695. int MidiMessage::getControllerNumber() const throw()
  21696. {
  21697. jassert (isController());
  21698. return data[1];
  21699. }
  21700. int MidiMessage::getControllerValue() const throw()
  21701. {
  21702. jassert (isController());
  21703. return data[2];
  21704. }
  21705. const MidiMessage MidiMessage::controllerEvent (const int channel,
  21706. const int controllerType,
  21707. const int value) throw()
  21708. {
  21709. // the channel must be between 1 and 16 inclusive
  21710. jassert (channel > 0 && channel <= 16);
  21711. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  21712. controllerType & 127,
  21713. value & 127);
  21714. }
  21715. const MidiMessage MidiMessage::noteOn (const int channel,
  21716. const int noteNumber,
  21717. const float velocity) throw()
  21718. {
  21719. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  21720. }
  21721. const MidiMessage MidiMessage::noteOn (const int channel,
  21722. const int noteNumber,
  21723. const uint8 velocity) throw()
  21724. {
  21725. jassert (channel > 0 && channel <= 16);
  21726. jassert (((unsigned int) noteNumber) <= 127);
  21727. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  21728. noteNumber & 127,
  21729. jlimit (0, 127, roundFloatToInt (velocity)));
  21730. }
  21731. const MidiMessage MidiMessage::noteOff (const int channel,
  21732. const int noteNumber) throw()
  21733. {
  21734. jassert (channel > 0 && channel <= 16);
  21735. jassert (((unsigned int) noteNumber) <= 127);
  21736. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  21737. }
  21738. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  21739. {
  21740. jassert (channel > 0 && channel <= 16);
  21741. return controllerEvent (channel, 123, 0);
  21742. }
  21743. bool MidiMessage::isAllNotesOff() const throw()
  21744. {
  21745. return (data[0] & 0xf0) == 0xb0
  21746. && data[1] == 123;
  21747. }
  21748. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  21749. {
  21750. return controllerEvent (channel, 120, 0);
  21751. }
  21752. bool MidiMessage::isAllSoundOff() const throw()
  21753. {
  21754. return (data[0] & 0xf0) == 0xb0
  21755. && data[1] == 120;
  21756. }
  21757. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  21758. {
  21759. return controllerEvent (channel, 121, 0);
  21760. }
  21761. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  21762. {
  21763. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  21764. uint8 buf[8];
  21765. buf[0] = 0xf0;
  21766. buf[1] = 0x7f;
  21767. buf[2] = 0x7f;
  21768. buf[3] = 0x04;
  21769. buf[4] = 0x01;
  21770. buf[5] = (uint8) (vol & 0x7f);
  21771. buf[6] = (uint8) (vol >> 7);
  21772. buf[7] = 0xf7;
  21773. return MidiMessage (buf, 8);
  21774. }
  21775. bool MidiMessage::isSysEx() const throw()
  21776. {
  21777. return *data == 0xf0;
  21778. }
  21779. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  21780. const int dataSize) throw()
  21781. {
  21782. MemoryBlock mm (dataSize + 2);
  21783. uint8* const m = (uint8*) mm.getData();
  21784. m[0] = 0xf0;
  21785. memcpy (m + 1, sysexData, dataSize);
  21786. m[dataSize + 1] = 0xf7;
  21787. return MidiMessage (m, dataSize + 2);
  21788. }
  21789. const uint8* MidiMessage::getSysExData() const throw()
  21790. {
  21791. return (isSysEx()) ? getRawData() + 1
  21792. : 0;
  21793. }
  21794. int MidiMessage::getSysExDataSize() const throw()
  21795. {
  21796. return (isSysEx()) ? size - 2
  21797. : 0;
  21798. }
  21799. bool MidiMessage::isMetaEvent() const throw()
  21800. {
  21801. return *data == 0xff;
  21802. }
  21803. bool MidiMessage::isActiveSense() const throw()
  21804. {
  21805. return *data == 0xfe;
  21806. }
  21807. int MidiMessage::getMetaEventType() const throw()
  21808. {
  21809. if (*data != 0xff)
  21810. return -1;
  21811. else
  21812. return data[1];
  21813. }
  21814. int MidiMessage::getMetaEventLength() const throw()
  21815. {
  21816. if (*data == 0xff)
  21817. {
  21818. int n;
  21819. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  21820. }
  21821. return 0;
  21822. }
  21823. const uint8* MidiMessage::getMetaEventData() const throw()
  21824. {
  21825. int n;
  21826. const uint8* d = data + 2;
  21827. readVariableLengthVal (d, n);
  21828. return d + n;
  21829. }
  21830. bool MidiMessage::isTrackMetaEvent() const throw()
  21831. {
  21832. return getMetaEventType() == 0;
  21833. }
  21834. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  21835. {
  21836. return getMetaEventType() == 47;
  21837. }
  21838. bool MidiMessage::isTextMetaEvent() const throw()
  21839. {
  21840. const int t = getMetaEventType();
  21841. return t > 0 && t < 16;
  21842. }
  21843. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  21844. {
  21845. return String ((const char*) getMetaEventData(),
  21846. getMetaEventLength());
  21847. }
  21848. bool MidiMessage::isTrackNameEvent() const throw()
  21849. {
  21850. return (data[1] == 3)
  21851. && (*data == 0xff);
  21852. }
  21853. bool MidiMessage::isTempoMetaEvent() const throw()
  21854. {
  21855. return (data[1] == 81)
  21856. && (*data == 0xff);
  21857. }
  21858. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  21859. {
  21860. return (data[1] == 0x20)
  21861. && (*data == 0xff)
  21862. && (data[2] == 1);
  21863. }
  21864. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  21865. {
  21866. return data[3] + 1;
  21867. }
  21868. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  21869. {
  21870. if (! isTempoMetaEvent())
  21871. return 0.0;
  21872. const uint8* const d = getMetaEventData();
  21873. return (((unsigned int) d[0] << 16)
  21874. | ((unsigned int) d[1] << 8)
  21875. | d[2])
  21876. / 1000000.0;
  21877. }
  21878. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  21879. {
  21880. if (timeFormat > 0)
  21881. {
  21882. if (! isTempoMetaEvent())
  21883. return 0.5 / timeFormat;
  21884. return getTempoSecondsPerQuarterNote() / timeFormat;
  21885. }
  21886. else
  21887. {
  21888. const int frameCode = (-timeFormat) >> 8;
  21889. double framesPerSecond;
  21890. switch (frameCode)
  21891. {
  21892. case 24: framesPerSecond = 24.0; break;
  21893. case 25: framesPerSecond = 25.0; break;
  21894. case 29: framesPerSecond = 29.97; break;
  21895. case 30: framesPerSecond = 30.0; break;
  21896. default: framesPerSecond = 30.0; break;
  21897. }
  21898. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  21899. }
  21900. }
  21901. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  21902. {
  21903. uint8 d[8];
  21904. d[0] = 0xff;
  21905. d[1] = 81;
  21906. d[2] = 3;
  21907. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  21908. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  21909. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  21910. return MidiMessage (d, 6, 0.0);
  21911. }
  21912. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  21913. {
  21914. return (data[1] == 0x58)
  21915. && (*data == (uint8) 0xff);
  21916. }
  21917. void MidiMessage::getTimeSignatureInfo (int& numerator,
  21918. int& denominator) const throw()
  21919. {
  21920. if (isTimeSignatureMetaEvent())
  21921. {
  21922. const uint8* const d = getMetaEventData();
  21923. numerator = d[0];
  21924. denominator = 1 << d[1];
  21925. }
  21926. else
  21927. {
  21928. numerator = 4;
  21929. denominator = 4;
  21930. }
  21931. }
  21932. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  21933. const int denominator) throw()
  21934. {
  21935. uint8 d[8];
  21936. d[0] = 0xff;
  21937. d[1] = 0x58;
  21938. d[2] = 0x04;
  21939. d[3] = (uint8) numerator;
  21940. int n = 1;
  21941. int powerOfTwo = 0;
  21942. while (n < denominator)
  21943. {
  21944. n <<= 1;
  21945. ++powerOfTwo;
  21946. }
  21947. d[4] = (uint8) powerOfTwo;
  21948. d[5] = 0x01;
  21949. d[6] = 96;
  21950. return MidiMessage (d, 7, 0.0);
  21951. }
  21952. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  21953. {
  21954. uint8 d[8];
  21955. d[0] = 0xff;
  21956. d[1] = 0x20;
  21957. d[2] = 0x01;
  21958. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  21959. return MidiMessage (d, 4, 0.0);
  21960. }
  21961. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  21962. {
  21963. return getMetaEventType() == 89;
  21964. }
  21965. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  21966. {
  21967. return (int) *getMetaEventData();
  21968. }
  21969. const MidiMessage MidiMessage::endOfTrack() throw()
  21970. {
  21971. return MidiMessage (0xff, 0x2f, 0, 0.0);
  21972. }
  21973. bool MidiMessage::isSongPositionPointer() const throw()
  21974. {
  21975. return *data == 0xf2;
  21976. }
  21977. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  21978. {
  21979. return data[1] | (data[2] << 7);
  21980. }
  21981. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  21982. {
  21983. return MidiMessage (0xf2,
  21984. positionInMidiBeats & 127,
  21985. (positionInMidiBeats >> 7) & 127);
  21986. }
  21987. bool MidiMessage::isMidiStart() const throw()
  21988. {
  21989. return *data == 0xfa;
  21990. }
  21991. const MidiMessage MidiMessage::midiStart() throw()
  21992. {
  21993. return MidiMessage (0xfa);
  21994. }
  21995. bool MidiMessage::isMidiContinue() const throw()
  21996. {
  21997. return *data == 0xfb;
  21998. }
  21999. const MidiMessage MidiMessage::midiContinue() throw()
  22000. {
  22001. return MidiMessage (0xfb);
  22002. }
  22003. bool MidiMessage::isMidiStop() const throw()
  22004. {
  22005. return *data == 0xfc;
  22006. }
  22007. const MidiMessage MidiMessage::midiStop() throw()
  22008. {
  22009. return MidiMessage (0xfc);
  22010. }
  22011. bool MidiMessage::isMidiClock() const throw()
  22012. {
  22013. return *data == 0xf8;
  22014. }
  22015. const MidiMessage MidiMessage::midiClock() throw()
  22016. {
  22017. return MidiMessage (0xf8);
  22018. }
  22019. bool MidiMessage::isQuarterFrame() const throw()
  22020. {
  22021. return *data == 0xf1;
  22022. }
  22023. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  22024. {
  22025. return ((int) data[1]) >> 4;
  22026. }
  22027. int MidiMessage::getQuarterFrameValue() const throw()
  22028. {
  22029. return ((int) data[1]) & 0x0f;
  22030. }
  22031. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  22032. const int value) throw()
  22033. {
  22034. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  22035. }
  22036. bool MidiMessage::isFullFrame() const throw()
  22037. {
  22038. return data[0] == 0xf0
  22039. && data[1] == 0x7f
  22040. && size >= 10
  22041. && data[3] == 0x01
  22042. && data[4] == 0x01;
  22043. }
  22044. void MidiMessage::getFullFrameParameters (int& hours,
  22045. int& minutes,
  22046. int& seconds,
  22047. int& frames,
  22048. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  22049. {
  22050. jassert (isFullFrame());
  22051. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  22052. hours = data[5] & 0x1f;
  22053. minutes = data[6];
  22054. seconds = data[7];
  22055. frames = data[8];
  22056. }
  22057. const MidiMessage MidiMessage::fullFrame (const int hours,
  22058. const int minutes,
  22059. const int seconds,
  22060. const int frames,
  22061. MidiMessage::SmpteTimecodeType timecodeType)
  22062. {
  22063. uint8 d[10];
  22064. d[0] = 0xf0;
  22065. d[1] = 0x7f;
  22066. d[2] = 0x7f;
  22067. d[3] = 0x01;
  22068. d[4] = 0x01;
  22069. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  22070. d[6] = (uint8) minutes;
  22071. d[7] = (uint8) seconds;
  22072. d[8] = (uint8) frames;
  22073. d[9] = 0xf7;
  22074. return MidiMessage (d, 10, 0.0);
  22075. }
  22076. bool MidiMessage::isMidiMachineControlMessage() const throw()
  22077. {
  22078. return data[0] == 0xf0
  22079. && data[1] == 0x7f
  22080. && data[3] == 0x06
  22081. && size > 5;
  22082. }
  22083. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  22084. {
  22085. jassert (isMidiMachineControlMessage());
  22086. return (MidiMachineControlCommand) data[4];
  22087. }
  22088. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  22089. {
  22090. uint8 d[6];
  22091. d[0] = 0xf0;
  22092. d[1] = 0x7f;
  22093. d[2] = 0x00;
  22094. d[3] = 0x06;
  22095. d[4] = (uint8) command;
  22096. d[5] = 0xf7;
  22097. return MidiMessage (d, 6, 0.0);
  22098. }
  22099. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  22100. int& minutes,
  22101. int& seconds,
  22102. int& frames) const throw()
  22103. {
  22104. if (size >= 12
  22105. && data[0] == 0xf0
  22106. && data[1] == 0x7f
  22107. && data[3] == 0x06
  22108. && data[4] == 0x44
  22109. && data[5] == 0x06
  22110. && data[6] == 0x01)
  22111. {
  22112. hours = data[7] % 24; // (that some machines send out hours > 24)
  22113. minutes = data[8];
  22114. seconds = data[9];
  22115. frames = data[10];
  22116. return true;
  22117. }
  22118. return false;
  22119. }
  22120. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  22121. int minutes,
  22122. int seconds,
  22123. int frames)
  22124. {
  22125. uint8 d[12];
  22126. d[0] = 0xf0;
  22127. d[1] = 0x7f;
  22128. d[2] = 0x00;
  22129. d[3] = 0x06;
  22130. d[4] = 0x44;
  22131. d[5] = 0x06;
  22132. d[6] = 0x01;
  22133. d[7] = (uint8) hours;
  22134. d[8] = (uint8) minutes;
  22135. d[9] = (uint8) seconds;
  22136. d[10] = (uint8) frames;
  22137. d[11] = 0xf7;
  22138. return MidiMessage (d, 12, 0.0);
  22139. }
  22140. const String MidiMessage::getMidiNoteName (int note,
  22141. bool useSharps,
  22142. bool includeOctaveNumber,
  22143. int octaveNumForMiddleC) throw()
  22144. {
  22145. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  22146. "F", "F#", "G", "G#", "A",
  22147. "A#", "B" };
  22148. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  22149. "F", "Gb", "G", "Ab", "A",
  22150. "Bb", "B" };
  22151. if (((unsigned int) note) < 128)
  22152. {
  22153. const String s ((useSharps) ? sharpNoteNames [note % 12]
  22154. : flatNoteNames [note % 12]);
  22155. if (includeOctaveNumber)
  22156. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  22157. else
  22158. return s;
  22159. }
  22160. return String::empty;
  22161. }
  22162. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  22163. {
  22164. noteNumber -= 12 * 6 + 9; // now 0 = A440
  22165. return 440.0 * pow (2.0, noteNumber / 12.0);
  22166. }
  22167. const String MidiMessage::getGMInstrumentName (int n) throw()
  22168. {
  22169. const char *names[] =
  22170. {
  22171. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  22172. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  22173. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  22174. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  22175. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  22176. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  22177. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  22178. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  22179. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  22180. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  22181. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  22182. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  22183. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  22184. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  22185. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  22186. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  22187. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  22188. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  22189. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  22190. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  22191. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  22192. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  22193. "Applause", "Gunshot"
  22194. };
  22195. return (((unsigned int) n) < 128) ? names[n]
  22196. : (const char*)0;
  22197. }
  22198. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  22199. {
  22200. const char* names[] =
  22201. {
  22202. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  22203. "Bass", "Strings", "Ensemble", "Brass",
  22204. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  22205. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  22206. };
  22207. return (((unsigned int) n) <= 15) ? names[n]
  22208. : (const char*)0;
  22209. }
  22210. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  22211. {
  22212. const char* names[] =
  22213. {
  22214. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  22215. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  22216. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  22217. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  22218. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  22219. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  22220. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  22221. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  22222. "Mute Triangle", "Open Triangle"
  22223. };
  22224. return (n >= 35 && n <= 81) ? names [n - 35]
  22225. : (const char*)0;
  22226. }
  22227. const String MidiMessage::getControllerName (int n) throw()
  22228. {
  22229. const char* names[] =
  22230. {
  22231. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  22232. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  22233. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  22234. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  22235. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  22236. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  22237. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  22238. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  22239. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  22240. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  22241. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  22242. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  22243. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  22244. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  22245. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  22246. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  22247. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  22248. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  22249. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  22250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  22251. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  22252. "Poly Operation"
  22253. };
  22254. return (((unsigned int) n) < 128) ? names[n]
  22255. : (const char*)0;
  22256. }
  22257. END_JUCE_NAMESPACE
  22258. /********* End of inlined file: juce_MidiMessage.cpp *********/
  22259. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  22260. BEGIN_JUCE_NAMESPACE
  22261. MidiMessageCollector::MidiMessageCollector()
  22262. : lastCallbackTime (0),
  22263. sampleRate (44100.0001)
  22264. {
  22265. }
  22266. MidiMessageCollector::~MidiMessageCollector()
  22267. {
  22268. }
  22269. void MidiMessageCollector::reset (const double sampleRate_)
  22270. {
  22271. jassert (sampleRate_ > 0);
  22272. const ScopedLock sl (midiCallbackLock);
  22273. sampleRate = sampleRate_;
  22274. incomingMessages.clear();
  22275. lastCallbackTime = Time::getMillisecondCounterHiRes();
  22276. }
  22277. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  22278. {
  22279. // you need to call reset() to set the correct sample rate before using this object
  22280. jassert (sampleRate != 44100.0001);
  22281. // the messages that come in here need to be time-stamped correctly - see MidiInput
  22282. // for details of what the number should be.
  22283. jassert (message.getTimeStamp() != 0);
  22284. const ScopedLock sl (midiCallbackLock);
  22285. const int sampleNumber
  22286. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  22287. incomingMessages.addEvent (message, sampleNumber);
  22288. // if the messages don't get used for over a second, we'd better
  22289. // get rid of any old ones to avoid the queue getting too big
  22290. if (sampleNumber > sampleRate)
  22291. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  22292. }
  22293. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  22294. const int numSamples)
  22295. {
  22296. // you need to call reset() to set the correct sample rate before using this object
  22297. jassert (sampleRate != 44100.0001);
  22298. const double timeNow = Time::getMillisecondCounterHiRes();
  22299. const double msElapsed = timeNow - lastCallbackTime;
  22300. const ScopedLock sl (midiCallbackLock);
  22301. lastCallbackTime = timeNow;
  22302. if (! incomingMessages.isEmpty())
  22303. {
  22304. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  22305. int startSample = 0;
  22306. int scale = 1 << 16;
  22307. const uint8* midiData;
  22308. int numBytes, samplePosition;
  22309. MidiBuffer::Iterator iter (incomingMessages);
  22310. if (numSourceSamples > numSamples)
  22311. {
  22312. // if our list of events is longer than the buffer we're being
  22313. // asked for, scale them down to squeeze them all in..
  22314. const int maxBlockLengthToUse = numSamples << 5;
  22315. if (numSourceSamples > maxBlockLengthToUse)
  22316. {
  22317. startSample = numSourceSamples - maxBlockLengthToUse;
  22318. numSourceSamples = maxBlockLengthToUse;
  22319. iter.setNextSamplePosition (startSample);
  22320. }
  22321. scale = (numSamples << 10) / numSourceSamples;
  22322. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22323. {
  22324. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  22325. destBuffer.addEvent (midiData, numBytes,
  22326. jlimit (0, numSamples - 1, samplePosition));
  22327. }
  22328. }
  22329. else
  22330. {
  22331. // if our event list is shorter than the number we need, put them
  22332. // towards the end of the buffer
  22333. startSample = numSamples - numSourceSamples;
  22334. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  22335. {
  22336. destBuffer.addEvent (midiData, numBytes,
  22337. jlimit (0, numSamples - 1, samplePosition + startSample));
  22338. }
  22339. }
  22340. incomingMessages.clear();
  22341. }
  22342. }
  22343. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  22344. {
  22345. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  22346. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22347. addMessageToQueue (m);
  22348. }
  22349. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  22350. {
  22351. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  22352. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  22353. addMessageToQueue (m);
  22354. }
  22355. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  22356. {
  22357. addMessageToQueue (message);
  22358. }
  22359. END_JUCE_NAMESPACE
  22360. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  22361. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  22362. BEGIN_JUCE_NAMESPACE
  22363. MidiMessageSequence::MidiMessageSequence()
  22364. {
  22365. }
  22366. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  22367. {
  22368. list.ensureStorageAllocated (other.list.size());
  22369. for (int i = 0; i < other.list.size(); ++i)
  22370. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22371. }
  22372. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  22373. {
  22374. if (this != &other)
  22375. {
  22376. clear();
  22377. for (int i = 0; i < other.list.size(); ++i)
  22378. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  22379. }
  22380. return *this;
  22381. }
  22382. MidiMessageSequence::~MidiMessageSequence()
  22383. {
  22384. }
  22385. void MidiMessageSequence::clear()
  22386. {
  22387. list.clear();
  22388. }
  22389. int MidiMessageSequence::getNumEvents() const
  22390. {
  22391. return list.size();
  22392. }
  22393. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  22394. {
  22395. return list [index];
  22396. }
  22397. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  22398. {
  22399. const MidiEventHolder* const meh = list [index];
  22400. if (meh != 0 && meh->noteOffObject != 0)
  22401. return meh->noteOffObject->message.getTimeStamp();
  22402. else
  22403. return 0.0;
  22404. }
  22405. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  22406. {
  22407. const MidiEventHolder* const meh = list [index];
  22408. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  22409. }
  22410. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  22411. {
  22412. return list.indexOf (event);
  22413. }
  22414. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  22415. {
  22416. const int numEvents = list.size();
  22417. int i;
  22418. for (i = 0; i < numEvents; ++i)
  22419. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  22420. break;
  22421. return i;
  22422. }
  22423. double MidiMessageSequence::getStartTime() const
  22424. {
  22425. if (list.size() > 0)
  22426. return list.getUnchecked(0)->message.getTimeStamp();
  22427. else
  22428. return 0;
  22429. }
  22430. double MidiMessageSequence::getEndTime() const
  22431. {
  22432. if (list.size() > 0)
  22433. return list.getLast()->message.getTimeStamp();
  22434. else
  22435. return 0;
  22436. }
  22437. double MidiMessageSequence::getEventTime (const int index) const
  22438. {
  22439. if (((unsigned int) index) < (unsigned int) list.size())
  22440. return list.getUnchecked (index)->message.getTimeStamp();
  22441. return 0.0;
  22442. }
  22443. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  22444. double timeAdjustment)
  22445. {
  22446. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  22447. timeAdjustment += newMessage.getTimeStamp();
  22448. newOne->message.setTimeStamp (timeAdjustment);
  22449. int i;
  22450. for (i = list.size(); --i >= 0;)
  22451. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  22452. break;
  22453. list.insert (i + 1, newOne);
  22454. }
  22455. void MidiMessageSequence::deleteEvent (const int index,
  22456. const bool deleteMatchingNoteUp)
  22457. {
  22458. if (((unsigned int) index) < (unsigned int) list.size())
  22459. {
  22460. if (deleteMatchingNoteUp)
  22461. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  22462. list.remove (index);
  22463. }
  22464. }
  22465. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  22466. double timeAdjustment,
  22467. double firstAllowableTime,
  22468. double endOfAllowableDestTimes)
  22469. {
  22470. firstAllowableTime -= timeAdjustment;
  22471. endOfAllowableDestTimes -= timeAdjustment;
  22472. for (int i = 0; i < other.list.size(); ++i)
  22473. {
  22474. const MidiMessage& m = other.list.getUnchecked(i)->message;
  22475. const double t = m.getTimeStamp();
  22476. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  22477. {
  22478. MidiEventHolder* const newOne = new MidiEventHolder (m);
  22479. newOne->message.setTimeStamp (timeAdjustment + t);
  22480. list.add (newOne);
  22481. }
  22482. }
  22483. sort();
  22484. }
  22485. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22486. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22487. {
  22488. const double diff = first->message.getTimeStamp()
  22489. - second->message.getTimeStamp();
  22490. return (diff > 0) - (diff < 0);
  22491. }
  22492. void MidiMessageSequence::sort()
  22493. {
  22494. list.sort (*this, true);
  22495. }
  22496. void MidiMessageSequence::updateMatchedPairs()
  22497. {
  22498. for (int i = 0; i < list.size(); ++i)
  22499. {
  22500. const MidiMessage& m1 = list.getUnchecked(i)->message;
  22501. if (m1.isNoteOn())
  22502. {
  22503. list.getUnchecked(i)->noteOffObject = 0;
  22504. const int note = m1.getNoteNumber();
  22505. const int chan = m1.getChannel();
  22506. const int len = list.size();
  22507. for (int j = i + 1; j < len; ++j)
  22508. {
  22509. const MidiMessage& m = list.getUnchecked(j)->message;
  22510. if (m.getNoteNumber() == note && m.getChannel() == chan)
  22511. {
  22512. if (m.isNoteOff())
  22513. {
  22514. list.getUnchecked(i)->noteOffObject = list[j];
  22515. break;
  22516. }
  22517. else if (m.isNoteOn())
  22518. {
  22519. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  22520. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  22521. list.getUnchecked(i)->noteOffObject = list[j];
  22522. break;
  22523. }
  22524. }
  22525. }
  22526. }
  22527. }
  22528. }
  22529. void MidiMessageSequence::addTimeToMessages (const double delta)
  22530. {
  22531. for (int i = list.size(); --i >= 0;)
  22532. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  22533. + delta);
  22534. }
  22535. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  22536. MidiMessageSequence& destSequence,
  22537. const bool alsoIncludeMetaEvents) const
  22538. {
  22539. for (int i = 0; i < list.size(); ++i)
  22540. {
  22541. const MidiMessage& mm = list.getUnchecked(i)->message;
  22542. if (mm.isForChannel (channelNumberToExtract)
  22543. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  22544. {
  22545. destSequence.addEvent (mm);
  22546. }
  22547. }
  22548. }
  22549. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  22550. {
  22551. for (int i = 0; i < list.size(); ++i)
  22552. {
  22553. const MidiMessage& mm = list.getUnchecked(i)->message;
  22554. if (mm.isSysEx())
  22555. destSequence.addEvent (mm);
  22556. }
  22557. }
  22558. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  22559. {
  22560. for (int i = list.size(); --i >= 0;)
  22561. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  22562. list.remove(i);
  22563. }
  22564. void MidiMessageSequence::deleteSysExMessages()
  22565. {
  22566. for (int i = list.size(); --i >= 0;)
  22567. if (list.getUnchecked(i)->message.isSysEx())
  22568. list.remove(i);
  22569. }
  22570. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  22571. const double time,
  22572. OwnedArray<MidiMessage>& dest)
  22573. {
  22574. bool doneProg = false;
  22575. bool donePitchWheel = false;
  22576. Array <int> doneControllers (32);
  22577. for (int i = list.size(); --i >= 0;)
  22578. {
  22579. const MidiMessage& mm = list.getUnchecked(i)->message;
  22580. if (mm.isForChannel (channelNumber)
  22581. && mm.getTimeStamp() <= time)
  22582. {
  22583. if (mm.isProgramChange())
  22584. {
  22585. if (! doneProg)
  22586. {
  22587. dest.add (new MidiMessage (mm, 0.0));
  22588. doneProg = true;
  22589. }
  22590. }
  22591. else if (mm.isController())
  22592. {
  22593. if (! doneControllers.contains (mm.getControllerNumber()))
  22594. {
  22595. dest.add (new MidiMessage (mm, 0.0));
  22596. doneControllers.add (mm.getControllerNumber());
  22597. }
  22598. }
  22599. else if (mm.isPitchWheel())
  22600. {
  22601. if (! donePitchWheel)
  22602. {
  22603. dest.add (new MidiMessage (mm, 0.0));
  22604. donePitchWheel = true;
  22605. }
  22606. }
  22607. }
  22608. }
  22609. }
  22610. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  22611. : message (message_),
  22612. noteOffObject (0)
  22613. {
  22614. }
  22615. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  22616. {
  22617. }
  22618. END_JUCE_NAMESPACE
  22619. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  22620. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  22621. BEGIN_JUCE_NAMESPACE
  22622. AudioPluginFormat::AudioPluginFormat() throw()
  22623. {
  22624. }
  22625. AudioPluginFormat::~AudioPluginFormat()
  22626. {
  22627. }
  22628. END_JUCE_NAMESPACE
  22629. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  22630. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22631. BEGIN_JUCE_NAMESPACE
  22632. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  22633. {
  22634. }
  22635. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  22636. {
  22637. clearSingletonInstance();
  22638. }
  22639. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  22640. void AudioPluginFormatManager::addDefaultFormats()
  22641. {
  22642. #ifdef JUCE_DEBUG
  22643. // you should only call this method once!
  22644. for (int i = formats.size(); --i >= 0;)
  22645. {
  22646. #if JUCE_PLUGINHOST_VST
  22647. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  22648. #endif
  22649. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22650. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  22651. #endif
  22652. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22653. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  22654. #endif
  22655. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22656. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  22657. #endif
  22658. }
  22659. #endif
  22660. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  22661. formats.add (new AudioUnitPluginFormat());
  22662. #endif
  22663. #if JUCE_PLUGINHOST_VST
  22664. formats.add (new VSTPluginFormat());
  22665. #endif
  22666. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  22667. formats.add (new DirectXPluginFormat());
  22668. #endif
  22669. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  22670. formats.add (new LADSPAPluginFormat());
  22671. #endif
  22672. }
  22673. int AudioPluginFormatManager::getNumFormats() throw()
  22674. {
  22675. return formats.size();
  22676. }
  22677. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  22678. {
  22679. return formats [index];
  22680. }
  22681. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  22682. {
  22683. formats.add (format);
  22684. }
  22685. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  22686. String& errorMessage) const
  22687. {
  22688. AudioPluginInstance* result = 0;
  22689. for (int i = 0; i < formats.size(); ++i)
  22690. {
  22691. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  22692. if (result != 0)
  22693. break;
  22694. }
  22695. if (result == 0)
  22696. {
  22697. if (! doesPluginStillExist (description))
  22698. errorMessage = TRANS ("This plug-in file no longer exists");
  22699. else
  22700. errorMessage = TRANS ("This plug-in failed to load correctly");
  22701. }
  22702. return result;
  22703. }
  22704. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  22705. {
  22706. for (int i = 0; i < formats.size(); ++i)
  22707. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  22708. return formats.getUnchecked(i)->doesPluginStillExist (description);
  22709. return false;
  22710. }
  22711. END_JUCE_NAMESPACE
  22712. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  22713. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  22714. #define JUCE_PLUGIN_HOST 1
  22715. BEGIN_JUCE_NAMESPACE
  22716. AudioPluginInstance::AudioPluginInstance()
  22717. {
  22718. }
  22719. AudioPluginInstance::~AudioPluginInstance()
  22720. {
  22721. }
  22722. END_JUCE_NAMESPACE
  22723. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  22724. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  22725. BEGIN_JUCE_NAMESPACE
  22726. KnownPluginList::KnownPluginList()
  22727. {
  22728. }
  22729. KnownPluginList::~KnownPluginList()
  22730. {
  22731. }
  22732. void KnownPluginList::clear()
  22733. {
  22734. if (types.size() > 0)
  22735. {
  22736. types.clear();
  22737. sendChangeMessage (this);
  22738. }
  22739. }
  22740. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const throw()
  22741. {
  22742. for (int i = 0; i < types.size(); ++i)
  22743. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  22744. return types.getUnchecked(i);
  22745. return 0;
  22746. }
  22747. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  22748. {
  22749. for (int i = 0; i < types.size(); ++i)
  22750. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  22751. return types.getUnchecked(i);
  22752. return 0;
  22753. }
  22754. bool KnownPluginList::addType (const PluginDescription& type)
  22755. {
  22756. for (int i = types.size(); --i >= 0;)
  22757. {
  22758. if (types.getUnchecked(i)->isDuplicateOf (type))
  22759. {
  22760. // strange - found a duplicate plugin with different info..
  22761. jassert (types.getUnchecked(i)->name == type.name);
  22762. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  22763. *types.getUnchecked(i) = type;
  22764. return false;
  22765. }
  22766. }
  22767. types.add (new PluginDescription (type));
  22768. sendChangeMessage (this);
  22769. return true;
  22770. }
  22771. void KnownPluginList::removeType (const int index) throw()
  22772. {
  22773. types.remove (index);
  22774. sendChangeMessage (this);
  22775. }
  22776. static Time getFileModTime (const String& fileOrIdentifier) throw()
  22777. {
  22778. if (fileOrIdentifier.startsWithChar (T('/'))
  22779. || fileOrIdentifier[1] == T(':'))
  22780. {
  22781. return File (fileOrIdentifier).getLastModificationTime();
  22782. }
  22783. return Time (0);
  22784. }
  22785. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  22786. {
  22787. return t1 != t2 || t1 == Time (0);
  22788. }
  22789. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const throw()
  22790. {
  22791. if (getTypeForFile (fileOrIdentifier) == 0)
  22792. return false;
  22793. for (int i = types.size(); --i >= 0;)
  22794. {
  22795. const PluginDescription* const d = types.getUnchecked(i);
  22796. if (d->fileOrIdentifier == fileOrIdentifier
  22797. && timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22798. {
  22799. return false;
  22800. }
  22801. }
  22802. return true;
  22803. }
  22804. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  22805. const bool dontRescanIfAlreadyInList,
  22806. OwnedArray <PluginDescription>& typesFound,
  22807. AudioPluginFormat& format)
  22808. {
  22809. bool addedOne = false;
  22810. if (dontRescanIfAlreadyInList
  22811. && getTypeForFile (fileOrIdentifier) != 0)
  22812. {
  22813. bool needsRescanning = false;
  22814. for (int i = types.size(); --i >= 0;)
  22815. {
  22816. const PluginDescription* const d = types.getUnchecked(i);
  22817. if (d->fileOrIdentifier == fileOrIdentifier)
  22818. {
  22819. if (timesAreDifferent (d->lastFileModTime, getFileModTime (fileOrIdentifier)))
  22820. needsRescanning = true;
  22821. else
  22822. typesFound.add (new PluginDescription (*d));
  22823. }
  22824. }
  22825. if (! needsRescanning)
  22826. return false;
  22827. }
  22828. OwnedArray <PluginDescription> found;
  22829. format.findAllTypesForFile (found, fileOrIdentifier);
  22830. for (int i = 0; i < found.size(); ++i)
  22831. {
  22832. PluginDescription* const desc = found.getUnchecked(i);
  22833. jassert (desc != 0);
  22834. if (addType (*desc))
  22835. addedOne = true;
  22836. typesFound.add (new PluginDescription (*desc));
  22837. }
  22838. return addedOne;
  22839. }
  22840. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  22841. OwnedArray <PluginDescription>& typesFound)
  22842. {
  22843. for (int i = 0; i < files.size(); ++i)
  22844. {
  22845. bool loaded = false;
  22846. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  22847. {
  22848. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  22849. if (scanAndAddFile (files[i], true, typesFound, *format))
  22850. loaded = true;
  22851. }
  22852. if (! loaded)
  22853. {
  22854. const File f (files[i]);
  22855. if (f.isDirectory())
  22856. {
  22857. StringArray s;
  22858. {
  22859. OwnedArray <File> subFiles;
  22860. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  22861. for (int j = 0; j < subFiles.size(); ++j)
  22862. s.add (subFiles.getUnchecked (j)->getFullPathName());
  22863. }
  22864. scanAndAddDragAndDroppedFiles (s, typesFound);
  22865. }
  22866. }
  22867. }
  22868. }
  22869. class PluginSorter
  22870. {
  22871. public:
  22872. KnownPluginList::SortMethod method;
  22873. PluginSorter() throw() {}
  22874. int compareElements (const PluginDescription* const first,
  22875. const PluginDescription* const second) const throw()
  22876. {
  22877. int diff = 0;
  22878. if (method == KnownPluginList::sortByCategory)
  22879. diff = first->category.compareLexicographically (second->category);
  22880. else if (method == KnownPluginList::sortByManufacturer)
  22881. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  22882. else if (method == KnownPluginList::sortByFileSystemLocation)
  22883. diff = first->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22884. .upToLastOccurrenceOf (T("/"), false, false)
  22885. .compare (second->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22886. .upToLastOccurrenceOf (T("/"), false, false));
  22887. if (diff == 0)
  22888. diff = first->name.compareLexicographically (second->name);
  22889. return diff;
  22890. }
  22891. };
  22892. void KnownPluginList::sort (const SortMethod method)
  22893. {
  22894. if (method != defaultOrder)
  22895. {
  22896. PluginSorter sorter;
  22897. sorter.method = method;
  22898. types.sort (sorter, true);
  22899. sendChangeMessage (this);
  22900. }
  22901. }
  22902. XmlElement* KnownPluginList::createXml() const
  22903. {
  22904. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  22905. for (int i = 0; i < types.size(); ++i)
  22906. e->addChildElement (types.getUnchecked(i)->createXml());
  22907. return e;
  22908. }
  22909. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  22910. {
  22911. clear();
  22912. if (xml.hasTagName (T("KNOWNPLUGINS")))
  22913. {
  22914. forEachXmlChildElement (xml, e)
  22915. {
  22916. PluginDescription info;
  22917. if (info.loadFromXml (*e))
  22918. addType (info);
  22919. }
  22920. }
  22921. }
  22922. const int menuIdBase = 0x324503f4;
  22923. // This is used to turn a bunch of paths into a nested menu structure.
  22924. struct PluginFilesystemTree
  22925. {
  22926. private:
  22927. String folder;
  22928. OwnedArray <PluginFilesystemTree> subFolders;
  22929. Array <PluginDescription*> plugins;
  22930. void addPlugin (PluginDescription* const pd, const String& path)
  22931. {
  22932. if (path.isEmpty())
  22933. {
  22934. plugins.add (pd);
  22935. }
  22936. else
  22937. {
  22938. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  22939. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  22940. for (int i = subFolders.size(); --i >= 0;)
  22941. {
  22942. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  22943. {
  22944. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  22945. return;
  22946. }
  22947. }
  22948. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  22949. newFolder->folder = firstSubFolder;
  22950. subFolders.add (newFolder);
  22951. newFolder->addPlugin (pd, remainingPath);
  22952. }
  22953. }
  22954. // removes any deeply nested folders that don't contain any actual plugins
  22955. void optimise()
  22956. {
  22957. for (int i = subFolders.size(); --i >= 0;)
  22958. {
  22959. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22960. sub->optimise();
  22961. if (sub->plugins.size() == 0)
  22962. {
  22963. for (int j = 0; j < sub->subFolders.size(); ++j)
  22964. subFolders.add (sub->subFolders.getUnchecked(j));
  22965. sub->subFolders.clear (false);
  22966. subFolders.remove (i);
  22967. }
  22968. }
  22969. }
  22970. public:
  22971. void buildTree (const Array <PluginDescription*>& allPlugins)
  22972. {
  22973. for (int i = 0; i < allPlugins.size(); ++i)
  22974. {
  22975. String path (allPlugins.getUnchecked(i)
  22976. ->fileOrIdentifier.replaceCharacter (T('\\'), T('/'))
  22977. .upToLastOccurrenceOf (T("/"), false, false));
  22978. if (path.substring (1, 2) == T(":"))
  22979. path = path.substring (2);
  22980. addPlugin (allPlugins.getUnchecked(i), path);
  22981. }
  22982. optimise();
  22983. }
  22984. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  22985. {
  22986. int i;
  22987. for (i = 0; i < subFolders.size(); ++i)
  22988. {
  22989. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  22990. PopupMenu subMenu;
  22991. sub->addToMenu (subMenu, allPlugins);
  22992. #if JUCE_MAC
  22993. // avoid the special AU formatting nonsense on Mac..
  22994. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (T(":"), false, false), subMenu);
  22995. #else
  22996. m.addSubMenu (sub->folder, subMenu);
  22997. #endif
  22998. }
  22999. for (i = 0; i < plugins.size(); ++i)
  23000. {
  23001. PluginDescription* const plugin = plugins.getUnchecked(i);
  23002. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  23003. plugin->name, true, false);
  23004. }
  23005. }
  23006. };
  23007. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  23008. {
  23009. Array <PluginDescription*> sorted;
  23010. {
  23011. PluginSorter sorter;
  23012. sorter.method = sortMethod;
  23013. for (int i = 0; i < types.size(); ++i)
  23014. sorted.addSorted (sorter, types.getUnchecked(i));
  23015. }
  23016. if (sortMethod == sortByCategory
  23017. || sortMethod == sortByManufacturer)
  23018. {
  23019. String lastSubMenuName;
  23020. PopupMenu sub;
  23021. for (int i = 0; i < sorted.size(); ++i)
  23022. {
  23023. const PluginDescription* const pd = sorted.getUnchecked(i);
  23024. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  23025. : pd->manufacturerName);
  23026. if (! thisSubMenuName.containsNonWhitespaceChars())
  23027. thisSubMenuName = T("Other");
  23028. if (thisSubMenuName != lastSubMenuName)
  23029. {
  23030. if (sub.getNumItems() > 0)
  23031. {
  23032. menu.addSubMenu (lastSubMenuName, sub);
  23033. sub.clear();
  23034. }
  23035. lastSubMenuName = thisSubMenuName;
  23036. }
  23037. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23038. }
  23039. if (sub.getNumItems() > 0)
  23040. menu.addSubMenu (lastSubMenuName, sub);
  23041. }
  23042. else if (sortMethod == sortByFileSystemLocation)
  23043. {
  23044. PluginFilesystemTree root;
  23045. root.buildTree (sorted);
  23046. root.addToMenu (menu, types);
  23047. }
  23048. else
  23049. {
  23050. for (int i = 0; i < sorted.size(); ++i)
  23051. {
  23052. const PluginDescription* const pd = sorted.getUnchecked(i);
  23053. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  23054. }
  23055. }
  23056. }
  23057. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  23058. {
  23059. const int i = menuResultCode - menuIdBase;
  23060. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  23061. }
  23062. END_JUCE_NAMESPACE
  23063. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  23064. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  23065. BEGIN_JUCE_NAMESPACE
  23066. PluginDescription::PluginDescription() throw()
  23067. : uid (0),
  23068. isInstrument (false),
  23069. numInputChannels (0),
  23070. numOutputChannels (0)
  23071. {
  23072. }
  23073. PluginDescription::~PluginDescription() throw()
  23074. {
  23075. }
  23076. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  23077. : name (other.name),
  23078. pluginFormatName (other.pluginFormatName),
  23079. category (other.category),
  23080. manufacturerName (other.manufacturerName),
  23081. version (other.version),
  23082. fileOrIdentifier (other.fileOrIdentifier),
  23083. lastFileModTime (other.lastFileModTime),
  23084. uid (other.uid),
  23085. isInstrument (other.isInstrument),
  23086. numInputChannels (other.numInputChannels),
  23087. numOutputChannels (other.numOutputChannels)
  23088. {
  23089. }
  23090. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  23091. {
  23092. name = other.name;
  23093. pluginFormatName = other.pluginFormatName;
  23094. category = other.category;
  23095. manufacturerName = other.manufacturerName;
  23096. version = other.version;
  23097. fileOrIdentifier = other.fileOrIdentifier;
  23098. uid = other.uid;
  23099. isInstrument = other.isInstrument;
  23100. lastFileModTime = other.lastFileModTime;
  23101. numInputChannels = other.numInputChannels;
  23102. numOutputChannels = other.numOutputChannels;
  23103. return *this;
  23104. }
  23105. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  23106. {
  23107. return fileOrIdentifier == other.fileOrIdentifier
  23108. && uid == other.uid;
  23109. }
  23110. const String PluginDescription::createIdentifierString() const throw()
  23111. {
  23112. return pluginFormatName
  23113. + T("-") + name
  23114. + T("-") + String::toHexString (fileOrIdentifier.hashCode())
  23115. + T("-") + String::toHexString (uid);
  23116. }
  23117. XmlElement* PluginDescription::createXml() const
  23118. {
  23119. XmlElement* const e = new XmlElement (T("PLUGIN"));
  23120. e->setAttribute (T("name"), name);
  23121. e->setAttribute (T("format"), pluginFormatName);
  23122. e->setAttribute (T("category"), category);
  23123. e->setAttribute (T("manufacturer"), manufacturerName);
  23124. e->setAttribute (T("version"), version);
  23125. e->setAttribute (T("file"), fileOrIdentifier);
  23126. e->setAttribute (T("uid"), String::toHexString (uid));
  23127. e->setAttribute (T("isInstrument"), isInstrument);
  23128. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  23129. e->setAttribute (T("numInputs"), numInputChannels);
  23130. e->setAttribute (T("numOutputs"), numOutputChannels);
  23131. return e;
  23132. }
  23133. bool PluginDescription::loadFromXml (const XmlElement& xml)
  23134. {
  23135. if (xml.hasTagName (T("PLUGIN")))
  23136. {
  23137. name = xml.getStringAttribute (T("name"));
  23138. pluginFormatName = xml.getStringAttribute (T("format"));
  23139. category = xml.getStringAttribute (T("category"));
  23140. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  23141. version = xml.getStringAttribute (T("version"));
  23142. fileOrIdentifier = xml.getStringAttribute (T("file"));
  23143. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  23144. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  23145. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  23146. numInputChannels = xml.getIntAttribute (T("numInputs"));
  23147. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  23148. return true;
  23149. }
  23150. return false;
  23151. }
  23152. END_JUCE_NAMESPACE
  23153. /********* End of inlined file: juce_PluginDescription.cpp *********/
  23154. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23155. BEGIN_JUCE_NAMESPACE
  23156. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  23157. AudioPluginFormat& formatToLookFor,
  23158. FileSearchPath directoriesToSearch,
  23159. const bool recursive,
  23160. const File& deadMansPedalFile_)
  23161. : list (listToAddTo),
  23162. format (formatToLookFor),
  23163. deadMansPedalFile (deadMansPedalFile_),
  23164. nextIndex (0),
  23165. progress (0)
  23166. {
  23167. directoriesToSearch.removeRedundantPaths();
  23168. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  23169. // If any plugins have crashed recently when being loaded, move them to the
  23170. // end of the list to give the others a chance to load correctly..
  23171. const StringArray crashedPlugins (getDeadMansPedalFile());
  23172. for (int i = 0; i < crashedPlugins.size(); ++i)
  23173. {
  23174. const String f = crashedPlugins[i];
  23175. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  23176. if (f == filesOrIdentifiersToScan[j])
  23177. filesOrIdentifiersToScan.move (j, -1);
  23178. }
  23179. }
  23180. PluginDirectoryScanner::~PluginDirectoryScanner()
  23181. {
  23182. }
  23183. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  23184. {
  23185. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  23186. }
  23187. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  23188. {
  23189. String file (filesOrIdentifiersToScan [nextIndex]);
  23190. if (file.isNotEmpty())
  23191. {
  23192. if (! list.isListingUpToDate (file))
  23193. {
  23194. OwnedArray <PluginDescription> typesFound;
  23195. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  23196. StringArray crashedPlugins (getDeadMansPedalFile());
  23197. crashedPlugins.removeString (file);
  23198. crashedPlugins.add (file);
  23199. setDeadMansPedalFile (crashedPlugins);
  23200. list.scanAndAddFile (file,
  23201. dontRescanIfAlreadyInList,
  23202. typesFound,
  23203. format);
  23204. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  23205. crashedPlugins.removeString (file);
  23206. setDeadMansPedalFile (crashedPlugins);
  23207. if (typesFound.size() == 0)
  23208. failedFiles.add (file);
  23209. }
  23210. ++nextIndex;
  23211. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  23212. }
  23213. return nextIndex < filesOrIdentifiersToScan.size();
  23214. }
  23215. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  23216. {
  23217. StringArray lines;
  23218. if (deadMansPedalFile != File::nonexistent)
  23219. {
  23220. lines.addLines (deadMansPedalFile.loadFileAsString());
  23221. lines.removeEmptyStrings();
  23222. }
  23223. return lines;
  23224. }
  23225. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  23226. {
  23227. if (deadMansPedalFile != File::nonexistent)
  23228. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  23229. }
  23230. END_JUCE_NAMESPACE
  23231. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  23232. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  23233. BEGIN_JUCE_NAMESPACE
  23234. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  23235. const File& deadMansPedalFile_,
  23236. PropertiesFile* const propertiesToUse_)
  23237. : list (listToEdit),
  23238. deadMansPedalFile (deadMansPedalFile_),
  23239. propertiesToUse (propertiesToUse_)
  23240. {
  23241. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  23242. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  23243. optionsButton->addButtonListener (this);
  23244. optionsButton->setTriggeredOnMouseDown (true);
  23245. setSize (400, 600);
  23246. list.addChangeListener (this);
  23247. }
  23248. PluginListComponent::~PluginListComponent()
  23249. {
  23250. list.removeChangeListener (this);
  23251. deleteAllChildren();
  23252. }
  23253. void PluginListComponent::resized()
  23254. {
  23255. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  23256. optionsButton->changeWidthToFitText (24);
  23257. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  23258. }
  23259. void PluginListComponent::changeListenerCallback (void*)
  23260. {
  23261. listBox->updateContent();
  23262. listBox->repaint();
  23263. }
  23264. int PluginListComponent::getNumRows()
  23265. {
  23266. return list.getNumTypes();
  23267. }
  23268. void PluginListComponent::paintListBoxItem (int row,
  23269. Graphics& g,
  23270. int width, int height,
  23271. bool rowIsSelected)
  23272. {
  23273. if (rowIsSelected)
  23274. g.fillAll (findColour (TextEditor::highlightColourId));
  23275. const PluginDescription* const pd = list.getType (row);
  23276. if (pd != 0)
  23277. {
  23278. GlyphArrangement ga;
  23279. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  23280. g.setColour (Colours::black);
  23281. ga.draw (g);
  23282. float x, y, r, b;
  23283. ga.getBoundingBox (0, -1, x, y, r, b, false);
  23284. String desc;
  23285. desc << pd->pluginFormatName
  23286. << (pd->isInstrument ? " instrument" : " effect")
  23287. << " - "
  23288. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  23289. << " / "
  23290. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  23291. if (pd->manufacturerName.isNotEmpty())
  23292. desc << " - " << pd->manufacturerName;
  23293. if (pd->version.isNotEmpty())
  23294. desc << " - " << pd->version;
  23295. if (pd->category.isNotEmpty())
  23296. desc << " - category: '" << pd->category << '\'';
  23297. g.setColour (Colours::grey);
  23298. ga.clear();
  23299. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  23300. ga.draw (g);
  23301. }
  23302. }
  23303. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  23304. {
  23305. list.removeType (lastRowSelected);
  23306. }
  23307. void PluginListComponent::buttonClicked (Button* b)
  23308. {
  23309. if (optionsButton == b)
  23310. {
  23311. PopupMenu menu;
  23312. menu.addItem (1, TRANS("Clear list"));
  23313. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  23314. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  23315. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  23316. menu.addSeparator();
  23317. menu.addItem (2, TRANS("Sort alphabetically"));
  23318. menu.addItem (3, TRANS("Sort by category"));
  23319. menu.addItem (4, TRANS("Sort by manufacturer"));
  23320. menu.addSeparator();
  23321. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  23322. {
  23323. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  23324. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  23325. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  23326. }
  23327. const int r = menu.showAt (optionsButton);
  23328. if (r == 1)
  23329. {
  23330. list.clear();
  23331. }
  23332. else if (r == 2)
  23333. {
  23334. list.sort (KnownPluginList::sortAlphabetically);
  23335. }
  23336. else if (r == 3)
  23337. {
  23338. list.sort (KnownPluginList::sortByCategory);
  23339. }
  23340. else if (r == 4)
  23341. {
  23342. list.sort (KnownPluginList::sortByManufacturer);
  23343. }
  23344. else if (r == 5)
  23345. {
  23346. const SparseSet <int> selected (listBox->getSelectedRows());
  23347. for (int i = list.getNumTypes(); --i >= 0;)
  23348. if (selected.contains (i))
  23349. list.removeType (i);
  23350. }
  23351. else if (r == 6)
  23352. {
  23353. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  23354. if (desc != 0)
  23355. {
  23356. if (File (desc->fileOrIdentifier).existsAsFile())
  23357. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  23358. }
  23359. }
  23360. else if (r == 7)
  23361. {
  23362. for (int i = list.getNumTypes(); --i >= 0;)
  23363. {
  23364. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  23365. {
  23366. list.removeType (i);
  23367. }
  23368. }
  23369. }
  23370. else if (r != 0)
  23371. {
  23372. typeToScan = r - 10;
  23373. startTimer (1);
  23374. }
  23375. }
  23376. }
  23377. void PluginListComponent::timerCallback()
  23378. {
  23379. stopTimer();
  23380. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  23381. }
  23382. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  23383. {
  23384. return true;
  23385. }
  23386. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  23387. {
  23388. OwnedArray <PluginDescription> typesFound;
  23389. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  23390. }
  23391. void PluginListComponent::scanFor (AudioPluginFormat* format)
  23392. {
  23393. if (format == 0)
  23394. return;
  23395. FileSearchPath path (format->getDefaultLocationsToSearch());
  23396. if (propertiesToUse != 0)
  23397. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23398. {
  23399. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  23400. FileSearchPathListComponent pathList;
  23401. pathList.setSize (500, 300);
  23402. pathList.setPath (path);
  23403. aw.addCustomComponent (&pathList);
  23404. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  23405. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23406. if (aw.runModalLoop() == 0)
  23407. return;
  23408. path = pathList.getPath();
  23409. }
  23410. if (propertiesToUse != 0)
  23411. {
  23412. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  23413. propertiesToUse->saveIfNeeded();
  23414. }
  23415. double progress = 0.0;
  23416. AlertWindow aw (TRANS("Scanning for plugins..."),
  23417. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  23418. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  23419. aw.addProgressBarComponent (progress);
  23420. aw.enterModalState();
  23421. MessageManager::getInstance()->runDispatchLoopUntil (300);
  23422. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  23423. for (;;)
  23424. {
  23425. aw.setMessage (TRANS("Testing:\n\n")
  23426. + scanner.getNextPluginFileThatWillBeScanned());
  23427. MessageManager::getInstance()->runDispatchLoopUntil (20);
  23428. if (! scanner.scanNextFile (true))
  23429. break;
  23430. if (! aw.isCurrentlyModal())
  23431. break;
  23432. progress = scanner.getProgress();
  23433. }
  23434. if (scanner.getFailedFiles().size() > 0)
  23435. {
  23436. StringArray shortNames;
  23437. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  23438. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  23439. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  23440. TRANS("Scan complete"),
  23441. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  23442. + shortNames.joinIntoString (", "));
  23443. }
  23444. }
  23445. END_JUCE_NAMESPACE
  23446. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  23447. /********* Start of inlined file: juce_AudioUnitPluginFormat.mm *********/
  23448. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  23449. #include <AudioUnit/AudioUnit.h>
  23450. #include <AudioUnit/AUCocoaUIView.h>
  23451. #include <CoreAudioKit/AUGenericView.h>
  23452. #if JUCE_SUPPORT_CARBON
  23453. #include <AudioToolbox/AudioUnitUtilities.h>
  23454. #include <AudioUnit/AudioUnitCarbonView.h>
  23455. #endif
  23456. BEGIN_JUCE_NAMESPACE
  23457. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  23458. #endif
  23459. #if JUCE_MAC
  23460. #if MACOS_10_3_OR_EARLIER
  23461. #define kAudioUnitType_Generator 'augn'
  23462. #endif
  23463. // Change this to disable logging of various activities
  23464. #ifndef AU_LOGGING
  23465. #define AU_LOGGING 1
  23466. #endif
  23467. #if AU_LOGGING
  23468. #define log(a) Logger::writeToLog(a);
  23469. #else
  23470. #define log(a)
  23471. #endif
  23472. static int insideCallback = 0;
  23473. static const String osTypeToString (OSType type) throw()
  23474. {
  23475. char s[4];
  23476. s[0] = (char) (((uint32) type) >> 24);
  23477. s[1] = (char) (((uint32) type) >> 16);
  23478. s[2] = (char) (((uint32) type) >> 8);
  23479. s[3] = (char) ((uint32) type);
  23480. return String (s, 4);
  23481. }
  23482. static OSType stringToOSType (const String& s1) throw()
  23483. {
  23484. const String s (s1 + " ");
  23485. return (((OSType) (unsigned char) s[0]) << 24)
  23486. | (((OSType) (unsigned char) s[1]) << 16)
  23487. | (((OSType) (unsigned char) s[2]) << 8)
  23488. | ((OSType) (unsigned char) s[3]);
  23489. }
  23490. static const tchar* auIdentifierPrefix = T("AudioUnit:");
  23491. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  23492. {
  23493. jassert (osTypeToString ('abcd') == T("abcd")); // agh, must have got the endianness wrong..
  23494. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  23495. String s (auIdentifierPrefix);
  23496. if (desc.componentType == kAudioUnitType_MusicDevice)
  23497. s << "Synths/";
  23498. else if (desc.componentType == kAudioUnitType_MusicEffect
  23499. || desc.componentType == kAudioUnitType_Effect)
  23500. s << "Effects/";
  23501. else if (desc.componentType == kAudioUnitType_Generator)
  23502. s << "Generators/";
  23503. else if (desc.componentType == kAudioUnitType_Panner)
  23504. s << "Panners/";
  23505. s << osTypeToString (desc.componentType)
  23506. << T(",")
  23507. << osTypeToString (desc.componentSubType)
  23508. << T(",")
  23509. << osTypeToString (desc.componentManufacturer);
  23510. return s;
  23511. }
  23512. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  23513. {
  23514. Handle componentNameHandle = NewHandle (sizeof (void*));
  23515. Handle componentInfoHandle = NewHandle (sizeof (void*));
  23516. if (componentNameHandle != 0 && componentInfoHandle != 0)
  23517. {
  23518. ComponentDescription desc;
  23519. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  23520. {
  23521. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  23522. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  23523. if (nameString != 0 && nameString[0] != 0)
  23524. {
  23525. const String all ((const char*) nameString + 1, nameString[0]);
  23526. DBG ("name: "+ all);
  23527. manufacturer = all.upToFirstOccurrenceOf (T(":"), false, false).trim();
  23528. name = all.fromFirstOccurrenceOf (T(":"), false, false).trim();
  23529. }
  23530. if (infoString != 0 && infoString[0] != 0)
  23531. {
  23532. const String all ((const char*) infoString + 1, infoString[0]);
  23533. DBG ("info: " + all);
  23534. }
  23535. if (name.isEmpty())
  23536. name = "<Unknown>";
  23537. }
  23538. DisposeHandle (componentNameHandle);
  23539. DisposeHandle (componentInfoHandle);
  23540. }
  23541. }
  23542. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  23543. String& name, String& version, String& manufacturer)
  23544. {
  23545. zerostruct (desc);
  23546. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  23547. {
  23548. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (T(':')),
  23549. fileOrIdentifier.lastIndexOfChar (T('/'))) + 1));
  23550. StringArray tokens;
  23551. tokens.addTokens (s, T(","), 0);
  23552. tokens.trim();
  23553. tokens.removeEmptyStrings();
  23554. if (tokens.size() == 3)
  23555. {
  23556. desc.componentType = stringToOSType (tokens[0]);
  23557. desc.componentSubType = stringToOSType (tokens[1]);
  23558. desc.componentManufacturer = stringToOSType (tokens[2]);
  23559. ComponentRecord* comp = FindNextComponent (0, &desc);
  23560. if (comp != 0)
  23561. {
  23562. getAUDetails (comp, name, manufacturer);
  23563. return true;
  23564. }
  23565. }
  23566. }
  23567. return false;
  23568. }
  23569. class AudioUnitPluginWindowCarbon;
  23570. class AudioUnitPluginWindowCocoa;
  23571. class AudioUnitPluginInstance : public AudioPluginInstance
  23572. {
  23573. public:
  23574. ~AudioUnitPluginInstance();
  23575. // AudioPluginInstance methods:
  23576. void fillInPluginDescription (PluginDescription& desc) const
  23577. {
  23578. desc.name = pluginName;
  23579. desc.fileOrIdentifier = createAUPluginIdentifier (componentDesc);
  23580. desc.uid = ((int) componentDesc.componentType)
  23581. ^ ((int) componentDesc.componentSubType)
  23582. ^ ((int) componentDesc.componentManufacturer);
  23583. desc.lastFileModTime = 0;
  23584. desc.pluginFormatName = "AudioUnit";
  23585. desc.category = getCategory();
  23586. desc.manufacturerName = manufacturer;
  23587. desc.version = version;
  23588. desc.numInputChannels = getNumInputChannels();
  23589. desc.numOutputChannels = getNumOutputChannels();
  23590. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  23591. }
  23592. const String getName() const { return pluginName; }
  23593. bool acceptsMidi() const { return wantsMidiMessages; }
  23594. bool producesMidi() const { return false; }
  23595. // AudioProcessor methods:
  23596. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23597. void releaseResources();
  23598. void processBlock (AudioSampleBuffer& buffer,
  23599. MidiBuffer& midiMessages);
  23600. AudioProcessorEditor* createEditor();
  23601. const String getInputChannelName (const int index) const;
  23602. bool isInputChannelStereoPair (int index) const;
  23603. const String getOutputChannelName (const int index) const;
  23604. bool isOutputChannelStereoPair (int index) const;
  23605. int getNumParameters();
  23606. float getParameter (int index);
  23607. void setParameter (int index, float newValue);
  23608. const String getParameterName (int index);
  23609. const String getParameterText (int index);
  23610. bool isParameterAutomatable (int index) const;
  23611. int getNumPrograms();
  23612. int getCurrentProgram();
  23613. void setCurrentProgram (int index);
  23614. const String getProgramName (int index);
  23615. void changeProgramName (int index, const String& newName);
  23616. void getStateInformation (MemoryBlock& destData);
  23617. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23618. void setStateInformation (const void* data, int sizeInBytes);
  23619. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23620. juce_UseDebuggingNewOperator
  23621. private:
  23622. friend class AudioUnitPluginWindowCarbon;
  23623. friend class AudioUnitPluginWindowCocoa;
  23624. friend class AudioUnitPluginFormat;
  23625. ComponentDescription componentDesc;
  23626. String pluginName, manufacturer, version;
  23627. String fileOrIdentifier;
  23628. CriticalSection lock;
  23629. bool initialised, wantsMidiMessages, wasPlaying;
  23630. AudioBufferList* outputBufferList;
  23631. AudioTimeStamp timeStamp;
  23632. AudioSampleBuffer* currentBuffer;
  23633. AudioUnit audioUnit;
  23634. Array <int> parameterIds;
  23635. bool getComponentDescFromFile (const String& fileOrIdentifier);
  23636. void initialise();
  23637. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23638. const AudioTimeStamp* inTimeStamp,
  23639. UInt32 inBusNumber,
  23640. UInt32 inNumberFrames,
  23641. AudioBufferList* ioData) const;
  23642. static OSStatus renderGetInputCallback (void* inRefCon,
  23643. AudioUnitRenderActionFlags* ioActionFlags,
  23644. const AudioTimeStamp* inTimeStamp,
  23645. UInt32 inBusNumber,
  23646. UInt32 inNumberFrames,
  23647. AudioBufferList* ioData)
  23648. {
  23649. return ((AudioUnitPluginInstance*) inRefCon)
  23650. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  23651. }
  23652. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  23653. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  23654. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  23655. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23656. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23657. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  23658. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  23659. {
  23660. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  23661. }
  23662. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  23663. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  23664. Float64* outCurrentMeasureDownBeat)
  23665. {
  23666. return ((AudioUnitPluginInstance*) inHostUserData)
  23667. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  23668. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  23669. }
  23670. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  23671. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  23672. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  23673. {
  23674. return ((AudioUnitPluginInstance*) inHostUserData)
  23675. ->getTransportState (outIsPlaying, outTransportStateChanged,
  23676. outCurrentSampleInTimeLine, outIsCycling,
  23677. outCycleStartBeat, outCycleEndBeat);
  23678. }
  23679. void getNumChannels (int& numIns, int& numOuts)
  23680. {
  23681. numIns = 0;
  23682. numOuts = 0;
  23683. AUChannelInfo supportedChannels [128];
  23684. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  23685. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  23686. 0, supportedChannels, &supportedChannelsSize) == noErr
  23687. && supportedChannelsSize > 0)
  23688. {
  23689. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  23690. {
  23691. numIns = jmax (numIns, supportedChannels[i].inChannels);
  23692. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  23693. }
  23694. }
  23695. else
  23696. {
  23697. // (this really means the plugin will take any number of ins/outs as long
  23698. // as they are the same)
  23699. numIns = numOuts = 2;
  23700. }
  23701. }
  23702. const String getCategory() const;
  23703. AudioUnitPluginInstance (const String& fileOrIdentifier);
  23704. };
  23705. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  23706. : fileOrIdentifier (fileOrIdentifier),
  23707. initialised (false),
  23708. wantsMidiMessages (false),
  23709. audioUnit (0),
  23710. outputBufferList (0),
  23711. currentBuffer (0)
  23712. {
  23713. try
  23714. {
  23715. ++insideCallback;
  23716. log (T("Opening AU: ") + fileOrIdentifier);
  23717. if (getComponentDescFromFile (fileOrIdentifier))
  23718. {
  23719. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  23720. if (comp != 0)
  23721. {
  23722. audioUnit = (AudioUnit) OpenComponent (comp);
  23723. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  23724. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  23725. }
  23726. }
  23727. --insideCallback;
  23728. }
  23729. catch (...)
  23730. {
  23731. --insideCallback;
  23732. }
  23733. }
  23734. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  23735. {
  23736. {
  23737. const ScopedLock sl (lock);
  23738. jassert (insideCallback == 0);
  23739. if (audioUnit != 0)
  23740. {
  23741. AudioUnitUninitialize (audioUnit);
  23742. CloseComponent (audioUnit);
  23743. audioUnit = 0;
  23744. }
  23745. }
  23746. juce_free (outputBufferList);
  23747. }
  23748. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  23749. {
  23750. zerostruct (componentDesc);
  23751. if (getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  23752. return true;
  23753. const File file (fileOrIdentifier);
  23754. if (! file.hasFileExtension (T(".component")))
  23755. return false;
  23756. const char* const utf8 = fileOrIdentifier.toUTF8();
  23757. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23758. strlen (utf8), file.isDirectory());
  23759. if (url != 0)
  23760. {
  23761. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23762. CFRelease (url);
  23763. if (bundleRef != 0)
  23764. {
  23765. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23766. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  23767. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  23768. if (pluginName.isEmpty())
  23769. pluginName = file.getFileNameWithoutExtension();
  23770. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  23771. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  23772. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  23773. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  23774. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  23775. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  23776. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23777. UseResFile (resFileId);
  23778. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  23779. {
  23780. Handle h = Get1IndResource ('thng', i);
  23781. if (h != 0)
  23782. {
  23783. HLock (h);
  23784. const uint32* const types = (const uint32*) *h;
  23785. if (types[0] == kAudioUnitType_MusicDevice
  23786. || types[0] == kAudioUnitType_MusicEffect
  23787. || types[0] == kAudioUnitType_Effect
  23788. || types[0] == kAudioUnitType_Generator
  23789. || types[0] == kAudioUnitType_Panner)
  23790. {
  23791. componentDesc.componentType = types[0];
  23792. componentDesc.componentSubType = types[1];
  23793. componentDesc.componentManufacturer = types[2];
  23794. break;
  23795. }
  23796. HUnlock (h);
  23797. ReleaseResource (h);
  23798. }
  23799. }
  23800. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23801. CFRelease (bundleRef);
  23802. }
  23803. }
  23804. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  23805. }
  23806. void AudioUnitPluginInstance::initialise()
  23807. {
  23808. if (initialised || audioUnit == 0)
  23809. return;
  23810. log (T("Initialising AU: ") + pluginName);
  23811. parameterIds.clear();
  23812. {
  23813. UInt32 paramListSize = 0;
  23814. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23815. 0, 0, &paramListSize);
  23816. if (paramListSize > 0)
  23817. {
  23818. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  23819. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  23820. 0, &parameterIds.getReference(0), &paramListSize);
  23821. }
  23822. }
  23823. {
  23824. AURenderCallbackStruct info;
  23825. zerostruct (info);
  23826. info.inputProcRefCon = this;
  23827. info.inputProc = renderGetInputCallback;
  23828. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  23829. 0, &info, sizeof (info));
  23830. }
  23831. {
  23832. HostCallbackInfo info;
  23833. zerostruct (info);
  23834. info.hostUserData = this;
  23835. info.beatAndTempoProc = getBeatAndTempoCallback;
  23836. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  23837. info.transportStateProc = getTransportStateCallback;
  23838. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  23839. 0, &info, sizeof (info));
  23840. }
  23841. int numIns, numOuts;
  23842. getNumChannels (numIns, numOuts);
  23843. setPlayConfigDetails (numIns, numOuts, 0, 0);
  23844. initialised = AudioUnitInitialize (audioUnit) == noErr;
  23845. setLatencySamples (0);
  23846. }
  23847. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  23848. int samplesPerBlockExpected)
  23849. {
  23850. initialise();
  23851. if (initialised)
  23852. {
  23853. int numIns, numOuts;
  23854. getNumChannels (numIns, numOuts);
  23855. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  23856. Float64 latencySecs = 0.0;
  23857. UInt32 latencySize = sizeof (latencySecs);
  23858. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  23859. 0, &latencySecs, &latencySize);
  23860. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  23861. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23862. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23863. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23864. AudioStreamBasicDescription stream;
  23865. zerostruct (stream);
  23866. stream.mSampleRate = sampleRate_;
  23867. stream.mFormatID = kAudioFormatLinearPCM;
  23868. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  23869. stream.mFramesPerPacket = 1;
  23870. stream.mBytesPerPacket = 4;
  23871. stream.mBytesPerFrame = 4;
  23872. stream.mBitsPerChannel = 32;
  23873. stream.mChannelsPerFrame = numIns;
  23874. OSStatus err = AudioUnitSetProperty (audioUnit,
  23875. kAudioUnitProperty_StreamFormat,
  23876. kAudioUnitScope_Input,
  23877. 0, &stream, sizeof (stream));
  23878. stream.mChannelsPerFrame = numOuts;
  23879. err = AudioUnitSetProperty (audioUnit,
  23880. kAudioUnitProperty_StreamFormat,
  23881. kAudioUnitScope_Output,
  23882. 0, &stream, sizeof (stream));
  23883. juce_free (outputBufferList);
  23884. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  23885. outputBufferList->mNumberBuffers = numOuts;
  23886. for (int i = numOuts; --i >= 0;)
  23887. outputBufferList->mBuffers[i].mNumberChannels = 1;
  23888. zerostruct (timeStamp);
  23889. timeStamp.mSampleTime = 0;
  23890. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23891. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  23892. currentBuffer = 0;
  23893. wasPlaying = false;
  23894. }
  23895. }
  23896. void AudioUnitPluginInstance::releaseResources()
  23897. {
  23898. if (initialised)
  23899. {
  23900. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  23901. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  23902. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  23903. juce_free (outputBufferList);
  23904. outputBufferList = 0;
  23905. currentBuffer = 0;
  23906. }
  23907. }
  23908. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  23909. const AudioTimeStamp* inTimeStamp,
  23910. UInt32 inBusNumber,
  23911. UInt32 inNumberFrames,
  23912. AudioBufferList* ioData) const
  23913. {
  23914. if (inBusNumber == 0
  23915. && currentBuffer != 0)
  23916. {
  23917. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  23918. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  23919. {
  23920. if (i < currentBuffer->getNumChannels())
  23921. {
  23922. memcpy (ioData->mBuffers[i].mData,
  23923. currentBuffer->getSampleData (i, 0),
  23924. sizeof (float) * inNumberFrames);
  23925. }
  23926. else
  23927. {
  23928. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  23929. }
  23930. }
  23931. }
  23932. return noErr;
  23933. }
  23934. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  23935. MidiBuffer& midiMessages)
  23936. {
  23937. const int numSamples = buffer.getNumSamples();
  23938. if (initialised)
  23939. {
  23940. AudioUnitRenderActionFlags flags = 0;
  23941. timeStamp.mHostTime = AudioGetCurrentHostTime();
  23942. for (int i = getNumOutputChannels(); --i >= 0;)
  23943. {
  23944. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  23945. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  23946. }
  23947. currentBuffer = &buffer;
  23948. if (wantsMidiMessages)
  23949. {
  23950. const uint8* midiEventData;
  23951. int midiEventSize, midiEventPosition;
  23952. MidiBuffer::Iterator i (midiMessages);
  23953. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  23954. {
  23955. if (midiEventSize <= 3)
  23956. MusicDeviceMIDIEvent (audioUnit,
  23957. midiEventData[0], midiEventData[1], midiEventData[2],
  23958. midiEventPosition);
  23959. else
  23960. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  23961. }
  23962. midiMessages.clear();
  23963. }
  23964. AudioUnitRender (audioUnit, &flags, &timeStamp,
  23965. 0, numSamples, outputBufferList);
  23966. timeStamp.mSampleTime += numSamples;
  23967. }
  23968. else
  23969. {
  23970. // Not initialised, so just bypass..
  23971. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23972. buffer.clear (i, 0, buffer.getNumSamples());
  23973. }
  23974. }
  23975. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  23976. {
  23977. AudioPlayHead* const ph = getPlayHead();
  23978. AudioPlayHead::CurrentPositionInfo result;
  23979. if (ph != 0 && ph->getCurrentPosition (result))
  23980. {
  23981. if (outCurrentBeat != 0)
  23982. *outCurrentBeat = result.ppqPosition;
  23983. if (outCurrentTempo != 0)
  23984. *outCurrentTempo = result.bpm;
  23985. }
  23986. else
  23987. {
  23988. if (outCurrentBeat != 0)
  23989. *outCurrentBeat = 0;
  23990. if (outCurrentTempo != 0)
  23991. *outCurrentTempo = 120.0;
  23992. }
  23993. return noErr;
  23994. }
  23995. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  23996. Float32* outTimeSig_Numerator,
  23997. UInt32* outTimeSig_Denominator,
  23998. Float64* outCurrentMeasureDownBeat) const
  23999. {
  24000. AudioPlayHead* const ph = getPlayHead();
  24001. AudioPlayHead::CurrentPositionInfo result;
  24002. if (ph != 0 && ph->getCurrentPosition (result))
  24003. {
  24004. if (outTimeSig_Numerator != 0)
  24005. *outTimeSig_Numerator = result.timeSigNumerator;
  24006. if (outTimeSig_Denominator != 0)
  24007. *outTimeSig_Denominator = result.timeSigDenominator;
  24008. if (outDeltaSampleOffsetToNextBeat != 0)
  24009. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  24010. if (outCurrentMeasureDownBeat != 0)
  24011. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  24012. }
  24013. else
  24014. {
  24015. if (outDeltaSampleOffsetToNextBeat != 0)
  24016. *outDeltaSampleOffsetToNextBeat = 0;
  24017. if (outTimeSig_Numerator != 0)
  24018. *outTimeSig_Numerator = 4;
  24019. if (outTimeSig_Denominator != 0)
  24020. *outTimeSig_Denominator = 4;
  24021. if (outCurrentMeasureDownBeat != 0)
  24022. *outCurrentMeasureDownBeat = 0;
  24023. }
  24024. return noErr;
  24025. }
  24026. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  24027. Boolean* outTransportStateChanged,
  24028. Float64* outCurrentSampleInTimeLine,
  24029. Boolean* outIsCycling,
  24030. Float64* outCycleStartBeat,
  24031. Float64* outCycleEndBeat)
  24032. {
  24033. AudioPlayHead* const ph = getPlayHead();
  24034. AudioPlayHead::CurrentPositionInfo result;
  24035. if (ph != 0 && ph->getCurrentPosition (result))
  24036. {
  24037. if (outIsPlaying != 0)
  24038. *outIsPlaying = result.isPlaying;
  24039. if (outTransportStateChanged != 0)
  24040. {
  24041. *outTransportStateChanged = result.isPlaying != wasPlaying;
  24042. wasPlaying = result.isPlaying;
  24043. }
  24044. if (outCurrentSampleInTimeLine != 0)
  24045. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  24046. if (outIsCycling != 0)
  24047. *outIsCycling = false;
  24048. if (outCycleStartBeat != 0)
  24049. *outCycleStartBeat = 0;
  24050. if (outCycleEndBeat != 0)
  24051. *outCycleEndBeat = 0;
  24052. }
  24053. else
  24054. {
  24055. if (outIsPlaying != 0)
  24056. *outIsPlaying = false;
  24057. if (outTransportStateChanged != 0)
  24058. *outTransportStateChanged = false;
  24059. if (outCurrentSampleInTimeLine != 0)
  24060. *outCurrentSampleInTimeLine = 0;
  24061. if (outIsCycling != 0)
  24062. *outIsCycling = false;
  24063. if (outCycleStartBeat != 0)
  24064. *outCycleStartBeat = 0;
  24065. if (outCycleEndBeat != 0)
  24066. *outCycleEndBeat = 0;
  24067. }
  24068. return noErr;
  24069. }
  24070. static VoidArray activeWindows;
  24071. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  24072. {
  24073. public:
  24074. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  24075. : AudioProcessorEditor (&plugin_),
  24076. plugin (plugin_),
  24077. wrapper (0)
  24078. {
  24079. addAndMakeVisible (wrapper = new NSViewComponent());
  24080. activeWindows.add (this);
  24081. setOpaque (true);
  24082. setVisible (true);
  24083. setSize (100, 100);
  24084. createView (createGenericViewIfNeeded);
  24085. }
  24086. ~AudioUnitPluginWindowCocoa()
  24087. {
  24088. const bool wasValid = isValid();
  24089. wrapper->setView (0);
  24090. activeWindows.removeValue (this);
  24091. if (wasValid)
  24092. plugin.editorBeingDeleted (this);
  24093. delete wrapper;
  24094. }
  24095. bool isValid() const { return wrapper->getView() != 0; }
  24096. void paint (Graphics& g)
  24097. {
  24098. g.fillAll (Colours::white);
  24099. }
  24100. void resized()
  24101. {
  24102. wrapper->setSize (getWidth(), getHeight());
  24103. }
  24104. private:
  24105. AudioUnitPluginInstance& plugin;
  24106. NSViewComponent* wrapper;
  24107. bool createView (const bool createGenericViewIfNeeded)
  24108. {
  24109. NSView* pluginView = 0;
  24110. UInt32 dataSize = 0;
  24111. Boolean isWritable = false;
  24112. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24113. 0, &dataSize, &isWritable) == noErr
  24114. && dataSize != 0
  24115. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24116. 0, &dataSize, &isWritable) == noErr)
  24117. {
  24118. AudioUnitCocoaViewInfo* info = (AudioUnitCocoaViewInfo*) juce_calloc (dataSize);
  24119. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  24120. 0, info, &dataSize) == noErr)
  24121. {
  24122. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  24123. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  24124. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  24125. Class viewClass = [viewBundle classNamed: viewClassName];
  24126. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  24127. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  24128. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  24129. {
  24130. id factory = [[[viewClass alloc] init] autorelease];
  24131. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  24132. withSize: NSMakeSize (getWidth(), getHeight())];
  24133. }
  24134. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  24135. {
  24136. CFRelease (info->mCocoaAUViewClass[i]);
  24137. CFRelease (info->mCocoaAUViewBundleLocation);
  24138. }
  24139. }
  24140. juce_free (info);
  24141. }
  24142. if (createGenericViewIfNeeded && (pluginView == 0))
  24143. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  24144. wrapper->setView (pluginView);
  24145. if (pluginView != 0)
  24146. setSize ([pluginView frame].size.width,
  24147. [pluginView frame].size.height);
  24148. return pluginView != 0;
  24149. }
  24150. };
  24151. #if JUCE_SUPPORT_CARBON
  24152. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  24153. {
  24154. public:
  24155. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  24156. : AudioProcessorEditor (&plugin_),
  24157. plugin (plugin_),
  24158. viewComponent (0)
  24159. {
  24160. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24161. activeWindows.add (this);
  24162. setOpaque (true);
  24163. setVisible (true);
  24164. setSize (400, 300);
  24165. ComponentDescription viewList [16];
  24166. UInt32 viewListSize = sizeof (viewList);
  24167. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  24168. 0, &viewList, &viewListSize);
  24169. componentRecord = FindNextComponent (0, &viewList[0]);
  24170. }
  24171. ~AudioUnitPluginWindowCarbon()
  24172. {
  24173. deleteAndZero (innerWrapper);
  24174. activeWindows.removeValue (this);
  24175. if (isValid())
  24176. plugin.editorBeingDeleted (this);
  24177. }
  24178. bool isValid() const throw() { return componentRecord != 0; }
  24179. void paint (Graphics& g)
  24180. {
  24181. g.fillAll (Colours::black);
  24182. }
  24183. void resized()
  24184. {
  24185. innerWrapper->setSize (getWidth(), getHeight());
  24186. }
  24187. bool keyStateChanged (const bool)
  24188. {
  24189. return false;
  24190. }
  24191. bool keyPressed (const KeyPress&)
  24192. {
  24193. return false;
  24194. }
  24195. void broughtToFront()
  24196. {
  24197. activeWindows.removeValue (this);
  24198. activeWindows.add (this);
  24199. }
  24200. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  24201. AudioUnitCarbonView getViewComponent()
  24202. {
  24203. if (viewComponent == 0 && componentRecord != 0)
  24204. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  24205. return viewComponent;
  24206. }
  24207. void closeViewComponent()
  24208. {
  24209. if (viewComponent != 0)
  24210. {
  24211. CloseComponent (viewComponent);
  24212. viewComponent = 0;
  24213. }
  24214. }
  24215. juce_UseDebuggingNewOperator
  24216. private:
  24217. AudioUnitPluginInstance& plugin;
  24218. ComponentRecord* componentRecord;
  24219. AudioUnitCarbonView viewComponent;
  24220. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24221. {
  24222. public:
  24223. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  24224. : owner (owner_)
  24225. {
  24226. }
  24227. ~InnerWrapperComponent()
  24228. {
  24229. deleteWindow();
  24230. }
  24231. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24232. {
  24233. log (T("Opening AU GUI: ") + owner->plugin.getName());
  24234. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  24235. if (viewComponent == 0)
  24236. return 0;
  24237. Float32Point pos = { 0, 0 };
  24238. Float32Point size = { 250, 200 };
  24239. HIViewRef pluginView = 0;
  24240. AudioUnitCarbonViewCreate (viewComponent,
  24241. owner->getAudioUnit(),
  24242. windowRef,
  24243. rootView,
  24244. &pos,
  24245. &size,
  24246. (ControlRef*) &pluginView);
  24247. return pluginView;
  24248. }
  24249. void removeView (HIViewRef)
  24250. {
  24251. log (T("Closing AU GUI: ") + owner->plugin.getName());
  24252. owner->closeViewComponent();
  24253. }
  24254. private:
  24255. AudioUnitPluginWindowCarbon* const owner;
  24256. };
  24257. friend class InnerWrapperComponent;
  24258. InnerWrapperComponent* innerWrapper;
  24259. };
  24260. #endif
  24261. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  24262. {
  24263. AudioProcessorEditor* w = new AudioUnitPluginWindowCocoa (*this, false);
  24264. if (! ((AudioUnitPluginWindowCocoa*) w)->isValid())
  24265. deleteAndZero (w);
  24266. #if JUCE_SUPPORT_CARBON
  24267. if (w == 0)
  24268. {
  24269. w = new AudioUnitPluginWindowCarbon (*this);
  24270. if (! ((AudioUnitPluginWindowCarbon*) w)->isValid())
  24271. deleteAndZero (w);
  24272. }
  24273. #endif
  24274. if (w == 0)
  24275. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  24276. return w;
  24277. }
  24278. const String AudioUnitPluginInstance::getCategory() const
  24279. {
  24280. const char* result = 0;
  24281. switch (componentDesc.componentType)
  24282. {
  24283. case kAudioUnitType_Effect:
  24284. case kAudioUnitType_MusicEffect:
  24285. result = "Effect";
  24286. break;
  24287. case kAudioUnitType_MusicDevice:
  24288. result = "Synth";
  24289. break;
  24290. case kAudioUnitType_Generator:
  24291. result = "Generator";
  24292. break;
  24293. case kAudioUnitType_Panner:
  24294. result = "Panner";
  24295. break;
  24296. default:
  24297. break;
  24298. }
  24299. return result;
  24300. }
  24301. int AudioUnitPluginInstance::getNumParameters()
  24302. {
  24303. return parameterIds.size();
  24304. }
  24305. float AudioUnitPluginInstance::getParameter (int index)
  24306. {
  24307. const ScopedLock sl (lock);
  24308. Float32 value = 0.0f;
  24309. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24310. {
  24311. AudioUnitGetParameter (audioUnit,
  24312. (UInt32) parameterIds.getUnchecked (index),
  24313. kAudioUnitScope_Global, 0,
  24314. &value);
  24315. }
  24316. return value;
  24317. }
  24318. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  24319. {
  24320. const ScopedLock sl (lock);
  24321. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  24322. {
  24323. AudioUnitSetParameter (audioUnit,
  24324. (UInt32) parameterIds.getUnchecked (index),
  24325. kAudioUnitScope_Global, 0,
  24326. newValue, 0);
  24327. }
  24328. }
  24329. const String AudioUnitPluginInstance::getParameterName (int index)
  24330. {
  24331. AudioUnitParameterInfo info;
  24332. zerostruct (info);
  24333. UInt32 sz = sizeof (info);
  24334. String name;
  24335. if (AudioUnitGetProperty (audioUnit,
  24336. kAudioUnitProperty_ParameterInfo,
  24337. kAudioUnitScope_Global,
  24338. parameterIds [index], &info, &sz) == noErr)
  24339. {
  24340. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  24341. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  24342. else
  24343. name = String (info.name, sizeof (info.name));
  24344. }
  24345. return name;
  24346. }
  24347. const String AudioUnitPluginInstance::getParameterText (int index)
  24348. {
  24349. return String (getParameter (index));
  24350. }
  24351. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  24352. {
  24353. AudioUnitParameterInfo info;
  24354. UInt32 sz = sizeof (info);
  24355. if (AudioUnitGetProperty (audioUnit,
  24356. kAudioUnitProperty_ParameterInfo,
  24357. kAudioUnitScope_Global,
  24358. parameterIds [index], &info, &sz) == noErr)
  24359. {
  24360. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  24361. }
  24362. return true;
  24363. }
  24364. int AudioUnitPluginInstance::getNumPrograms()
  24365. {
  24366. CFArrayRef presets;
  24367. UInt32 sz = sizeof (CFArrayRef);
  24368. int num = 0;
  24369. if (AudioUnitGetProperty (audioUnit,
  24370. kAudioUnitProperty_FactoryPresets,
  24371. kAudioUnitScope_Global,
  24372. 0, &presets, &sz) == noErr)
  24373. {
  24374. num = (int) CFArrayGetCount (presets);
  24375. CFRelease (presets);
  24376. }
  24377. return num;
  24378. }
  24379. int AudioUnitPluginInstance::getCurrentProgram()
  24380. {
  24381. AUPreset current;
  24382. current.presetNumber = 0;
  24383. UInt32 sz = sizeof (AUPreset);
  24384. AudioUnitGetProperty (audioUnit,
  24385. kAudioUnitProperty_FactoryPresets,
  24386. kAudioUnitScope_Global,
  24387. 0, &current, &sz);
  24388. return current.presetNumber;
  24389. }
  24390. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  24391. {
  24392. AUPreset current;
  24393. current.presetNumber = newIndex;
  24394. current.presetName = 0;
  24395. AudioUnitSetProperty (audioUnit,
  24396. kAudioUnitProperty_FactoryPresets,
  24397. kAudioUnitScope_Global,
  24398. 0, &current, sizeof (AUPreset));
  24399. }
  24400. const String AudioUnitPluginInstance::getProgramName (int index)
  24401. {
  24402. String s;
  24403. CFArrayRef presets;
  24404. UInt32 sz = sizeof (CFArrayRef);
  24405. if (AudioUnitGetProperty (audioUnit,
  24406. kAudioUnitProperty_FactoryPresets,
  24407. kAudioUnitScope_Global,
  24408. 0, &presets, &sz) == noErr)
  24409. {
  24410. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  24411. {
  24412. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  24413. if (p != 0 && p->presetNumber == index)
  24414. {
  24415. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  24416. break;
  24417. }
  24418. }
  24419. CFRelease (presets);
  24420. }
  24421. return s;
  24422. }
  24423. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  24424. {
  24425. jassertfalse // xxx not implemented!
  24426. }
  24427. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  24428. {
  24429. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  24430. return T("Input ") + String (index + 1);
  24431. return String::empty;
  24432. }
  24433. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  24434. {
  24435. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  24436. return false;
  24437. return true;
  24438. }
  24439. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  24440. {
  24441. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  24442. return T("Output ") + String (index + 1);
  24443. return String::empty;
  24444. }
  24445. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  24446. {
  24447. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  24448. return false;
  24449. return true;
  24450. }
  24451. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  24452. {
  24453. getCurrentProgramStateInformation (destData);
  24454. }
  24455. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24456. {
  24457. CFPropertyListRef propertyList = 0;
  24458. UInt32 sz = sizeof (CFPropertyListRef);
  24459. if (AudioUnitGetProperty (audioUnit,
  24460. kAudioUnitProperty_ClassInfo,
  24461. kAudioUnitScope_Global,
  24462. 0, &propertyList, &sz) == noErr)
  24463. {
  24464. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  24465. CFWriteStreamOpen (stream);
  24466. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  24467. CFWriteStreamClose (stream);
  24468. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  24469. destData.setSize (bytesWritten);
  24470. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  24471. CFRelease (data);
  24472. CFRelease (stream);
  24473. CFRelease (propertyList);
  24474. }
  24475. }
  24476. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24477. {
  24478. setCurrentProgramStateInformation (data, sizeInBytes);
  24479. }
  24480. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24481. {
  24482. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  24483. (const UInt8*) data,
  24484. sizeInBytes,
  24485. kCFAllocatorNull);
  24486. CFReadStreamOpen (stream);
  24487. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  24488. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  24489. stream,
  24490. 0,
  24491. kCFPropertyListImmutable,
  24492. &format,
  24493. 0);
  24494. CFRelease (stream);
  24495. if (propertyList != 0)
  24496. AudioUnitSetProperty (audioUnit,
  24497. kAudioUnitProperty_ClassInfo,
  24498. kAudioUnitScope_Global,
  24499. 0, &propertyList, sizeof (propertyList));
  24500. }
  24501. AudioUnitPluginFormat::AudioUnitPluginFormat()
  24502. {
  24503. }
  24504. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  24505. {
  24506. }
  24507. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24508. const String& fileOrIdentifier)
  24509. {
  24510. if (! fileMightContainThisPluginType (fileOrIdentifier))
  24511. return;
  24512. PluginDescription desc;
  24513. desc.fileOrIdentifier = fileOrIdentifier;
  24514. desc.uid = 0;
  24515. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  24516. if (instance == 0)
  24517. return;
  24518. try
  24519. {
  24520. instance->fillInPluginDescription (desc);
  24521. results.add (new PluginDescription (desc));
  24522. }
  24523. catch (...)
  24524. {
  24525. // crashed while loading...
  24526. }
  24527. deleteAndZero (instance);
  24528. }
  24529. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24530. {
  24531. AudioUnitPluginInstance* result = 0;
  24532. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  24533. {
  24534. result = new AudioUnitPluginInstance (desc.fileOrIdentifier);
  24535. if (result->audioUnit != 0)
  24536. {
  24537. result->initialise();
  24538. }
  24539. else
  24540. {
  24541. deleteAndZero (result);
  24542. }
  24543. }
  24544. return result;
  24545. }
  24546. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  24547. const bool /*recursive*/)
  24548. {
  24549. StringArray result;
  24550. ComponentRecord* comp = 0;
  24551. ComponentDescription desc;
  24552. zerostruct (desc);
  24553. for (;;)
  24554. {
  24555. zerostruct (desc);
  24556. comp = FindNextComponent (comp, &desc);
  24557. if (comp == 0)
  24558. break;
  24559. GetComponentInfo (comp, &desc, 0, 0, 0);
  24560. if (desc.componentType == kAudioUnitType_MusicDevice
  24561. || desc.componentType == kAudioUnitType_MusicEffect
  24562. || desc.componentType == kAudioUnitType_Effect
  24563. || desc.componentType == kAudioUnitType_Generator
  24564. || desc.componentType == kAudioUnitType_Panner)
  24565. {
  24566. const String s (createAUPluginIdentifier (desc));
  24567. DBG (s);
  24568. result.add (s);
  24569. }
  24570. }
  24571. return result;
  24572. }
  24573. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  24574. {
  24575. ComponentDescription desc;
  24576. String name, version, manufacturer;
  24577. if (getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  24578. return FindNextComponent (0, &desc) != 0;
  24579. const File f (fileOrIdentifier);
  24580. return f.hasFileExtension (T(".component"))
  24581. && f.isDirectory();
  24582. }
  24583. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  24584. {
  24585. ComponentDescription desc;
  24586. String name, version, manufacturer;
  24587. getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  24588. if (name.isEmpty())
  24589. name = fileOrIdentifier;
  24590. return name;
  24591. }
  24592. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  24593. {
  24594. return File (desc.fileOrIdentifier).exists();
  24595. }
  24596. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  24597. {
  24598. return FileSearchPath ("/(Default AudioUnit locations)");
  24599. }
  24600. #endif
  24601. END_JUCE_NAMESPACE
  24602. #undef log
  24603. #endif
  24604. /********* End of inlined file: juce_AudioUnitPluginFormat.mm *********/
  24605. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  24606. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  24607. #define JUCE_MAC_VST_INCLUDED 1
  24608. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  24609. #if JUCE_PLUGINHOST_VST
  24610. #if (defined (_WIN32) || defined (_WIN64))
  24611. #undef _WIN32_WINNT
  24612. #define _WIN32_WINNT 0x500
  24613. #undef STRICT
  24614. #define STRICT
  24615. #include <windows.h>
  24616. #include <float.h>
  24617. #pragma warning (disable : 4312 4355)
  24618. #elif defined (LINUX) || defined (__linux__)
  24619. #include <float.h>
  24620. #include <sys/time.h>
  24621. #include <X11/Xlib.h>
  24622. #include <X11/Xutil.h>
  24623. #include <X11/Xatom.h>
  24624. #undef Font
  24625. #undef KeyPress
  24626. #undef Drawable
  24627. #undef Time
  24628. #else
  24629. #ifndef JUCE_MAC_VST_INCLUDED
  24630. // On the mac, this file needs to be compiled indirectly, by using
  24631. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  24632. #error
  24633. #endif
  24634. #include <Cocoa/Cocoa.h>
  24635. #include <Carbon/Carbon.h>
  24636. #endif
  24637. #if ! (JUCE_MAC && JUCE_64BIT)
  24638. BEGIN_JUCE_NAMESPACE
  24639. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  24640. #endif
  24641. #undef PRAGMA_ALIGN_SUPPORTED
  24642. #define VST_FORCE_DEPRECATED 0
  24643. #ifdef _MSC_VER
  24644. #pragma warning (push)
  24645. #pragma warning (disable: 4996)
  24646. #endif
  24647. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  24648. your include path if you want to add VST support.
  24649. If you're not interested in VSTs, you can disable them by changing the
  24650. JUCE_PLUGINHOST_VST flag in juce_Config.h
  24651. */
  24652. #include "pluginterfaces/vst2.x/aeffectx.h"
  24653. #ifdef _MSC_VER
  24654. #pragma warning (pop)
  24655. #endif
  24656. #if JUCE_LINUX
  24657. #define Font JUCE_NAMESPACE::Font
  24658. #define KeyPress JUCE_NAMESPACE::KeyPress
  24659. #define Drawable JUCE_NAMESPACE::Drawable
  24660. #define Time JUCE_NAMESPACE::Time
  24661. #endif
  24662. /********* Start of inlined file: juce_VSTMidiEventList.h *********/
  24663. #ifdef __aeffect__
  24664. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24665. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24666. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  24667. events to the list.
  24668. This is used by both the VST hosting code and the plugin wrapper.
  24669. */
  24670. class VSTMidiEventList
  24671. {
  24672. public:
  24673. VSTMidiEventList()
  24674. : events (0), numEventsUsed (0), numEventsAllocated (0)
  24675. {
  24676. }
  24677. ~VSTMidiEventList()
  24678. {
  24679. freeEvents();
  24680. }
  24681. void clear()
  24682. {
  24683. numEventsUsed = 0;
  24684. if (events != 0)
  24685. events->numEvents = 0;
  24686. }
  24687. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  24688. {
  24689. ensureSize (numEventsUsed + 1);
  24690. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  24691. events->numEvents = ++numEventsUsed;
  24692. if (numBytes <= 4)
  24693. {
  24694. if (e->type == kVstSysExType)
  24695. {
  24696. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24697. e->type = kVstMidiType;
  24698. e->byteSize = sizeof (VstMidiEvent);
  24699. e->noteLength = 0;
  24700. e->noteOffset = 0;
  24701. e->detune = 0;
  24702. e->noteOffVelocity = 0;
  24703. }
  24704. e->deltaFrames = frameOffset;
  24705. memcpy (e->midiData, midiData, numBytes);
  24706. }
  24707. else
  24708. {
  24709. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  24710. if (se->type == kVstSysExType)
  24711. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  24712. else
  24713. se->sysexDump = (char*) juce_malloc (numBytes);
  24714. memcpy (se->sysexDump, midiData, numBytes);
  24715. se->type = kVstSysExType;
  24716. se->byteSize = sizeof (VstMidiSysexEvent);
  24717. se->deltaFrames = frameOffset;
  24718. se->flags = 0;
  24719. se->dumpBytes = numBytes;
  24720. se->resvd1 = 0;
  24721. se->resvd2 = 0;
  24722. }
  24723. }
  24724. // Handy method to pull the events out of an event buffer supplied by the host
  24725. // or plugin.
  24726. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  24727. {
  24728. for (int i = 0; i < events->numEvents; ++i)
  24729. {
  24730. const VstEvent* const e = events->events[i];
  24731. if (e != 0)
  24732. {
  24733. if (e->type == kVstMidiType)
  24734. {
  24735. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  24736. 4, e->deltaFrames);
  24737. }
  24738. else if (e->type == kVstSysExType)
  24739. {
  24740. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  24741. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  24742. e->deltaFrames);
  24743. }
  24744. }
  24745. }
  24746. }
  24747. void ensureSize (int numEventsNeeded)
  24748. {
  24749. if (numEventsNeeded > numEventsAllocated)
  24750. {
  24751. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24752. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24753. if (events == 0)
  24754. events = (VstEvents*) juce_calloc (size);
  24755. else
  24756. events = (VstEvents*) juce_realloc (events, size);
  24757. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  24758. {
  24759. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  24760. (int) sizeof (VstMidiSysexEvent)));
  24761. e->type = kVstMidiType;
  24762. e->byteSize = sizeof (VstMidiEvent);
  24763. events->events[i] = (VstEvent*) e;
  24764. }
  24765. numEventsAllocated = numEventsNeeded;
  24766. }
  24767. }
  24768. void freeEvents()
  24769. {
  24770. if (events != 0)
  24771. {
  24772. for (int i = numEventsAllocated; --i >= 0;)
  24773. {
  24774. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  24775. if (e->type == kVstSysExType)
  24776. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  24777. juce_free (e);
  24778. }
  24779. juce_free (events);
  24780. events = 0;
  24781. numEventsUsed = 0;
  24782. numEventsAllocated = 0;
  24783. }
  24784. }
  24785. VstEvents* events;
  24786. private:
  24787. int numEventsUsed, numEventsAllocated;
  24788. };
  24789. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24790. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  24791. /********* End of inlined file: juce_VSTMidiEventList.h *********/
  24792. #if ! JUCE_WIN32
  24793. #define _fpreset()
  24794. #define _clearfp()
  24795. #endif
  24796. extern void juce_callAnyTimersSynchronously();
  24797. const int fxbVersionNum = 1;
  24798. struct fxProgram
  24799. {
  24800. long chunkMagic; // 'CcnK'
  24801. long byteSize; // of this chunk, excl. magic + byteSize
  24802. long fxMagic; // 'FxCk'
  24803. long version;
  24804. long fxID; // fx unique id
  24805. long fxVersion;
  24806. long numParams;
  24807. char prgName[28];
  24808. float params[1]; // variable no. of parameters
  24809. };
  24810. struct fxSet
  24811. {
  24812. long chunkMagic; // 'CcnK'
  24813. long byteSize; // of this chunk, excl. magic + byteSize
  24814. long fxMagic; // 'FxBk'
  24815. long version;
  24816. long fxID; // fx unique id
  24817. long fxVersion;
  24818. long numPrograms;
  24819. char future[128];
  24820. fxProgram programs[1]; // variable no. of programs
  24821. };
  24822. struct fxChunkSet
  24823. {
  24824. long chunkMagic; // 'CcnK'
  24825. long byteSize; // of this chunk, excl. magic + byteSize
  24826. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24827. long version;
  24828. long fxID; // fx unique id
  24829. long fxVersion;
  24830. long numPrograms;
  24831. char future[128];
  24832. long chunkSize;
  24833. char chunk[8]; // variable
  24834. };
  24835. struct fxProgramSet
  24836. {
  24837. long chunkMagic; // 'CcnK'
  24838. long byteSize; // of this chunk, excl. magic + byteSize
  24839. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  24840. long version;
  24841. long fxID; // fx unique id
  24842. long fxVersion;
  24843. long numPrograms;
  24844. char name[28];
  24845. long chunkSize;
  24846. char chunk[8]; // variable
  24847. };
  24848. #ifdef JUCE_LITTLE_ENDIAN
  24849. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  24850. static float vst_swapFloat (const float x) throw()
  24851. {
  24852. union { uint32 asInt; float asFloat; } n;
  24853. n.asFloat = x;
  24854. n.asInt = swapByteOrder (n.asInt);
  24855. return n.asFloat;
  24856. }
  24857. #else
  24858. #define vst_swap(x) (x)
  24859. #define vst_swapFloat(x) (x)
  24860. #endif
  24861. typedef AEffect* (*MainCall) (audioMasterCallback);
  24862. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  24863. static int shellUIDToCreate = 0;
  24864. static int insideVSTCallback = 0;
  24865. class VSTPluginWindow;
  24866. // Change this to disable logging of various VST activities
  24867. #ifndef VST_LOGGING
  24868. #define VST_LOGGING 1
  24869. #endif
  24870. #if VST_LOGGING
  24871. #define log(a) Logger::writeToLog(a);
  24872. #else
  24873. #define log(a)
  24874. #endif
  24875. #if JUCE_MAC && JUCE_PPC
  24876. static void* NewCFMFromMachO (void* const machofp) throw()
  24877. {
  24878. void* result = juce_malloc (8);
  24879. ((void**) result)[0] = machofp;
  24880. ((void**) result)[1] = result;
  24881. return result;
  24882. }
  24883. #endif
  24884. #if JUCE_LINUX
  24885. extern Display* display;
  24886. extern XContext improbableNumber;
  24887. typedef void (*EventProcPtr) (XEvent* ev);
  24888. static bool xErrorTriggered;
  24889. static int temporaryErrorHandler (Display*, XErrorEvent*)
  24890. {
  24891. xErrorTriggered = true;
  24892. return 0;
  24893. }
  24894. static int getPropertyFromXWindow (Window handle, Atom atom)
  24895. {
  24896. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  24897. xErrorTriggered = false;
  24898. int userSize;
  24899. unsigned long bytes, userCount;
  24900. unsigned char* data;
  24901. Atom userType;
  24902. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  24903. &userType, &userSize, &userCount, &bytes, &data);
  24904. XSetErrorHandler (oldErrorHandler);
  24905. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  24906. : 0;
  24907. }
  24908. static Window getChildWindow (Window windowToCheck)
  24909. {
  24910. Window rootWindow, parentWindow;
  24911. Window* childWindows;
  24912. unsigned int numChildren;
  24913. XQueryTree (display,
  24914. windowToCheck,
  24915. &rootWindow,
  24916. &parentWindow,
  24917. &childWindows,
  24918. &numChildren);
  24919. if (numChildren > 0)
  24920. return childWindows [0];
  24921. return 0;
  24922. }
  24923. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  24924. {
  24925. if (e.mods.isLeftButtonDown())
  24926. {
  24927. ev.xbutton.button = Button1;
  24928. ev.xbutton.state |= Button1Mask;
  24929. }
  24930. else if (e.mods.isRightButtonDown())
  24931. {
  24932. ev.xbutton.button = Button3;
  24933. ev.xbutton.state |= Button3Mask;
  24934. }
  24935. else if (e.mods.isMiddleButtonDown())
  24936. {
  24937. ev.xbutton.button = Button2;
  24938. ev.xbutton.state |= Button2Mask;
  24939. }
  24940. }
  24941. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  24942. {
  24943. if (e.mods.isLeftButtonDown())
  24944. ev.xmotion.state |= Button1Mask;
  24945. else if (e.mods.isRightButtonDown())
  24946. ev.xmotion.state |= Button3Mask;
  24947. else if (e.mods.isMiddleButtonDown())
  24948. ev.xmotion.state |= Button2Mask;
  24949. }
  24950. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  24951. {
  24952. if (e.mods.isLeftButtonDown())
  24953. ev.xcrossing.state |= Button1Mask;
  24954. else if (e.mods.isRightButtonDown())
  24955. ev.xcrossing.state |= Button3Mask;
  24956. else if (e.mods.isMiddleButtonDown())
  24957. ev.xcrossing.state |= Button2Mask;
  24958. }
  24959. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  24960. {
  24961. if (increment < 0)
  24962. {
  24963. ev.xbutton.button = Button5;
  24964. ev.xbutton.state |= Button5Mask;
  24965. }
  24966. else if (increment > 0)
  24967. {
  24968. ev.xbutton.button = Button4;
  24969. ev.xbutton.state |= Button4Mask;
  24970. }
  24971. }
  24972. #endif
  24973. static VoidArray activeModules;
  24974. class ModuleHandle : public ReferenceCountedObject
  24975. {
  24976. public:
  24977. File file;
  24978. MainCall moduleMain;
  24979. String pluginName;
  24980. static ModuleHandle* findOrCreateModule (const File& file)
  24981. {
  24982. for (int i = activeModules.size(); --i >= 0;)
  24983. {
  24984. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  24985. if (module->file == file)
  24986. return module;
  24987. }
  24988. _fpreset(); // (doesn't do any harm)
  24989. ++insideVSTCallback;
  24990. shellUIDToCreate = 0;
  24991. log ("Attempting to load VST: " + file.getFullPathName());
  24992. ModuleHandle* m = new ModuleHandle (file);
  24993. if (! m->open())
  24994. deleteAndZero (m);
  24995. --insideVSTCallback;
  24996. _fpreset(); // (doesn't do any harm)
  24997. return m;
  24998. }
  24999. ModuleHandle (const File& file_)
  25000. : file (file_),
  25001. moduleMain (0),
  25002. #if JUCE_WIN32 || JUCE_LINUX
  25003. hModule (0)
  25004. #elif JUCE_MAC
  25005. fragId (0),
  25006. resHandle (0),
  25007. bundleRef (0),
  25008. resFileId (0)
  25009. #endif
  25010. {
  25011. activeModules.add (this);
  25012. #if JUCE_WIN32 || JUCE_LINUX
  25013. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  25014. #elif JUCE_MAC
  25015. FSRef ref;
  25016. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  25017. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  25018. #endif
  25019. }
  25020. ~ModuleHandle()
  25021. {
  25022. activeModules.removeValue (this);
  25023. close();
  25024. }
  25025. juce_UseDebuggingNewOperator
  25026. #if JUCE_WIN32 || JUCE_LINUX
  25027. void* hModule;
  25028. String fullParentDirectoryPathName;
  25029. bool open()
  25030. {
  25031. #if JUCE_WIN32
  25032. static bool timePeriodSet = false;
  25033. if (! timePeriodSet)
  25034. {
  25035. timePeriodSet = true;
  25036. timeBeginPeriod (2);
  25037. }
  25038. #endif
  25039. pluginName = file.getFileNameWithoutExtension();
  25040. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  25041. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  25042. if (moduleMain == 0)
  25043. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  25044. return moduleMain != 0;
  25045. }
  25046. void close()
  25047. {
  25048. _fpreset(); // (doesn't do any harm)
  25049. PlatformUtilities::freeDynamicLibrary (hModule);
  25050. }
  25051. void closeEffect (AEffect* eff)
  25052. {
  25053. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25054. }
  25055. #else
  25056. CFragConnectionID fragId;
  25057. Handle resHandle;
  25058. CFBundleRef bundleRef;
  25059. FSSpec parentDirFSSpec;
  25060. short resFileId;
  25061. bool open()
  25062. {
  25063. bool ok = false;
  25064. const String filename (file.getFullPathName());
  25065. if (file.hasFileExtension (T(".vst")))
  25066. {
  25067. const char* const utf8 = filename.toUTF8();
  25068. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25069. strlen (utf8), file.isDirectory());
  25070. if (url != 0)
  25071. {
  25072. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25073. CFRelease (url);
  25074. if (bundleRef != 0)
  25075. {
  25076. if (CFBundleLoadExecutable (bundleRef))
  25077. {
  25078. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  25079. if (moduleMain == 0)
  25080. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  25081. if (moduleMain != 0)
  25082. {
  25083. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25084. if (name != 0)
  25085. {
  25086. if (CFGetTypeID (name) == CFStringGetTypeID())
  25087. {
  25088. char buffer[1024];
  25089. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  25090. pluginName = buffer;
  25091. }
  25092. }
  25093. if (pluginName.isEmpty())
  25094. pluginName = file.getFileNameWithoutExtension();
  25095. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25096. ok = true;
  25097. }
  25098. }
  25099. if (! ok)
  25100. {
  25101. CFBundleUnloadExecutable (bundleRef);
  25102. CFRelease (bundleRef);
  25103. bundleRef = 0;
  25104. }
  25105. }
  25106. }
  25107. }
  25108. #if JUCE_PPC
  25109. else
  25110. {
  25111. FSRef fn;
  25112. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  25113. {
  25114. resFileId = FSOpenResFile (&fn, fsRdPerm);
  25115. if (resFileId != -1)
  25116. {
  25117. const int numEffs = Count1Resources ('aEff');
  25118. for (int i = 0; i < numEffs; ++i)
  25119. {
  25120. resHandle = Get1IndResource ('aEff', i + 1);
  25121. if (resHandle != 0)
  25122. {
  25123. OSType type;
  25124. Str255 name;
  25125. SInt16 id;
  25126. GetResInfo (resHandle, &id, &type, name);
  25127. pluginName = String ((const char*) name + 1, name[0]);
  25128. DetachResource (resHandle);
  25129. HLock (resHandle);
  25130. Ptr ptr;
  25131. Str255 errorText;
  25132. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  25133. name, kPrivateCFragCopy,
  25134. &fragId, &ptr, errorText);
  25135. if (err == noErr)
  25136. {
  25137. moduleMain = (MainCall) newMachOFromCFM (ptr);
  25138. ok = true;
  25139. }
  25140. else
  25141. {
  25142. HUnlock (resHandle);
  25143. }
  25144. break;
  25145. }
  25146. }
  25147. if (! ok)
  25148. CloseResFile (resFileId);
  25149. }
  25150. }
  25151. }
  25152. #endif
  25153. return ok;
  25154. }
  25155. void close()
  25156. {
  25157. #if JUCE_PPC
  25158. if (fragId != 0)
  25159. {
  25160. if (moduleMain != 0)
  25161. disposeMachOFromCFM ((void*) moduleMain);
  25162. CloseConnection (&fragId);
  25163. HUnlock (resHandle);
  25164. if (resFileId != 0)
  25165. CloseResFile (resFileId);
  25166. }
  25167. else
  25168. #endif
  25169. if (bundleRef != 0)
  25170. {
  25171. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25172. if (CFGetRetainCount (bundleRef) == 1)
  25173. CFBundleUnloadExecutable (bundleRef);
  25174. if (CFGetRetainCount (bundleRef) > 0)
  25175. CFRelease (bundleRef);
  25176. }
  25177. }
  25178. void closeEffect (AEffect* eff)
  25179. {
  25180. #if JUCE_PPC
  25181. if (fragId != 0)
  25182. {
  25183. VoidArray thingsToDelete;
  25184. thingsToDelete.add ((void*) eff->dispatcher);
  25185. thingsToDelete.add ((void*) eff->process);
  25186. thingsToDelete.add ((void*) eff->setParameter);
  25187. thingsToDelete.add ((void*) eff->getParameter);
  25188. thingsToDelete.add ((void*) eff->processReplacing);
  25189. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25190. for (int i = thingsToDelete.size(); --i >= 0;)
  25191. disposeMachOFromCFM (thingsToDelete[i]);
  25192. }
  25193. else
  25194. #endif
  25195. {
  25196. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  25197. }
  25198. }
  25199. #if JUCE_PPC
  25200. static void* newMachOFromCFM (void* cfmfp)
  25201. {
  25202. if (cfmfp == 0)
  25203. return 0;
  25204. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  25205. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  25206. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  25207. mfp[2] = 0x800c0000;
  25208. mfp[3] = 0x804c0004;
  25209. mfp[4] = 0x7c0903a6;
  25210. mfp[5] = 0x4e800420;
  25211. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  25212. return mfp;
  25213. }
  25214. static void disposeMachOFromCFM (void* ptr)
  25215. {
  25216. juce_free (ptr);
  25217. }
  25218. void coerceAEffectFunctionCalls (AEffect* eff)
  25219. {
  25220. if (fragId != 0)
  25221. {
  25222. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  25223. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  25224. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  25225. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  25226. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  25227. }
  25228. }
  25229. #endif
  25230. #endif
  25231. };
  25232. /**
  25233. An instance of a plugin, created by a VSTPluginFormat.
  25234. */
  25235. class VSTPluginInstance : public AudioPluginInstance,
  25236. private Timer,
  25237. private AsyncUpdater
  25238. {
  25239. public:
  25240. ~VSTPluginInstance();
  25241. // AudioPluginInstance methods:
  25242. void fillInPluginDescription (PluginDescription& desc) const
  25243. {
  25244. desc.name = name;
  25245. desc.fileOrIdentifier = module->file.getFullPathName();
  25246. desc.uid = getUID();
  25247. desc.lastFileModTime = module->file.getLastModificationTime();
  25248. desc.pluginFormatName = "VST";
  25249. desc.category = getCategory();
  25250. {
  25251. char buffer [kVstMaxVendorStrLen + 8];
  25252. zerostruct (buffer);
  25253. dispatch (effGetVendorString, 0, 0, buffer, 0);
  25254. desc.manufacturerName = buffer;
  25255. }
  25256. desc.version = getVersion();
  25257. desc.numInputChannels = getNumInputChannels();
  25258. desc.numOutputChannels = getNumOutputChannels();
  25259. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  25260. }
  25261. const String getName() const { return name; }
  25262. int getUID() const throw();
  25263. bool acceptsMidi() const { return wantsMidiMessages; }
  25264. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  25265. // AudioProcessor methods:
  25266. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25267. void releaseResources();
  25268. void processBlock (AudioSampleBuffer& buffer,
  25269. MidiBuffer& midiMessages);
  25270. AudioProcessorEditor* createEditor();
  25271. const String getInputChannelName (const int index) const;
  25272. bool isInputChannelStereoPair (int index) const;
  25273. const String getOutputChannelName (const int index) const;
  25274. bool isOutputChannelStereoPair (int index) const;
  25275. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  25276. float getParameter (int index);
  25277. void setParameter (int index, float newValue);
  25278. const String getParameterName (int index);
  25279. const String getParameterText (int index);
  25280. bool isParameterAutomatable (int index) const;
  25281. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  25282. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  25283. void setCurrentProgram (int index);
  25284. const String getProgramName (int index);
  25285. void changeProgramName (int index, const String& newName);
  25286. void getStateInformation (MemoryBlock& destData);
  25287. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25288. void setStateInformation (const void* data, int sizeInBytes);
  25289. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25290. void timerCallback();
  25291. void handleAsyncUpdate();
  25292. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  25293. juce_UseDebuggingNewOperator
  25294. private:
  25295. friend class VSTPluginWindow;
  25296. friend class VSTPluginFormat;
  25297. AEffect* effect;
  25298. String name;
  25299. CriticalSection lock;
  25300. bool wantsMidiMessages, initialised, isPowerOn;
  25301. mutable StringArray programNames;
  25302. AudioSampleBuffer tempBuffer;
  25303. CriticalSection midiInLock;
  25304. MidiBuffer incomingMidi;
  25305. VSTMidiEventList midiEventsToSend;
  25306. VstTimeInfo vstHostTime;
  25307. float** channels;
  25308. ReferenceCountedObjectPtr <ModuleHandle> module;
  25309. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  25310. bool restoreProgramSettings (const fxProgram* const prog);
  25311. const String getCurrentProgramName();
  25312. void setParamsInProgramBlock (fxProgram* const prog) throw();
  25313. void updateStoredProgramNames();
  25314. void initialise();
  25315. void handleMidiFromPlugin (const VstEvents* const events);
  25316. void createTempParameterStore (MemoryBlock& dest);
  25317. void restoreFromTempParameterStore (const MemoryBlock& mb);
  25318. const String getParameterLabel (int index) const;
  25319. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  25320. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  25321. void setChunkData (const char* data, int size, bool isPreset);
  25322. bool loadFromFXBFile (const void* data, int numBytes);
  25323. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  25324. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  25325. const String getVersion() const throw();
  25326. const String getCategory() const throw();
  25327. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  25328. void setPower (const bool on);
  25329. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  25330. };
  25331. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  25332. : effect (0),
  25333. wantsMidiMessages (false),
  25334. initialised (false),
  25335. isPowerOn (false),
  25336. tempBuffer (1, 1),
  25337. channels (0),
  25338. module (module_)
  25339. {
  25340. try
  25341. {
  25342. _fpreset();
  25343. ++insideVSTCallback;
  25344. name = module->pluginName;
  25345. log (T("Creating VST instance: ") + name);
  25346. #if JUCE_MAC
  25347. if (module->resFileId != 0)
  25348. UseResFile (module->resFileId);
  25349. #if JUCE_PPC
  25350. if (module->fragId != 0)
  25351. {
  25352. static void* audioMasterCoerced = 0;
  25353. if (audioMasterCoerced == 0)
  25354. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  25355. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  25356. }
  25357. else
  25358. #endif
  25359. #endif
  25360. {
  25361. effect = module->moduleMain (&audioMaster);
  25362. }
  25363. --insideVSTCallback;
  25364. if (effect != 0 && effect->magic == kEffectMagic)
  25365. {
  25366. #if JUCE_PPC
  25367. module->coerceAEffectFunctionCalls (effect);
  25368. #endif
  25369. jassert (effect->resvd2 == 0);
  25370. jassert (effect->object != 0);
  25371. _fpreset(); // some dodgy plugs fuck around with this
  25372. }
  25373. else
  25374. {
  25375. effect = 0;
  25376. }
  25377. }
  25378. catch (...)
  25379. {
  25380. --insideVSTCallback;
  25381. }
  25382. }
  25383. VSTPluginInstance::~VSTPluginInstance()
  25384. {
  25385. {
  25386. const ScopedLock sl (lock);
  25387. jassert (insideVSTCallback == 0);
  25388. if (effect != 0 && effect->magic == kEffectMagic)
  25389. {
  25390. try
  25391. {
  25392. #if JUCE_MAC
  25393. if (module->resFileId != 0)
  25394. UseResFile (module->resFileId);
  25395. #endif
  25396. // Must delete any editors before deleting the plugin instance!
  25397. jassert (getActiveEditor() == 0);
  25398. _fpreset(); // some dodgy plugs fuck around with this
  25399. module->closeEffect (effect);
  25400. }
  25401. catch (...)
  25402. {}
  25403. }
  25404. module = 0;
  25405. effect = 0;
  25406. }
  25407. juce_free (channels);
  25408. channels = 0;
  25409. }
  25410. void VSTPluginInstance::initialise()
  25411. {
  25412. if (initialised || effect == 0)
  25413. return;
  25414. log (T("Initialising VST: ") + module->pluginName);
  25415. initialised = true;
  25416. dispatch (effIdentify, 0, 0, 0, 0);
  25417. // this code would ask the plugin for its name, but so few plugins
  25418. // actually bother implementing this correctly, that it's better to
  25419. // just ignore it and use the file name instead.
  25420. /* {
  25421. char buffer [256];
  25422. zerostruct (buffer);
  25423. dispatch (effGetEffectName, 0, 0, buffer, 0);
  25424. name = String (buffer).trim();
  25425. if (name.isEmpty())
  25426. name = module->pluginName;
  25427. }
  25428. */
  25429. if (getSampleRate() > 0)
  25430. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  25431. if (getBlockSize() > 0)
  25432. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  25433. dispatch (effOpen, 0, 0, 0, 0);
  25434. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25435. getSampleRate(), getBlockSize());
  25436. if (getNumPrograms() > 1)
  25437. setCurrentProgram (0);
  25438. else
  25439. dispatch (effSetProgram, 0, 0, 0, 0);
  25440. int i;
  25441. for (i = effect->numInputs; --i >= 0;)
  25442. dispatch (effConnectInput, i, 1, 0, 0);
  25443. for (i = effect->numOutputs; --i >= 0;)
  25444. dispatch (effConnectOutput, i, 1, 0, 0);
  25445. updateStoredProgramNames();
  25446. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  25447. setLatencySamples (effect->initialDelay);
  25448. }
  25449. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  25450. int samplesPerBlockExpected)
  25451. {
  25452. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  25453. sampleRate_, samplesPerBlockExpected);
  25454. setLatencySamples (effect->initialDelay);
  25455. juce_free (channels);
  25456. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  25457. vstHostTime.tempo = 120.0;
  25458. vstHostTime.timeSigNumerator = 4;
  25459. vstHostTime.timeSigDenominator = 4;
  25460. vstHostTime.sampleRate = sampleRate_;
  25461. vstHostTime.samplePos = 0;
  25462. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  25463. initialise();
  25464. if (initialised)
  25465. {
  25466. wantsMidiMessages = wantsMidiMessages
  25467. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  25468. if (wantsMidiMessages)
  25469. midiEventsToSend.ensureSize (256);
  25470. else
  25471. midiEventsToSend.freeEvents();
  25472. incomingMidi.clear();
  25473. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  25474. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  25475. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  25476. if (! isPowerOn)
  25477. setPower (true);
  25478. // dodgy hack to force some plugins to initialise the sample rate..
  25479. if ((! hasEditor()) && getNumParameters() > 0)
  25480. {
  25481. const float old = getParameter (0);
  25482. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  25483. setParameter (0, old);
  25484. }
  25485. dispatch (effStartProcess, 0, 0, 0, 0);
  25486. }
  25487. }
  25488. void VSTPluginInstance::releaseResources()
  25489. {
  25490. if (initialised)
  25491. {
  25492. dispatch (effStopProcess, 0, 0, 0, 0);
  25493. setPower (false);
  25494. }
  25495. tempBuffer.setSize (1, 1);
  25496. incomingMidi.clear();
  25497. midiEventsToSend.freeEvents();
  25498. juce_free (channels);
  25499. channels = 0;
  25500. }
  25501. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25502. MidiBuffer& midiMessages)
  25503. {
  25504. const int numSamples = buffer.getNumSamples();
  25505. if (initialised)
  25506. {
  25507. AudioPlayHead* playHead = getPlayHead();
  25508. if (playHead != 0)
  25509. {
  25510. AudioPlayHead::CurrentPositionInfo position;
  25511. playHead->getCurrentPosition (position);
  25512. vstHostTime.tempo = position.bpm;
  25513. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  25514. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  25515. vstHostTime.ppqPos = position.ppqPosition;
  25516. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  25517. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  25518. if (position.isPlaying)
  25519. vstHostTime.flags |= kVstTransportPlaying;
  25520. else
  25521. vstHostTime.flags &= ~kVstTransportPlaying;
  25522. }
  25523. #if JUCE_WIN32
  25524. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  25525. #elif JUCE_LINUX
  25526. timeval micro;
  25527. gettimeofday (&micro, 0);
  25528. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  25529. #elif JUCE_MAC
  25530. UnsignedWide micro;
  25531. Microseconds (&micro);
  25532. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  25533. #endif
  25534. if (wantsMidiMessages)
  25535. {
  25536. midiEventsToSend.clear();
  25537. midiEventsToSend.ensureSize (1);
  25538. MidiBuffer::Iterator iter (midiMessages);
  25539. const uint8* midiData;
  25540. int numBytesOfMidiData, samplePosition;
  25541. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  25542. {
  25543. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  25544. jlimit (0, numSamples - 1, samplePosition));
  25545. }
  25546. try
  25547. {
  25548. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  25549. }
  25550. catch (...)
  25551. {}
  25552. }
  25553. int i;
  25554. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  25555. for (i = 0; i < maxChans; ++i)
  25556. channels[i] = buffer.getSampleData (i);
  25557. channels [maxChans] = 0;
  25558. _clearfp();
  25559. if ((effect->flags & effFlagsCanReplacing) != 0)
  25560. {
  25561. try
  25562. {
  25563. effect->processReplacing (effect, channels, channels, numSamples);
  25564. }
  25565. catch (...)
  25566. {}
  25567. }
  25568. else
  25569. {
  25570. tempBuffer.setSize (effect->numOutputs, numSamples);
  25571. tempBuffer.clear();
  25572. float* outs [64];
  25573. for (i = effect->numOutputs; --i >= 0;)
  25574. outs[i] = tempBuffer.getSampleData (i);
  25575. outs [effect->numOutputs] = 0;
  25576. try
  25577. {
  25578. effect->process (effect, channels, outs, numSamples);
  25579. }
  25580. catch (...)
  25581. {}
  25582. for (i = effect->numOutputs; --i >= 0;)
  25583. buffer.copyFrom (i, 0, outs[i], numSamples);
  25584. }
  25585. }
  25586. else
  25587. {
  25588. // Not initialised, so just bypass..
  25589. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25590. buffer.clear (i, 0, buffer.getNumSamples());
  25591. }
  25592. {
  25593. // copy any incoming midi..
  25594. const ScopedLock sl (midiInLock);
  25595. midiMessages = incomingMidi;
  25596. incomingMidi.clear();
  25597. }
  25598. }
  25599. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  25600. {
  25601. if (events != 0)
  25602. {
  25603. const ScopedLock sl (midiInLock);
  25604. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  25605. }
  25606. }
  25607. static Array <VSTPluginWindow*> activeVSTWindows;
  25608. class VSTPluginWindow : public AudioProcessorEditor,
  25609. #if ! JUCE_MAC
  25610. public ComponentMovementWatcher,
  25611. #endif
  25612. public Timer
  25613. {
  25614. public:
  25615. VSTPluginWindow (VSTPluginInstance& plugin_)
  25616. : AudioProcessorEditor (&plugin_),
  25617. #if ! JUCE_MAC
  25618. ComponentMovementWatcher (this),
  25619. #endif
  25620. plugin (plugin_),
  25621. isOpen (false),
  25622. wasShowing (false),
  25623. pluginRefusesToResize (false),
  25624. pluginWantsKeys (false),
  25625. alreadyInside (false),
  25626. recursiveResize (false)
  25627. {
  25628. #if JUCE_WIN32
  25629. sizeCheckCount = 0;
  25630. pluginHWND = 0;
  25631. #elif JUCE_LINUX
  25632. pluginWindow = None;
  25633. pluginProc = None;
  25634. #else
  25635. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25636. #endif
  25637. activeVSTWindows.add (this);
  25638. setSize (1, 1);
  25639. setOpaque (true);
  25640. setVisible (true);
  25641. }
  25642. ~VSTPluginWindow()
  25643. {
  25644. #if JUCE_MAC
  25645. deleteAndZero (innerWrapper);
  25646. #else
  25647. closePluginWindow();
  25648. #endif
  25649. activeVSTWindows.removeValue (this);
  25650. plugin.editorBeingDeleted (this);
  25651. }
  25652. #if ! JUCE_MAC
  25653. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  25654. {
  25655. if (recursiveResize)
  25656. return;
  25657. Component* const topComp = getTopLevelComponent();
  25658. if (topComp->getPeer() != 0)
  25659. {
  25660. int x = 0, y = 0;
  25661. relativePositionToOtherComponent (topComp, x, y);
  25662. recursiveResize = true;
  25663. #if JUCE_WIN32
  25664. if (pluginHWND != 0)
  25665. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  25666. #elif JUCE_LINUX
  25667. if (pluginWindow != 0)
  25668. {
  25669. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  25670. XMoveWindow (display, pluginWindow, x, y);
  25671. XMapRaised (display, pluginWindow);
  25672. }
  25673. #endif
  25674. recursiveResize = false;
  25675. }
  25676. }
  25677. void componentVisibilityChanged (Component&)
  25678. {
  25679. const bool isShowingNow = isShowing();
  25680. if (wasShowing != isShowingNow)
  25681. {
  25682. wasShowing = isShowingNow;
  25683. if (isShowingNow)
  25684. openPluginWindow();
  25685. else
  25686. closePluginWindow();
  25687. }
  25688. componentMovedOrResized (true, true);
  25689. }
  25690. void componentPeerChanged()
  25691. {
  25692. closePluginWindow();
  25693. openPluginWindow();
  25694. }
  25695. #endif
  25696. bool keyStateChanged (const bool)
  25697. {
  25698. return pluginWantsKeys;
  25699. }
  25700. bool keyPressed (const KeyPress&)
  25701. {
  25702. return pluginWantsKeys;
  25703. }
  25704. #if JUCE_MAC
  25705. void paint (Graphics& g)
  25706. {
  25707. g.fillAll (Colours::black);
  25708. }
  25709. #else
  25710. void paint (Graphics& g)
  25711. {
  25712. if (isOpen)
  25713. {
  25714. ComponentPeer* const peer = getPeer();
  25715. if (peer != 0)
  25716. {
  25717. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  25718. getScreenY() - peer->getScreenY(),
  25719. getWidth(), getHeight());
  25720. #if JUCE_LINUX
  25721. if (pluginWindow != 0)
  25722. {
  25723. const Rectangle clip (g.getClipBounds());
  25724. XEvent ev;
  25725. zerostruct (ev);
  25726. ev.xexpose.type = Expose;
  25727. ev.xexpose.display = display;
  25728. ev.xexpose.window = pluginWindow;
  25729. ev.xexpose.x = clip.getX();
  25730. ev.xexpose.y = clip.getY();
  25731. ev.xexpose.width = clip.getWidth();
  25732. ev.xexpose.height = clip.getHeight();
  25733. sendEventToChild (&ev);
  25734. }
  25735. #endif
  25736. }
  25737. }
  25738. else
  25739. {
  25740. g.fillAll (Colours::black);
  25741. }
  25742. }
  25743. #endif
  25744. void timerCallback()
  25745. {
  25746. #if JUCE_WIN32
  25747. if (--sizeCheckCount <= 0)
  25748. {
  25749. sizeCheckCount = 10;
  25750. checkPluginWindowSize();
  25751. }
  25752. #endif
  25753. try
  25754. {
  25755. static bool reentrant = false;
  25756. if (! reentrant)
  25757. {
  25758. reentrant = true;
  25759. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  25760. reentrant = false;
  25761. }
  25762. }
  25763. catch (...)
  25764. {}
  25765. }
  25766. void mouseDown (const MouseEvent& e)
  25767. {
  25768. #if JUCE_LINUX
  25769. if (pluginWindow == 0)
  25770. return;
  25771. toFront (true);
  25772. XEvent ev;
  25773. zerostruct (ev);
  25774. ev.xbutton.display = display;
  25775. ev.xbutton.type = ButtonPress;
  25776. ev.xbutton.window = pluginWindow;
  25777. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  25778. ev.xbutton.time = CurrentTime;
  25779. ev.xbutton.x = e.x;
  25780. ev.xbutton.y = e.y;
  25781. ev.xbutton.x_root = e.getScreenX();
  25782. ev.xbutton.y_root = e.getScreenY();
  25783. translateJuceToXButtonModifiers (e, ev);
  25784. sendEventToChild (&ev);
  25785. #elif JUCE_WIN32
  25786. (void) e;
  25787. toFront (true);
  25788. #endif
  25789. }
  25790. void broughtToFront()
  25791. {
  25792. activeVSTWindows.removeValue (this);
  25793. activeVSTWindows.add (this);
  25794. #if JUCE_MAC
  25795. dispatch (effEditTop, 0, 0, 0, 0);
  25796. #endif
  25797. }
  25798. juce_UseDebuggingNewOperator
  25799. private:
  25800. VSTPluginInstance& plugin;
  25801. bool isOpen, wasShowing, recursiveResize;
  25802. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  25803. #if JUCE_WIN32
  25804. HWND pluginHWND;
  25805. void* originalWndProc;
  25806. int sizeCheckCount;
  25807. #elif JUCE_LINUX
  25808. Window pluginWindow;
  25809. EventProcPtr pluginProc;
  25810. #endif
  25811. #if JUCE_MAC
  25812. void openPluginWindow (WindowRef parentWindow)
  25813. {
  25814. if (isOpen || parentWindow == 0)
  25815. return;
  25816. isOpen = true;
  25817. ERect* rect = 0;
  25818. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25819. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  25820. // do this before and after like in the steinberg example
  25821. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25822. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25823. // Install keyboard hooks
  25824. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25825. // double-check it's not too tiny
  25826. int w = 250, h = 150;
  25827. if (rect != 0)
  25828. {
  25829. w = rect->right - rect->left;
  25830. h = rect->bottom - rect->top;
  25831. if (w == 0 || h == 0)
  25832. {
  25833. w = 250;
  25834. h = 150;
  25835. }
  25836. }
  25837. w = jmax (w, 32);
  25838. h = jmax (h, 32);
  25839. setSize (w, h);
  25840. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25841. repaint();
  25842. }
  25843. #else
  25844. void openPluginWindow()
  25845. {
  25846. if (isOpen || getWindowHandle() == 0)
  25847. return;
  25848. log (T("Opening VST UI: ") + plugin.name);
  25849. isOpen = true;
  25850. ERect* rect = 0;
  25851. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25852. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  25853. // do this before and after like in the steinberg example
  25854. dispatch (effEditGetRect, 0, 0, &rect, 0);
  25855. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  25856. // Install keyboard hooks
  25857. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  25858. #if JUCE_WIN32
  25859. originalWndProc = 0;
  25860. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  25861. if (pluginHWND == 0)
  25862. {
  25863. isOpen = false;
  25864. setSize (300, 150);
  25865. return;
  25866. }
  25867. #pragma warning (push)
  25868. #pragma warning (disable: 4244)
  25869. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  25870. if (! pluginWantsKeys)
  25871. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  25872. #pragma warning (pop)
  25873. int w, h;
  25874. RECT r;
  25875. GetWindowRect (pluginHWND, &r);
  25876. w = r.right - r.left;
  25877. h = r.bottom - r.top;
  25878. if (rect != 0)
  25879. {
  25880. const int rw = rect->right - rect->left;
  25881. const int rh = rect->bottom - rect->top;
  25882. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  25883. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  25884. {
  25885. // very dodgy logic to decide which size is right.
  25886. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  25887. {
  25888. SetWindowPos (pluginHWND, 0,
  25889. 0, 0, rw, rh,
  25890. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  25891. GetWindowRect (pluginHWND, &r);
  25892. w = r.right - r.left;
  25893. h = r.bottom - r.top;
  25894. pluginRefusesToResize = (w != rw) || (h != rh);
  25895. w = rw;
  25896. h = rh;
  25897. }
  25898. }
  25899. }
  25900. #elif JUCE_LINUX
  25901. pluginWindow = getChildWindow ((Window) getWindowHandle());
  25902. if (pluginWindow != 0)
  25903. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  25904. XInternAtom (display, "_XEventProc", False));
  25905. int w = 250, h = 150;
  25906. if (rect != 0)
  25907. {
  25908. w = rect->right - rect->left;
  25909. h = rect->bottom - rect->top;
  25910. if (w == 0 || h == 0)
  25911. {
  25912. w = 250;
  25913. h = 150;
  25914. }
  25915. }
  25916. if (pluginWindow != 0)
  25917. XMapRaised (display, pluginWindow);
  25918. #endif
  25919. // double-check it's not too tiny
  25920. w = jmax (w, 32);
  25921. h = jmax (h, 32);
  25922. setSize (w, h);
  25923. #if JUCE_WIN32
  25924. checkPluginWindowSize();
  25925. #endif
  25926. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  25927. repaint();
  25928. }
  25929. #endif
  25930. #if ! JUCE_MAC
  25931. void closePluginWindow()
  25932. {
  25933. if (isOpen)
  25934. {
  25935. log (T("Closing VST UI: ") + plugin.getName());
  25936. isOpen = false;
  25937. dispatch (effEditClose, 0, 0, 0, 0);
  25938. #if JUCE_WIN32
  25939. #pragma warning (push)
  25940. #pragma warning (disable: 4244)
  25941. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25942. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  25943. #pragma warning (pop)
  25944. stopTimer();
  25945. if (pluginHWND != 0 && IsWindow (pluginHWND))
  25946. DestroyWindow (pluginHWND);
  25947. pluginHWND = 0;
  25948. #elif JUCE_LINUX
  25949. stopTimer();
  25950. pluginWindow = 0;
  25951. pluginProc = 0;
  25952. #endif
  25953. }
  25954. }
  25955. #endif
  25956. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  25957. {
  25958. return plugin.dispatch (opcode, index, value, ptr, opt);
  25959. }
  25960. #if JUCE_WIN32
  25961. void checkPluginWindowSize() throw()
  25962. {
  25963. RECT r;
  25964. GetWindowRect (pluginHWND, &r);
  25965. const int w = r.right - r.left;
  25966. const int h = r.bottom - r.top;
  25967. if (isShowing() && w > 0 && h > 0
  25968. && (w != getWidth() || h != getHeight())
  25969. && ! pluginRefusesToResize)
  25970. {
  25971. setSize (w, h);
  25972. sizeCheckCount = 0;
  25973. }
  25974. }
  25975. // hooks to get keyboard events from VST windows..
  25976. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  25977. {
  25978. for (int i = activeVSTWindows.size(); --i >= 0;)
  25979. {
  25980. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  25981. if (w->pluginHWND == hW)
  25982. {
  25983. if (message == WM_CHAR
  25984. || message == WM_KEYDOWN
  25985. || message == WM_SYSKEYDOWN
  25986. || message == WM_KEYUP
  25987. || message == WM_SYSKEYUP
  25988. || message == WM_APPCOMMAND)
  25989. {
  25990. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  25991. message, wParam, lParam);
  25992. }
  25993. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  25994. (HWND) w->pluginHWND,
  25995. message,
  25996. wParam,
  25997. lParam);
  25998. }
  25999. }
  26000. return DefWindowProc (hW, message, wParam, lParam);
  26001. }
  26002. #endif
  26003. #if JUCE_LINUX
  26004. // overload mouse/keyboard events to forward them to the plugin's inner window..
  26005. void sendEventToChild (XEvent* event)
  26006. {
  26007. if (pluginProc != 0)
  26008. {
  26009. // if the plugin publishes an event procedure, pass the event directly..
  26010. pluginProc (event);
  26011. }
  26012. else if (pluginWindow != 0)
  26013. {
  26014. // if the plugin has a window, then send the event to the window so that
  26015. // its message thread will pick it up..
  26016. XSendEvent (display, pluginWindow, False, 0L, event);
  26017. XFlush (display);
  26018. }
  26019. }
  26020. void mouseEnter (const MouseEvent& e)
  26021. {
  26022. if (pluginWindow != 0)
  26023. {
  26024. XEvent ev;
  26025. zerostruct (ev);
  26026. ev.xcrossing.display = display;
  26027. ev.xcrossing.type = EnterNotify;
  26028. ev.xcrossing.window = pluginWindow;
  26029. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26030. ev.xcrossing.time = CurrentTime;
  26031. ev.xcrossing.x = e.x;
  26032. ev.xcrossing.y = e.y;
  26033. ev.xcrossing.x_root = e.getScreenX();
  26034. ev.xcrossing.y_root = e.getScreenY();
  26035. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26036. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26037. translateJuceToXCrossingModifiers (e, ev);
  26038. sendEventToChild (&ev);
  26039. }
  26040. }
  26041. void mouseExit (const MouseEvent& e)
  26042. {
  26043. if (pluginWindow != 0)
  26044. {
  26045. XEvent ev;
  26046. zerostruct (ev);
  26047. ev.xcrossing.display = display;
  26048. ev.xcrossing.type = LeaveNotify;
  26049. ev.xcrossing.window = pluginWindow;
  26050. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  26051. ev.xcrossing.time = CurrentTime;
  26052. ev.xcrossing.x = e.x;
  26053. ev.xcrossing.y = e.y;
  26054. ev.xcrossing.x_root = e.getScreenX();
  26055. ev.xcrossing.y_root = e.getScreenY();
  26056. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  26057. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  26058. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  26059. translateJuceToXCrossingModifiers (e, ev);
  26060. sendEventToChild (&ev);
  26061. }
  26062. }
  26063. void mouseMove (const MouseEvent& e)
  26064. {
  26065. if (pluginWindow != 0)
  26066. {
  26067. XEvent ev;
  26068. zerostruct (ev);
  26069. ev.xmotion.display = display;
  26070. ev.xmotion.type = MotionNotify;
  26071. ev.xmotion.window = pluginWindow;
  26072. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26073. ev.xmotion.time = CurrentTime;
  26074. ev.xmotion.is_hint = NotifyNormal;
  26075. ev.xmotion.x = e.x;
  26076. ev.xmotion.y = e.y;
  26077. ev.xmotion.x_root = e.getScreenX();
  26078. ev.xmotion.y_root = e.getScreenY();
  26079. sendEventToChild (&ev);
  26080. }
  26081. }
  26082. void mouseDrag (const MouseEvent& e)
  26083. {
  26084. if (pluginWindow != 0)
  26085. {
  26086. XEvent ev;
  26087. zerostruct (ev);
  26088. ev.xmotion.display = display;
  26089. ev.xmotion.type = MotionNotify;
  26090. ev.xmotion.window = pluginWindow;
  26091. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  26092. ev.xmotion.time = CurrentTime;
  26093. ev.xmotion.x = e.x ;
  26094. ev.xmotion.y = e.y;
  26095. ev.xmotion.x_root = e.getScreenX();
  26096. ev.xmotion.y_root = e.getScreenY();
  26097. ev.xmotion.is_hint = NotifyNormal;
  26098. translateJuceToXMotionModifiers (e, ev);
  26099. sendEventToChild (&ev);
  26100. }
  26101. }
  26102. void mouseUp (const MouseEvent& e)
  26103. {
  26104. if (pluginWindow != 0)
  26105. {
  26106. XEvent ev;
  26107. zerostruct (ev);
  26108. ev.xbutton.display = display;
  26109. ev.xbutton.type = ButtonRelease;
  26110. ev.xbutton.window = pluginWindow;
  26111. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26112. ev.xbutton.time = CurrentTime;
  26113. ev.xbutton.x = e.x;
  26114. ev.xbutton.y = e.y;
  26115. ev.xbutton.x_root = e.getScreenX();
  26116. ev.xbutton.y_root = e.getScreenY();
  26117. translateJuceToXButtonModifiers (e, ev);
  26118. sendEventToChild (&ev);
  26119. }
  26120. }
  26121. void mouseWheelMove (const MouseEvent& e,
  26122. float incrementX,
  26123. float incrementY)
  26124. {
  26125. if (pluginWindow != 0)
  26126. {
  26127. XEvent ev;
  26128. zerostruct (ev);
  26129. ev.xbutton.display = display;
  26130. ev.xbutton.type = ButtonPress;
  26131. ev.xbutton.window = pluginWindow;
  26132. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  26133. ev.xbutton.time = CurrentTime;
  26134. ev.xbutton.x = e.x;
  26135. ev.xbutton.y = e.y;
  26136. ev.xbutton.x_root = e.getScreenX();
  26137. ev.xbutton.y_root = e.getScreenY();
  26138. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  26139. sendEventToChild (&ev);
  26140. // TODO - put a usleep here ?
  26141. ev.xbutton.type = ButtonRelease;
  26142. sendEventToChild (&ev);
  26143. }
  26144. }
  26145. #endif
  26146. #if JUCE_MAC
  26147. #if ! JUCE_SUPPORT_CARBON
  26148. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  26149. #endif
  26150. class InnerWrapperComponent : public CarbonViewWrapperComponent
  26151. {
  26152. public:
  26153. InnerWrapperComponent (VSTPluginWindow* const owner_)
  26154. : owner (owner_),
  26155. alreadyInside (false)
  26156. {
  26157. }
  26158. ~InnerWrapperComponent()
  26159. {
  26160. deleteWindow();
  26161. }
  26162. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  26163. {
  26164. owner->openPluginWindow (windowRef);
  26165. return 0;
  26166. }
  26167. void removeView (HIViewRef)
  26168. {
  26169. owner->dispatch (effEditClose, 0, 0, 0, 0);
  26170. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  26171. }
  26172. bool getEmbeddedViewSize (int& w, int& h)
  26173. {
  26174. ERect* rect = 0;
  26175. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  26176. w = rect->right - rect->left;
  26177. h = rect->bottom - rect->top;
  26178. return true;
  26179. }
  26180. void mouseDown (int x, int y)
  26181. {
  26182. if (! alreadyInside)
  26183. {
  26184. alreadyInside = true;
  26185. getTopLevelComponent()->toFront (true);
  26186. owner->dispatch (effEditMouse, x, y, 0, 0);
  26187. alreadyInside = false;
  26188. }
  26189. else
  26190. {
  26191. PostEvent (::mouseDown, 0);
  26192. }
  26193. }
  26194. void paint()
  26195. {
  26196. ComponentPeer* const peer = getPeer();
  26197. if (peer != 0)
  26198. {
  26199. ERect r;
  26200. r.left = getScreenX() - peer->getScreenX();
  26201. r.right = r.left + getWidth();
  26202. r.top = getScreenY() - peer->getScreenY();
  26203. r.bottom = r.top + getHeight();
  26204. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  26205. }
  26206. }
  26207. private:
  26208. VSTPluginWindow* const owner;
  26209. bool alreadyInside;
  26210. };
  26211. friend class InnerWrapperComponent;
  26212. InnerWrapperComponent* innerWrapper;
  26213. void resized()
  26214. {
  26215. innerWrapper->setSize (getWidth(), getHeight());
  26216. }
  26217. #endif
  26218. };
  26219. AudioProcessorEditor* VSTPluginInstance::createEditor()
  26220. {
  26221. if (hasEditor())
  26222. return new VSTPluginWindow (*this);
  26223. return 0;
  26224. }
  26225. void VSTPluginInstance::handleAsyncUpdate()
  26226. {
  26227. // indicates that something about the plugin has changed..
  26228. updateHostDisplay();
  26229. }
  26230. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  26231. {
  26232. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  26233. {
  26234. changeProgramName (getCurrentProgram(), prog->prgName);
  26235. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26236. setParameter (i, vst_swapFloat (prog->params[i]));
  26237. return true;
  26238. }
  26239. return false;
  26240. }
  26241. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  26242. const int dataSize)
  26243. {
  26244. if (dataSize < 28)
  26245. return false;
  26246. const fxSet* const set = (const fxSet*) data;
  26247. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  26248. || vst_swap (set->version) > fxbVersionNum)
  26249. return false;
  26250. if (vst_swap (set->fxMagic) == 'FxBk')
  26251. {
  26252. // bank of programs
  26253. if (vst_swap (set->numPrograms) >= 0)
  26254. {
  26255. const int oldProg = getCurrentProgram();
  26256. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  26257. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26258. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  26259. {
  26260. if (i != oldProg)
  26261. {
  26262. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  26263. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26264. return false;
  26265. if (vst_swap (set->numPrograms) > 0)
  26266. setCurrentProgram (i);
  26267. if (! restoreProgramSettings (prog))
  26268. return false;
  26269. }
  26270. }
  26271. if (vst_swap (set->numPrograms) > 0)
  26272. setCurrentProgram (oldProg);
  26273. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  26274. if (((const char*) prog) - ((const char*) set) >= dataSize)
  26275. return false;
  26276. if (! restoreProgramSettings (prog))
  26277. return false;
  26278. }
  26279. }
  26280. else if (vst_swap (set->fxMagic) == 'FxCk')
  26281. {
  26282. // single program
  26283. const fxProgram* const prog = (const fxProgram*) data;
  26284. if (vst_swap (prog->chunkMagic) != 'CcnK')
  26285. return false;
  26286. changeProgramName (getCurrentProgram(), prog->prgName);
  26287. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  26288. setParameter (i, vst_swapFloat (prog->params[i]));
  26289. }
  26290. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  26291. {
  26292. // non-preset chunk
  26293. const fxChunkSet* const cset = (const fxChunkSet*) data;
  26294. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  26295. return false;
  26296. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  26297. }
  26298. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  26299. {
  26300. // preset chunk
  26301. const fxProgramSet* const cset = (const fxProgramSet*) data;
  26302. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  26303. return false;
  26304. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  26305. changeProgramName (getCurrentProgram(), cset->name);
  26306. }
  26307. else
  26308. {
  26309. return false;
  26310. }
  26311. return true;
  26312. }
  26313. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  26314. {
  26315. const int numParams = getNumParameters();
  26316. prog->chunkMagic = vst_swap ('CcnK');
  26317. prog->byteSize = 0;
  26318. prog->fxMagic = vst_swap ('FxCk');
  26319. prog->version = vst_swap (fxbVersionNum);
  26320. prog->fxID = vst_swap (getUID());
  26321. prog->fxVersion = vst_swap (getVersionNumber());
  26322. prog->numParams = vst_swap (numParams);
  26323. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  26324. for (int i = 0; i < numParams; ++i)
  26325. prog->params[i] = vst_swapFloat (getParameter (i));
  26326. }
  26327. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  26328. {
  26329. const int numPrograms = getNumPrograms();
  26330. const int numParams = getNumParameters();
  26331. if (usesChunks())
  26332. {
  26333. if (isFXB)
  26334. {
  26335. MemoryBlock chunk;
  26336. getChunkData (chunk, false, maxSizeMB);
  26337. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  26338. dest.setSize (totalLen, true);
  26339. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  26340. set->chunkMagic = vst_swap ('CcnK');
  26341. set->byteSize = 0;
  26342. set->fxMagic = vst_swap ('FBCh');
  26343. set->version = vst_swap (fxbVersionNum);
  26344. set->fxID = vst_swap (getUID());
  26345. set->fxVersion = vst_swap (getVersionNumber());
  26346. set->numPrograms = vst_swap (numPrograms);
  26347. set->chunkSize = vst_swap (chunk.getSize());
  26348. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26349. }
  26350. else
  26351. {
  26352. MemoryBlock chunk;
  26353. getChunkData (chunk, true, maxSizeMB);
  26354. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  26355. dest.setSize (totalLen, true);
  26356. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  26357. set->chunkMagic = vst_swap ('CcnK');
  26358. set->byteSize = 0;
  26359. set->fxMagic = vst_swap ('FPCh');
  26360. set->version = vst_swap (fxbVersionNum);
  26361. set->fxID = vst_swap (getUID());
  26362. set->fxVersion = vst_swap (getVersionNumber());
  26363. set->numPrograms = vst_swap (numPrograms);
  26364. set->chunkSize = vst_swap (chunk.getSize());
  26365. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  26366. chunk.copyTo (set->chunk, 0, chunk.getSize());
  26367. }
  26368. }
  26369. else
  26370. {
  26371. if (isFXB)
  26372. {
  26373. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26374. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  26375. dest.setSize (len, true);
  26376. fxSet* const set = (fxSet*) dest.getData();
  26377. set->chunkMagic = vst_swap ('CcnK');
  26378. set->byteSize = 0;
  26379. set->fxMagic = vst_swap ('FxBk');
  26380. set->version = vst_swap (fxbVersionNum);
  26381. set->fxID = vst_swap (getUID());
  26382. set->fxVersion = vst_swap (getVersionNumber());
  26383. set->numPrograms = vst_swap (numPrograms);
  26384. const int oldProgram = getCurrentProgram();
  26385. MemoryBlock oldSettings;
  26386. createTempParameterStore (oldSettings);
  26387. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  26388. for (int i = 0; i < numPrograms; ++i)
  26389. {
  26390. if (i != oldProgram)
  26391. {
  26392. setCurrentProgram (i);
  26393. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  26394. }
  26395. }
  26396. setCurrentProgram (oldProgram);
  26397. restoreFromTempParameterStore (oldSettings);
  26398. }
  26399. else
  26400. {
  26401. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  26402. dest.setSize (totalLen, true);
  26403. setParamsInProgramBlock ((fxProgram*) dest.getData());
  26404. }
  26405. }
  26406. return true;
  26407. }
  26408. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  26409. {
  26410. if (usesChunks())
  26411. {
  26412. void* data = 0;
  26413. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  26414. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  26415. {
  26416. mb.setSize (bytes);
  26417. mb.copyFrom (data, 0, bytes);
  26418. }
  26419. }
  26420. }
  26421. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  26422. {
  26423. if (size > 0 && usesChunks())
  26424. {
  26425. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  26426. if (! isPreset)
  26427. updateStoredProgramNames();
  26428. }
  26429. }
  26430. void VSTPluginInstance::timerCallback()
  26431. {
  26432. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  26433. stopTimer();
  26434. }
  26435. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  26436. {
  26437. const ScopedLock sl (lock);
  26438. ++insideVSTCallback;
  26439. int result = 0;
  26440. try
  26441. {
  26442. if (effect != 0)
  26443. {
  26444. #if JUCE_MAC
  26445. if (module->resFileId != 0)
  26446. UseResFile (module->resFileId);
  26447. CGrafPtr oldPort;
  26448. if (getActiveEditor() != 0)
  26449. {
  26450. int x = 0, y = 0;
  26451. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  26452. GetPort (&oldPort);
  26453. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  26454. SetOrigin (-x, -y);
  26455. }
  26456. #endif
  26457. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  26458. #if JUCE_MAC
  26459. if (getActiveEditor() != 0)
  26460. SetPort (oldPort);
  26461. module->resFileId = CurResFile();
  26462. #endif
  26463. --insideVSTCallback;
  26464. return result;
  26465. }
  26466. }
  26467. catch (...)
  26468. {
  26469. //char s[512];
  26470. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  26471. }
  26472. --insideVSTCallback;
  26473. return result;
  26474. }
  26475. // handles non plugin-specific callbacks..
  26476. static const int defaultVSTSampleRateValue = 16384;
  26477. static const int defaultVSTBlockSizeValue = 512;
  26478. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26479. {
  26480. (void) index;
  26481. (void) value;
  26482. (void) opt;
  26483. switch (opcode)
  26484. {
  26485. case audioMasterCanDo:
  26486. {
  26487. static const char* canDos[] = { "supplyIdle",
  26488. "sendVstEvents",
  26489. "sendVstMidiEvent",
  26490. "sendVstTimeInfo",
  26491. "receiveVstEvents",
  26492. "receiveVstMidiEvent",
  26493. "supportShell",
  26494. "shellCategory" };
  26495. for (int i = 0; i < numElementsInArray (canDos); ++i)
  26496. if (strcmp (canDos[i], (const char*) ptr) == 0)
  26497. return 1;
  26498. return 0;
  26499. }
  26500. case audioMasterVersion:
  26501. return 0x2400;
  26502. case audioMasterCurrentId:
  26503. return shellUIDToCreate;
  26504. case audioMasterGetNumAutomatableParameters:
  26505. return 0;
  26506. case audioMasterGetAutomationState:
  26507. return 1;
  26508. case audioMasterGetVendorVersion:
  26509. return 0x0101;
  26510. case audioMasterGetVendorString:
  26511. case audioMasterGetProductString:
  26512. {
  26513. String hostName ("Juce VST Host");
  26514. if (JUCEApplication::getInstance() != 0)
  26515. hostName = JUCEApplication::getInstance()->getApplicationName();
  26516. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  26517. }
  26518. break;
  26519. case audioMasterGetSampleRate:
  26520. return (VstIntPtr) defaultVSTSampleRateValue;
  26521. case audioMasterGetBlockSize:
  26522. return (VstIntPtr) defaultVSTBlockSizeValue;
  26523. case audioMasterSetOutputSampleRate:
  26524. return 0;
  26525. default:
  26526. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  26527. break;
  26528. }
  26529. return 0;
  26530. }
  26531. // handles callbacks for a specific plugin
  26532. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  26533. {
  26534. switch (opcode)
  26535. {
  26536. case audioMasterAutomate:
  26537. sendParamChangeMessageToListeners (index, opt);
  26538. break;
  26539. case audioMasterProcessEvents:
  26540. handleMidiFromPlugin ((const VstEvents*) ptr);
  26541. break;
  26542. case audioMasterGetTime:
  26543. #ifdef _MSC_VER
  26544. #pragma warning (push)
  26545. #pragma warning (disable: 4311)
  26546. #endif
  26547. return (VstIntPtr) &vstHostTime;
  26548. #ifdef _MSC_VER
  26549. #pragma warning (pop)
  26550. #endif
  26551. break;
  26552. case audioMasterIdle:
  26553. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  26554. {
  26555. ++insideVSTCallback;
  26556. #if JUCE_MAC
  26557. if (getActiveEditor() != 0)
  26558. dispatch (effEditIdle, 0, 0, 0, 0);
  26559. #endif
  26560. juce_callAnyTimersSynchronously();
  26561. handleUpdateNowIfNeeded();
  26562. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  26563. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  26564. --insideVSTCallback;
  26565. }
  26566. break;
  26567. case audioMasterUpdateDisplay:
  26568. triggerAsyncUpdate();
  26569. break;
  26570. case audioMasterTempoAt:
  26571. // returns (10000 * bpm)
  26572. break;
  26573. case audioMasterNeedIdle:
  26574. startTimer (50);
  26575. break;
  26576. case audioMasterSizeWindow:
  26577. if (getActiveEditor() != 0)
  26578. getActiveEditor()->setSize (index, value);
  26579. return 1;
  26580. case audioMasterGetSampleRate:
  26581. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  26582. case audioMasterGetBlockSize:
  26583. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  26584. case audioMasterWantMidi:
  26585. wantsMidiMessages = true;
  26586. break;
  26587. case audioMasterGetDirectory:
  26588. #if JUCE_MAC
  26589. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  26590. #else
  26591. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  26592. #endif
  26593. case audioMasterGetAutomationState:
  26594. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  26595. break;
  26596. // none of these are handled (yet)..
  26597. case audioMasterBeginEdit:
  26598. case audioMasterEndEdit:
  26599. case audioMasterSetTime:
  26600. case audioMasterPinConnected:
  26601. case audioMasterGetParameterQuantization:
  26602. case audioMasterIOChanged:
  26603. case audioMasterGetInputLatency:
  26604. case audioMasterGetOutputLatency:
  26605. case audioMasterGetPreviousPlug:
  26606. case audioMasterGetNextPlug:
  26607. case audioMasterWillReplaceOrAccumulate:
  26608. case audioMasterGetCurrentProcessLevel:
  26609. case audioMasterOfflineStart:
  26610. case audioMasterOfflineRead:
  26611. case audioMasterOfflineWrite:
  26612. case audioMasterOfflineGetCurrentPass:
  26613. case audioMasterOfflineGetCurrentMetaPass:
  26614. case audioMasterVendorSpecific:
  26615. case audioMasterSetIcon:
  26616. case audioMasterGetLanguage:
  26617. case audioMasterOpenWindow:
  26618. case audioMasterCloseWindow:
  26619. break;
  26620. default:
  26621. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26622. }
  26623. return 0;
  26624. }
  26625. // entry point for all callbacks from the plugin
  26626. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  26627. {
  26628. try
  26629. {
  26630. if (effect != 0 && effect->resvd2 != 0)
  26631. {
  26632. return ((VSTPluginInstance*)(effect->resvd2))
  26633. ->handleCallback (opcode, index, value, ptr, opt);
  26634. }
  26635. return handleGeneralCallback (opcode, index, value, ptr, opt);
  26636. }
  26637. catch (...)
  26638. {
  26639. return 0;
  26640. }
  26641. }
  26642. const String VSTPluginInstance::getVersion() const throw()
  26643. {
  26644. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  26645. String s;
  26646. if (v == 0 || v == -1)
  26647. v = getVersionNumber();
  26648. if (v != 0)
  26649. {
  26650. int versionBits[4];
  26651. int n = 0;
  26652. while (v != 0)
  26653. {
  26654. versionBits [n++] = (v & 0xff);
  26655. v >>= 8;
  26656. }
  26657. s << 'V';
  26658. while (n > 0)
  26659. {
  26660. s << versionBits [--n];
  26661. if (n > 0)
  26662. s << '.';
  26663. }
  26664. }
  26665. return s;
  26666. }
  26667. int VSTPluginInstance::getUID() const throw()
  26668. {
  26669. int uid = effect != 0 ? effect->uniqueID : 0;
  26670. if (uid == 0)
  26671. uid = module->file.hashCode();
  26672. return uid;
  26673. }
  26674. const String VSTPluginInstance::getCategory() const throw()
  26675. {
  26676. const char* result = 0;
  26677. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  26678. {
  26679. case kPlugCategEffect:
  26680. result = "Effect";
  26681. break;
  26682. case kPlugCategSynth:
  26683. result = "Synth";
  26684. break;
  26685. case kPlugCategAnalysis:
  26686. result = "Anaylsis";
  26687. break;
  26688. case kPlugCategMastering:
  26689. result = "Mastering";
  26690. break;
  26691. case kPlugCategSpacializer:
  26692. result = "Spacial";
  26693. break;
  26694. case kPlugCategRoomFx:
  26695. result = "Reverb";
  26696. break;
  26697. case kPlugSurroundFx:
  26698. result = "Surround";
  26699. break;
  26700. case kPlugCategRestoration:
  26701. result = "Restoration";
  26702. break;
  26703. case kPlugCategGenerator:
  26704. result = "Tone generation";
  26705. break;
  26706. default:
  26707. break;
  26708. }
  26709. return result;
  26710. }
  26711. float VSTPluginInstance::getParameter (int index)
  26712. {
  26713. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26714. {
  26715. try
  26716. {
  26717. const ScopedLock sl (lock);
  26718. return effect->getParameter (effect, index);
  26719. }
  26720. catch (...)
  26721. {
  26722. }
  26723. }
  26724. return 0.0f;
  26725. }
  26726. void VSTPluginInstance::setParameter (int index, float newValue)
  26727. {
  26728. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  26729. {
  26730. try
  26731. {
  26732. const ScopedLock sl (lock);
  26733. if (effect->getParameter (effect, index) != newValue)
  26734. effect->setParameter (effect, index, newValue);
  26735. }
  26736. catch (...)
  26737. {
  26738. }
  26739. }
  26740. }
  26741. const String VSTPluginInstance::getParameterName (int index)
  26742. {
  26743. if (effect != 0)
  26744. {
  26745. jassert (index >= 0 && index < effect->numParams);
  26746. char nm [256];
  26747. zerostruct (nm);
  26748. dispatch (effGetParamName, index, 0, nm, 0);
  26749. return String (nm).trim();
  26750. }
  26751. return String::empty;
  26752. }
  26753. const String VSTPluginInstance::getParameterLabel (int index) const
  26754. {
  26755. if (effect != 0)
  26756. {
  26757. jassert (index >= 0 && index < effect->numParams);
  26758. char nm [256];
  26759. zerostruct (nm);
  26760. dispatch (effGetParamLabel, index, 0, nm, 0);
  26761. return String (nm).trim();
  26762. }
  26763. return String::empty;
  26764. }
  26765. const String VSTPluginInstance::getParameterText (int index)
  26766. {
  26767. if (effect != 0)
  26768. {
  26769. jassert (index >= 0 && index < effect->numParams);
  26770. char nm [256];
  26771. zerostruct (nm);
  26772. dispatch (effGetParamDisplay, index, 0, nm, 0);
  26773. return String (nm).trim();
  26774. }
  26775. return String::empty;
  26776. }
  26777. bool VSTPluginInstance::isParameterAutomatable (int index) const
  26778. {
  26779. if (effect != 0)
  26780. {
  26781. jassert (index >= 0 && index < effect->numParams);
  26782. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  26783. }
  26784. return false;
  26785. }
  26786. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  26787. {
  26788. dest.setSize (64 + 4 * getNumParameters());
  26789. dest.fillWith (0);
  26790. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  26791. float* const p = (float*) (((char*) dest.getData()) + 64);
  26792. for (int i = 0; i < getNumParameters(); ++i)
  26793. p[i] = getParameter(i);
  26794. }
  26795. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  26796. {
  26797. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  26798. float* p = (float*) (((char*) m.getData()) + 64);
  26799. for (int i = 0; i < getNumParameters(); ++i)
  26800. setParameter (i, p[i]);
  26801. }
  26802. void VSTPluginInstance::setCurrentProgram (int newIndex)
  26803. {
  26804. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  26805. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  26806. }
  26807. const String VSTPluginInstance::getProgramName (int index)
  26808. {
  26809. if (index == getCurrentProgram())
  26810. {
  26811. return getCurrentProgramName();
  26812. }
  26813. else if (effect != 0)
  26814. {
  26815. char nm [256];
  26816. zerostruct (nm);
  26817. if (dispatch (effGetProgramNameIndexed,
  26818. jlimit (0, getNumPrograms(), index),
  26819. -1, nm, 0) != 0)
  26820. {
  26821. return String (nm).trim();
  26822. }
  26823. }
  26824. return programNames [index];
  26825. }
  26826. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  26827. {
  26828. if (index == getCurrentProgram())
  26829. {
  26830. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  26831. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  26832. }
  26833. else
  26834. {
  26835. jassertfalse // xxx not implemented!
  26836. }
  26837. }
  26838. void VSTPluginInstance::updateStoredProgramNames()
  26839. {
  26840. if (effect != 0 && getNumPrograms() > 0)
  26841. {
  26842. char nm [256];
  26843. zerostruct (nm);
  26844. // only do this if the plugin can't use indexed names..
  26845. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  26846. {
  26847. const int oldProgram = getCurrentProgram();
  26848. MemoryBlock oldSettings;
  26849. createTempParameterStore (oldSettings);
  26850. for (int i = 0; i < getNumPrograms(); ++i)
  26851. {
  26852. setCurrentProgram (i);
  26853. getCurrentProgramName(); // (this updates the list)
  26854. }
  26855. setCurrentProgram (oldProgram);
  26856. restoreFromTempParameterStore (oldSettings);
  26857. }
  26858. }
  26859. }
  26860. const String VSTPluginInstance::getCurrentProgramName()
  26861. {
  26862. if (effect != 0)
  26863. {
  26864. char nm [256];
  26865. zerostruct (nm);
  26866. dispatch (effGetProgramName, 0, 0, nm, 0);
  26867. const int index = getCurrentProgram();
  26868. if (programNames[index].isEmpty())
  26869. {
  26870. while (programNames.size() < index)
  26871. programNames.add (String::empty);
  26872. programNames.set (index, String (nm).trim());
  26873. }
  26874. return String (nm).trim();
  26875. }
  26876. return String::empty;
  26877. }
  26878. const String VSTPluginInstance::getInputChannelName (const int index) const
  26879. {
  26880. if (index >= 0 && index < getNumInputChannels())
  26881. {
  26882. VstPinProperties pinProps;
  26883. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26884. return String (pinProps.label, sizeof (pinProps.label));
  26885. }
  26886. return String::empty;
  26887. }
  26888. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  26889. {
  26890. if (index < 0 || index >= getNumInputChannels())
  26891. return false;
  26892. VstPinProperties pinProps;
  26893. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  26894. return (pinProps.flags & kVstPinIsStereo) != 0;
  26895. return true;
  26896. }
  26897. const String VSTPluginInstance::getOutputChannelName (const int index) const
  26898. {
  26899. if (index >= 0 && index < getNumOutputChannels())
  26900. {
  26901. VstPinProperties pinProps;
  26902. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26903. return String (pinProps.label, sizeof (pinProps.label));
  26904. }
  26905. return String::empty;
  26906. }
  26907. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  26908. {
  26909. if (index < 0 || index >= getNumOutputChannels())
  26910. return false;
  26911. VstPinProperties pinProps;
  26912. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  26913. return (pinProps.flags & kVstPinIsStereo) != 0;
  26914. return true;
  26915. }
  26916. void VSTPluginInstance::setPower (const bool on)
  26917. {
  26918. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  26919. isPowerOn = on;
  26920. }
  26921. const int defaultMaxSizeMB = 64;
  26922. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  26923. {
  26924. saveToFXBFile (destData, true, defaultMaxSizeMB);
  26925. }
  26926. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26927. {
  26928. saveToFXBFile (destData, false, defaultMaxSizeMB);
  26929. }
  26930. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26931. {
  26932. loadFromFXBFile (data, sizeInBytes);
  26933. }
  26934. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26935. {
  26936. loadFromFXBFile (data, sizeInBytes);
  26937. }
  26938. VSTPluginFormat::VSTPluginFormat()
  26939. {
  26940. }
  26941. VSTPluginFormat::~VSTPluginFormat()
  26942. {
  26943. }
  26944. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26945. const String& fileOrIdentifier)
  26946. {
  26947. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26948. return;
  26949. PluginDescription desc;
  26950. desc.fileOrIdentifier = fileOrIdentifier;
  26951. desc.uid = 0;
  26952. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  26953. if (instance == 0)
  26954. return;
  26955. try
  26956. {
  26957. #if JUCE_MAC
  26958. if (instance->module->resFileId != 0)
  26959. UseResFile (instance->module->resFileId);
  26960. #endif
  26961. instance->fillInPluginDescription (desc);
  26962. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  26963. if (category != kPlugCategShell)
  26964. {
  26965. // Normal plugin...
  26966. results.add (new PluginDescription (desc));
  26967. ++insideVSTCallback;
  26968. instance->dispatch (effOpen, 0, 0, 0, 0);
  26969. --insideVSTCallback;
  26970. }
  26971. else
  26972. {
  26973. // It's a shell plugin, so iterate all the subtypes...
  26974. char shellEffectName [64];
  26975. for (;;)
  26976. {
  26977. zerostruct (shellEffectName);
  26978. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  26979. if (uid == 0)
  26980. {
  26981. break;
  26982. }
  26983. else
  26984. {
  26985. desc.uid = uid;
  26986. desc.name = shellEffectName;
  26987. bool alreadyThere = false;
  26988. for (int i = results.size(); --i >= 0;)
  26989. {
  26990. PluginDescription* const d = results.getUnchecked(i);
  26991. if (d->isDuplicateOf (desc))
  26992. {
  26993. alreadyThere = true;
  26994. break;
  26995. }
  26996. }
  26997. if (! alreadyThere)
  26998. results.add (new PluginDescription (desc));
  26999. }
  27000. }
  27001. }
  27002. }
  27003. catch (...)
  27004. {
  27005. // crashed while loading...
  27006. }
  27007. deleteAndZero (instance);
  27008. }
  27009. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  27010. {
  27011. VSTPluginInstance* result = 0;
  27012. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  27013. {
  27014. File file (desc.fileOrIdentifier);
  27015. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  27016. file.getParentDirectory().setAsCurrentWorkingDirectory();
  27017. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  27018. if (module != 0)
  27019. {
  27020. shellUIDToCreate = desc.uid;
  27021. result = new VSTPluginInstance (module);
  27022. if (result->effect != 0)
  27023. {
  27024. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  27025. result->initialise();
  27026. }
  27027. else
  27028. {
  27029. deleteAndZero (result);
  27030. }
  27031. }
  27032. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  27033. }
  27034. return result;
  27035. }
  27036. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  27037. {
  27038. const File f (fileOrIdentifier);
  27039. #if JUCE_MAC
  27040. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  27041. return true;
  27042. #if JUCE_PPC
  27043. FSRef fileRef;
  27044. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  27045. {
  27046. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  27047. if (resFileId != -1)
  27048. {
  27049. const int numEffects = Count1Resources ('aEff');
  27050. CloseResFile (resFileId);
  27051. if (numEffects > 0)
  27052. return true;
  27053. }
  27054. }
  27055. #endif
  27056. return false;
  27057. #elif JUCE_WIN32
  27058. return f.existsAsFile()
  27059. && f.hasFileExtension (T(".dll"));
  27060. #elif JUCE_LINUX
  27061. return f.existsAsFile()
  27062. && f.hasFileExtension (T(".so"));
  27063. #endif
  27064. }
  27065. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  27066. {
  27067. return fileOrIdentifier;
  27068. }
  27069. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  27070. {
  27071. return File (desc.fileOrIdentifier).exists();
  27072. }
  27073. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  27074. {
  27075. StringArray results;
  27076. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  27077. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  27078. return results;
  27079. }
  27080. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  27081. {
  27082. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  27083. // .component or .vst directories.
  27084. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  27085. while (iter.next())
  27086. {
  27087. const File f (iter.getFile());
  27088. bool isPlugin = false;
  27089. if (fileMightContainThisPluginType (f.getFullPathName()))
  27090. {
  27091. isPlugin = true;
  27092. results.add (f.getFullPathName());
  27093. }
  27094. if (recursive && (! isPlugin) && f.isDirectory())
  27095. recursiveFileSearch (results, f, true);
  27096. }
  27097. }
  27098. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  27099. {
  27100. #if JUCE_MAC
  27101. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  27102. #elif JUCE_WIN32
  27103. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  27104. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  27105. #elif JUCE_LINUX
  27106. return FileSearchPath ("/usr/lib/vst");
  27107. #endif
  27108. }
  27109. END_JUCE_NAMESPACE
  27110. #endif
  27111. #undef log
  27112. #endif
  27113. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  27114. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  27115. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  27116. BEGIN_JUCE_NAMESPACE
  27117. AudioProcessor::AudioProcessor()
  27118. : playHead (0),
  27119. activeEditor (0),
  27120. sampleRate (0),
  27121. blockSize (0),
  27122. numInputChannels (0),
  27123. numOutputChannels (0),
  27124. latencySamples (0),
  27125. suspended (false),
  27126. nonRealtime (false)
  27127. {
  27128. }
  27129. AudioProcessor::~AudioProcessor()
  27130. {
  27131. // ooh, nasty - the editor should have been deleted before the filter
  27132. // that it refers to is deleted..
  27133. jassert (activeEditor == 0);
  27134. #ifdef JUCE_DEBUG
  27135. // This will fail if you've called beginParameterChangeGesture() for one
  27136. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  27137. jassert (changingParams.countNumberOfSetBits() == 0);
  27138. #endif
  27139. }
  27140. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  27141. {
  27142. playHead = newPlayHead;
  27143. }
  27144. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  27145. {
  27146. const ScopedLock sl (listenerLock);
  27147. listeners.addIfNotAlreadyThere (newListener);
  27148. }
  27149. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  27150. {
  27151. const ScopedLock sl (listenerLock);
  27152. listeners.removeValue (listenerToRemove);
  27153. }
  27154. void AudioProcessor::setPlayConfigDetails (const int numIns,
  27155. const int numOuts,
  27156. const double sampleRate_,
  27157. const int blockSize_) throw()
  27158. {
  27159. numInputChannels = numIns;
  27160. numOutputChannels = numOuts;
  27161. sampleRate = sampleRate_;
  27162. blockSize = blockSize_;
  27163. }
  27164. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  27165. {
  27166. nonRealtime = nonRealtime_;
  27167. }
  27168. void AudioProcessor::setLatencySamples (const int newLatency)
  27169. {
  27170. if (latencySamples != newLatency)
  27171. {
  27172. latencySamples = newLatency;
  27173. updateHostDisplay();
  27174. }
  27175. }
  27176. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  27177. const float newValue)
  27178. {
  27179. setParameter (parameterIndex, newValue);
  27180. sendParamChangeMessageToListeners (parameterIndex, newValue);
  27181. }
  27182. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  27183. {
  27184. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27185. for (int i = listeners.size(); --i >= 0;)
  27186. {
  27187. listenerLock.enter();
  27188. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27189. listenerLock.exit();
  27190. if (l != 0)
  27191. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  27192. }
  27193. }
  27194. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  27195. {
  27196. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27197. #ifdef JUCE_DEBUG
  27198. // This means you've called beginParameterChangeGesture twice in succession without a matching
  27199. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  27200. jassert (! changingParams [parameterIndex]);
  27201. changingParams.setBit (parameterIndex);
  27202. #endif
  27203. for (int i = listeners.size(); --i >= 0;)
  27204. {
  27205. listenerLock.enter();
  27206. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27207. listenerLock.exit();
  27208. if (l != 0)
  27209. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  27210. }
  27211. }
  27212. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  27213. {
  27214. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  27215. #ifdef JUCE_DEBUG
  27216. // This means you've called endParameterChangeGesture without having previously called
  27217. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  27218. // calls matched correctly.
  27219. jassert (changingParams [parameterIndex]);
  27220. changingParams.clearBit (parameterIndex);
  27221. #endif
  27222. for (int i = listeners.size(); --i >= 0;)
  27223. {
  27224. listenerLock.enter();
  27225. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27226. listenerLock.exit();
  27227. if (l != 0)
  27228. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  27229. }
  27230. }
  27231. void AudioProcessor::updateHostDisplay()
  27232. {
  27233. for (int i = listeners.size(); --i >= 0;)
  27234. {
  27235. listenerLock.enter();
  27236. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  27237. listenerLock.exit();
  27238. if (l != 0)
  27239. l->audioProcessorChanged (this);
  27240. }
  27241. }
  27242. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  27243. {
  27244. return true;
  27245. }
  27246. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  27247. {
  27248. return false;
  27249. }
  27250. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  27251. {
  27252. const ScopedLock sl (callbackLock);
  27253. suspended = shouldBeSuspended;
  27254. }
  27255. void AudioProcessor::reset()
  27256. {
  27257. }
  27258. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  27259. {
  27260. const ScopedLock sl (callbackLock);
  27261. jassert (activeEditor == editor);
  27262. if (activeEditor == editor)
  27263. activeEditor = 0;
  27264. }
  27265. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  27266. {
  27267. if (activeEditor != 0)
  27268. return activeEditor;
  27269. AudioProcessorEditor* const ed = createEditor();
  27270. if (ed != 0)
  27271. {
  27272. // you must give your editor comp a size before returning it..
  27273. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  27274. const ScopedLock sl (callbackLock);
  27275. activeEditor = ed;
  27276. }
  27277. return ed;
  27278. }
  27279. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  27280. {
  27281. getStateInformation (destData);
  27282. }
  27283. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  27284. {
  27285. setStateInformation (data, sizeInBytes);
  27286. }
  27287. // magic number to identify memory blocks that we've stored as XML
  27288. const uint32 magicXmlNumber = 0x21324356;
  27289. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  27290. JUCE_NAMESPACE::MemoryBlock& destData)
  27291. {
  27292. const String xmlString (xml.createDocument (String::empty, true, false));
  27293. const int stringLength = xmlString.length();
  27294. destData.setSize (stringLength + 10);
  27295. char* const d = (char*) destData.getData();
  27296. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  27297. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  27298. xmlString.copyToBuffer (d + 8, stringLength);
  27299. }
  27300. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  27301. const int sizeInBytes)
  27302. {
  27303. if (sizeInBytes > 8
  27304. && littleEndianInt ((const char*) data) == magicXmlNumber)
  27305. {
  27306. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  27307. if (stringLength > 0)
  27308. {
  27309. XmlDocument doc (String (((const char*) data) + 8,
  27310. jmin ((sizeInBytes - 8), stringLength)));
  27311. return doc.getDocumentElement();
  27312. }
  27313. }
  27314. return 0;
  27315. }
  27316. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  27317. {
  27318. }
  27319. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  27320. {
  27321. }
  27322. END_JUCE_NAMESPACE
  27323. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  27324. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  27325. BEGIN_JUCE_NAMESPACE
  27326. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  27327. : owner (owner_)
  27328. {
  27329. // the filter must be valid..
  27330. jassert (owner != 0);
  27331. }
  27332. AudioProcessorEditor::~AudioProcessorEditor()
  27333. {
  27334. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  27335. // filter for some reason..
  27336. jassert (owner->getActiveEditor() != this);
  27337. }
  27338. END_JUCE_NAMESPACE
  27339. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  27340. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  27341. BEGIN_JUCE_NAMESPACE
  27342. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  27343. AudioProcessorGraph::Node::Node (const uint32 id_,
  27344. AudioProcessor* const processor_) throw()
  27345. : id (id_),
  27346. processor (processor_),
  27347. isPrepared (false)
  27348. {
  27349. jassert (processor_ != 0);
  27350. }
  27351. AudioProcessorGraph::Node::~Node()
  27352. {
  27353. delete processor;
  27354. }
  27355. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  27356. AudioProcessorGraph* const graph)
  27357. {
  27358. if (! isPrepared)
  27359. {
  27360. isPrepared = true;
  27361. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27362. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  27363. if (ioProc != 0)
  27364. ioProc->setParentGraph (graph);
  27365. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  27366. processor->getNumOutputChannels(),
  27367. sampleRate, blockSize);
  27368. processor->prepareToPlay (sampleRate, blockSize);
  27369. }
  27370. }
  27371. void AudioProcessorGraph::Node::unprepare()
  27372. {
  27373. if (isPrepared)
  27374. {
  27375. isPrepared = false;
  27376. processor->releaseResources();
  27377. }
  27378. }
  27379. AudioProcessorGraph::AudioProcessorGraph()
  27380. : lastNodeId (0),
  27381. renderingBuffers (1, 1),
  27382. currentAudioOutputBuffer (1, 1)
  27383. {
  27384. }
  27385. AudioProcessorGraph::~AudioProcessorGraph()
  27386. {
  27387. clearRenderingSequence();
  27388. clear();
  27389. }
  27390. const String AudioProcessorGraph::getName() const
  27391. {
  27392. return "Audio Graph";
  27393. }
  27394. void AudioProcessorGraph::clear()
  27395. {
  27396. nodes.clear();
  27397. connections.clear();
  27398. triggerAsyncUpdate();
  27399. }
  27400. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  27401. {
  27402. for (int i = nodes.size(); --i >= 0;)
  27403. if (nodes.getUnchecked(i)->id == nodeId)
  27404. return nodes.getUnchecked(i);
  27405. return 0;
  27406. }
  27407. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  27408. uint32 nodeId)
  27409. {
  27410. if (newProcessor == 0)
  27411. {
  27412. jassertfalse
  27413. return 0;
  27414. }
  27415. if (nodeId == 0)
  27416. {
  27417. nodeId = ++lastNodeId;
  27418. }
  27419. else
  27420. {
  27421. // you can't add a node with an id that already exists in the graph..
  27422. jassert (getNodeForId (nodeId) == 0);
  27423. removeNode (nodeId);
  27424. }
  27425. lastNodeId = nodeId;
  27426. Node* const n = new Node (nodeId, newProcessor);
  27427. nodes.add (n);
  27428. triggerAsyncUpdate();
  27429. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27430. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  27431. if (ioProc != 0)
  27432. ioProc->setParentGraph (this);
  27433. return n;
  27434. }
  27435. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  27436. {
  27437. disconnectNode (nodeId);
  27438. for (int i = nodes.size(); --i >= 0;)
  27439. {
  27440. if (nodes.getUnchecked(i)->id == nodeId)
  27441. {
  27442. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  27443. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  27444. if (ioProc != 0)
  27445. ioProc->setParentGraph (0);
  27446. nodes.remove (i);
  27447. triggerAsyncUpdate();
  27448. return true;
  27449. }
  27450. }
  27451. return false;
  27452. }
  27453. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  27454. const int sourceChannelIndex,
  27455. const uint32 destNodeId,
  27456. const int destChannelIndex) const throw()
  27457. {
  27458. for (int i = connections.size(); --i >= 0;)
  27459. {
  27460. const Connection* const c = connections.getUnchecked(i);
  27461. if (c->sourceNodeId == sourceNodeId
  27462. && c->destNodeId == destNodeId
  27463. && c->sourceChannelIndex == sourceChannelIndex
  27464. && c->destChannelIndex == destChannelIndex)
  27465. {
  27466. return c;
  27467. }
  27468. }
  27469. return 0;
  27470. }
  27471. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  27472. const uint32 possibleDestNodeId) const throw()
  27473. {
  27474. for (int i = connections.size(); --i >= 0;)
  27475. {
  27476. const Connection* const c = connections.getUnchecked(i);
  27477. if (c->sourceNodeId == possibleSourceNodeId
  27478. && c->destNodeId == possibleDestNodeId)
  27479. {
  27480. return true;
  27481. }
  27482. }
  27483. return false;
  27484. }
  27485. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  27486. const int sourceChannelIndex,
  27487. const uint32 destNodeId,
  27488. const int destChannelIndex) const throw()
  27489. {
  27490. if (sourceChannelIndex < 0
  27491. || destChannelIndex < 0
  27492. || sourceNodeId == destNodeId
  27493. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  27494. return false;
  27495. const Node* const source = getNodeForId (sourceNodeId);
  27496. if (source == 0
  27497. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  27498. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  27499. return false;
  27500. const Node* const dest = getNodeForId (destNodeId);
  27501. if (dest == 0
  27502. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  27503. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  27504. return false;
  27505. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  27506. destNodeId, destChannelIndex) == 0;
  27507. }
  27508. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  27509. const int sourceChannelIndex,
  27510. const uint32 destNodeId,
  27511. const int destChannelIndex)
  27512. {
  27513. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  27514. return false;
  27515. Connection* const c = new Connection();
  27516. c->sourceNodeId = sourceNodeId;
  27517. c->sourceChannelIndex = sourceChannelIndex;
  27518. c->destNodeId = destNodeId;
  27519. c->destChannelIndex = destChannelIndex;
  27520. connections.add (c);
  27521. triggerAsyncUpdate();
  27522. return true;
  27523. }
  27524. void AudioProcessorGraph::removeConnection (const int index)
  27525. {
  27526. connections.remove (index);
  27527. triggerAsyncUpdate();
  27528. }
  27529. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  27530. const uint32 destNodeId, const int destChannelIndex)
  27531. {
  27532. bool doneAnything = false;
  27533. for (int i = connections.size(); --i >= 0;)
  27534. {
  27535. const Connection* const c = connections.getUnchecked(i);
  27536. if (c->sourceNodeId == sourceNodeId
  27537. && c->destNodeId == destNodeId
  27538. && c->sourceChannelIndex == sourceChannelIndex
  27539. && c->destChannelIndex == destChannelIndex)
  27540. {
  27541. removeConnection (i);
  27542. doneAnything = true;
  27543. triggerAsyncUpdate();
  27544. }
  27545. }
  27546. return doneAnything;
  27547. }
  27548. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  27549. {
  27550. bool doneAnything = false;
  27551. for (int i = connections.size(); --i >= 0;)
  27552. {
  27553. const Connection* const c = connections.getUnchecked(i);
  27554. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  27555. {
  27556. removeConnection (i);
  27557. doneAnything = true;
  27558. triggerAsyncUpdate();
  27559. }
  27560. }
  27561. return doneAnything;
  27562. }
  27563. bool AudioProcessorGraph::removeIllegalConnections()
  27564. {
  27565. bool doneAnything = false;
  27566. for (int i = connections.size(); --i >= 0;)
  27567. {
  27568. const Connection* const c = connections.getUnchecked(i);
  27569. const Node* const source = getNodeForId (c->sourceNodeId);
  27570. const Node* const dest = getNodeForId (c->destNodeId);
  27571. if (source == 0 || dest == 0
  27572. || (c->sourceChannelIndex != midiChannelIndex
  27573. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  27574. || (c->sourceChannelIndex == midiChannelIndex
  27575. && ! source->processor->producesMidi())
  27576. || (c->destChannelIndex != midiChannelIndex
  27577. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  27578. || (c->destChannelIndex == midiChannelIndex
  27579. && ! dest->processor->acceptsMidi()))
  27580. {
  27581. removeConnection (i);
  27582. doneAnything = true;
  27583. triggerAsyncUpdate();
  27584. }
  27585. }
  27586. return doneAnything;
  27587. }
  27588. namespace GraphRenderingOps
  27589. {
  27590. class AudioGraphRenderingOp
  27591. {
  27592. public:
  27593. AudioGraphRenderingOp() throw() {}
  27594. virtual ~AudioGraphRenderingOp() throw() {}
  27595. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  27596. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  27597. const int numSamples) throw() = 0;
  27598. juce_UseDebuggingNewOperator
  27599. };
  27600. class ClearChannelOp : public AudioGraphRenderingOp
  27601. {
  27602. public:
  27603. ClearChannelOp (const int channelNum_) throw()
  27604. : channelNum (channelNum_)
  27605. {}
  27606. ~ClearChannelOp() throw() {}
  27607. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27608. {
  27609. sharedBufferChans.clear (channelNum, 0, numSamples);
  27610. }
  27611. private:
  27612. const int channelNum;
  27613. ClearChannelOp (const ClearChannelOp&);
  27614. const ClearChannelOp& operator= (const ClearChannelOp&);
  27615. };
  27616. class CopyChannelOp : public AudioGraphRenderingOp
  27617. {
  27618. public:
  27619. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27620. : srcChannelNum (srcChannelNum_),
  27621. dstChannelNum (dstChannelNum_)
  27622. {}
  27623. ~CopyChannelOp() throw() {}
  27624. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27625. {
  27626. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27627. }
  27628. private:
  27629. const int srcChannelNum, dstChannelNum;
  27630. CopyChannelOp (const CopyChannelOp&);
  27631. const CopyChannelOp& operator= (const CopyChannelOp&);
  27632. };
  27633. class AddChannelOp : public AudioGraphRenderingOp
  27634. {
  27635. public:
  27636. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  27637. : srcChannelNum (srcChannelNum_),
  27638. dstChannelNum (dstChannelNum_)
  27639. {}
  27640. ~AddChannelOp() throw() {}
  27641. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  27642. {
  27643. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  27644. }
  27645. private:
  27646. const int srcChannelNum, dstChannelNum;
  27647. AddChannelOp (const AddChannelOp&);
  27648. const AddChannelOp& operator= (const AddChannelOp&);
  27649. };
  27650. class ClearMidiBufferOp : public AudioGraphRenderingOp
  27651. {
  27652. public:
  27653. ClearMidiBufferOp (const int bufferNum_) throw()
  27654. : bufferNum (bufferNum_)
  27655. {}
  27656. ~ClearMidiBufferOp() throw() {}
  27657. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27658. {
  27659. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  27660. }
  27661. private:
  27662. const int bufferNum;
  27663. ClearMidiBufferOp (const ClearMidiBufferOp&);
  27664. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  27665. };
  27666. class CopyMidiBufferOp : public AudioGraphRenderingOp
  27667. {
  27668. public:
  27669. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27670. : srcBufferNum (srcBufferNum_),
  27671. dstBufferNum (dstBufferNum_)
  27672. {}
  27673. ~CopyMidiBufferOp() throw() {}
  27674. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  27675. {
  27676. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  27677. }
  27678. private:
  27679. const int srcBufferNum, dstBufferNum;
  27680. CopyMidiBufferOp (const CopyMidiBufferOp&);
  27681. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  27682. };
  27683. class AddMidiBufferOp : public AudioGraphRenderingOp
  27684. {
  27685. public:
  27686. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  27687. : srcBufferNum (srcBufferNum_),
  27688. dstBufferNum (dstBufferNum_)
  27689. {}
  27690. ~AddMidiBufferOp() throw() {}
  27691. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27692. {
  27693. sharedMidiBuffers.getUnchecked (dstBufferNum)
  27694. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  27695. }
  27696. private:
  27697. const int srcBufferNum, dstBufferNum;
  27698. AddMidiBufferOp (const AddMidiBufferOp&);
  27699. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  27700. };
  27701. class ProcessBufferOp : public AudioGraphRenderingOp
  27702. {
  27703. public:
  27704. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  27705. const Array <int>& audioChannelsToUse_,
  27706. const int totalChans_,
  27707. const int midiBufferToUse_) throw()
  27708. : node (node_),
  27709. processor (node_->processor),
  27710. audioChannelsToUse (audioChannelsToUse_),
  27711. totalChans (jmax (1, totalChans_)),
  27712. midiBufferToUse (midiBufferToUse_)
  27713. {
  27714. channels = (float**) juce_calloc (sizeof (float*) * totalChans);
  27715. while (audioChannelsToUse.size() < totalChans)
  27716. audioChannelsToUse.add (0);
  27717. }
  27718. ~ProcessBufferOp() throw()
  27719. {
  27720. juce_free (channels);
  27721. }
  27722. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  27723. {
  27724. for (int i = totalChans; --i >= 0;)
  27725. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  27726. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  27727. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  27728. }
  27729. const AudioProcessorGraph::Node::Ptr node;
  27730. AudioProcessor* const processor;
  27731. private:
  27732. Array <int> audioChannelsToUse;
  27733. float** channels;
  27734. int totalChans;
  27735. int midiBufferToUse;
  27736. ProcessBufferOp (const ProcessBufferOp&);
  27737. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  27738. };
  27739. /** Used to calculate the correct sequence of rendering ops needed, based on
  27740. the best re-use of shared buffers at each stage.
  27741. */
  27742. class RenderingOpSequenceCalculator
  27743. {
  27744. public:
  27745. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  27746. const VoidArray& orderedNodes_,
  27747. VoidArray& renderingOps)
  27748. : graph (graph_),
  27749. orderedNodes (orderedNodes_)
  27750. {
  27751. nodeIds.add (-2); // first buffer is read-only zeros
  27752. channels.add (0);
  27753. midiNodeIds.add (-2);
  27754. for (int i = 0; i < orderedNodes.size(); ++i)
  27755. {
  27756. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  27757. renderingOps, i);
  27758. markAnyUnusedBuffersAsFree (i);
  27759. }
  27760. }
  27761. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  27762. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  27763. juce_UseDebuggingNewOperator
  27764. private:
  27765. AudioProcessorGraph& graph;
  27766. const VoidArray& orderedNodes;
  27767. Array <int> nodeIds, channels, midiNodeIds;
  27768. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  27769. VoidArray& renderingOps,
  27770. const int ourRenderingIndex)
  27771. {
  27772. const int numIns = node->processor->getNumInputChannels();
  27773. const int numOuts = node->processor->getNumOutputChannels();
  27774. const int totalChans = jmax (numIns, numOuts);
  27775. Array <int> audioChannelsToUse;
  27776. int midiBufferToUse = -1;
  27777. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  27778. {
  27779. // get a list of all the inputs to this node
  27780. Array <int> sourceNodes, sourceOutputChans;
  27781. for (int i = graph.getNumConnections(); --i >= 0;)
  27782. {
  27783. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27784. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  27785. {
  27786. sourceNodes.add (c->sourceNodeId);
  27787. sourceOutputChans.add (c->sourceChannelIndex);
  27788. }
  27789. }
  27790. int bufIndex = -1;
  27791. if (sourceNodes.size() == 0)
  27792. {
  27793. // unconnected input channel
  27794. if (inputChan >= numOuts)
  27795. {
  27796. bufIndex = getReadOnlyEmptyBuffer();
  27797. jassert (bufIndex >= 0);
  27798. }
  27799. else
  27800. {
  27801. bufIndex = getFreeBuffer (false);
  27802. renderingOps.add (new ClearChannelOp (bufIndex));
  27803. }
  27804. }
  27805. else if (sourceNodes.size() == 1)
  27806. {
  27807. // channel with a straightforward single input..
  27808. const int srcNode = sourceNodes.getUnchecked(0);
  27809. const int srcChan = sourceOutputChans.getUnchecked(0);
  27810. bufIndex = getBufferContaining (srcNode, srcChan);
  27811. if (bufIndex < 0)
  27812. {
  27813. // if not found, this is probably a feedback loop
  27814. bufIndex = getReadOnlyEmptyBuffer();
  27815. jassert (bufIndex >= 0);
  27816. }
  27817. if (inputChan < numOuts
  27818. && isBufferNeededLater (ourRenderingIndex,
  27819. inputChan,
  27820. srcNode, srcChan))
  27821. {
  27822. // can't mess up this channel because it's needed later by another node, so we
  27823. // need to use a copy of it..
  27824. const int newFreeBuffer = getFreeBuffer (false);
  27825. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  27826. bufIndex = newFreeBuffer;
  27827. }
  27828. }
  27829. else
  27830. {
  27831. // channel with a mix of several inputs..
  27832. // try to find a re-usable channel from our inputs..
  27833. int reusableInputIndex = -1;
  27834. for (int i = 0; i < sourceNodes.size(); ++i)
  27835. {
  27836. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  27837. sourceOutputChans.getUnchecked(i));
  27838. if (sourceBufIndex >= 0
  27839. && ! isBufferNeededLater (ourRenderingIndex,
  27840. inputChan,
  27841. sourceNodes.getUnchecked(i),
  27842. sourceOutputChans.getUnchecked(i)))
  27843. {
  27844. // we've found one of our input chans that can be re-used..
  27845. reusableInputIndex = i;
  27846. bufIndex = sourceBufIndex;
  27847. break;
  27848. }
  27849. }
  27850. if (reusableInputIndex < 0)
  27851. {
  27852. // can't re-use any of our input chans, so get a new one and copy everything into it..
  27853. bufIndex = getFreeBuffer (false);
  27854. jassert (bufIndex != 0);
  27855. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  27856. sourceOutputChans.getUnchecked (0));
  27857. if (srcIndex < 0)
  27858. {
  27859. // if not found, this is probably a feedback loop
  27860. renderingOps.add (new ClearChannelOp (bufIndex));
  27861. }
  27862. else
  27863. {
  27864. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  27865. }
  27866. reusableInputIndex = 0;
  27867. }
  27868. for (int j = 0; j < sourceNodes.size(); ++j)
  27869. {
  27870. if (j != reusableInputIndex)
  27871. {
  27872. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  27873. sourceOutputChans.getUnchecked(j));
  27874. if (srcIndex >= 0)
  27875. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  27876. }
  27877. }
  27878. }
  27879. jassert (bufIndex >= 0);
  27880. audioChannelsToUse.add (bufIndex);
  27881. if (inputChan < numOuts)
  27882. markBufferAsContaining (bufIndex, node->id, inputChan);
  27883. }
  27884. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  27885. {
  27886. const int bufIndex = getFreeBuffer (false);
  27887. jassert (bufIndex != 0);
  27888. audioChannelsToUse.add (bufIndex);
  27889. markBufferAsContaining (bufIndex, node->id, outputChan);
  27890. }
  27891. // Now the same thing for midi..
  27892. Array <int> midiSourceNodes;
  27893. for (int i = graph.getNumConnections(); --i >= 0;)
  27894. {
  27895. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  27896. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  27897. midiSourceNodes.add (c->sourceNodeId);
  27898. }
  27899. if (midiSourceNodes.size() == 0)
  27900. {
  27901. // No midi inputs..
  27902. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27903. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  27904. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27905. }
  27906. else if (midiSourceNodes.size() == 1)
  27907. {
  27908. // One midi input..
  27909. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27910. AudioProcessorGraph::midiChannelIndex);
  27911. if (midiBufferToUse >= 0)
  27912. {
  27913. if (isBufferNeededLater (ourRenderingIndex,
  27914. AudioProcessorGraph::midiChannelIndex,
  27915. midiSourceNodes.getUnchecked(0),
  27916. AudioProcessorGraph::midiChannelIndex))
  27917. {
  27918. // can't mess up this channel because it's needed later by another node, so we
  27919. // need to use a copy of it..
  27920. const int newFreeBuffer = getFreeBuffer (true);
  27921. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  27922. midiBufferToUse = newFreeBuffer;
  27923. }
  27924. }
  27925. else
  27926. {
  27927. // probably a feedback loop, so just use an empty one..
  27928. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  27929. }
  27930. }
  27931. else
  27932. {
  27933. // More than one midi input being mixed..
  27934. int reusableInputIndex = -1;
  27935. for (int i = 0; i < midiSourceNodes.size(); ++i)
  27936. {
  27937. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  27938. AudioProcessorGraph::midiChannelIndex);
  27939. if (sourceBufIndex >= 0
  27940. && ! isBufferNeededLater (ourRenderingIndex,
  27941. AudioProcessorGraph::midiChannelIndex,
  27942. midiSourceNodes.getUnchecked(i),
  27943. AudioProcessorGraph::midiChannelIndex))
  27944. {
  27945. // we've found one of our input buffers that can be re-used..
  27946. reusableInputIndex = i;
  27947. midiBufferToUse = sourceBufIndex;
  27948. break;
  27949. }
  27950. }
  27951. if (reusableInputIndex < 0)
  27952. {
  27953. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  27954. midiBufferToUse = getFreeBuffer (true);
  27955. jassert (midiBufferToUse >= 0);
  27956. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  27957. AudioProcessorGraph::midiChannelIndex);
  27958. if (srcIndex >= 0)
  27959. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  27960. else
  27961. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  27962. reusableInputIndex = 0;
  27963. }
  27964. for (int j = 0; j < midiSourceNodes.size(); ++j)
  27965. {
  27966. if (j != reusableInputIndex)
  27967. {
  27968. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  27969. AudioProcessorGraph::midiChannelIndex);
  27970. if (srcIndex >= 0)
  27971. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  27972. }
  27973. }
  27974. }
  27975. if (node->processor->producesMidi())
  27976. markBufferAsContaining (midiBufferToUse, node->id,
  27977. AudioProcessorGraph::midiChannelIndex);
  27978. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  27979. totalChans, midiBufferToUse));
  27980. }
  27981. int getFreeBuffer (const bool forMidi)
  27982. {
  27983. if (forMidi)
  27984. {
  27985. for (int i = 1; i < midiNodeIds.size(); ++i)
  27986. if (midiNodeIds.getUnchecked(i) < 0)
  27987. return i;
  27988. midiNodeIds.add (-1);
  27989. return midiNodeIds.size() - 1;
  27990. }
  27991. else
  27992. {
  27993. for (int i = 1; i < nodeIds.size(); ++i)
  27994. if (nodeIds.getUnchecked(i) < 0)
  27995. return i;
  27996. nodeIds.add (-1);
  27997. channels.add (0);
  27998. return nodeIds.size() - 1;
  27999. }
  28000. }
  28001. int getReadOnlyEmptyBuffer() const throw()
  28002. {
  28003. return 0;
  28004. }
  28005. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  28006. {
  28007. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  28008. {
  28009. for (int i = midiNodeIds.size(); --i >= 0;)
  28010. if (midiNodeIds.getUnchecked(i) == nodeId)
  28011. return i;
  28012. }
  28013. else
  28014. {
  28015. for (int i = nodeIds.size(); --i >= 0;)
  28016. if (nodeIds.getUnchecked(i) == nodeId
  28017. && channels.getUnchecked(i) == outputChannel)
  28018. return i;
  28019. }
  28020. return -1;
  28021. }
  28022. void markAnyUnusedBuffersAsFree (const int stepIndex)
  28023. {
  28024. int i;
  28025. for (i = 0; i < nodeIds.size(); ++i)
  28026. {
  28027. if (nodeIds.getUnchecked(i) >= 0
  28028. && ! isBufferNeededLater (stepIndex, -1,
  28029. nodeIds.getUnchecked(i),
  28030. channels.getUnchecked(i)))
  28031. {
  28032. nodeIds.set (i, -1);
  28033. }
  28034. }
  28035. for (i = 0; i < midiNodeIds.size(); ++i)
  28036. {
  28037. if (midiNodeIds.getUnchecked(i) >= 0
  28038. && ! isBufferNeededLater (stepIndex, -1,
  28039. midiNodeIds.getUnchecked(i),
  28040. AudioProcessorGraph::midiChannelIndex))
  28041. {
  28042. midiNodeIds.set (i, -1);
  28043. }
  28044. }
  28045. }
  28046. bool isBufferNeededLater (int stepIndexToSearchFrom,
  28047. int inputChannelOfIndexToIgnore,
  28048. const int nodeId,
  28049. const int outputChanIndex) const throw()
  28050. {
  28051. while (stepIndexToSearchFrom < orderedNodes.size())
  28052. {
  28053. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  28054. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  28055. {
  28056. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  28057. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  28058. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  28059. return true;
  28060. }
  28061. else
  28062. {
  28063. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  28064. if (i != inputChannelOfIndexToIgnore
  28065. && graph.getConnectionBetween (nodeId, outputChanIndex,
  28066. node->id, i) != 0)
  28067. return true;
  28068. }
  28069. inputChannelOfIndexToIgnore = -1;
  28070. ++stepIndexToSearchFrom;
  28071. }
  28072. return false;
  28073. }
  28074. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  28075. {
  28076. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  28077. {
  28078. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  28079. midiNodeIds.set (bufferNum, nodeId);
  28080. }
  28081. else
  28082. {
  28083. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  28084. nodeIds.set (bufferNum, nodeId);
  28085. channels.set (bufferNum, outputIndex);
  28086. }
  28087. }
  28088. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  28089. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  28090. };
  28091. }
  28092. void AudioProcessorGraph::clearRenderingSequence()
  28093. {
  28094. const ScopedLock sl (renderLock);
  28095. for (int i = renderingOps.size(); --i >= 0;)
  28096. {
  28097. GraphRenderingOps::AudioGraphRenderingOp* const r
  28098. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28099. renderingOps.remove (i);
  28100. delete r;
  28101. }
  28102. }
  28103. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  28104. const uint32 possibleDestinationId,
  28105. const int recursionCheck) const throw()
  28106. {
  28107. if (recursionCheck > 0)
  28108. {
  28109. for (int i = connections.size(); --i >= 0;)
  28110. {
  28111. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  28112. if (c->destNodeId == possibleDestinationId
  28113. && (c->sourceNodeId == possibleInputId
  28114. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  28115. return true;
  28116. }
  28117. }
  28118. return false;
  28119. }
  28120. void AudioProcessorGraph::buildRenderingSequence()
  28121. {
  28122. VoidArray newRenderingOps;
  28123. int numRenderingBuffersNeeded = 2;
  28124. int numMidiBuffersNeeded = 1;
  28125. {
  28126. MessageManagerLock mml;
  28127. VoidArray orderedNodes;
  28128. int i;
  28129. for (i = 0; i < nodes.size(); ++i)
  28130. {
  28131. Node* const node = nodes.getUnchecked(i);
  28132. node->prepare (getSampleRate(), getBlockSize(), this);
  28133. int j = 0;
  28134. for (; j < orderedNodes.size(); ++j)
  28135. if (isAnInputTo (node->id,
  28136. ((Node*) orderedNodes.getUnchecked (j))->id,
  28137. nodes.size() + 1))
  28138. break;
  28139. orderedNodes.insert (j, node);
  28140. }
  28141. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  28142. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  28143. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  28144. }
  28145. VoidArray oldRenderingOps (renderingOps);
  28146. {
  28147. // swap over to the new rendering sequence..
  28148. const ScopedLock sl (renderLock);
  28149. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  28150. renderingBuffers.clear();
  28151. for (int i = midiBuffers.size(); --i >= 0;)
  28152. midiBuffers.getUnchecked(i)->clear();
  28153. while (midiBuffers.size() < numMidiBuffersNeeded)
  28154. midiBuffers.add (new MidiBuffer());
  28155. renderingOps = newRenderingOps;
  28156. }
  28157. for (int i = oldRenderingOps.size(); --i >= 0;)
  28158. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  28159. }
  28160. void AudioProcessorGraph::handleAsyncUpdate()
  28161. {
  28162. buildRenderingSequence();
  28163. }
  28164. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  28165. {
  28166. currentAudioInputBuffer = 0;
  28167. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  28168. currentMidiInputBuffer = 0;
  28169. currentMidiOutputBuffer.clear();
  28170. clearRenderingSequence();
  28171. buildRenderingSequence();
  28172. }
  28173. void AudioProcessorGraph::releaseResources()
  28174. {
  28175. for (int i = 0; i < nodes.size(); ++i)
  28176. nodes.getUnchecked(i)->unprepare();
  28177. renderingBuffers.setSize (1, 1);
  28178. midiBuffers.clear();
  28179. currentAudioInputBuffer = 0;
  28180. currentAudioOutputBuffer.setSize (1, 1);
  28181. currentMidiInputBuffer = 0;
  28182. currentMidiOutputBuffer.clear();
  28183. }
  28184. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  28185. {
  28186. const int numSamples = buffer.getNumSamples();
  28187. const ScopedLock sl (renderLock);
  28188. currentAudioInputBuffer = &buffer;
  28189. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  28190. currentAudioOutputBuffer.clear();
  28191. currentMidiInputBuffer = &midiMessages;
  28192. currentMidiOutputBuffer.clear();
  28193. int i;
  28194. for (i = 0; i < renderingOps.size(); ++i)
  28195. {
  28196. GraphRenderingOps::AudioGraphRenderingOp* const op
  28197. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  28198. op->perform (renderingBuffers, midiBuffers, numSamples);
  28199. }
  28200. for (i = 0; i < buffer.getNumChannels(); ++i)
  28201. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  28202. }
  28203. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  28204. {
  28205. return "Input " + String (channelIndex + 1);
  28206. }
  28207. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  28208. {
  28209. return "Output " + String (channelIndex + 1);
  28210. }
  28211. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  28212. {
  28213. return true;
  28214. }
  28215. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  28216. {
  28217. return true;
  28218. }
  28219. bool AudioProcessorGraph::acceptsMidi() const
  28220. {
  28221. return true;
  28222. }
  28223. bool AudioProcessorGraph::producesMidi() const
  28224. {
  28225. return true;
  28226. }
  28227. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  28228. {
  28229. }
  28230. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  28231. {
  28232. }
  28233. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  28234. : type (type_),
  28235. graph (0)
  28236. {
  28237. }
  28238. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  28239. {
  28240. }
  28241. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  28242. {
  28243. switch (type)
  28244. {
  28245. case audioOutputNode:
  28246. return "Audio Output";
  28247. case audioInputNode:
  28248. return "Audio Input";
  28249. case midiOutputNode:
  28250. return "Midi Output";
  28251. case midiInputNode:
  28252. return "Midi Input";
  28253. default:
  28254. break;
  28255. }
  28256. return String::empty;
  28257. }
  28258. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  28259. {
  28260. d.name = getName();
  28261. d.uid = d.name.hashCode();
  28262. d.category = "I/O devices";
  28263. d.pluginFormatName = "Internal";
  28264. d.manufacturerName = "Raw Material Software";
  28265. d.version = "1.0";
  28266. d.isInstrument = false;
  28267. d.numInputChannels = getNumInputChannels();
  28268. if (type == audioOutputNode && graph != 0)
  28269. d.numInputChannels = graph->getNumInputChannels();
  28270. d.numOutputChannels = getNumOutputChannels();
  28271. if (type == audioInputNode && graph != 0)
  28272. d.numOutputChannels = graph->getNumOutputChannels();
  28273. }
  28274. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  28275. {
  28276. jassert (graph != 0);
  28277. }
  28278. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  28279. {
  28280. }
  28281. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  28282. MidiBuffer& midiMessages)
  28283. {
  28284. jassert (graph != 0);
  28285. switch (type)
  28286. {
  28287. case audioOutputNode:
  28288. {
  28289. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  28290. buffer.getNumChannels()); --i >= 0;)
  28291. {
  28292. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  28293. }
  28294. break;
  28295. }
  28296. case audioInputNode:
  28297. {
  28298. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  28299. buffer.getNumChannels()); --i >= 0;)
  28300. {
  28301. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  28302. }
  28303. break;
  28304. }
  28305. case midiOutputNode:
  28306. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  28307. break;
  28308. case midiInputNode:
  28309. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  28310. break;
  28311. default:
  28312. break;
  28313. }
  28314. }
  28315. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  28316. {
  28317. return type == midiOutputNode;
  28318. }
  28319. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  28320. {
  28321. return type == midiInputNode;
  28322. }
  28323. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  28324. {
  28325. switch (type)
  28326. {
  28327. case audioOutputNode:
  28328. return "Output " + String (channelIndex + 1);
  28329. case midiOutputNode:
  28330. return "Midi Output";
  28331. default:
  28332. break;
  28333. }
  28334. return String::empty;
  28335. }
  28336. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  28337. {
  28338. switch (type)
  28339. {
  28340. case audioInputNode:
  28341. return "Input " + String (channelIndex + 1);
  28342. case midiInputNode:
  28343. return "Midi Input";
  28344. default:
  28345. break;
  28346. }
  28347. return String::empty;
  28348. }
  28349. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  28350. {
  28351. return type == audioInputNode || type == audioOutputNode;
  28352. }
  28353. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  28354. {
  28355. return isInputChannelStereoPair (index);
  28356. }
  28357. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  28358. {
  28359. return type == audioInputNode || type == midiInputNode;
  28360. }
  28361. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  28362. {
  28363. return type == audioOutputNode || type == midiOutputNode;
  28364. }
  28365. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  28366. {
  28367. return 0;
  28368. }
  28369. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  28370. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  28371. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  28372. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  28373. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  28374. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  28375. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  28376. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  28377. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  28378. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  28379. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  28380. {
  28381. }
  28382. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  28383. {
  28384. }
  28385. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  28386. {
  28387. graph = newGraph;
  28388. if (graph != 0)
  28389. {
  28390. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  28391. type == audioInputNode ? graph->getNumInputChannels() : 0,
  28392. getSampleRate(),
  28393. getBlockSize());
  28394. updateHostDisplay();
  28395. }
  28396. }
  28397. END_JUCE_NAMESPACE
  28398. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  28399. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28400. BEGIN_JUCE_NAMESPACE
  28401. AudioProcessorPlayer::AudioProcessorPlayer()
  28402. : processor (0),
  28403. sampleRate (0),
  28404. blockSize (0),
  28405. isPrepared (false),
  28406. numInputChans (0),
  28407. numOutputChans (0),
  28408. tempBuffer (1, 1)
  28409. {
  28410. }
  28411. AudioProcessorPlayer::~AudioProcessorPlayer()
  28412. {
  28413. setProcessor (0);
  28414. }
  28415. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  28416. {
  28417. if (processor != processorToPlay)
  28418. {
  28419. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  28420. {
  28421. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  28422. sampleRate, blockSize);
  28423. processorToPlay->prepareToPlay (sampleRate, blockSize);
  28424. }
  28425. lock.enter();
  28426. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  28427. processor = processorToPlay;
  28428. isPrepared = true;
  28429. lock.exit();
  28430. if (oldOne != 0)
  28431. oldOne->releaseResources();
  28432. }
  28433. }
  28434. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  28435. int numInputChannels,
  28436. float** outputChannelData,
  28437. int numOutputChannels,
  28438. int numSamples)
  28439. {
  28440. // these should have been prepared by audioDeviceAboutToStart()...
  28441. jassert (sampleRate > 0 && blockSize > 0);
  28442. incomingMidi.clear();
  28443. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  28444. int i, totalNumChans = 0;
  28445. if (numInputChannels > numOutputChannels)
  28446. {
  28447. // if there aren't enough output channels for the number of
  28448. // inputs, we need to create some temporary extra ones (can't
  28449. // use the input data in case it gets written to)
  28450. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  28451. false, false, true);
  28452. for (i = 0; i < numOutputChannels; ++i)
  28453. {
  28454. channels[totalNumChans] = outputChannelData[i];
  28455. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28456. ++totalNumChans;
  28457. }
  28458. for (i = numOutputChannels; i < numInputChannels; ++i)
  28459. {
  28460. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  28461. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28462. ++totalNumChans;
  28463. }
  28464. }
  28465. else
  28466. {
  28467. for (i = 0; i < numInputChannels; ++i)
  28468. {
  28469. channels[totalNumChans] = outputChannelData[i];
  28470. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  28471. ++totalNumChans;
  28472. }
  28473. for (i = numInputChannels; i < numOutputChannels; ++i)
  28474. {
  28475. channels[totalNumChans] = outputChannelData[i];
  28476. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  28477. ++totalNumChans;
  28478. }
  28479. }
  28480. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  28481. const ScopedLock sl (lock);
  28482. if (processor != 0)
  28483. processor->processBlock (buffer, incomingMidi);
  28484. }
  28485. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  28486. {
  28487. const ScopedLock sl (lock);
  28488. sampleRate = device->getCurrentSampleRate();
  28489. blockSize = device->getCurrentBufferSizeSamples();
  28490. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  28491. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  28492. messageCollector.reset (sampleRate);
  28493. zeromem (channels, sizeof (channels));
  28494. if (processor != 0)
  28495. {
  28496. if (isPrepared)
  28497. processor->releaseResources();
  28498. AudioProcessor* const oldProcessor = processor;
  28499. setProcessor (0);
  28500. setProcessor (oldProcessor);
  28501. }
  28502. }
  28503. void AudioProcessorPlayer::audioDeviceStopped()
  28504. {
  28505. const ScopedLock sl (lock);
  28506. if (processor != 0 && isPrepared)
  28507. processor->releaseResources();
  28508. sampleRate = 0.0;
  28509. blockSize = 0;
  28510. isPrepared = false;
  28511. tempBuffer.setSize (1, 1);
  28512. }
  28513. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  28514. {
  28515. messageCollector.addMessageToQueue (message);
  28516. }
  28517. END_JUCE_NAMESPACE
  28518. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  28519. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28520. BEGIN_JUCE_NAMESPACE
  28521. class ProcessorParameterPropertyComp : public PropertyComponent,
  28522. public AudioProcessorListener,
  28523. public AsyncUpdater
  28524. {
  28525. public:
  28526. ProcessorParameterPropertyComp (const String& name,
  28527. AudioProcessor* const owner_,
  28528. const int index_)
  28529. : PropertyComponent (name),
  28530. owner (owner_),
  28531. index (index_)
  28532. {
  28533. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  28534. owner_->addListener (this);
  28535. }
  28536. ~ProcessorParameterPropertyComp()
  28537. {
  28538. owner->removeListener (this);
  28539. deleteAllChildren();
  28540. }
  28541. void refresh()
  28542. {
  28543. slider->setValue (owner->getParameter (index), false);
  28544. }
  28545. void audioProcessorChanged (AudioProcessor*) {}
  28546. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  28547. {
  28548. if (parameterIndex == index)
  28549. triggerAsyncUpdate();
  28550. }
  28551. void handleAsyncUpdate()
  28552. {
  28553. refresh();
  28554. }
  28555. juce_UseDebuggingNewOperator
  28556. private:
  28557. AudioProcessor* const owner;
  28558. const int index;
  28559. Slider* slider;
  28560. class ParamSlider : public Slider
  28561. {
  28562. public:
  28563. ParamSlider (AudioProcessor* const owner_, const int index_)
  28564. : Slider (String::empty),
  28565. owner (owner_),
  28566. index (index_)
  28567. {
  28568. setRange (0.0, 1.0, 0.0);
  28569. setSliderStyle (Slider::LinearBar);
  28570. setTextBoxIsEditable (false);
  28571. setScrollWheelEnabled (false);
  28572. }
  28573. ~ParamSlider()
  28574. {
  28575. }
  28576. void valueChanged()
  28577. {
  28578. const float newVal = (float) getValue();
  28579. if (owner->getParameter (index) != newVal)
  28580. owner->setParameter (index, newVal);
  28581. }
  28582. const String getTextFromValue (double /*value*/)
  28583. {
  28584. return owner->getParameterText (index);
  28585. }
  28586. juce_UseDebuggingNewOperator
  28587. private:
  28588. AudioProcessor* const owner;
  28589. const int index;
  28590. };
  28591. };
  28592. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  28593. : AudioProcessorEditor (owner)
  28594. {
  28595. setOpaque (true);
  28596. addAndMakeVisible (panel = new PropertyPanel());
  28597. Array <PropertyComponent*> params;
  28598. const int numParams = owner->getNumParameters();
  28599. int totalHeight = 0;
  28600. for (int i = 0; i < numParams; ++i)
  28601. {
  28602. String name (owner->getParameterName (i));
  28603. if (name.trim().isEmpty())
  28604. name = "Unnamed";
  28605. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  28606. params.add (pc);
  28607. totalHeight += pc->getPreferredHeight();
  28608. }
  28609. panel->addProperties (params);
  28610. setSize (400, jlimit (25, 400, totalHeight));
  28611. }
  28612. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  28613. {
  28614. deleteAllChildren();
  28615. }
  28616. void GenericAudioProcessorEditor::paint (Graphics& g)
  28617. {
  28618. g.fillAll (Colours::white);
  28619. }
  28620. void GenericAudioProcessorEditor::resized()
  28621. {
  28622. panel->setSize (getWidth(), getHeight());
  28623. }
  28624. END_JUCE_NAMESPACE
  28625. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  28626. /********* Start of inlined file: juce_Sampler.cpp *********/
  28627. BEGIN_JUCE_NAMESPACE
  28628. SamplerSound::SamplerSound (const String& name_,
  28629. AudioFormatReader& source,
  28630. const BitArray& midiNotes_,
  28631. const int midiNoteForNormalPitch,
  28632. const double attackTimeSecs,
  28633. const double releaseTimeSecs,
  28634. const double maxSampleLengthSeconds)
  28635. : name (name_),
  28636. midiNotes (midiNotes_),
  28637. midiRootNote (midiNoteForNormalPitch)
  28638. {
  28639. sourceSampleRate = source.sampleRate;
  28640. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  28641. {
  28642. data = 0;
  28643. length = 0;
  28644. attackSamples = 0;
  28645. releaseSamples = 0;
  28646. }
  28647. else
  28648. {
  28649. length = jmin ((int) source.lengthInSamples,
  28650. (int) (maxSampleLengthSeconds * sourceSampleRate));
  28651. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  28652. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  28653. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  28654. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  28655. }
  28656. }
  28657. SamplerSound::~SamplerSound()
  28658. {
  28659. delete data;
  28660. data = 0;
  28661. }
  28662. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  28663. {
  28664. return midiNotes [midiNoteNumber];
  28665. }
  28666. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  28667. {
  28668. return true;
  28669. }
  28670. SamplerVoice::SamplerVoice()
  28671. : pitchRatio (0.0),
  28672. sourceSamplePosition (0.0),
  28673. lgain (0.0f),
  28674. rgain (0.0f),
  28675. isInAttack (false),
  28676. isInRelease (false)
  28677. {
  28678. }
  28679. SamplerVoice::~SamplerVoice()
  28680. {
  28681. }
  28682. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  28683. {
  28684. return dynamic_cast <const SamplerSound*> (sound) != 0;
  28685. }
  28686. void SamplerVoice::startNote (const int midiNoteNumber,
  28687. const float velocity,
  28688. SynthesiserSound* s,
  28689. const int /*currentPitchWheelPosition*/)
  28690. {
  28691. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  28692. jassert (sound != 0); // this object can only play SamplerSounds!
  28693. if (sound != 0)
  28694. {
  28695. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  28696. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  28697. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  28698. sourceSamplePosition = 0.0;
  28699. lgain = velocity;
  28700. rgain = velocity;
  28701. isInAttack = (sound->attackSamples > 0);
  28702. isInRelease = false;
  28703. if (isInAttack)
  28704. {
  28705. attackReleaseLevel = 0.0f;
  28706. attackDelta = (float) (pitchRatio / sound->attackSamples);
  28707. }
  28708. else
  28709. {
  28710. attackReleaseLevel = 1.0f;
  28711. attackDelta = 0.0f;
  28712. }
  28713. if (sound->releaseSamples > 0)
  28714. {
  28715. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  28716. }
  28717. else
  28718. {
  28719. releaseDelta = 0.0f;
  28720. }
  28721. }
  28722. }
  28723. void SamplerVoice::stopNote (const bool allowTailOff)
  28724. {
  28725. if (allowTailOff)
  28726. {
  28727. isInAttack = false;
  28728. isInRelease = true;
  28729. }
  28730. else
  28731. {
  28732. clearCurrentNote();
  28733. }
  28734. }
  28735. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  28736. {
  28737. }
  28738. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  28739. const int /*newValue*/)
  28740. {
  28741. }
  28742. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  28743. {
  28744. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  28745. if (playingSound != 0)
  28746. {
  28747. const float* const inL = playingSound->data->getSampleData (0, 0);
  28748. const float* const inR = playingSound->data->getNumChannels() > 1
  28749. ? playingSound->data->getSampleData (1, 0) : 0;
  28750. float* outL = outputBuffer.getSampleData (0, startSample);
  28751. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  28752. while (--numSamples >= 0)
  28753. {
  28754. const int pos = (int) sourceSamplePosition;
  28755. const float alpha = (float) (sourceSamplePosition - pos);
  28756. const float invAlpha = 1.0f - alpha;
  28757. // just using a very simple linear interpolation here..
  28758. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  28759. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  28760. : l;
  28761. l *= lgain;
  28762. r *= rgain;
  28763. if (isInAttack)
  28764. {
  28765. l *= attackReleaseLevel;
  28766. r *= attackReleaseLevel;
  28767. attackReleaseLevel += attackDelta;
  28768. if (attackReleaseLevel >= 1.0f)
  28769. {
  28770. attackReleaseLevel = 1.0f;
  28771. isInAttack = false;
  28772. }
  28773. }
  28774. else if (isInRelease)
  28775. {
  28776. l *= attackReleaseLevel;
  28777. r *= attackReleaseLevel;
  28778. attackReleaseLevel += releaseDelta;
  28779. if (attackReleaseLevel <= 0.0f)
  28780. {
  28781. stopNote (false);
  28782. break;
  28783. }
  28784. }
  28785. if (outR != 0)
  28786. {
  28787. *outL++ += l;
  28788. *outR++ += r;
  28789. }
  28790. else
  28791. {
  28792. *outL++ += (l + r) * 0.5f;
  28793. }
  28794. sourceSamplePosition += pitchRatio;
  28795. if (sourceSamplePosition > playingSound->length)
  28796. {
  28797. stopNote (false);
  28798. break;
  28799. }
  28800. }
  28801. }
  28802. }
  28803. END_JUCE_NAMESPACE
  28804. /********* End of inlined file: juce_Sampler.cpp *********/
  28805. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  28806. BEGIN_JUCE_NAMESPACE
  28807. SynthesiserSound::SynthesiserSound()
  28808. {
  28809. }
  28810. SynthesiserSound::~SynthesiserSound()
  28811. {
  28812. }
  28813. SynthesiserVoice::SynthesiserVoice()
  28814. : currentSampleRate (44100.0),
  28815. currentlyPlayingNote (-1),
  28816. noteOnTime (0),
  28817. currentlyPlayingSound (0)
  28818. {
  28819. }
  28820. SynthesiserVoice::~SynthesiserVoice()
  28821. {
  28822. }
  28823. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  28824. {
  28825. return currentlyPlayingSound != 0
  28826. && currentlyPlayingSound->appliesToChannel (midiChannel);
  28827. }
  28828. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  28829. {
  28830. currentSampleRate = newRate;
  28831. }
  28832. void SynthesiserVoice::clearCurrentNote()
  28833. {
  28834. currentlyPlayingNote = -1;
  28835. currentlyPlayingSound = 0;
  28836. }
  28837. Synthesiser::Synthesiser()
  28838. : voices (2),
  28839. sounds (2),
  28840. sampleRate (0),
  28841. lastNoteOnCounter (0),
  28842. shouldStealNotes (true)
  28843. {
  28844. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  28845. lastPitchWheelValues[i] = 0x2000;
  28846. }
  28847. Synthesiser::~Synthesiser()
  28848. {
  28849. }
  28850. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  28851. {
  28852. const ScopedLock sl (lock);
  28853. return voices [index];
  28854. }
  28855. void Synthesiser::clearVoices()
  28856. {
  28857. const ScopedLock sl (lock);
  28858. voices.clear();
  28859. }
  28860. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  28861. {
  28862. const ScopedLock sl (lock);
  28863. voices.add (newVoice);
  28864. }
  28865. void Synthesiser::removeVoice (const int index)
  28866. {
  28867. const ScopedLock sl (lock);
  28868. voices.remove (index);
  28869. }
  28870. void Synthesiser::clearSounds()
  28871. {
  28872. const ScopedLock sl (lock);
  28873. sounds.clear();
  28874. }
  28875. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  28876. {
  28877. const ScopedLock sl (lock);
  28878. sounds.add (newSound);
  28879. }
  28880. void Synthesiser::removeSound (const int index)
  28881. {
  28882. const ScopedLock sl (lock);
  28883. sounds.remove (index);
  28884. }
  28885. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  28886. {
  28887. shouldStealNotes = shouldStealNotes_;
  28888. }
  28889. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  28890. {
  28891. if (sampleRate != newRate)
  28892. {
  28893. const ScopedLock sl (lock);
  28894. allNotesOff (0, false);
  28895. sampleRate = newRate;
  28896. for (int i = voices.size(); --i >= 0;)
  28897. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  28898. }
  28899. }
  28900. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  28901. const MidiBuffer& midiData,
  28902. int startSample,
  28903. int numSamples)
  28904. {
  28905. // must set the sample rate before using this!
  28906. jassert (sampleRate != 0);
  28907. const ScopedLock sl (lock);
  28908. MidiBuffer::Iterator midiIterator (midiData);
  28909. midiIterator.setNextSamplePosition (startSample);
  28910. MidiMessage m (0xf4, 0.0);
  28911. while (numSamples > 0)
  28912. {
  28913. int midiEventPos;
  28914. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  28915. && midiEventPos < startSample + numSamples;
  28916. const int numThisTime = useEvent ? midiEventPos - startSample
  28917. : numSamples;
  28918. if (numThisTime > 0)
  28919. {
  28920. for (int i = voices.size(); --i >= 0;)
  28921. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  28922. }
  28923. if (useEvent)
  28924. {
  28925. if (m.isNoteOn())
  28926. {
  28927. const int channel = m.getChannel();
  28928. noteOn (channel,
  28929. m.getNoteNumber(),
  28930. m.getFloatVelocity());
  28931. }
  28932. else if (m.isNoteOff())
  28933. {
  28934. noteOff (m.getChannel(),
  28935. m.getNoteNumber(),
  28936. true);
  28937. }
  28938. else if (m.isAllNotesOff() || m.isAllSoundOff())
  28939. {
  28940. allNotesOff (m.getChannel(), true);
  28941. }
  28942. else if (m.isPitchWheel())
  28943. {
  28944. const int channel = m.getChannel();
  28945. const int wheelPos = m.getPitchWheelValue();
  28946. lastPitchWheelValues [channel - 1] = wheelPos;
  28947. handlePitchWheel (channel, wheelPos);
  28948. }
  28949. else if (m.isController())
  28950. {
  28951. handleController (m.getChannel(),
  28952. m.getControllerNumber(),
  28953. m.getControllerValue());
  28954. }
  28955. }
  28956. startSample += numThisTime;
  28957. numSamples -= numThisTime;
  28958. }
  28959. }
  28960. void Synthesiser::noteOn (const int midiChannel,
  28961. const int midiNoteNumber,
  28962. const float velocity)
  28963. {
  28964. const ScopedLock sl (lock);
  28965. for (int i = sounds.size(); --i >= 0;)
  28966. {
  28967. SynthesiserSound* const sound = sounds.getUnchecked(i);
  28968. if (sound->appliesToNote (midiNoteNumber)
  28969. && sound->appliesToChannel (midiChannel))
  28970. {
  28971. startVoice (findFreeVoice (sound, shouldStealNotes),
  28972. sound, midiChannel, midiNoteNumber, velocity);
  28973. }
  28974. }
  28975. }
  28976. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  28977. SynthesiserSound* const sound,
  28978. const int midiChannel,
  28979. const int midiNoteNumber,
  28980. const float velocity)
  28981. {
  28982. if (voice != 0 && sound != 0)
  28983. {
  28984. if (voice->currentlyPlayingSound != 0)
  28985. voice->stopNote (false);
  28986. voice->startNote (midiNoteNumber,
  28987. velocity,
  28988. sound,
  28989. lastPitchWheelValues [midiChannel - 1]);
  28990. voice->currentlyPlayingNote = midiNoteNumber;
  28991. voice->noteOnTime = ++lastNoteOnCounter;
  28992. voice->currentlyPlayingSound = sound;
  28993. }
  28994. }
  28995. void Synthesiser::noteOff (const int midiChannel,
  28996. const int midiNoteNumber,
  28997. const bool allowTailOff)
  28998. {
  28999. const ScopedLock sl (lock);
  29000. for (int i = voices.size(); --i >= 0;)
  29001. {
  29002. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29003. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  29004. {
  29005. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  29006. if (sound != 0
  29007. && sound->appliesToNote (midiNoteNumber)
  29008. && sound->appliesToChannel (midiChannel))
  29009. {
  29010. voice->stopNote (allowTailOff);
  29011. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  29012. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  29013. }
  29014. }
  29015. }
  29016. }
  29017. void Synthesiser::allNotesOff (const int midiChannel,
  29018. const bool allowTailOff)
  29019. {
  29020. const ScopedLock sl (lock);
  29021. for (int i = voices.size(); --i >= 0;)
  29022. {
  29023. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29024. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29025. voice->stopNote (allowTailOff);
  29026. }
  29027. }
  29028. void Synthesiser::handlePitchWheel (const int midiChannel,
  29029. const int wheelValue)
  29030. {
  29031. const ScopedLock sl (lock);
  29032. for (int i = voices.size(); --i >= 0;)
  29033. {
  29034. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29035. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  29036. {
  29037. voice->pitchWheelMoved (wheelValue);
  29038. }
  29039. }
  29040. }
  29041. void Synthesiser::handleController (const int midiChannel,
  29042. const int controllerNumber,
  29043. const int controllerValue)
  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. voice->controllerMoved (controllerNumber, controllerValue);
  29051. }
  29052. }
  29053. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  29054. const bool stealIfNoneAvailable) const
  29055. {
  29056. const ScopedLock sl (lock);
  29057. for (int i = voices.size(); --i >= 0;)
  29058. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  29059. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  29060. return voices.getUnchecked (i);
  29061. if (stealIfNoneAvailable)
  29062. {
  29063. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  29064. SynthesiserVoice* oldest = 0;
  29065. for (int i = voices.size(); --i >= 0;)
  29066. {
  29067. SynthesiserVoice* const voice = voices.getUnchecked (i);
  29068. if (voice->canPlaySound (soundToPlay)
  29069. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  29070. oldest = voice;
  29071. }
  29072. jassert (oldest != 0);
  29073. return oldest;
  29074. }
  29075. return 0;
  29076. }
  29077. END_JUCE_NAMESPACE
  29078. /********* End of inlined file: juce_Synthesiser.cpp *********/
  29079. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  29080. BEGIN_JUCE_NAMESPACE
  29081. ActionBroadcaster::ActionBroadcaster() throw()
  29082. {
  29083. // are you trying to create this object before or after juce has been intialised??
  29084. jassert (MessageManager::instance != 0);
  29085. }
  29086. ActionBroadcaster::~ActionBroadcaster()
  29087. {
  29088. // all event-based objects must be deleted BEFORE juce is shut down!
  29089. jassert (MessageManager::instance != 0);
  29090. }
  29091. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  29092. {
  29093. actionListenerList.addActionListener (listener);
  29094. }
  29095. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  29096. {
  29097. jassert (actionListenerList.isValidMessageListener());
  29098. if (actionListenerList.isValidMessageListener())
  29099. actionListenerList.removeActionListener (listener);
  29100. }
  29101. void ActionBroadcaster::removeAllActionListeners()
  29102. {
  29103. actionListenerList.removeAllActionListeners();
  29104. }
  29105. void ActionBroadcaster::sendActionMessage (const String& message) const
  29106. {
  29107. actionListenerList.sendActionMessage (message);
  29108. }
  29109. END_JUCE_NAMESPACE
  29110. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  29111. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  29112. BEGIN_JUCE_NAMESPACE
  29113. // special message of our own with a string in it
  29114. class ActionMessage : public Message
  29115. {
  29116. public:
  29117. const String message;
  29118. ActionMessage (const String& messageText,
  29119. void* const listener_) throw()
  29120. : message (messageText)
  29121. {
  29122. pointerParameter = listener_;
  29123. }
  29124. ~ActionMessage() throw()
  29125. {
  29126. }
  29127. private:
  29128. ActionMessage (const ActionMessage&);
  29129. const ActionMessage& operator= (const ActionMessage&);
  29130. };
  29131. ActionListenerList::ActionListenerList() throw()
  29132. {
  29133. }
  29134. ActionListenerList::~ActionListenerList() throw()
  29135. {
  29136. }
  29137. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  29138. {
  29139. const ScopedLock sl (actionListenerLock_);
  29140. jassert (listener != 0);
  29141. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  29142. if (listener != 0)
  29143. actionListeners_.add (listener);
  29144. }
  29145. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  29146. {
  29147. const ScopedLock sl (actionListenerLock_);
  29148. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  29149. actionListeners_.removeValue (listener);
  29150. }
  29151. void ActionListenerList::removeAllActionListeners() throw()
  29152. {
  29153. const ScopedLock sl (actionListenerLock_);
  29154. actionListeners_.clear();
  29155. }
  29156. void ActionListenerList::sendActionMessage (const String& message) const
  29157. {
  29158. const ScopedLock sl (actionListenerLock_);
  29159. for (int i = actionListeners_.size(); --i >= 0;)
  29160. {
  29161. postMessage (new ActionMessage (message,
  29162. (ActionListener*) actionListeners_.getUnchecked(i)));
  29163. }
  29164. }
  29165. void ActionListenerList::handleMessage (const Message& message)
  29166. {
  29167. const ActionMessage& am = (const ActionMessage&) message;
  29168. if (actionListeners_.contains (am.pointerParameter))
  29169. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  29170. }
  29171. END_JUCE_NAMESPACE
  29172. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  29173. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  29174. BEGIN_JUCE_NAMESPACE
  29175. AsyncUpdater::AsyncUpdater() throw()
  29176. : asyncMessagePending (false)
  29177. {
  29178. internalAsyncHandler.owner = this;
  29179. }
  29180. AsyncUpdater::~AsyncUpdater()
  29181. {
  29182. }
  29183. void AsyncUpdater::triggerAsyncUpdate() throw()
  29184. {
  29185. if (! asyncMessagePending)
  29186. {
  29187. asyncMessagePending = true;
  29188. internalAsyncHandler.postMessage (new Message());
  29189. }
  29190. }
  29191. void AsyncUpdater::cancelPendingUpdate() throw()
  29192. {
  29193. asyncMessagePending = false;
  29194. }
  29195. void AsyncUpdater::handleUpdateNowIfNeeded()
  29196. {
  29197. if (asyncMessagePending)
  29198. {
  29199. asyncMessagePending = false;
  29200. handleAsyncUpdate();
  29201. }
  29202. }
  29203. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  29204. {
  29205. owner->handleUpdateNowIfNeeded();
  29206. }
  29207. END_JUCE_NAMESPACE
  29208. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  29209. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  29210. BEGIN_JUCE_NAMESPACE
  29211. ChangeBroadcaster::ChangeBroadcaster() throw()
  29212. {
  29213. // are you trying to create this object before or after juce has been intialised??
  29214. jassert (MessageManager::instance != 0);
  29215. }
  29216. ChangeBroadcaster::~ChangeBroadcaster()
  29217. {
  29218. // all event-based objects must be deleted BEFORE juce is shut down!
  29219. jassert (MessageManager::instance != 0);
  29220. }
  29221. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  29222. {
  29223. changeListenerList.addChangeListener (listener);
  29224. }
  29225. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  29226. {
  29227. jassert (changeListenerList.isValidMessageListener());
  29228. if (changeListenerList.isValidMessageListener())
  29229. changeListenerList.removeChangeListener (listener);
  29230. }
  29231. void ChangeBroadcaster::removeAllChangeListeners() throw()
  29232. {
  29233. changeListenerList.removeAllChangeListeners();
  29234. }
  29235. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  29236. {
  29237. changeListenerList.sendChangeMessage (objectThatHasChanged);
  29238. }
  29239. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  29240. {
  29241. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  29242. }
  29243. void ChangeBroadcaster::dispatchPendingMessages()
  29244. {
  29245. changeListenerList.dispatchPendingMessages();
  29246. }
  29247. END_JUCE_NAMESPACE
  29248. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  29249. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  29250. BEGIN_JUCE_NAMESPACE
  29251. ChangeListenerList::ChangeListenerList() throw()
  29252. : lastChangedObject (0),
  29253. messagePending (false)
  29254. {
  29255. }
  29256. ChangeListenerList::~ChangeListenerList() throw()
  29257. {
  29258. }
  29259. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  29260. {
  29261. const ScopedLock sl (lock);
  29262. jassert (listener != 0);
  29263. if (listener != 0)
  29264. listeners.add (listener);
  29265. }
  29266. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  29267. {
  29268. const ScopedLock sl (lock);
  29269. listeners.removeValue (listener);
  29270. }
  29271. void ChangeListenerList::removeAllChangeListeners() throw()
  29272. {
  29273. const ScopedLock sl (lock);
  29274. listeners.clear();
  29275. }
  29276. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  29277. {
  29278. const ScopedLock sl (lock);
  29279. if ((! messagePending) && (listeners.size() > 0))
  29280. {
  29281. lastChangedObject = objectThatHasChanged;
  29282. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  29283. messagePending = true;
  29284. }
  29285. }
  29286. void ChangeListenerList::handleMessage (const Message& message)
  29287. {
  29288. sendSynchronousChangeMessage (message.pointerParameter);
  29289. }
  29290. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  29291. {
  29292. const ScopedLock sl (lock);
  29293. messagePending = false;
  29294. for (int i = listeners.size(); --i >= 0;)
  29295. {
  29296. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  29297. {
  29298. const ScopedUnlock tempUnlocker (lock);
  29299. l->changeListenerCallback (objectThatHasChanged);
  29300. }
  29301. i = jmin (i, listeners.size());
  29302. }
  29303. }
  29304. void ChangeListenerList::dispatchPendingMessages()
  29305. {
  29306. if (messagePending)
  29307. sendSynchronousChangeMessage (lastChangedObject);
  29308. }
  29309. END_JUCE_NAMESPACE
  29310. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  29311. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  29312. BEGIN_JUCE_NAMESPACE
  29313. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  29314. const uint32 magicMessageHeaderNumber)
  29315. : Thread ("Juce IPC connection"),
  29316. socket (0),
  29317. pipe (0),
  29318. callbackConnectionState (false),
  29319. useMessageThread (callbacksOnMessageThread),
  29320. magicMessageHeader (magicMessageHeaderNumber),
  29321. pipeReceiveMessageTimeout (-1)
  29322. {
  29323. }
  29324. InterprocessConnection::~InterprocessConnection()
  29325. {
  29326. callbackConnectionState = false;
  29327. disconnect();
  29328. }
  29329. bool InterprocessConnection::connectToSocket (const String& hostName,
  29330. const int portNumber,
  29331. const int timeOutMillisecs)
  29332. {
  29333. disconnect();
  29334. const ScopedLock sl (pipeAndSocketLock);
  29335. socket = new StreamingSocket();
  29336. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  29337. {
  29338. connectionMadeInt();
  29339. startThread();
  29340. return true;
  29341. }
  29342. else
  29343. {
  29344. deleteAndZero (socket);
  29345. return false;
  29346. }
  29347. }
  29348. bool InterprocessConnection::connectToPipe (const String& pipeName,
  29349. const int pipeReceiveMessageTimeoutMs)
  29350. {
  29351. disconnect();
  29352. NamedPipe* const newPipe = new NamedPipe();
  29353. if (newPipe->openExisting (pipeName))
  29354. {
  29355. const ScopedLock sl (pipeAndSocketLock);
  29356. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29357. initialiseWithPipe (newPipe);
  29358. return true;
  29359. }
  29360. else
  29361. {
  29362. delete newPipe;
  29363. return false;
  29364. }
  29365. }
  29366. bool InterprocessConnection::createPipe (const String& pipeName,
  29367. const int pipeReceiveMessageTimeoutMs)
  29368. {
  29369. disconnect();
  29370. NamedPipe* const newPipe = new NamedPipe();
  29371. if (newPipe->createNewPipe (pipeName))
  29372. {
  29373. const ScopedLock sl (pipeAndSocketLock);
  29374. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  29375. initialiseWithPipe (newPipe);
  29376. return true;
  29377. }
  29378. else
  29379. {
  29380. delete newPipe;
  29381. return false;
  29382. }
  29383. }
  29384. void InterprocessConnection::disconnect()
  29385. {
  29386. if (socket != 0)
  29387. socket->close();
  29388. if (pipe != 0)
  29389. {
  29390. pipe->cancelPendingReads();
  29391. pipe->close();
  29392. }
  29393. stopThread (4000);
  29394. {
  29395. const ScopedLock sl (pipeAndSocketLock);
  29396. deleteAndZero (socket);
  29397. deleteAndZero (pipe);
  29398. }
  29399. connectionLostInt();
  29400. }
  29401. bool InterprocessConnection::isConnected() const
  29402. {
  29403. const ScopedLock sl (pipeAndSocketLock);
  29404. return ((socket != 0 && socket->isConnected())
  29405. || (pipe != 0 && pipe->isOpen()))
  29406. && isThreadRunning();
  29407. }
  29408. const String InterprocessConnection::getConnectedHostName() const
  29409. {
  29410. if (pipe != 0)
  29411. {
  29412. return "localhost";
  29413. }
  29414. else if (socket != 0)
  29415. {
  29416. if (! socket->isLocal())
  29417. return socket->getHostName();
  29418. return "localhost";
  29419. }
  29420. return String::empty;
  29421. }
  29422. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  29423. {
  29424. uint32 messageHeader[2];
  29425. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  29426. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  29427. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  29428. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  29429. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  29430. int bytesWritten = 0;
  29431. const ScopedLock sl (pipeAndSocketLock);
  29432. if (socket != 0)
  29433. {
  29434. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  29435. }
  29436. else if (pipe != 0)
  29437. {
  29438. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  29439. }
  29440. if (bytesWritten < 0)
  29441. {
  29442. // error..
  29443. return false;
  29444. }
  29445. return (bytesWritten == messageData.getSize());
  29446. }
  29447. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  29448. {
  29449. jassert (socket == 0);
  29450. socket = socket_;
  29451. connectionMadeInt();
  29452. startThread();
  29453. }
  29454. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  29455. {
  29456. jassert (pipe == 0);
  29457. pipe = pipe_;
  29458. connectionMadeInt();
  29459. startThread();
  29460. }
  29461. const int messageMagicNumber = 0xb734128b;
  29462. void InterprocessConnection::handleMessage (const Message& message)
  29463. {
  29464. if (message.intParameter1 == messageMagicNumber)
  29465. {
  29466. switch (message.intParameter2)
  29467. {
  29468. case 0:
  29469. {
  29470. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  29471. messageReceived (*data);
  29472. delete data;
  29473. break;
  29474. }
  29475. case 1:
  29476. connectionMade();
  29477. break;
  29478. case 2:
  29479. connectionLost();
  29480. break;
  29481. }
  29482. }
  29483. }
  29484. void InterprocessConnection::connectionMadeInt()
  29485. {
  29486. if (! callbackConnectionState)
  29487. {
  29488. callbackConnectionState = true;
  29489. if (useMessageThread)
  29490. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  29491. else
  29492. connectionMade();
  29493. }
  29494. }
  29495. void InterprocessConnection::connectionLostInt()
  29496. {
  29497. if (callbackConnectionState)
  29498. {
  29499. callbackConnectionState = false;
  29500. if (useMessageThread)
  29501. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  29502. else
  29503. connectionLost();
  29504. }
  29505. }
  29506. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  29507. {
  29508. jassert (callbackConnectionState);
  29509. if (useMessageThread)
  29510. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  29511. else
  29512. messageReceived (data);
  29513. }
  29514. bool InterprocessConnection::readNextMessageInt()
  29515. {
  29516. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  29517. uint32 messageHeader[2];
  29518. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  29519. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  29520. if (bytes == sizeof (messageHeader)
  29521. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  29522. {
  29523. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  29524. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  29525. {
  29526. MemoryBlock messageData (bytesInMessage, true);
  29527. int bytesRead = 0;
  29528. while (bytesRead < bytesInMessage)
  29529. {
  29530. if (threadShouldExit())
  29531. return false;
  29532. const int numThisTime = jmin (bytesInMessage, 65536);
  29533. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime, true)
  29534. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  29535. pipeReceiveMessageTimeout);
  29536. if (bytesIn <= 0)
  29537. break;
  29538. bytesRead += bytesIn;
  29539. }
  29540. if (bytesRead >= 0)
  29541. deliverDataInt (messageData);
  29542. }
  29543. }
  29544. else if (bytes < 0)
  29545. {
  29546. {
  29547. const ScopedLock sl (pipeAndSocketLock);
  29548. deleteAndZero (socket);
  29549. }
  29550. connectionLostInt();
  29551. return false;
  29552. }
  29553. return true;
  29554. }
  29555. void InterprocessConnection::run()
  29556. {
  29557. while (! threadShouldExit())
  29558. {
  29559. if (socket != 0)
  29560. {
  29561. const int ready = socket->waitUntilReady (true, 0);
  29562. if (ready < 0)
  29563. {
  29564. {
  29565. const ScopedLock sl (pipeAndSocketLock);
  29566. deleteAndZero (socket);
  29567. }
  29568. connectionLostInt();
  29569. break;
  29570. }
  29571. else if (ready > 0)
  29572. {
  29573. if (! readNextMessageInt())
  29574. break;
  29575. }
  29576. else
  29577. {
  29578. Thread::sleep (2);
  29579. }
  29580. }
  29581. else if (pipe != 0)
  29582. {
  29583. if (! pipe->isOpen())
  29584. {
  29585. {
  29586. const ScopedLock sl (pipeAndSocketLock);
  29587. deleteAndZero (pipe);
  29588. }
  29589. connectionLostInt();
  29590. break;
  29591. }
  29592. else
  29593. {
  29594. if (! readNextMessageInt())
  29595. break;
  29596. }
  29597. }
  29598. else
  29599. {
  29600. break;
  29601. }
  29602. }
  29603. }
  29604. END_JUCE_NAMESPACE
  29605. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  29606. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29607. BEGIN_JUCE_NAMESPACE
  29608. InterprocessConnectionServer::InterprocessConnectionServer()
  29609. : Thread ("Juce IPC server"),
  29610. socket (0)
  29611. {
  29612. }
  29613. InterprocessConnectionServer::~InterprocessConnectionServer()
  29614. {
  29615. stop();
  29616. }
  29617. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  29618. {
  29619. stop();
  29620. socket = new StreamingSocket();
  29621. if (socket->createListener (portNumber))
  29622. {
  29623. startThread();
  29624. return true;
  29625. }
  29626. deleteAndZero (socket);
  29627. return false;
  29628. }
  29629. void InterprocessConnectionServer::stop()
  29630. {
  29631. signalThreadShouldExit();
  29632. if (socket != 0)
  29633. socket->close();
  29634. stopThread (4000);
  29635. deleteAndZero (socket);
  29636. }
  29637. void InterprocessConnectionServer::run()
  29638. {
  29639. while ((! threadShouldExit()) && socket != 0)
  29640. {
  29641. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  29642. if (clientSocket != 0)
  29643. {
  29644. InterprocessConnection* newConnection = createConnectionObject();
  29645. if (newConnection != 0)
  29646. {
  29647. newConnection->initialiseWithSocket (clientSocket);
  29648. }
  29649. else
  29650. {
  29651. delete clientSocket;
  29652. }
  29653. }
  29654. }
  29655. }
  29656. END_JUCE_NAMESPACE
  29657. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  29658. /********* Start of inlined file: juce_Message.cpp *********/
  29659. BEGIN_JUCE_NAMESPACE
  29660. Message::Message() throw()
  29661. {
  29662. }
  29663. Message::~Message() throw()
  29664. {
  29665. }
  29666. Message::Message (const int intParameter1_,
  29667. const int intParameter2_,
  29668. const int intParameter3_,
  29669. void* const pointerParameter_) throw()
  29670. : intParameter1 (intParameter1_),
  29671. intParameter2 (intParameter2_),
  29672. intParameter3 (intParameter3_),
  29673. pointerParameter (pointerParameter_)
  29674. {
  29675. }
  29676. END_JUCE_NAMESPACE
  29677. /********* End of inlined file: juce_Message.cpp *********/
  29678. /********* Start of inlined file: juce_MessageListener.cpp *********/
  29679. BEGIN_JUCE_NAMESPACE
  29680. MessageListener::MessageListener() throw()
  29681. {
  29682. // are you trying to create a messagelistener before or after juce has been intialised??
  29683. jassert (MessageManager::instance != 0);
  29684. if (MessageManager::instance != 0)
  29685. MessageManager::instance->messageListeners.add (this);
  29686. }
  29687. MessageListener::~MessageListener()
  29688. {
  29689. if (MessageManager::instance != 0)
  29690. MessageManager::instance->messageListeners.removeValue (this);
  29691. }
  29692. void MessageListener::postMessage (Message* const message) const throw()
  29693. {
  29694. message->messageRecipient = const_cast <MessageListener*> (this);
  29695. if (MessageManager::instance == 0)
  29696. MessageManager::getInstance();
  29697. MessageManager::instance->postMessageToQueue (message);
  29698. }
  29699. bool MessageListener::isValidMessageListener() const throw()
  29700. {
  29701. return (MessageManager::instance != 0)
  29702. && MessageManager::instance->messageListeners.contains (this);
  29703. }
  29704. END_JUCE_NAMESPACE
  29705. /********* End of inlined file: juce_MessageListener.cpp *********/
  29706. /********* Start of inlined file: juce_MessageManager.cpp *********/
  29707. BEGIN_JUCE_NAMESPACE
  29708. // platform-specific functions..
  29709. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  29710. bool juce_postMessageToSystemQueue (void* message);
  29711. MessageManager* MessageManager::instance = 0;
  29712. static const int quitMessageId = 0xfffff321;
  29713. MessageManager::MessageManager() throw()
  29714. : broadcastListeners (0),
  29715. quitMessagePosted (false),
  29716. quitMessageReceived (false),
  29717. threadWithLock (0)
  29718. {
  29719. messageThreadId = Thread::getCurrentThreadId();
  29720. }
  29721. MessageManager::~MessageManager() throw()
  29722. {
  29723. deleteAndZero (broadcastListeners);
  29724. doPlatformSpecificShutdown();
  29725. jassert (instance == this);
  29726. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  29727. }
  29728. MessageManager* MessageManager::getInstance() throw()
  29729. {
  29730. if (instance == 0)
  29731. {
  29732. instance = new MessageManager();
  29733. doPlatformSpecificInitialisation();
  29734. }
  29735. return instance;
  29736. }
  29737. void MessageManager::postMessageToQueue (Message* const message)
  29738. {
  29739. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  29740. delete message;
  29741. }
  29742. CallbackMessage::CallbackMessage() throw() {}
  29743. CallbackMessage::~CallbackMessage() throw() {}
  29744. void CallbackMessage::post()
  29745. {
  29746. if (MessageManager::instance != 0)
  29747. MessageManager::instance->postCallbackMessage (this);
  29748. }
  29749. void MessageManager::postCallbackMessage (Message* const message)
  29750. {
  29751. message->messageRecipient = 0;
  29752. postMessageToQueue (message);
  29753. }
  29754. // not for public use..
  29755. void MessageManager::deliverMessage (void* message)
  29756. {
  29757. Message* const m = (Message*) message;
  29758. MessageListener* const recipient = m->messageRecipient;
  29759. JUCE_TRY
  29760. {
  29761. if (messageListeners.contains (recipient))
  29762. {
  29763. recipient->handleMessage (*m);
  29764. }
  29765. else if (recipient == 0)
  29766. {
  29767. if (m->intParameter1 == quitMessageId)
  29768. {
  29769. quitMessageReceived = true;
  29770. }
  29771. else if (dynamic_cast <CallbackMessage*> (m) != 0)
  29772. {
  29773. (dynamic_cast <CallbackMessage*> (m))->messageCallback();
  29774. }
  29775. }
  29776. }
  29777. JUCE_CATCH_EXCEPTION
  29778. delete m;
  29779. }
  29780. #if ! JUCE_MAC
  29781. void MessageManager::runDispatchLoop()
  29782. {
  29783. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29784. runDispatchLoopUntil (-1);
  29785. }
  29786. void MessageManager::stopDispatchLoop()
  29787. {
  29788. Message* const m = new Message (quitMessageId, 0, 0, 0);
  29789. m->messageRecipient = 0;
  29790. postMessageToQueue (m);
  29791. quitMessagePosted = true;
  29792. }
  29793. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  29794. {
  29795. jassert (isThisTheMessageThread()); // must only be called by the message thread
  29796. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  29797. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  29798. && ! quitMessageReceived)
  29799. {
  29800. JUCE_TRY
  29801. {
  29802. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  29803. {
  29804. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  29805. if (msToWait > 0)
  29806. Thread::sleep (jmin (5, msToWait));
  29807. }
  29808. }
  29809. JUCE_CATCH_EXCEPTION
  29810. }
  29811. return ! quitMessageReceived;
  29812. }
  29813. #endif
  29814. void MessageManager::deliverBroadcastMessage (const String& value)
  29815. {
  29816. if (broadcastListeners != 0)
  29817. broadcastListeners->sendActionMessage (value);
  29818. }
  29819. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29820. {
  29821. if (broadcastListeners == 0)
  29822. broadcastListeners = new ActionListenerList();
  29823. broadcastListeners->addActionListener (listener);
  29824. }
  29825. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29826. {
  29827. if (broadcastListeners != 0)
  29828. broadcastListeners->removeActionListener (listener);
  29829. }
  29830. bool MessageManager::isThisTheMessageThread() const throw()
  29831. {
  29832. return Thread::getCurrentThreadId() == messageThreadId;
  29833. }
  29834. void MessageManager::setCurrentMessageThread (const Thread::ThreadID threadId) throw()
  29835. {
  29836. messageThreadId = threadId;
  29837. }
  29838. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29839. {
  29840. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  29841. return thisThread == messageThreadId || thisThread == threadWithLock;
  29842. }
  29843. /* The only safe way to lock the message thread while another thread does
  29844. some work is by posting a special message, whose purpose is to tie up the event
  29845. loop until the other thread has finished its business.
  29846. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  29847. get locked before making an event callback, because if the same OS lock gets indirectly
  29848. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  29849. in Cocoa).
  29850. */
  29851. class SharedLockingEvents : public ReferenceCountedObject
  29852. {
  29853. public:
  29854. SharedLockingEvents() throw() {}
  29855. ~SharedLockingEvents() {}
  29856. /* This class just holds a couple of events to communicate between the MMLockMessage
  29857. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  29858. this shared data must be kept in a separate, ref-counted container. */
  29859. WaitableEvent lockedEvent, releaseEvent;
  29860. };
  29861. class MMLockMessage : public CallbackMessage
  29862. {
  29863. public:
  29864. MMLockMessage (SharedLockingEvents* const events_) throw()
  29865. : events (events_)
  29866. {}
  29867. ~MMLockMessage() throw() {}
  29868. ReferenceCountedObjectPtr <SharedLockingEvents> events;
  29869. void messageCallback()
  29870. {
  29871. events->lockedEvent.signal();
  29872. events->releaseEvent.wait();
  29873. }
  29874. juce_UseDebuggingNewOperator
  29875. MMLockMessage (const MMLockMessage&);
  29876. const MMLockMessage& operator= (const MMLockMessage&);
  29877. };
  29878. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck) throw()
  29879. : locked (false),
  29880. needsUnlocking (false)
  29881. {
  29882. init (threadToCheck, 0);
  29883. }
  29884. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal) throw()
  29885. : locked (false),
  29886. needsUnlocking (false)
  29887. {
  29888. init (0, jobToCheckForExitSignal);
  29889. }
  29890. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job) throw()
  29891. {
  29892. if (MessageManager::instance != 0)
  29893. {
  29894. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  29895. {
  29896. locked = true; // either we're on the message thread, or this is a re-entrant call.
  29897. }
  29898. else
  29899. {
  29900. if (threadToCheck == 0 && job == 0)
  29901. {
  29902. MessageManager::instance->lockingLock.enter();
  29903. }
  29904. else
  29905. {
  29906. while (! MessageManager::instance->lockingLock.tryEnter())
  29907. {
  29908. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29909. || (job != 0 && job->shouldExit()))
  29910. return;
  29911. Thread::sleep (1);
  29912. }
  29913. }
  29914. SharedLockingEvents* const events = new SharedLockingEvents();
  29915. sharedEvents = events;
  29916. events->incReferenceCount();
  29917. (new MMLockMessage (events))->post();
  29918. while (! events->lockedEvent.wait (50))
  29919. {
  29920. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  29921. || (job != 0 && job->shouldExit()))
  29922. {
  29923. events->releaseEvent.signal();
  29924. events->decReferenceCount();
  29925. MessageManager::instance->lockingLock.exit();
  29926. return;
  29927. }
  29928. }
  29929. jassert (MessageManager::instance->threadWithLock == 0);
  29930. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  29931. locked = true;
  29932. needsUnlocking = true;
  29933. }
  29934. }
  29935. }
  29936. MessageManagerLock::~MessageManagerLock() throw()
  29937. {
  29938. if (needsUnlocking && MessageManager::instance != 0)
  29939. {
  29940. jassert (MessageManager::instance->currentThreadHasLockedMessageManager());
  29941. ((SharedLockingEvents*) sharedEvents)->releaseEvent.signal();
  29942. ((SharedLockingEvents*) sharedEvents)->decReferenceCount();
  29943. MessageManager::instance->threadWithLock = 0;
  29944. MessageManager::instance->lockingLock.exit();
  29945. }
  29946. }
  29947. END_JUCE_NAMESPACE
  29948. /********* End of inlined file: juce_MessageManager.cpp *********/
  29949. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  29950. BEGIN_JUCE_NAMESPACE
  29951. class InternalMultiTimerCallback : public Timer
  29952. {
  29953. public:
  29954. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  29955. : timerId (timerId_),
  29956. owner (owner_)
  29957. {
  29958. }
  29959. ~InternalMultiTimerCallback()
  29960. {
  29961. }
  29962. void timerCallback()
  29963. {
  29964. owner.timerCallback (timerId);
  29965. }
  29966. const int timerId;
  29967. private:
  29968. MultiTimer& owner;
  29969. };
  29970. MultiTimer::MultiTimer() throw()
  29971. {
  29972. }
  29973. MultiTimer::MultiTimer (const MultiTimer&) throw()
  29974. {
  29975. }
  29976. MultiTimer::~MultiTimer()
  29977. {
  29978. const ScopedLock sl (timerListLock);
  29979. for (int i = timers.size(); --i >= 0;)
  29980. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29981. timers.clear();
  29982. }
  29983. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  29984. {
  29985. const ScopedLock sl (timerListLock);
  29986. for (int i = timers.size(); --i >= 0;)
  29987. {
  29988. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29989. if (t->timerId == timerId)
  29990. {
  29991. t->startTimer (intervalInMilliseconds);
  29992. return;
  29993. }
  29994. }
  29995. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  29996. timers.add (newTimer);
  29997. newTimer->startTimer (intervalInMilliseconds);
  29998. }
  29999. void MultiTimer::stopTimer (const int timerId) throw()
  30000. {
  30001. const ScopedLock sl (timerListLock);
  30002. for (int i = timers.size(); --i >= 0;)
  30003. {
  30004. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30005. if (t->timerId == timerId)
  30006. t->stopTimer();
  30007. }
  30008. }
  30009. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  30010. {
  30011. const ScopedLock sl (timerListLock);
  30012. for (int i = timers.size(); --i >= 0;)
  30013. {
  30014. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30015. if (t->timerId == timerId)
  30016. return t->isTimerRunning();
  30017. }
  30018. return false;
  30019. }
  30020. int MultiTimer::getTimerInterval (const int timerId) const throw()
  30021. {
  30022. const ScopedLock sl (timerListLock);
  30023. for (int i = timers.size(); --i >= 0;)
  30024. {
  30025. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  30026. if (t->timerId == timerId)
  30027. return t->getTimerInterval();
  30028. }
  30029. return 0;
  30030. }
  30031. END_JUCE_NAMESPACE
  30032. /********* End of inlined file: juce_MultiTimer.cpp *********/
  30033. /********* Start of inlined file: juce_Timer.cpp *********/
  30034. BEGIN_JUCE_NAMESPACE
  30035. class InternalTimerThread : private Thread,
  30036. private MessageListener,
  30037. private DeletedAtShutdown,
  30038. private AsyncUpdater
  30039. {
  30040. private:
  30041. friend class Timer;
  30042. static InternalTimerThread* instance;
  30043. static CriticalSection lock;
  30044. Timer* volatile firstTimer;
  30045. bool volatile callbackNeeded;
  30046. InternalTimerThread (const InternalTimerThread&);
  30047. const InternalTimerThread& operator= (const InternalTimerThread&);
  30048. void addTimer (Timer* const t) throw()
  30049. {
  30050. #ifdef JUCE_DEBUG
  30051. Timer* tt = firstTimer;
  30052. while (tt != 0)
  30053. {
  30054. // trying to add a timer that's already here - shouldn't get to this point,
  30055. // so if you get this assertion, let me know!
  30056. jassert (tt != t);
  30057. tt = tt->next;
  30058. }
  30059. jassert (t->previous == 0 && t->next == 0);
  30060. #endif
  30061. Timer* i = firstTimer;
  30062. if (i == 0 || i->countdownMs > t->countdownMs)
  30063. {
  30064. t->next = firstTimer;
  30065. firstTimer = t;
  30066. }
  30067. else
  30068. {
  30069. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  30070. i = i->next;
  30071. jassert (i != 0);
  30072. t->next = i->next;
  30073. t->previous = i;
  30074. i->next = t;
  30075. }
  30076. if (t->next != 0)
  30077. t->next->previous = t;
  30078. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  30079. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  30080. notify();
  30081. }
  30082. void removeTimer (Timer* const t) throw()
  30083. {
  30084. #ifdef JUCE_DEBUG
  30085. Timer* tt = firstTimer;
  30086. bool found = false;
  30087. while (tt != 0)
  30088. {
  30089. if (tt == t)
  30090. {
  30091. found = true;
  30092. break;
  30093. }
  30094. tt = tt->next;
  30095. }
  30096. // trying to remove a timer that's not here - shouldn't get to this point,
  30097. // so if you get this assertion, let me know!
  30098. jassert (found);
  30099. #endif
  30100. if (t->previous != 0)
  30101. {
  30102. jassert (firstTimer != t);
  30103. t->previous->next = t->next;
  30104. }
  30105. else
  30106. {
  30107. jassert (firstTimer == t);
  30108. firstTimer = t->next;
  30109. }
  30110. if (t->next != 0)
  30111. t->next->previous = t->previous;
  30112. t->next = 0;
  30113. t->previous = 0;
  30114. }
  30115. void decrementAllCounters (const int numMillisecs) const
  30116. {
  30117. Timer* t = firstTimer;
  30118. while (t != 0)
  30119. {
  30120. t->countdownMs -= numMillisecs;
  30121. t = t->next;
  30122. }
  30123. }
  30124. void handleAsyncUpdate()
  30125. {
  30126. startThread (7);
  30127. }
  30128. public:
  30129. InternalTimerThread()
  30130. : Thread ("Juce Timer"),
  30131. firstTimer (0),
  30132. callbackNeeded (false)
  30133. {
  30134. triggerAsyncUpdate();
  30135. }
  30136. ~InternalTimerThread() throw()
  30137. {
  30138. stopThread (4000);
  30139. jassert (instance == this || instance == 0);
  30140. if (instance == this)
  30141. instance = 0;
  30142. }
  30143. void run()
  30144. {
  30145. uint32 lastTime = Time::getMillisecondCounter();
  30146. while (! threadShouldExit())
  30147. {
  30148. uint32 now = Time::getMillisecondCounter();
  30149. if (now <= lastTime)
  30150. {
  30151. wait (2);
  30152. continue;
  30153. }
  30154. const int elapsed = now - lastTime;
  30155. lastTime = now;
  30156. lock.enter();
  30157. decrementAllCounters (elapsed);
  30158. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  30159. : 1000;
  30160. lock.exit();
  30161. if (timeUntilFirstTimer <= 0)
  30162. {
  30163. callbackNeeded = true;
  30164. postMessage (new Message());
  30165. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  30166. // so this is how long to wait before assuming the message has been lost and trying again.
  30167. const uint32 messageDeliveryTimeout = now + 2000;
  30168. while (callbackNeeded)
  30169. {
  30170. wait (4);
  30171. if (threadShouldExit())
  30172. return;
  30173. now = Time::getMillisecondCounter();
  30174. if (now > messageDeliveryTimeout)
  30175. break;
  30176. }
  30177. }
  30178. else
  30179. {
  30180. // don't wait for too long because running this loop also helps keep the
  30181. // Time::getApproximateMillisecondTimer value stay up-to-date
  30182. wait (jlimit (1, 50, timeUntilFirstTimer));
  30183. }
  30184. }
  30185. }
  30186. void handleMessage (const Message&)
  30187. {
  30188. const ScopedLock sl (lock);
  30189. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  30190. {
  30191. Timer* const t = firstTimer;
  30192. t->countdownMs = t->periodMs;
  30193. removeTimer (t);
  30194. addTimer (t);
  30195. const ScopedUnlock ul (lock);
  30196. JUCE_TRY
  30197. {
  30198. t->timerCallback();
  30199. }
  30200. JUCE_CATCH_EXCEPTION
  30201. }
  30202. callbackNeeded = false;
  30203. }
  30204. static void callAnyTimersSynchronously()
  30205. {
  30206. if (InternalTimerThread::instance != 0)
  30207. {
  30208. const Message m;
  30209. InternalTimerThread::instance->handleMessage (m);
  30210. }
  30211. }
  30212. static inline void add (Timer* const tim) throw()
  30213. {
  30214. if (instance == 0)
  30215. instance = new InternalTimerThread();
  30216. const ScopedLock sl (instance->lock);
  30217. instance->addTimer (tim);
  30218. }
  30219. static inline void remove (Timer* const tim) throw()
  30220. {
  30221. if (instance != 0)
  30222. {
  30223. const ScopedLock sl (instance->lock);
  30224. instance->removeTimer (tim);
  30225. }
  30226. }
  30227. static inline void resetCounter (Timer* const tim,
  30228. const int newCounter) throw()
  30229. {
  30230. if (instance != 0)
  30231. {
  30232. tim->countdownMs = newCounter;
  30233. tim->periodMs = newCounter;
  30234. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  30235. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  30236. {
  30237. const ScopedLock sl (instance->lock);
  30238. instance->removeTimer (tim);
  30239. instance->addTimer (tim);
  30240. }
  30241. }
  30242. }
  30243. };
  30244. InternalTimerThread* InternalTimerThread::instance = 0;
  30245. CriticalSection InternalTimerThread::lock;
  30246. void juce_callAnyTimersSynchronously()
  30247. {
  30248. InternalTimerThread::callAnyTimersSynchronously();
  30249. }
  30250. #ifdef JUCE_DEBUG
  30251. static SortedSet <Timer*> activeTimers;
  30252. #endif
  30253. Timer::Timer() throw()
  30254. : countdownMs (0),
  30255. periodMs (0),
  30256. previous (0),
  30257. next (0)
  30258. {
  30259. #ifdef JUCE_DEBUG
  30260. activeTimers.add (this);
  30261. #endif
  30262. }
  30263. Timer::Timer (const Timer&) throw()
  30264. : countdownMs (0),
  30265. periodMs (0),
  30266. previous (0),
  30267. next (0)
  30268. {
  30269. #ifdef JUCE_DEBUG
  30270. activeTimers.add (this);
  30271. #endif
  30272. }
  30273. Timer::~Timer()
  30274. {
  30275. stopTimer();
  30276. #ifdef JUCE_DEBUG
  30277. activeTimers.removeValue (this);
  30278. #endif
  30279. }
  30280. void Timer::startTimer (const int interval) throw()
  30281. {
  30282. const ScopedLock sl (InternalTimerThread::lock);
  30283. #ifdef JUCE_DEBUG
  30284. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30285. jassert (activeTimers.contains (this));
  30286. #endif
  30287. if (periodMs == 0)
  30288. {
  30289. countdownMs = interval;
  30290. periodMs = jmax (1, interval);
  30291. InternalTimerThread::add (this);
  30292. }
  30293. else
  30294. {
  30295. InternalTimerThread::resetCounter (this, interval);
  30296. }
  30297. }
  30298. void Timer::stopTimer() throw()
  30299. {
  30300. const ScopedLock sl (InternalTimerThread::lock);
  30301. #ifdef JUCE_DEBUG
  30302. // this isn't a valid object! Your timer might be a dangling pointer or something..
  30303. jassert (activeTimers.contains (this));
  30304. #endif
  30305. if (periodMs > 0)
  30306. {
  30307. InternalTimerThread::remove (this);
  30308. periodMs = 0;
  30309. }
  30310. }
  30311. END_JUCE_NAMESPACE
  30312. /********* End of inlined file: juce_Timer.cpp *********/
  30313. /********* Start of inlined file: juce_Component.cpp *********/
  30314. BEGIN_JUCE_NAMESPACE
  30315. Component* Component::componentUnderMouse = 0;
  30316. Component* Component::currentlyFocusedComponent = 0;
  30317. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  30318. static Array <int> modalReturnValues (4);
  30319. static const int customCommandMessage = 0x7fff0001;
  30320. static const int exitModalStateMessage = 0x7fff0002;
  30321. // these are also used by ComponentPeer
  30322. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  30323. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  30324. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  30325. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  30326. int juce_LastMousePosX = 0;
  30327. int juce_LastMousePosY = 0;
  30328. int juce_MouseClickCounter = 0;
  30329. bool juce_MouseHasMovedSignificantlySincePressed = false;
  30330. static int countMouseClicks() throw()
  30331. {
  30332. int numClicks = 0;
  30333. if (juce_recentMouseDownTimes[0] != 0)
  30334. {
  30335. if (! juce_MouseHasMovedSignificantlySincePressed)
  30336. ++numClicks;
  30337. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  30338. {
  30339. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  30340. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  30341. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  30342. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  30343. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  30344. {
  30345. ++numClicks;
  30346. }
  30347. else
  30348. {
  30349. break;
  30350. }
  30351. }
  30352. }
  30353. return numClicks;
  30354. }
  30355. static int unboundedMouseOffsetX = 0;
  30356. static int unboundedMouseOffsetY = 0;
  30357. static bool isUnboundedMouseModeOn = false;
  30358. static bool isCursorVisibleUntilOffscreen;
  30359. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  30360. static uint32 nextComponentUID = 0;
  30361. Component::Component() throw()
  30362. : parentComponent_ (0),
  30363. componentUID (++nextComponentUID),
  30364. numDeepMouseListeners (0),
  30365. childComponentList_ (16),
  30366. lookAndFeel_ (0),
  30367. effect_ (0),
  30368. bufferedImage_ (0),
  30369. mouseListeners_ (0),
  30370. keyListeners_ (0),
  30371. componentListeners_ (0),
  30372. propertySet_ (0),
  30373. componentFlags_ (0)
  30374. {
  30375. }
  30376. Component::Component (const String& name) throw()
  30377. : componentName_ (name),
  30378. parentComponent_ (0),
  30379. componentUID (++nextComponentUID),
  30380. numDeepMouseListeners (0),
  30381. childComponentList_ (16),
  30382. lookAndFeel_ (0),
  30383. effect_ (0),
  30384. bufferedImage_ (0),
  30385. mouseListeners_ (0),
  30386. keyListeners_ (0),
  30387. componentListeners_ (0),
  30388. propertySet_ (0),
  30389. componentFlags_ (0)
  30390. {
  30391. }
  30392. Component::~Component()
  30393. {
  30394. if (parentComponent_ != 0)
  30395. {
  30396. parentComponent_->removeChildComponent (this);
  30397. }
  30398. else if ((currentlyFocusedComponent == this)
  30399. || isParentOf (currentlyFocusedComponent))
  30400. {
  30401. giveAwayFocus();
  30402. }
  30403. if (componentUnderMouse == this)
  30404. componentUnderMouse = 0;
  30405. if (flags.hasHeavyweightPeerFlag)
  30406. removeFromDesktop();
  30407. modalComponentStack.removeValue (this);
  30408. for (int i = childComponentList_.size(); --i >= 0;)
  30409. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  30410. delete bufferedImage_;
  30411. delete mouseListeners_;
  30412. delete keyListeners_;
  30413. delete componentListeners_;
  30414. delete propertySet_;
  30415. }
  30416. void Component::setName (const String& name)
  30417. {
  30418. // if component methods are being called from threads other than the message
  30419. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30420. checkMessageManagerIsLocked
  30421. if (componentName_ != name)
  30422. {
  30423. componentName_ = name;
  30424. if (flags.hasHeavyweightPeerFlag)
  30425. {
  30426. ComponentPeer* const peer = getPeer();
  30427. jassert (peer != 0);
  30428. if (peer != 0)
  30429. peer->setTitle (name);
  30430. }
  30431. if (componentListeners_ != 0)
  30432. {
  30433. const ComponentDeletionWatcher deletionChecker (this);
  30434. for (int i = componentListeners_->size(); --i >= 0;)
  30435. {
  30436. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30437. ->componentNameChanged (*this);
  30438. if (deletionChecker.hasBeenDeleted())
  30439. return;
  30440. i = jmin (i, componentListeners_->size());
  30441. }
  30442. }
  30443. }
  30444. }
  30445. void Component::setVisible (bool shouldBeVisible)
  30446. {
  30447. if (flags.visibleFlag != shouldBeVisible)
  30448. {
  30449. // if component methods are being called from threads other than the message
  30450. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30451. checkMessageManagerIsLocked
  30452. const ComponentDeletionWatcher deletionChecker (this);
  30453. flags.visibleFlag = shouldBeVisible;
  30454. internalRepaint (0, 0, getWidth(), getHeight());
  30455. sendFakeMouseMove();
  30456. if (! shouldBeVisible)
  30457. {
  30458. if (currentlyFocusedComponent == this
  30459. || isParentOf (currentlyFocusedComponent))
  30460. {
  30461. if (parentComponent_ != 0)
  30462. parentComponent_->grabKeyboardFocus();
  30463. else
  30464. giveAwayFocus();
  30465. }
  30466. }
  30467. sendVisibilityChangeMessage();
  30468. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  30469. {
  30470. ComponentPeer* const peer = getPeer();
  30471. jassert (peer != 0);
  30472. if (peer != 0)
  30473. {
  30474. peer->setVisible (shouldBeVisible);
  30475. internalHierarchyChanged();
  30476. }
  30477. }
  30478. }
  30479. }
  30480. void Component::visibilityChanged()
  30481. {
  30482. }
  30483. void Component::sendVisibilityChangeMessage()
  30484. {
  30485. const ComponentDeletionWatcher deletionChecker (this);
  30486. visibilityChanged();
  30487. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  30488. {
  30489. for (int i = componentListeners_->size(); --i >= 0;)
  30490. {
  30491. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30492. ->componentVisibilityChanged (*this);
  30493. if (deletionChecker.hasBeenDeleted())
  30494. return;
  30495. i = jmin (i, componentListeners_->size());
  30496. }
  30497. }
  30498. }
  30499. bool Component::isShowing() const throw()
  30500. {
  30501. if (flags.visibleFlag)
  30502. {
  30503. if (parentComponent_ != 0)
  30504. {
  30505. return parentComponent_->isShowing();
  30506. }
  30507. else
  30508. {
  30509. const ComponentPeer* const peer = getPeer();
  30510. return peer != 0 && ! peer->isMinimised();
  30511. }
  30512. }
  30513. return false;
  30514. }
  30515. class FadeOutProxyComponent : public Component,
  30516. public Timer
  30517. {
  30518. public:
  30519. FadeOutProxyComponent (Component* comp,
  30520. const int fadeLengthMs,
  30521. const int deltaXToMove,
  30522. const int deltaYToMove,
  30523. const float scaleFactorAtEnd)
  30524. : lastTime (0),
  30525. alpha (1.0f),
  30526. scale (1.0f)
  30527. {
  30528. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  30529. setBounds (comp->getBounds());
  30530. comp->getParentComponent()->addAndMakeVisible (this);
  30531. toBehind (comp);
  30532. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  30533. centreX = comp->getX() + comp->getWidth() * 0.5f;
  30534. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  30535. centreY = comp->getY() + comp->getHeight() * 0.5f;
  30536. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  30537. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  30538. setInterceptsMouseClicks (false, false);
  30539. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  30540. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  30541. }
  30542. ~FadeOutProxyComponent()
  30543. {
  30544. delete image;
  30545. }
  30546. void paint (Graphics& g)
  30547. {
  30548. g.setOpacity (alpha);
  30549. g.drawImage (image,
  30550. 0, 0, getWidth(), getHeight(),
  30551. 0, 0, image->getWidth(), image->getHeight());
  30552. }
  30553. void timerCallback()
  30554. {
  30555. const uint32 now = Time::getMillisecondCounter();
  30556. if (lastTime == 0)
  30557. lastTime = now;
  30558. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  30559. lastTime = now;
  30560. alpha += alphaChangePerMs * msPassed;
  30561. if (alpha > 0)
  30562. {
  30563. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  30564. {
  30565. centreX += xChangePerMs * msPassed;
  30566. centreY += yChangePerMs * msPassed;
  30567. scale += scaleChangePerMs * msPassed;
  30568. const int w = roundFloatToInt (image->getWidth() * scale);
  30569. const int h = roundFloatToInt (image->getHeight() * scale);
  30570. setBounds (roundFloatToInt (centreX) - w / 2,
  30571. roundFloatToInt (centreY) - h / 2,
  30572. w, h);
  30573. }
  30574. repaint();
  30575. }
  30576. else
  30577. {
  30578. delete this;
  30579. }
  30580. }
  30581. juce_UseDebuggingNewOperator
  30582. private:
  30583. Image* image;
  30584. uint32 lastTime;
  30585. float alpha, alphaChangePerMs;
  30586. float centreX, xChangePerMs;
  30587. float centreY, yChangePerMs;
  30588. float scale, scaleChangePerMs;
  30589. FadeOutProxyComponent (const FadeOutProxyComponent&);
  30590. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  30591. };
  30592. void Component::fadeOutComponent (const int millisecondsToFade,
  30593. const int deltaXToMove,
  30594. const int deltaYToMove,
  30595. const float scaleFactorAtEnd)
  30596. {
  30597. //xxx won't work for comps without parents
  30598. if (isShowing() && millisecondsToFade > 0)
  30599. new FadeOutProxyComponent (this, millisecondsToFade,
  30600. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  30601. setVisible (false);
  30602. }
  30603. bool Component::isValidComponent() const throw()
  30604. {
  30605. return (this != 0) && isValidMessageListener();
  30606. }
  30607. void* Component::getWindowHandle() const throw()
  30608. {
  30609. const ComponentPeer* const peer = getPeer();
  30610. if (peer != 0)
  30611. return peer->getNativeHandle();
  30612. return 0;
  30613. }
  30614. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  30615. {
  30616. // if component methods are being called from threads other than the message
  30617. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30618. checkMessageManagerIsLocked
  30619. if (! isOpaque())
  30620. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  30621. int currentStyleFlags = 0;
  30622. // don't use getPeer(), so that we only get the peer that's specifically
  30623. // for this comp, and not for one of its parents.
  30624. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  30625. if (peer != 0)
  30626. currentStyleFlags = peer->getStyleFlags();
  30627. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  30628. {
  30629. const ComponentDeletionWatcher deletionChecker (this);
  30630. #if JUCE_LINUX
  30631. // it's wise to give the component a non-zero size before
  30632. // putting it on the desktop, as X windows get confused by this, and
  30633. // a (1, 1) minimum size is enforced here.
  30634. setSize (jmax (1, getWidth()),
  30635. jmax (1, getHeight()));
  30636. #endif
  30637. int x = 0, y = 0;
  30638. relativePositionToGlobal (x, y);
  30639. bool wasFullscreen = false;
  30640. bool wasMinimised = false;
  30641. ComponentBoundsConstrainer* currentConstainer = 0;
  30642. Rectangle oldNonFullScreenBounds;
  30643. if (peer != 0)
  30644. {
  30645. wasFullscreen = peer->isFullScreen();
  30646. wasMinimised = peer->isMinimised();
  30647. currentConstainer = peer->getConstrainer();
  30648. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  30649. removeFromDesktop();
  30650. setTopLeftPosition (x, y);
  30651. }
  30652. if (parentComponent_ != 0)
  30653. parentComponent_->removeChildComponent (this);
  30654. if (! deletionChecker.hasBeenDeleted())
  30655. {
  30656. flags.hasHeavyweightPeerFlag = true;
  30657. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  30658. Desktop::getInstance().addDesktopComponent (this);
  30659. bounds_.setPosition (x, y);
  30660. peer->setBounds (x, y, getWidth(), getHeight(), false);
  30661. peer->setVisible (isVisible());
  30662. if (wasFullscreen)
  30663. {
  30664. peer->setFullScreen (true);
  30665. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  30666. }
  30667. if (wasMinimised)
  30668. peer->setMinimised (true);
  30669. if (isAlwaysOnTop())
  30670. peer->setAlwaysOnTop (true);
  30671. peer->setConstrainer (currentConstainer);
  30672. repaint();
  30673. }
  30674. internalHierarchyChanged();
  30675. }
  30676. }
  30677. void Component::removeFromDesktop()
  30678. {
  30679. // if component methods are being called from threads other than the message
  30680. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30681. checkMessageManagerIsLocked
  30682. if (flags.hasHeavyweightPeerFlag)
  30683. {
  30684. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30685. flags.hasHeavyweightPeerFlag = false;
  30686. jassert (peer != 0);
  30687. delete peer;
  30688. Desktop::getInstance().removeDesktopComponent (this);
  30689. }
  30690. }
  30691. bool Component::isOnDesktop() const throw()
  30692. {
  30693. return flags.hasHeavyweightPeerFlag;
  30694. }
  30695. void Component::userTriedToCloseWindow()
  30696. {
  30697. /* This means that the user's trying to get rid of your window with the 'close window' system
  30698. menu option (on windows) or possibly the task manager - you should really handle this
  30699. and delete or hide your component in an appropriate way.
  30700. If you want to ignore the event and don't want to trigger this assertion, just override
  30701. this method and do nothing.
  30702. */
  30703. jassertfalse
  30704. }
  30705. void Component::minimisationStateChanged (bool)
  30706. {
  30707. }
  30708. void Component::setOpaque (const bool shouldBeOpaque) throw()
  30709. {
  30710. if (shouldBeOpaque != flags.opaqueFlag)
  30711. {
  30712. flags.opaqueFlag = shouldBeOpaque;
  30713. if (flags.hasHeavyweightPeerFlag)
  30714. {
  30715. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  30716. if (peer != 0)
  30717. {
  30718. // to make it recreate the heavyweight window
  30719. addToDesktop (peer->getStyleFlags());
  30720. }
  30721. }
  30722. repaint();
  30723. }
  30724. }
  30725. bool Component::isOpaque() const throw()
  30726. {
  30727. return flags.opaqueFlag;
  30728. }
  30729. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  30730. {
  30731. if (shouldBeBuffered != flags.bufferToImageFlag)
  30732. {
  30733. deleteAndZero (bufferedImage_);
  30734. flags.bufferToImageFlag = shouldBeBuffered;
  30735. }
  30736. }
  30737. void Component::toFront (const bool setAsForeground)
  30738. {
  30739. // if component methods are being called from threads other than the message
  30740. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30741. checkMessageManagerIsLocked
  30742. if (flags.hasHeavyweightPeerFlag)
  30743. {
  30744. ComponentPeer* const peer = getPeer();
  30745. if (peer != 0)
  30746. {
  30747. peer->toFront (setAsForeground);
  30748. if (setAsForeground && ! hasKeyboardFocus (true))
  30749. grabKeyboardFocus();
  30750. }
  30751. }
  30752. else if (parentComponent_ != 0)
  30753. {
  30754. if (parentComponent_->childComponentList_.getLast() != this)
  30755. {
  30756. const int index = parentComponent_->childComponentList_.indexOf (this);
  30757. if (index >= 0)
  30758. {
  30759. int insertIndex = -1;
  30760. if (! flags.alwaysOnTopFlag)
  30761. {
  30762. insertIndex = parentComponent_->childComponentList_.size() - 1;
  30763. while (insertIndex > 0
  30764. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30765. {
  30766. --insertIndex;
  30767. }
  30768. }
  30769. if (index != insertIndex)
  30770. {
  30771. parentComponent_->childComponentList_.move (index, insertIndex);
  30772. sendFakeMouseMove();
  30773. repaintParent();
  30774. }
  30775. }
  30776. }
  30777. if (setAsForeground)
  30778. {
  30779. internalBroughtToFront();
  30780. grabKeyboardFocus();
  30781. }
  30782. }
  30783. }
  30784. void Component::toBehind (Component* const other)
  30785. {
  30786. if (other != 0)
  30787. {
  30788. // the two components must belong to the same parent..
  30789. jassert (parentComponent_ == other->parentComponent_);
  30790. if (parentComponent_ != 0)
  30791. {
  30792. const int index = parentComponent_->childComponentList_.indexOf (this);
  30793. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  30794. if (index >= 0
  30795. && otherIndex >= 0
  30796. && index != otherIndex - 1
  30797. && other != this)
  30798. {
  30799. if (index < otherIndex)
  30800. --otherIndex;
  30801. parentComponent_->childComponentList_.move (index, otherIndex);
  30802. sendFakeMouseMove();
  30803. repaintParent();
  30804. }
  30805. }
  30806. else if (isOnDesktop())
  30807. {
  30808. jassert (other->isOnDesktop());
  30809. if (other->isOnDesktop())
  30810. {
  30811. ComponentPeer* const us = getPeer();
  30812. ComponentPeer* const them = other->getPeer();
  30813. jassert (us != 0 && them != 0);
  30814. if (us != 0 && them != 0)
  30815. us->toBehind (them);
  30816. }
  30817. }
  30818. }
  30819. }
  30820. void Component::toBack()
  30821. {
  30822. if (isOnDesktop())
  30823. {
  30824. jassertfalse //xxx need to add this to native window
  30825. }
  30826. else if (parentComponent_ != 0
  30827. && parentComponent_->childComponentList_.getFirst() != this)
  30828. {
  30829. const int index = parentComponent_->childComponentList_.indexOf (this);
  30830. if (index > 0)
  30831. {
  30832. int insertIndex = 0;
  30833. if (flags.alwaysOnTopFlag)
  30834. {
  30835. while (insertIndex < parentComponent_->childComponentList_.size()
  30836. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  30837. {
  30838. ++insertIndex;
  30839. }
  30840. }
  30841. if (index != insertIndex)
  30842. {
  30843. parentComponent_->childComponentList_.move (index, insertIndex);
  30844. sendFakeMouseMove();
  30845. repaintParent();
  30846. }
  30847. }
  30848. }
  30849. }
  30850. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  30851. {
  30852. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  30853. {
  30854. flags.alwaysOnTopFlag = shouldStayOnTop;
  30855. if (isOnDesktop())
  30856. {
  30857. ComponentPeer* const peer = getPeer();
  30858. jassert (peer != 0);
  30859. if (peer != 0)
  30860. {
  30861. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  30862. {
  30863. // some kinds of peer can't change their always-on-top status, so
  30864. // for these, we'll need to create a new window
  30865. const int oldFlags = peer->getStyleFlags();
  30866. removeFromDesktop();
  30867. addToDesktop (oldFlags);
  30868. }
  30869. }
  30870. }
  30871. if (shouldStayOnTop)
  30872. toFront (false);
  30873. internalHierarchyChanged();
  30874. }
  30875. }
  30876. bool Component::isAlwaysOnTop() const throw()
  30877. {
  30878. return flags.alwaysOnTopFlag;
  30879. }
  30880. int Component::proportionOfWidth (const float proportion) const throw()
  30881. {
  30882. return roundDoubleToInt (proportion * bounds_.getWidth());
  30883. }
  30884. int Component::proportionOfHeight (const float proportion) const throw()
  30885. {
  30886. return roundDoubleToInt (proportion * bounds_.getHeight());
  30887. }
  30888. int Component::getParentWidth() const throw()
  30889. {
  30890. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  30891. : getParentMonitorArea().getWidth();
  30892. }
  30893. int Component::getParentHeight() const throw()
  30894. {
  30895. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  30896. : getParentMonitorArea().getHeight();
  30897. }
  30898. int Component::getScreenX() const throw()
  30899. {
  30900. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  30901. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  30902. : getX());
  30903. }
  30904. int Component::getScreenY() const throw()
  30905. {
  30906. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  30907. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  30908. : getY());
  30909. }
  30910. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  30911. {
  30912. const Component* c = this;
  30913. do
  30914. {
  30915. if (c->flags.hasHeavyweightPeerFlag)
  30916. {
  30917. c->getPeer()->relativePositionToGlobal (x, y);
  30918. break;
  30919. }
  30920. x += c->getX();
  30921. y += c->getY();
  30922. c = c->parentComponent_;
  30923. }
  30924. while (c != 0);
  30925. }
  30926. void Component::globalPositionToRelative (int& x, int& y) const throw()
  30927. {
  30928. if (flags.hasHeavyweightPeerFlag)
  30929. {
  30930. getPeer()->globalPositionToRelative (x, y);
  30931. }
  30932. else
  30933. {
  30934. if (parentComponent_ != 0)
  30935. parentComponent_->globalPositionToRelative (x, y);
  30936. x -= getX();
  30937. y -= getY();
  30938. }
  30939. }
  30940. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  30941. {
  30942. if (targetComponent != 0)
  30943. {
  30944. const Component* c = this;
  30945. do
  30946. {
  30947. if (c == targetComponent)
  30948. return;
  30949. if (c->flags.hasHeavyweightPeerFlag)
  30950. {
  30951. c->getPeer()->relativePositionToGlobal (x, y);
  30952. break;
  30953. }
  30954. x += c->getX();
  30955. y += c->getY();
  30956. c = c->parentComponent_;
  30957. }
  30958. while (c != 0);
  30959. targetComponent->globalPositionToRelative (x, y);
  30960. }
  30961. }
  30962. void Component::setBounds (int x, int y, int w, int h)
  30963. {
  30964. // if component methods are being called from threads other than the message
  30965. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30966. checkMessageManagerIsLocked
  30967. if (w < 0) w = 0;
  30968. if (h < 0) h = 0;
  30969. const bool wasResized = (getWidth() != w || getHeight() != h);
  30970. const bool wasMoved = (getX() != x || getY() != y);
  30971. #ifdef JUCE_DEBUG
  30972. // It's a very bad idea to try to resize a window during its paint() method!
  30973. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  30974. #endif
  30975. if (wasMoved || wasResized)
  30976. {
  30977. if (flags.visibleFlag)
  30978. {
  30979. // send a fake mouse move to trigger enter/exit messages if needed..
  30980. sendFakeMouseMove();
  30981. if (! flags.hasHeavyweightPeerFlag)
  30982. repaintParent();
  30983. }
  30984. bounds_.setBounds (x, y, w, h);
  30985. if (wasResized)
  30986. repaint();
  30987. else if (! flags.hasHeavyweightPeerFlag)
  30988. repaintParent();
  30989. if (flags.hasHeavyweightPeerFlag)
  30990. {
  30991. ComponentPeer* const peer = getPeer();
  30992. if (peer != 0)
  30993. {
  30994. if (wasMoved && wasResized)
  30995. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  30996. else if (wasMoved)
  30997. peer->setPosition (getX(), getY());
  30998. else if (wasResized)
  30999. peer->setSize (getWidth(), getHeight());
  31000. }
  31001. }
  31002. sendMovedResizedMessages (wasMoved, wasResized);
  31003. }
  31004. }
  31005. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  31006. {
  31007. JUCE_TRY
  31008. {
  31009. if (wasMoved)
  31010. moved();
  31011. if (wasResized)
  31012. {
  31013. resized();
  31014. for (int i = childComponentList_.size(); --i >= 0;)
  31015. {
  31016. childComponentList_.getUnchecked(i)->parentSizeChanged();
  31017. i = jmin (i, childComponentList_.size());
  31018. }
  31019. }
  31020. if (parentComponent_ != 0)
  31021. parentComponent_->childBoundsChanged (this);
  31022. if (componentListeners_ != 0)
  31023. {
  31024. const ComponentDeletionWatcher deletionChecker (this);
  31025. for (int i = componentListeners_->size(); --i >= 0;)
  31026. {
  31027. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31028. ->componentMovedOrResized (*this, wasMoved, wasResized);
  31029. if (deletionChecker.hasBeenDeleted())
  31030. return;
  31031. i = jmin (i, componentListeners_->size());
  31032. }
  31033. }
  31034. }
  31035. JUCE_CATCH_EXCEPTION
  31036. }
  31037. void Component::setSize (const int w, const int h)
  31038. {
  31039. setBounds (getX(), getY(), w, h);
  31040. }
  31041. void Component::setTopLeftPosition (const int x, const int y)
  31042. {
  31043. setBounds (x, y, getWidth(), getHeight());
  31044. }
  31045. void Component::setTopRightPosition (const int x, const int y)
  31046. {
  31047. setTopLeftPosition (x - getWidth(), y);
  31048. }
  31049. void Component::setBounds (const Rectangle& r)
  31050. {
  31051. setBounds (r.getX(),
  31052. r.getY(),
  31053. r.getWidth(),
  31054. r.getHeight());
  31055. }
  31056. void Component::setBoundsRelative (const float x, const float y,
  31057. const float w, const float h)
  31058. {
  31059. const int pw = getParentWidth();
  31060. const int ph = getParentHeight();
  31061. setBounds (roundFloatToInt (x * pw),
  31062. roundFloatToInt (y * ph),
  31063. roundFloatToInt (w * pw),
  31064. roundFloatToInt (h * ph));
  31065. }
  31066. void Component::setCentrePosition (const int x, const int y)
  31067. {
  31068. setTopLeftPosition (x - getWidth() / 2,
  31069. y - getHeight() / 2);
  31070. }
  31071. void Component::setCentreRelative (const float x, const float y)
  31072. {
  31073. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  31074. roundFloatToInt (getParentHeight() * y));
  31075. }
  31076. void Component::centreWithSize (const int width, const int height)
  31077. {
  31078. setBounds ((getParentWidth() - width) / 2,
  31079. (getParentHeight() - height) / 2,
  31080. width,
  31081. height);
  31082. }
  31083. void Component::setBoundsInset (const BorderSize& borders)
  31084. {
  31085. setBounds (borders.getLeft(),
  31086. borders.getTop(),
  31087. getParentWidth() - (borders.getLeftAndRight()),
  31088. getParentHeight() - (borders.getTopAndBottom()));
  31089. }
  31090. void Component::setBoundsToFit (int x, int y, int width, int height,
  31091. const Justification& justification,
  31092. const bool onlyReduceInSize)
  31093. {
  31094. // it's no good calling this method unless both the component and
  31095. // target rectangle have a finite size.
  31096. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  31097. if (getWidth() > 0 && getHeight() > 0
  31098. && width > 0 && height > 0)
  31099. {
  31100. int newW, newH;
  31101. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  31102. {
  31103. newW = getWidth();
  31104. newH = getHeight();
  31105. }
  31106. else
  31107. {
  31108. const double imageRatio = getHeight() / (double) getWidth();
  31109. const double targetRatio = height / (double) width;
  31110. if (imageRatio <= targetRatio)
  31111. {
  31112. newW = width;
  31113. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  31114. }
  31115. else
  31116. {
  31117. newH = height;
  31118. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  31119. }
  31120. }
  31121. if (newW > 0 && newH > 0)
  31122. {
  31123. int newX, newY;
  31124. justification.applyToRectangle (newX, newY, newW, newH,
  31125. x, y, width, height);
  31126. setBounds (newX, newY, newW, newH);
  31127. }
  31128. }
  31129. }
  31130. bool Component::hitTest (int x, int y)
  31131. {
  31132. if (! flags.ignoresMouseClicksFlag)
  31133. return true;
  31134. if (flags.allowChildMouseClicksFlag)
  31135. {
  31136. for (int i = getNumChildComponents(); --i >= 0;)
  31137. {
  31138. Component* const c = getChildComponent (i);
  31139. if (c->isVisible()
  31140. && c->bounds_.contains (x, y)
  31141. && c->hitTest (x - c->getX(),
  31142. y - c->getY()))
  31143. {
  31144. return true;
  31145. }
  31146. }
  31147. }
  31148. return false;
  31149. }
  31150. void Component::setInterceptsMouseClicks (const bool allowClicks,
  31151. const bool allowClicksOnChildComponents) throw()
  31152. {
  31153. flags.ignoresMouseClicksFlag = ! allowClicks;
  31154. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  31155. }
  31156. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  31157. bool& allowsClicksOnChildComponents) const throw()
  31158. {
  31159. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  31160. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  31161. }
  31162. bool Component::contains (const int x, const int y)
  31163. {
  31164. if (((unsigned int) x) < (unsigned int) getWidth()
  31165. && ((unsigned int) y) < (unsigned int) getHeight()
  31166. && hitTest (x, y))
  31167. {
  31168. if (parentComponent_ != 0)
  31169. {
  31170. return parentComponent_->contains (x + getX(),
  31171. y + getY());
  31172. }
  31173. else if (flags.hasHeavyweightPeerFlag)
  31174. {
  31175. const ComponentPeer* const peer = getPeer();
  31176. if (peer != 0)
  31177. return peer->contains (x, y, true);
  31178. }
  31179. }
  31180. return false;
  31181. }
  31182. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  31183. {
  31184. if (! contains (x, y))
  31185. return false;
  31186. Component* p = this;
  31187. while (p->parentComponent_ != 0)
  31188. {
  31189. x += p->getX();
  31190. y += p->getY();
  31191. p = p->parentComponent_;
  31192. }
  31193. const Component* const c = p->getComponentAt (x, y);
  31194. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  31195. }
  31196. Component* Component::getComponentAt (const int x, const int y)
  31197. {
  31198. if (flags.visibleFlag
  31199. && ((unsigned int) x) < (unsigned int) getWidth()
  31200. && ((unsigned int) y) < (unsigned int) getHeight()
  31201. && hitTest (x, y))
  31202. {
  31203. for (int i = childComponentList_.size(); --i >= 0;)
  31204. {
  31205. Component* const child = childComponentList_.getUnchecked(i);
  31206. Component* const c = child->getComponentAt (x - child->getX(),
  31207. y - child->getY());
  31208. if (c != 0)
  31209. return c;
  31210. }
  31211. return this;
  31212. }
  31213. return 0;
  31214. }
  31215. void Component::addChildComponent (Component* const child, int zOrder)
  31216. {
  31217. // if component methods are being called from threads other than the message
  31218. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31219. checkMessageManagerIsLocked
  31220. if (child != 0 && child->parentComponent_ != this)
  31221. {
  31222. if (child->parentComponent_ != 0)
  31223. child->parentComponent_->removeChildComponent (child);
  31224. else
  31225. child->removeFromDesktop();
  31226. child->parentComponent_ = this;
  31227. if (child->isVisible())
  31228. child->repaintParent();
  31229. if (! child->isAlwaysOnTop())
  31230. {
  31231. if (zOrder < 0 || zOrder > childComponentList_.size())
  31232. zOrder = childComponentList_.size();
  31233. while (zOrder > 0)
  31234. {
  31235. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  31236. break;
  31237. --zOrder;
  31238. }
  31239. }
  31240. childComponentList_.insert (zOrder, child);
  31241. child->internalHierarchyChanged();
  31242. internalChildrenChanged();
  31243. }
  31244. }
  31245. void Component::addAndMakeVisible (Component* const child, int zOrder)
  31246. {
  31247. if (child != 0)
  31248. {
  31249. child->setVisible (true);
  31250. addChildComponent (child, zOrder);
  31251. }
  31252. }
  31253. void Component::removeChildComponent (Component* const child)
  31254. {
  31255. removeChildComponent (childComponentList_.indexOf (child));
  31256. }
  31257. Component* Component::removeChildComponent (const int index)
  31258. {
  31259. // if component methods are being called from threads other than the message
  31260. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31261. checkMessageManagerIsLocked
  31262. Component* const child = childComponentList_ [index];
  31263. if (child != 0)
  31264. {
  31265. sendFakeMouseMove();
  31266. child->repaintParent();
  31267. childComponentList_.remove (index);
  31268. child->parentComponent_ = 0;
  31269. JUCE_TRY
  31270. {
  31271. if ((currentlyFocusedComponent == child)
  31272. || child->isParentOf (currentlyFocusedComponent))
  31273. {
  31274. // get rid first to force the grabKeyboardFocus to change to us.
  31275. giveAwayFocus();
  31276. grabKeyboardFocus();
  31277. }
  31278. }
  31279. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31280. catch (const std::exception& e)
  31281. {
  31282. currentlyFocusedComponent = 0;
  31283. Desktop::getInstance().triggerFocusCallback();
  31284. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31285. }
  31286. catch (...)
  31287. {
  31288. currentlyFocusedComponent = 0;
  31289. Desktop::getInstance().triggerFocusCallback();
  31290. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31291. }
  31292. #endif
  31293. child->internalHierarchyChanged();
  31294. internalChildrenChanged();
  31295. }
  31296. return child;
  31297. }
  31298. void Component::removeAllChildren()
  31299. {
  31300. for (int i = childComponentList_.size(); --i >= 0;)
  31301. removeChildComponent (i);
  31302. }
  31303. void Component::deleteAllChildren()
  31304. {
  31305. for (int i = childComponentList_.size(); --i >= 0;)
  31306. delete (removeChildComponent (i));
  31307. }
  31308. int Component::getNumChildComponents() const throw()
  31309. {
  31310. return childComponentList_.size();
  31311. }
  31312. Component* Component::getChildComponent (const int index) const throw()
  31313. {
  31314. return childComponentList_ [index];
  31315. }
  31316. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  31317. {
  31318. return childComponentList_.indexOf (const_cast <Component*> (child));
  31319. }
  31320. Component* Component::getTopLevelComponent() const throw()
  31321. {
  31322. const Component* comp = this;
  31323. while (comp->parentComponent_ != 0)
  31324. comp = comp->parentComponent_;
  31325. return (Component*) comp;
  31326. }
  31327. bool Component::isParentOf (const Component* possibleChild) const throw()
  31328. {
  31329. while (possibleChild->isValidComponent())
  31330. {
  31331. possibleChild = possibleChild->parentComponent_;
  31332. if (possibleChild == this)
  31333. return true;
  31334. }
  31335. return false;
  31336. }
  31337. void Component::parentHierarchyChanged()
  31338. {
  31339. }
  31340. void Component::childrenChanged()
  31341. {
  31342. }
  31343. void Component::internalChildrenChanged()
  31344. {
  31345. const ComponentDeletionWatcher deletionChecker (this);
  31346. const bool hasListeners = componentListeners_ != 0;
  31347. childrenChanged();
  31348. if (hasListeners)
  31349. {
  31350. if (deletionChecker.hasBeenDeleted())
  31351. return;
  31352. for (int i = componentListeners_->size(); --i >= 0;)
  31353. {
  31354. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31355. ->componentChildrenChanged (*this);
  31356. if (deletionChecker.hasBeenDeleted())
  31357. return;
  31358. i = jmin (i, componentListeners_->size());
  31359. }
  31360. }
  31361. }
  31362. void Component::internalHierarchyChanged()
  31363. {
  31364. parentHierarchyChanged();
  31365. const ComponentDeletionWatcher deletionChecker (this);
  31366. if (componentListeners_ != 0)
  31367. {
  31368. for (int i = componentListeners_->size(); --i >= 0;)
  31369. {
  31370. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31371. ->componentParentHierarchyChanged (*this);
  31372. if (deletionChecker.hasBeenDeleted())
  31373. return;
  31374. i = jmin (i, componentListeners_->size());
  31375. }
  31376. }
  31377. for (int i = childComponentList_.size(); --i >= 0;)
  31378. {
  31379. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  31380. // you really shouldn't delete the parent component during a callback telling you
  31381. // that it's changed..
  31382. jassert (! deletionChecker.hasBeenDeleted());
  31383. if (deletionChecker.hasBeenDeleted())
  31384. return;
  31385. i = jmin (i, childComponentList_.size());
  31386. }
  31387. }
  31388. void* Component::runModalLoopCallback (void* userData)
  31389. {
  31390. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  31391. }
  31392. int Component::runModalLoop()
  31393. {
  31394. if (! MessageManager::getInstance()->isThisTheMessageThread())
  31395. {
  31396. // use a callback so this can be called from non-gui threads
  31397. return (int) (pointer_sized_int)
  31398. MessageManager::getInstance()
  31399. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  31400. }
  31401. Component* const prevFocused = getCurrentlyFocusedComponent();
  31402. ComponentDeletionWatcher* deletionChecker = 0;
  31403. if (prevFocused != 0)
  31404. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  31405. if (! isCurrentlyModal())
  31406. enterModalState();
  31407. JUCE_TRY
  31408. {
  31409. while (flags.currentlyModalFlag && flags.visibleFlag)
  31410. {
  31411. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  31412. break;
  31413. // check whether this component was deleted during the last message
  31414. if (! isValidMessageListener())
  31415. break;
  31416. }
  31417. }
  31418. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31419. catch (const std::exception& e)
  31420. {
  31421. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31422. return 0;
  31423. }
  31424. catch (...)
  31425. {
  31426. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31427. return 0;
  31428. }
  31429. #endif
  31430. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31431. int returnValue = 0;
  31432. if (modalIndex >= 0)
  31433. {
  31434. modalComponentReturnValueKeys.remove (modalIndex);
  31435. returnValue = modalReturnValues.remove (modalIndex);
  31436. }
  31437. modalComponentStack.removeValue (this);
  31438. if (deletionChecker != 0)
  31439. {
  31440. if (! deletionChecker->hasBeenDeleted())
  31441. prevFocused->grabKeyboardFocus();
  31442. delete deletionChecker;
  31443. }
  31444. return returnValue;
  31445. }
  31446. void Component::enterModalState (const bool takeKeyboardFocus)
  31447. {
  31448. // if component methods are being called from threads other than the message
  31449. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31450. checkMessageManagerIsLocked
  31451. // Check for an attempt to make a component modal when it already is!
  31452. // This can cause nasty problems..
  31453. jassert (! flags.currentlyModalFlag);
  31454. if (! isCurrentlyModal())
  31455. {
  31456. modalComponentStack.add (this);
  31457. modalComponentReturnValueKeys.add (this);
  31458. modalReturnValues.add (0);
  31459. flags.currentlyModalFlag = true;
  31460. setVisible (true);
  31461. if (takeKeyboardFocus)
  31462. grabKeyboardFocus();
  31463. }
  31464. }
  31465. void Component::exitModalState (const int returnValue)
  31466. {
  31467. if (isCurrentlyModal())
  31468. {
  31469. if (MessageManager::getInstance()->isThisTheMessageThread())
  31470. {
  31471. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  31472. if (modalIndex >= 0)
  31473. {
  31474. modalReturnValues.set (modalIndex, returnValue);
  31475. }
  31476. else
  31477. {
  31478. modalComponentReturnValueKeys.add (this);
  31479. modalReturnValues.add (returnValue);
  31480. }
  31481. modalComponentStack.removeValue (this);
  31482. flags.currentlyModalFlag = false;
  31483. bringModalComponentToFront();
  31484. }
  31485. else
  31486. {
  31487. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  31488. }
  31489. }
  31490. }
  31491. bool Component::isCurrentlyModal() const throw()
  31492. {
  31493. return flags.currentlyModalFlag
  31494. && getCurrentlyModalComponent() == this;
  31495. }
  31496. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  31497. {
  31498. Component* const mc = getCurrentlyModalComponent();
  31499. return mc != 0
  31500. && mc != this
  31501. && (! mc->isParentOf (this))
  31502. && ! mc->canModalEventBeSentToComponent (this);
  31503. }
  31504. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  31505. {
  31506. return modalComponentStack.size();
  31507. }
  31508. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  31509. {
  31510. Component* const c = (Component*) (modalComponentStack [modalComponentStack.size() - index - 1]);
  31511. return c->isValidComponent() ? c : 0;
  31512. }
  31513. void Component::bringModalComponentToFront()
  31514. {
  31515. ComponentPeer* lastOne = 0;
  31516. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  31517. {
  31518. Component* const c = getCurrentlyModalComponent (i);
  31519. if (c == 0)
  31520. break;
  31521. ComponentPeer* peer = c->getPeer();
  31522. if (peer != 0 && peer != lastOne)
  31523. {
  31524. if (lastOne == 0)
  31525. {
  31526. peer->toFront (true);
  31527. peer->grabFocus();
  31528. }
  31529. else
  31530. peer->toBehind (lastOne);
  31531. lastOne = peer;
  31532. }
  31533. }
  31534. }
  31535. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  31536. {
  31537. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  31538. }
  31539. bool Component::isBroughtToFrontOnMouseClick() const throw()
  31540. {
  31541. return flags.bringToFrontOnClickFlag;
  31542. }
  31543. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  31544. {
  31545. cursor_ = cursor;
  31546. if (flags.visibleFlag)
  31547. {
  31548. int mx, my;
  31549. getMouseXYRelative (mx, my);
  31550. if (flags.draggingFlag || reallyContains (mx, my, false))
  31551. {
  31552. internalUpdateMouseCursor (false);
  31553. }
  31554. }
  31555. }
  31556. const MouseCursor Component::getMouseCursor()
  31557. {
  31558. return cursor_;
  31559. }
  31560. void Component::updateMouseCursor() const throw()
  31561. {
  31562. sendFakeMouseMove();
  31563. }
  31564. void Component::internalUpdateMouseCursor (bool forcedUpdate) throw()
  31565. {
  31566. ComponentPeer* const peer = getPeer();
  31567. if (peer != 0)
  31568. {
  31569. MouseCursor mc (getMouseCursor());
  31570. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  31571. || unboundedMouseOffsetY != 0
  31572. || ! isCursorVisibleUntilOffscreen))
  31573. {
  31574. mc = MouseCursor::NoCursor;
  31575. forcedUpdate = true;
  31576. }
  31577. static void* currentCursorHandle = 0;
  31578. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  31579. {
  31580. currentCursorHandle = mc.getHandle();
  31581. mc.showInWindow (peer);
  31582. }
  31583. }
  31584. }
  31585. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  31586. {
  31587. flags.repaintOnMouseActivityFlag = shouldRepaint;
  31588. }
  31589. void Component::repaintParent() throw()
  31590. {
  31591. if (flags.visibleFlag)
  31592. internalRepaint (0, 0, getWidth(), getHeight());
  31593. }
  31594. void Component::repaint() throw()
  31595. {
  31596. repaint (0, 0, getWidth(), getHeight());
  31597. }
  31598. void Component::repaint (const int x, const int y,
  31599. const int w, const int h) throw()
  31600. {
  31601. deleteAndZero (bufferedImage_);
  31602. if (flags.visibleFlag)
  31603. internalRepaint (x, y, w, h);
  31604. }
  31605. void Component::internalRepaint (int x, int y, int w, int h)
  31606. {
  31607. // if component methods are being called from threads other than the message
  31608. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31609. checkMessageManagerIsLocked
  31610. if (x < 0)
  31611. {
  31612. w += x;
  31613. x = 0;
  31614. }
  31615. if (x + w > getWidth())
  31616. w = getWidth() - x;
  31617. if (w > 0)
  31618. {
  31619. if (y < 0)
  31620. {
  31621. h += y;
  31622. y = 0;
  31623. }
  31624. if (y + h > getHeight())
  31625. h = getHeight() - y;
  31626. if (h > 0)
  31627. {
  31628. if (parentComponent_ != 0)
  31629. {
  31630. x += getX();
  31631. y += getY();
  31632. if (parentComponent_->flags.visibleFlag)
  31633. parentComponent_->internalRepaint (x, y, w, h);
  31634. }
  31635. else if (flags.hasHeavyweightPeerFlag)
  31636. {
  31637. ComponentPeer* const peer = getPeer();
  31638. if (peer != 0)
  31639. peer->repaint (x, y, w, h);
  31640. }
  31641. }
  31642. }
  31643. }
  31644. void Component::paintEntireComponent (Graphics& originalContext)
  31645. {
  31646. jassert (! originalContext.isClipEmpty());
  31647. #ifdef JUCE_DEBUG
  31648. flags.isInsidePaintCall = true;
  31649. #endif
  31650. Graphics* g = &originalContext;
  31651. Image* effectImage = 0;
  31652. if (effect_ != 0)
  31653. {
  31654. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31655. getWidth(), getHeight(),
  31656. ! flags.opaqueFlag);
  31657. g = new Graphics (*effectImage);
  31658. }
  31659. g->saveState();
  31660. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  31661. if (! g->isClipEmpty())
  31662. {
  31663. if (bufferedImage_ != 0)
  31664. {
  31665. g->setColour (Colours::black);
  31666. g->drawImageAt (bufferedImage_, 0, 0);
  31667. }
  31668. else
  31669. {
  31670. if (flags.bufferToImageFlag)
  31671. {
  31672. if (bufferedImage_ == 0)
  31673. {
  31674. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31675. getWidth(), getHeight(), ! flags.opaqueFlag);
  31676. Graphics imG (*bufferedImage_);
  31677. paint (imG);
  31678. }
  31679. g->setColour (Colours::black);
  31680. g->drawImageAt (bufferedImage_, 0, 0);
  31681. }
  31682. else
  31683. {
  31684. paint (*g);
  31685. g->resetToDefaultState();
  31686. }
  31687. }
  31688. }
  31689. g->restoreState();
  31690. for (int i = 0; i < childComponentList_.size(); ++i)
  31691. {
  31692. Component* const child = childComponentList_.getUnchecked (i);
  31693. if (child->isVisible())
  31694. {
  31695. g->saveState();
  31696. if (g->reduceClipRegion (child->getX(), child->getY(),
  31697. child->getWidth(), child->getHeight()))
  31698. {
  31699. for (int j = i + 1; j < childComponentList_.size(); ++j)
  31700. {
  31701. const Component* const sibling = childComponentList_.getUnchecked (j);
  31702. if (sibling->flags.opaqueFlag && sibling->isVisible())
  31703. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  31704. sibling->getWidth(), sibling->getHeight());
  31705. }
  31706. if (! g->isClipEmpty())
  31707. {
  31708. g->setOrigin (child->getX(), child->getY());
  31709. child->paintEntireComponent (*g);
  31710. }
  31711. }
  31712. g->restoreState();
  31713. }
  31714. }
  31715. JUCE_TRY
  31716. {
  31717. g->saveState();
  31718. paintOverChildren (*g);
  31719. g->restoreState();
  31720. }
  31721. JUCE_CATCH_EXCEPTION
  31722. if (effect_ != 0)
  31723. {
  31724. delete g;
  31725. effect_->applyEffect (*effectImage, originalContext);
  31726. delete effectImage;
  31727. }
  31728. #ifdef JUCE_DEBUG
  31729. flags.isInsidePaintCall = false;
  31730. #endif
  31731. }
  31732. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  31733. const bool clipImageToComponentBounds)
  31734. {
  31735. Rectangle r (areaToGrab);
  31736. if (clipImageToComponentBounds)
  31737. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  31738. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  31739. jmax (1, r.getWidth()),
  31740. jmax (1, r.getHeight()),
  31741. true);
  31742. Graphics imageContext (*componentImage);
  31743. imageContext.setOrigin (-r.getX(),
  31744. -r.getY());
  31745. paintEntireComponent (imageContext);
  31746. return componentImage;
  31747. }
  31748. void Component::setComponentEffect (ImageEffectFilter* const effect)
  31749. {
  31750. if (effect_ != effect)
  31751. {
  31752. effect_ = effect;
  31753. repaint();
  31754. }
  31755. }
  31756. LookAndFeel& Component::getLookAndFeel() const throw()
  31757. {
  31758. const Component* c = this;
  31759. do
  31760. {
  31761. if (c->lookAndFeel_ != 0)
  31762. return *(c->lookAndFeel_);
  31763. c = c->parentComponent_;
  31764. }
  31765. while (c != 0);
  31766. return LookAndFeel::getDefaultLookAndFeel();
  31767. }
  31768. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  31769. {
  31770. if (lookAndFeel_ != newLookAndFeel)
  31771. {
  31772. lookAndFeel_ = newLookAndFeel;
  31773. sendLookAndFeelChange();
  31774. }
  31775. }
  31776. void Component::lookAndFeelChanged()
  31777. {
  31778. }
  31779. void Component::sendLookAndFeelChange()
  31780. {
  31781. repaint();
  31782. lookAndFeelChanged();
  31783. // (it's not a great idea to do anything that would delete this component
  31784. // during the lookAndFeelChanged() callback)
  31785. jassert (isValidComponent());
  31786. const ComponentDeletionWatcher deletionChecker (this);
  31787. for (int i = childComponentList_.size(); --i >= 0;)
  31788. {
  31789. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  31790. if (deletionChecker.hasBeenDeleted())
  31791. return;
  31792. i = jmin (i, childComponentList_.size());
  31793. }
  31794. }
  31795. static const String getColourPropertyName (const int colourId) throw()
  31796. {
  31797. String s;
  31798. s.preallocateStorage (18);
  31799. s << T("jcclr_") << colourId;
  31800. return s;
  31801. }
  31802. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  31803. {
  31804. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  31805. inheritFromParent,
  31806. String::empty));
  31807. if (customColour.isNotEmpty())
  31808. return Colour (customColour.getIntValue());
  31809. return getLookAndFeel().findColour (colourId);
  31810. }
  31811. bool Component::isColourSpecified (const int colourId) const throw()
  31812. {
  31813. return getComponentProperty (getColourPropertyName (colourId),
  31814. false,
  31815. String::empty).isNotEmpty();
  31816. }
  31817. void Component::removeColour (const int colourId)
  31818. {
  31819. if (isColourSpecified (colourId))
  31820. {
  31821. removeComponentProperty (getColourPropertyName (colourId));
  31822. colourChanged();
  31823. }
  31824. }
  31825. void Component::setColour (const int colourId, const Colour& colour)
  31826. {
  31827. const String colourName (getColourPropertyName (colourId));
  31828. const String customColour (getComponentProperty (colourName, false, String::empty));
  31829. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  31830. {
  31831. setComponentProperty (colourName, colour);
  31832. colourChanged();
  31833. }
  31834. }
  31835. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  31836. {
  31837. if (propertySet_ != 0)
  31838. {
  31839. const StringPairArray& props = propertySet_->getAllProperties();
  31840. const StringArray& keys = props.getAllKeys();
  31841. for (int i = 0; i < keys.size(); ++i)
  31842. {
  31843. if (keys[i].startsWith (T("jcclr_")))
  31844. {
  31845. target.setComponentProperty (keys[i],
  31846. props.getAllValues() [i]);
  31847. }
  31848. }
  31849. target.colourChanged();
  31850. }
  31851. }
  31852. void Component::colourChanged()
  31853. {
  31854. }
  31855. const Rectangle Component::getUnclippedArea() const
  31856. {
  31857. int x = 0, y = 0, w = getWidth(), h = getHeight();
  31858. Component* p = parentComponent_;
  31859. int px = getX();
  31860. int py = getY();
  31861. while (p != 0)
  31862. {
  31863. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  31864. return Rectangle();
  31865. px += p->getX();
  31866. py += p->getY();
  31867. p = p->parentComponent_;
  31868. }
  31869. return Rectangle (x, y, w, h);
  31870. }
  31871. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  31872. const int deltaX, const int deltaY) const throw()
  31873. {
  31874. for (int i = childComponentList_.size(); --i >= 0;)
  31875. {
  31876. const Component* const c = childComponentList_.getUnchecked(i);
  31877. if (c->isVisible())
  31878. {
  31879. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31880. if (! newClip.isEmpty())
  31881. {
  31882. if (c->isOpaque())
  31883. {
  31884. g.excludeClipRegion (deltaX + newClip.getX(),
  31885. deltaY + newClip.getY(),
  31886. newClip.getWidth(),
  31887. newClip.getHeight());
  31888. }
  31889. else
  31890. {
  31891. newClip.translate (-c->getX(), -c->getY());
  31892. c->clipObscuredRegions (g, newClip,
  31893. c->getX() + deltaX,
  31894. c->getY() + deltaY);
  31895. }
  31896. }
  31897. }
  31898. }
  31899. }
  31900. void Component::getVisibleArea (RectangleList& result,
  31901. const bool includeSiblings) const
  31902. {
  31903. result.clear();
  31904. const Rectangle unclipped (getUnclippedArea());
  31905. if (! unclipped.isEmpty())
  31906. {
  31907. result.add (unclipped);
  31908. if (includeSiblings)
  31909. {
  31910. const Component* const c = getTopLevelComponent();
  31911. int x = 0, y = 0;
  31912. c->relativePositionToOtherComponent (this, x, y);
  31913. c->subtractObscuredRegions (result, x, y,
  31914. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  31915. this);
  31916. }
  31917. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  31918. result.consolidate();
  31919. }
  31920. }
  31921. void Component::subtractObscuredRegions (RectangleList& result,
  31922. const int deltaX,
  31923. const int deltaY,
  31924. const Rectangle& clipRect,
  31925. const Component* const compToAvoid) const throw()
  31926. {
  31927. for (int i = childComponentList_.size(); --i >= 0;)
  31928. {
  31929. const Component* const c = childComponentList_.getUnchecked(i);
  31930. if (c != compToAvoid && c->isVisible())
  31931. {
  31932. if (c->isOpaque())
  31933. {
  31934. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  31935. childBounds.translate (deltaX, deltaY);
  31936. result.subtract (childBounds);
  31937. }
  31938. else
  31939. {
  31940. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31941. newClip.translate (-c->getX(), -c->getY());
  31942. c->subtractObscuredRegions (result,
  31943. c->getX() + deltaX,
  31944. c->getY() + deltaY,
  31945. newClip,
  31946. compToAvoid);
  31947. }
  31948. }
  31949. }
  31950. }
  31951. void Component::mouseEnter (const MouseEvent&)
  31952. {
  31953. // base class does nothing
  31954. }
  31955. void Component::mouseExit (const MouseEvent&)
  31956. {
  31957. // base class does nothing
  31958. }
  31959. void Component::mouseDown (const MouseEvent&)
  31960. {
  31961. // base class does nothing
  31962. }
  31963. void Component::mouseUp (const MouseEvent&)
  31964. {
  31965. // base class does nothing
  31966. }
  31967. void Component::mouseDrag (const MouseEvent&)
  31968. {
  31969. // base class does nothing
  31970. }
  31971. void Component::mouseMove (const MouseEvent&)
  31972. {
  31973. // base class does nothing
  31974. }
  31975. void Component::mouseDoubleClick (const MouseEvent&)
  31976. {
  31977. // base class does nothing
  31978. }
  31979. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  31980. {
  31981. // the base class just passes this event up to its parent..
  31982. if (parentComponent_ != 0)
  31983. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  31984. wheelIncrementX, wheelIncrementY);
  31985. }
  31986. void Component::resized()
  31987. {
  31988. // base class does nothing
  31989. }
  31990. void Component::moved()
  31991. {
  31992. // base class does nothing
  31993. }
  31994. void Component::childBoundsChanged (Component*)
  31995. {
  31996. // base class does nothing
  31997. }
  31998. void Component::parentSizeChanged()
  31999. {
  32000. // base class does nothing
  32001. }
  32002. void Component::addComponentListener (ComponentListener* const newListener) throw()
  32003. {
  32004. if (componentListeners_ == 0)
  32005. componentListeners_ = new VoidArray (4);
  32006. componentListeners_->addIfNotAlreadyThere (newListener);
  32007. }
  32008. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  32009. {
  32010. jassert (isValidComponent());
  32011. if (componentListeners_ != 0)
  32012. componentListeners_->removeValue (listenerToRemove);
  32013. }
  32014. void Component::inputAttemptWhenModal()
  32015. {
  32016. bringModalComponentToFront();
  32017. getLookAndFeel().playAlertSound();
  32018. }
  32019. bool Component::canModalEventBeSentToComponent (const Component*)
  32020. {
  32021. return false;
  32022. }
  32023. void Component::internalModalInputAttempt()
  32024. {
  32025. Component* const current = getCurrentlyModalComponent();
  32026. if (current != 0)
  32027. current->inputAttemptWhenModal();
  32028. }
  32029. void Component::paint (Graphics&)
  32030. {
  32031. // all painting is done in the subclasses
  32032. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  32033. }
  32034. void Component::paintOverChildren (Graphics&)
  32035. {
  32036. // all painting is done in the subclasses
  32037. }
  32038. void Component::handleMessage (const Message& message)
  32039. {
  32040. if (message.intParameter1 == exitModalStateMessage)
  32041. {
  32042. exitModalState (message.intParameter2);
  32043. }
  32044. else if (message.intParameter1 == customCommandMessage)
  32045. {
  32046. handleCommandMessage (message.intParameter2);
  32047. }
  32048. }
  32049. void Component::postCommandMessage (const int commandId) throw()
  32050. {
  32051. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  32052. }
  32053. void Component::handleCommandMessage (int)
  32054. {
  32055. // used by subclasses
  32056. }
  32057. void Component::addMouseListener (MouseListener* const newListener,
  32058. const bool wantsEventsForAllNestedChildComponents) throw()
  32059. {
  32060. // if component methods are being called from threads other than the message
  32061. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32062. checkMessageManagerIsLocked
  32063. if (mouseListeners_ == 0)
  32064. mouseListeners_ = new VoidArray (4);
  32065. if (! mouseListeners_->contains (newListener))
  32066. {
  32067. if (wantsEventsForAllNestedChildComponents)
  32068. {
  32069. mouseListeners_->insert (0, newListener);
  32070. ++numDeepMouseListeners;
  32071. }
  32072. else
  32073. {
  32074. mouseListeners_->add (newListener);
  32075. }
  32076. }
  32077. }
  32078. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  32079. {
  32080. // if component methods are being called from threads other than the message
  32081. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32082. checkMessageManagerIsLocked
  32083. if (mouseListeners_ != 0)
  32084. {
  32085. const int index = mouseListeners_->indexOf (listenerToRemove);
  32086. if (index >= 0)
  32087. {
  32088. if (index < numDeepMouseListeners)
  32089. --numDeepMouseListeners;
  32090. mouseListeners_->remove (index);
  32091. }
  32092. }
  32093. }
  32094. void Component::internalMouseEnter (int x, int y, int64 time)
  32095. {
  32096. if (isCurrentlyBlockedByAnotherModalComponent())
  32097. {
  32098. // if something else is modal, always just show a normal mouse cursor
  32099. if (componentUnderMouse == this)
  32100. {
  32101. ComponentPeer* const peer = getPeer();
  32102. if (peer != 0)
  32103. {
  32104. MouseCursor mc (MouseCursor::NormalCursor);
  32105. mc.showInWindow (peer);
  32106. }
  32107. }
  32108. return;
  32109. }
  32110. if (! flags.mouseInsideFlag)
  32111. {
  32112. flags.mouseInsideFlag = true;
  32113. flags.mouseOverFlag = true;
  32114. flags.draggingFlag = false;
  32115. if (isValidComponent())
  32116. {
  32117. const ComponentDeletionWatcher deletionChecker (this);
  32118. if (flags.repaintOnMouseActivityFlag)
  32119. repaint();
  32120. const MouseEvent me (x, y,
  32121. ModifierKeys::getCurrentModifiers(),
  32122. this,
  32123. Time (time),
  32124. x, y,
  32125. Time (time),
  32126. 0, false);
  32127. mouseEnter (me);
  32128. if (deletionChecker.hasBeenDeleted())
  32129. return;
  32130. Desktop::getInstance().resetTimer();
  32131. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32132. {
  32133. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  32134. if (deletionChecker.hasBeenDeleted())
  32135. return;
  32136. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32137. }
  32138. if (mouseListeners_ != 0)
  32139. {
  32140. for (int i = mouseListeners_->size(); --i >= 0;)
  32141. {
  32142. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  32143. if (deletionChecker.hasBeenDeleted())
  32144. return;
  32145. i = jmin (i, mouseListeners_->size());
  32146. }
  32147. }
  32148. const Component* p = parentComponent_;
  32149. while (p != 0)
  32150. {
  32151. const ComponentDeletionWatcher parentDeletionChecker (p);
  32152. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32153. {
  32154. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  32155. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32156. return;
  32157. i = jmin (i, p->numDeepMouseListeners);
  32158. }
  32159. p = p->parentComponent_;
  32160. }
  32161. }
  32162. }
  32163. if (componentUnderMouse == this)
  32164. internalUpdateMouseCursor (true);
  32165. }
  32166. void Component::internalMouseExit (int x, int y, int64 time)
  32167. {
  32168. const ComponentDeletionWatcher deletionChecker (this);
  32169. if (flags.draggingFlag)
  32170. {
  32171. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  32172. if (deletionChecker.hasBeenDeleted())
  32173. return;
  32174. }
  32175. enableUnboundedMouseMovement (false);
  32176. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  32177. {
  32178. flags.mouseInsideFlag = false;
  32179. flags.mouseOverFlag = false;
  32180. flags.draggingFlag = false;
  32181. if (flags.repaintOnMouseActivityFlag)
  32182. repaint();
  32183. const MouseEvent me (x, y,
  32184. ModifierKeys::getCurrentModifiers(),
  32185. this,
  32186. Time (time),
  32187. x, y,
  32188. Time (time),
  32189. 0, false);
  32190. mouseExit (me);
  32191. if (deletionChecker.hasBeenDeleted())
  32192. return;
  32193. Desktop::getInstance().resetTimer();
  32194. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32195. {
  32196. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  32197. if (deletionChecker.hasBeenDeleted())
  32198. return;
  32199. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32200. }
  32201. if (mouseListeners_ != 0)
  32202. {
  32203. for (int i = mouseListeners_->size(); --i >= 0;)
  32204. {
  32205. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  32206. if (deletionChecker.hasBeenDeleted())
  32207. return;
  32208. i = jmin (i, mouseListeners_->size());
  32209. }
  32210. }
  32211. const Component* p = parentComponent_;
  32212. while (p != 0)
  32213. {
  32214. const ComponentDeletionWatcher parentDeletionChecker (p);
  32215. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32216. {
  32217. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  32218. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32219. return;
  32220. i = jmin (i, p->numDeepMouseListeners);
  32221. }
  32222. p = p->parentComponent_;
  32223. }
  32224. }
  32225. }
  32226. class InternalDragRepeater : public Timer
  32227. {
  32228. public:
  32229. InternalDragRepeater()
  32230. {}
  32231. ~InternalDragRepeater()
  32232. {}
  32233. void timerCallback()
  32234. {
  32235. Component* const c = Component::getComponentUnderMouse();
  32236. if (c != 0 && c->isMouseButtonDown())
  32237. {
  32238. int x, y;
  32239. c->getMouseXYRelative (x, y);
  32240. // the offsets have been added on, so must be taken off before calling the
  32241. // drag.. otherwise they'll be added twice
  32242. x -= unboundedMouseOffsetX;
  32243. y -= unboundedMouseOffsetY;
  32244. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  32245. }
  32246. }
  32247. juce_UseDebuggingNewOperator
  32248. };
  32249. static InternalDragRepeater* dragRepeater = 0;
  32250. void Component::beginDragAutoRepeat (const int interval)
  32251. {
  32252. if (interval > 0)
  32253. {
  32254. if (dragRepeater == 0)
  32255. dragRepeater = new InternalDragRepeater();
  32256. if (dragRepeater->getTimerInterval() != interval)
  32257. dragRepeater->startTimer (interval);
  32258. }
  32259. else
  32260. {
  32261. deleteAndZero (dragRepeater);
  32262. }
  32263. }
  32264. void Component::internalMouseDown (const int x, const int y)
  32265. {
  32266. const ComponentDeletionWatcher deletionChecker (this);
  32267. if (isCurrentlyBlockedByAnotherModalComponent())
  32268. {
  32269. internalModalInputAttempt();
  32270. if (deletionChecker.hasBeenDeleted())
  32271. return;
  32272. // If processing the input attempt has exited the modal loop, we'll allow the event
  32273. // to be delivered..
  32274. if (isCurrentlyBlockedByAnotherModalComponent())
  32275. {
  32276. // allow blocked mouse-events to go to global listeners..
  32277. const MouseEvent me (x, y,
  32278. ModifierKeys::getCurrentModifiers(),
  32279. this,
  32280. Time (juce_recentMouseDownTimes[0]),
  32281. x, y,
  32282. Time (juce_recentMouseDownTimes[0]),
  32283. countMouseClicks(),
  32284. false);
  32285. Desktop::getInstance().resetTimer();
  32286. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32287. {
  32288. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32289. if (deletionChecker.hasBeenDeleted())
  32290. return;
  32291. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32292. }
  32293. return;
  32294. }
  32295. }
  32296. {
  32297. Component* c = this;
  32298. while (c != 0)
  32299. {
  32300. if (c->isBroughtToFrontOnMouseClick())
  32301. {
  32302. c->toFront (true);
  32303. if (deletionChecker.hasBeenDeleted())
  32304. return;
  32305. }
  32306. c = c->parentComponent_;
  32307. }
  32308. }
  32309. if (! flags.dontFocusOnMouseClickFlag)
  32310. grabFocusInternal (focusChangedByMouseClick);
  32311. if (! deletionChecker.hasBeenDeleted())
  32312. {
  32313. flags.draggingFlag = true;
  32314. flags.mouseOverFlag = true;
  32315. if (flags.repaintOnMouseActivityFlag)
  32316. repaint();
  32317. const MouseEvent me (x, y,
  32318. ModifierKeys::getCurrentModifiers(),
  32319. this,
  32320. Time (juce_recentMouseDownTimes[0]),
  32321. x, y,
  32322. Time (juce_recentMouseDownTimes[0]),
  32323. countMouseClicks(),
  32324. false);
  32325. mouseDown (me);
  32326. if (deletionChecker.hasBeenDeleted())
  32327. return;
  32328. Desktop::getInstance().resetTimer();
  32329. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32330. {
  32331. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  32332. if (deletionChecker.hasBeenDeleted())
  32333. return;
  32334. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32335. }
  32336. if (mouseListeners_ != 0)
  32337. {
  32338. for (int i = mouseListeners_->size(); --i >= 0;)
  32339. {
  32340. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  32341. if (deletionChecker.hasBeenDeleted())
  32342. return;
  32343. i = jmin (i, mouseListeners_->size());
  32344. }
  32345. }
  32346. const Component* p = parentComponent_;
  32347. while (p != 0)
  32348. {
  32349. const ComponentDeletionWatcher parentDeletionChecker (p);
  32350. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32351. {
  32352. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  32353. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32354. return;
  32355. i = jmin (i, p->numDeepMouseListeners);
  32356. }
  32357. p = p->parentComponent_;
  32358. }
  32359. }
  32360. }
  32361. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  32362. {
  32363. if (isValidComponent() && flags.draggingFlag)
  32364. {
  32365. flags.draggingFlag = false;
  32366. deleteAndZero (dragRepeater);
  32367. x += unboundedMouseOffsetX;
  32368. y += unboundedMouseOffsetY;
  32369. juce_LastMousePosX = x;
  32370. juce_LastMousePosY = y;
  32371. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32372. const ComponentDeletionWatcher deletionChecker (this);
  32373. if (flags.repaintOnMouseActivityFlag)
  32374. repaint();
  32375. int mdx = juce_recentMouseDownX[0];
  32376. int mdy = juce_recentMouseDownY[0];
  32377. globalPositionToRelative (mdx, mdy);
  32378. const MouseEvent me (x, y,
  32379. oldModifiers,
  32380. this,
  32381. Time (time),
  32382. mdx, mdy,
  32383. Time (juce_recentMouseDownTimes [0]),
  32384. countMouseClicks(),
  32385. juce_MouseHasMovedSignificantlySincePressed
  32386. || juce_recentMouseDownTimes[0] + 300 < time);
  32387. mouseUp (me);
  32388. if (deletionChecker.hasBeenDeleted())
  32389. return;
  32390. Desktop::getInstance().resetTimer();
  32391. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32392. {
  32393. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  32394. if (deletionChecker.hasBeenDeleted())
  32395. return;
  32396. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32397. }
  32398. if (mouseListeners_ != 0)
  32399. {
  32400. for (int i = mouseListeners_->size(); --i >= 0;)
  32401. {
  32402. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  32403. if (deletionChecker.hasBeenDeleted())
  32404. return;
  32405. i = jmin (i, mouseListeners_->size());
  32406. }
  32407. }
  32408. {
  32409. const Component* p = parentComponent_;
  32410. while (p != 0)
  32411. {
  32412. const ComponentDeletionWatcher parentDeletionChecker (p);
  32413. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32414. {
  32415. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  32416. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32417. return;
  32418. i = jmin (i, p->numDeepMouseListeners);
  32419. }
  32420. p = p->parentComponent_;
  32421. }
  32422. }
  32423. // check for double-click
  32424. if (me.getNumberOfClicks() >= 2)
  32425. {
  32426. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  32427. mouseDoubleClick (me);
  32428. int i;
  32429. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32430. {
  32431. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  32432. if (deletionChecker.hasBeenDeleted())
  32433. return;
  32434. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32435. }
  32436. for (i = numListeners; --i >= 0;)
  32437. {
  32438. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  32439. return;
  32440. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  32441. if (ml != 0)
  32442. ml->mouseDoubleClick (me);
  32443. }
  32444. if (deletionChecker.hasBeenDeleted())
  32445. return;
  32446. const Component* p = parentComponent_;
  32447. while (p != 0)
  32448. {
  32449. const ComponentDeletionWatcher parentDeletionChecker (p);
  32450. for (i = p->numDeepMouseListeners; --i >= 0;)
  32451. {
  32452. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  32453. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32454. return;
  32455. i = jmin (i, p->numDeepMouseListeners);
  32456. }
  32457. p = p->parentComponent_;
  32458. }
  32459. }
  32460. }
  32461. enableUnboundedMouseMovement (false);
  32462. }
  32463. void Component::internalMouseDrag (int x, int y, const int64 time)
  32464. {
  32465. if (isValidComponent() && flags.draggingFlag)
  32466. {
  32467. flags.mouseOverFlag = reallyContains (x, y, false);
  32468. x += unboundedMouseOffsetX;
  32469. y += unboundedMouseOffsetY;
  32470. juce_LastMousePosX = x;
  32471. juce_LastMousePosY = y;
  32472. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  32473. juce_MouseHasMovedSignificantlySincePressed
  32474. = juce_MouseHasMovedSignificantlySincePressed
  32475. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  32476. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  32477. const ComponentDeletionWatcher deletionChecker (this);
  32478. int mdx = juce_recentMouseDownX[0];
  32479. int mdy = juce_recentMouseDownY[0];
  32480. globalPositionToRelative (mdx, mdy);
  32481. const MouseEvent me (x, y,
  32482. ModifierKeys::getCurrentModifiers(),
  32483. this,
  32484. Time (time),
  32485. mdx, mdy,
  32486. Time (juce_recentMouseDownTimes[0]),
  32487. countMouseClicks(),
  32488. juce_MouseHasMovedSignificantlySincePressed
  32489. || juce_recentMouseDownTimes[0] + 300 < time);
  32490. mouseDrag (me);
  32491. if (deletionChecker.hasBeenDeleted())
  32492. return;
  32493. Desktop::getInstance().resetTimer();
  32494. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32495. {
  32496. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  32497. if (deletionChecker.hasBeenDeleted())
  32498. return;
  32499. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32500. }
  32501. if (mouseListeners_ != 0)
  32502. {
  32503. for (int i = mouseListeners_->size(); --i >= 0;)
  32504. {
  32505. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  32506. if (deletionChecker.hasBeenDeleted())
  32507. return;
  32508. i = jmin (i, mouseListeners_->size());
  32509. }
  32510. }
  32511. const Component* p = parentComponent_;
  32512. while (p != 0)
  32513. {
  32514. const ComponentDeletionWatcher parentDeletionChecker (p);
  32515. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32516. {
  32517. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  32518. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32519. return;
  32520. i = jmin (i, p->numDeepMouseListeners);
  32521. }
  32522. p = p->parentComponent_;
  32523. }
  32524. if (this == componentUnderMouse)
  32525. {
  32526. if (isUnboundedMouseModeOn)
  32527. {
  32528. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  32529. int mx, my;
  32530. Desktop::getMousePosition (mx, my);
  32531. if (! screenArea.contains (mx, my))
  32532. {
  32533. int deltaX = 0, deltaY = 0;
  32534. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  32535. deltaX = getScreenX() + getWidth() / 2 - mx;
  32536. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  32537. deltaY = getScreenY() + getHeight() / 2 - my;
  32538. unboundedMouseOffsetX -= deltaX;
  32539. unboundedMouseOffsetY -= deltaY;
  32540. Desktop::setMousePosition (mx + deltaX,
  32541. my + deltaY);
  32542. }
  32543. else if (isCursorVisibleUntilOffscreen
  32544. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  32545. && screenArea.contains (mx + unboundedMouseOffsetX,
  32546. my + unboundedMouseOffsetY))
  32547. {
  32548. mx += unboundedMouseOffsetX;
  32549. my += unboundedMouseOffsetY;
  32550. unboundedMouseOffsetX = 0;
  32551. unboundedMouseOffsetY = 0;
  32552. Desktop::setMousePosition (mx, my);
  32553. }
  32554. }
  32555. internalUpdateMouseCursor (false);
  32556. }
  32557. }
  32558. }
  32559. void Component::internalMouseMove (const int x, const int y, const int64 time)
  32560. {
  32561. const ComponentDeletionWatcher deletionChecker (this);
  32562. if (isValidComponent())
  32563. {
  32564. const MouseEvent me (x, y,
  32565. ModifierKeys::getCurrentModifiers(),
  32566. this,
  32567. Time (time),
  32568. x, y,
  32569. Time (time),
  32570. 0, false);
  32571. if (isCurrentlyBlockedByAnotherModalComponent())
  32572. {
  32573. // allow blocked mouse-events to go to global listeners..
  32574. Desktop::getInstance().sendMouseMove();
  32575. }
  32576. else
  32577. {
  32578. if (this == componentUnderMouse)
  32579. internalUpdateMouseCursor (false);
  32580. flags.mouseOverFlag = true;
  32581. mouseMove (me);
  32582. if (deletionChecker.hasBeenDeleted())
  32583. return;
  32584. Desktop::getInstance().resetTimer();
  32585. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32586. {
  32587. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  32588. if (deletionChecker.hasBeenDeleted())
  32589. return;
  32590. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32591. }
  32592. if (mouseListeners_ != 0)
  32593. {
  32594. for (int i = mouseListeners_->size(); --i >= 0;)
  32595. {
  32596. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  32597. if (deletionChecker.hasBeenDeleted())
  32598. return;
  32599. i = jmin (i, mouseListeners_->size());
  32600. }
  32601. }
  32602. const Component* p = parentComponent_;
  32603. while (p != 0)
  32604. {
  32605. const ComponentDeletionWatcher parentDeletionChecker (p);
  32606. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32607. {
  32608. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  32609. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32610. return;
  32611. i = jmin (i, p->numDeepMouseListeners);
  32612. }
  32613. p = p->parentComponent_;
  32614. }
  32615. }
  32616. }
  32617. }
  32618. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  32619. {
  32620. const ComponentDeletionWatcher deletionChecker (this);
  32621. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  32622. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  32623. int mx, my;
  32624. getMouseXYRelative (mx, my);
  32625. const MouseEvent me (mx, my,
  32626. ModifierKeys::getCurrentModifiers(),
  32627. this,
  32628. Time (time),
  32629. mx, my,
  32630. Time (time),
  32631. 0, false);
  32632. if (isCurrentlyBlockedByAnotherModalComponent())
  32633. {
  32634. // allow blocked mouse-events to go to global listeners..
  32635. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32636. {
  32637. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32638. if (deletionChecker.hasBeenDeleted())
  32639. return;
  32640. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32641. }
  32642. }
  32643. else
  32644. {
  32645. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32646. if (deletionChecker.hasBeenDeleted())
  32647. return;
  32648. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  32649. {
  32650. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32651. if (deletionChecker.hasBeenDeleted())
  32652. return;
  32653. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  32654. }
  32655. if (mouseListeners_ != 0)
  32656. {
  32657. for (int i = mouseListeners_->size(); --i >= 0;)
  32658. {
  32659. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32660. if (deletionChecker.hasBeenDeleted())
  32661. return;
  32662. i = jmin (i, mouseListeners_->size());
  32663. }
  32664. }
  32665. const Component* p = parentComponent_;
  32666. while (p != 0)
  32667. {
  32668. const ComponentDeletionWatcher parentDeletionChecker (p);
  32669. for (int i = p->numDeepMouseListeners; --i >= 0;)
  32670. {
  32671. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  32672. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  32673. return;
  32674. i = jmin (i, p->numDeepMouseListeners);
  32675. }
  32676. p = p->parentComponent_;
  32677. }
  32678. sendFakeMouseMove();
  32679. }
  32680. }
  32681. void Component::sendFakeMouseMove() const
  32682. {
  32683. ComponentPeer* const peer = getPeer();
  32684. if (peer != 0)
  32685. peer->sendFakeMouseMove();
  32686. }
  32687. void Component::broughtToFront()
  32688. {
  32689. }
  32690. void Component::internalBroughtToFront()
  32691. {
  32692. if (isValidComponent())
  32693. {
  32694. if (flags.hasHeavyweightPeerFlag)
  32695. Desktop::getInstance().componentBroughtToFront (this);
  32696. const ComponentDeletionWatcher deletionChecker (this);
  32697. broughtToFront();
  32698. if (deletionChecker.hasBeenDeleted())
  32699. return;
  32700. if (componentListeners_ != 0)
  32701. {
  32702. for (int i = componentListeners_->size(); --i >= 0;)
  32703. {
  32704. ((ComponentListener*) componentListeners_->getUnchecked (i))
  32705. ->componentBroughtToFront (*this);
  32706. if (deletionChecker.hasBeenDeleted())
  32707. return;
  32708. i = jmin (i, componentListeners_->size());
  32709. }
  32710. }
  32711. // when brought to the front and there's a modal component blocking this one,
  32712. // we need to bring the modal one to the front instead..
  32713. Component* const cm = getCurrentlyModalComponent();
  32714. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  32715. bringModalComponentToFront();
  32716. }
  32717. }
  32718. void Component::focusGained (FocusChangeType)
  32719. {
  32720. // base class does nothing
  32721. }
  32722. void Component::internalFocusGain (const FocusChangeType cause)
  32723. {
  32724. const ComponentDeletionWatcher deletionChecker (this);
  32725. focusGained (cause);
  32726. if (! deletionChecker.hasBeenDeleted())
  32727. internalChildFocusChange (cause);
  32728. }
  32729. void Component::focusLost (FocusChangeType)
  32730. {
  32731. // base class does nothing
  32732. }
  32733. void Component::internalFocusLoss (const FocusChangeType cause)
  32734. {
  32735. const ComponentDeletionWatcher deletionChecker (this);
  32736. focusLost (focusChangedDirectly);
  32737. if (! deletionChecker.hasBeenDeleted())
  32738. internalChildFocusChange (cause);
  32739. }
  32740. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  32741. {
  32742. // base class does nothing
  32743. }
  32744. void Component::internalChildFocusChange (FocusChangeType cause)
  32745. {
  32746. const bool childIsNowFocused = hasKeyboardFocus (true);
  32747. if (flags.childCompFocusedFlag != childIsNowFocused)
  32748. {
  32749. flags.childCompFocusedFlag = childIsNowFocused;
  32750. const ComponentDeletionWatcher deletionChecker (this);
  32751. focusOfChildComponentChanged (cause);
  32752. if (deletionChecker.hasBeenDeleted())
  32753. return;
  32754. }
  32755. if (parentComponent_ != 0)
  32756. parentComponent_->internalChildFocusChange (cause);
  32757. }
  32758. bool Component::isEnabled() const throw()
  32759. {
  32760. return (! flags.isDisabledFlag)
  32761. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  32762. }
  32763. void Component::setEnabled (const bool shouldBeEnabled)
  32764. {
  32765. if (flags.isDisabledFlag == shouldBeEnabled)
  32766. {
  32767. flags.isDisabledFlag = ! shouldBeEnabled;
  32768. // if any parent components are disabled, setting our flag won't make a difference,
  32769. // so no need to send a change message
  32770. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  32771. sendEnablementChangeMessage();
  32772. }
  32773. }
  32774. void Component::sendEnablementChangeMessage()
  32775. {
  32776. const ComponentDeletionWatcher deletionChecker (this);
  32777. enablementChanged();
  32778. if (deletionChecker.hasBeenDeleted())
  32779. return;
  32780. for (int i = getNumChildComponents(); --i >= 0;)
  32781. {
  32782. Component* const c = getChildComponent (i);
  32783. if (c != 0)
  32784. {
  32785. c->sendEnablementChangeMessage();
  32786. if (deletionChecker.hasBeenDeleted())
  32787. return;
  32788. }
  32789. }
  32790. }
  32791. void Component::enablementChanged()
  32792. {
  32793. }
  32794. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  32795. {
  32796. flags.wantsFocusFlag = wantsFocus;
  32797. }
  32798. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  32799. {
  32800. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  32801. }
  32802. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  32803. {
  32804. return ! flags.dontFocusOnMouseClickFlag;
  32805. }
  32806. bool Component::getWantsKeyboardFocus() const throw()
  32807. {
  32808. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  32809. }
  32810. void Component::setFocusContainer (const bool isFocusContainer) throw()
  32811. {
  32812. flags.isFocusContainerFlag = isFocusContainer;
  32813. }
  32814. bool Component::isFocusContainer() const throw()
  32815. {
  32816. return flags.isFocusContainerFlag;
  32817. }
  32818. int Component::getExplicitFocusOrder() const throw()
  32819. {
  32820. return getComponentPropertyInt (T("_jexfo"), false, 0);
  32821. }
  32822. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  32823. {
  32824. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  32825. }
  32826. KeyboardFocusTraverser* Component::createFocusTraverser()
  32827. {
  32828. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  32829. return new KeyboardFocusTraverser();
  32830. return parentComponent_->createFocusTraverser();
  32831. }
  32832. void Component::takeKeyboardFocus (const FocusChangeType cause)
  32833. {
  32834. // give the focus to this component
  32835. if (currentlyFocusedComponent != this)
  32836. {
  32837. JUCE_TRY
  32838. {
  32839. // get the focus onto our desktop window
  32840. ComponentPeer* const peer = getPeer();
  32841. if (peer != 0)
  32842. {
  32843. const ComponentDeletionWatcher deletionChecker (this);
  32844. peer->grabFocus();
  32845. if (peer->isFocused() && currentlyFocusedComponent != this)
  32846. {
  32847. Component* const componentLosingFocus = currentlyFocusedComponent;
  32848. currentlyFocusedComponent = this;
  32849. Desktop::getInstance().triggerFocusCallback();
  32850. // call this after setting currentlyFocusedComponent so that the one that's
  32851. // losing it has a chance to see where focus is going
  32852. if (componentLosingFocus->isValidComponent())
  32853. componentLosingFocus->internalFocusLoss (cause);
  32854. if (currentlyFocusedComponent == this)
  32855. {
  32856. focusGained (cause);
  32857. if (! deletionChecker.hasBeenDeleted())
  32858. internalChildFocusChange (cause);
  32859. }
  32860. }
  32861. }
  32862. }
  32863. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32864. catch (const std::exception& e)
  32865. {
  32866. currentlyFocusedComponent = 0;
  32867. Desktop::getInstance().triggerFocusCallback();
  32868. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32869. }
  32870. catch (...)
  32871. {
  32872. currentlyFocusedComponent = 0;
  32873. Desktop::getInstance().triggerFocusCallback();
  32874. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32875. }
  32876. #endif
  32877. }
  32878. }
  32879. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  32880. {
  32881. if (isShowing())
  32882. {
  32883. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  32884. {
  32885. takeKeyboardFocus (cause);
  32886. }
  32887. else
  32888. {
  32889. if (isParentOf (currentlyFocusedComponent)
  32890. && currentlyFocusedComponent->isShowing())
  32891. {
  32892. // do nothing if the focused component is actually a child of ours..
  32893. }
  32894. else
  32895. {
  32896. // find the default child component..
  32897. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32898. if (traverser != 0)
  32899. {
  32900. Component* const defaultComp = traverser->getDefaultComponent (this);
  32901. delete traverser;
  32902. if (defaultComp != 0)
  32903. {
  32904. defaultComp->grabFocusInternal (cause, false);
  32905. return;
  32906. }
  32907. }
  32908. if (canTryParent && parentComponent_ != 0)
  32909. {
  32910. // if no children want it and we're allowed to try our parent comp,
  32911. // then pass up to parent, which will try our siblings.
  32912. parentComponent_->grabFocusInternal (cause, true);
  32913. }
  32914. }
  32915. }
  32916. }
  32917. }
  32918. void Component::grabKeyboardFocus()
  32919. {
  32920. // if component methods are being called from threads other than the message
  32921. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32922. checkMessageManagerIsLocked
  32923. grabFocusInternal (focusChangedDirectly);
  32924. }
  32925. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  32926. {
  32927. // if component methods are being called from threads other than the message
  32928. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32929. checkMessageManagerIsLocked
  32930. if (parentComponent_ != 0)
  32931. {
  32932. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32933. if (traverser != 0)
  32934. {
  32935. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  32936. : traverser->getPreviousComponent (this);
  32937. delete traverser;
  32938. if (nextComp != 0)
  32939. {
  32940. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32941. {
  32942. const ComponentDeletionWatcher deletionChecker (nextComp);
  32943. internalModalInputAttempt();
  32944. if (deletionChecker.hasBeenDeleted()
  32945. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32946. return;
  32947. }
  32948. nextComp->grabFocusInternal (focusChangedByTabKey);
  32949. return;
  32950. }
  32951. }
  32952. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  32953. }
  32954. }
  32955. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  32956. {
  32957. return (currentlyFocusedComponent == this)
  32958. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  32959. }
  32960. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  32961. {
  32962. return currentlyFocusedComponent;
  32963. }
  32964. void Component::giveAwayFocus()
  32965. {
  32966. // use a copy so we can clear the value before the call
  32967. Component* const componentLosingFocus = currentlyFocusedComponent;
  32968. currentlyFocusedComponent = 0;
  32969. Desktop::getInstance().triggerFocusCallback();
  32970. if (componentLosingFocus->isValidComponent())
  32971. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  32972. }
  32973. bool Component::isMouseOver() const throw()
  32974. {
  32975. return flags.mouseOverFlag;
  32976. }
  32977. bool Component::isMouseButtonDown() const throw()
  32978. {
  32979. return flags.draggingFlag;
  32980. }
  32981. bool Component::isMouseOverOrDragging() const throw()
  32982. {
  32983. return flags.mouseOverFlag || flags.draggingFlag;
  32984. }
  32985. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  32986. {
  32987. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  32988. }
  32989. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  32990. {
  32991. Desktop::getMousePosition (mx, my);
  32992. globalPositionToRelative (mx, my);
  32993. mx += unboundedMouseOffsetX;
  32994. my += unboundedMouseOffsetY;
  32995. }
  32996. void Component::enableUnboundedMouseMovement (bool enable,
  32997. bool keepCursorVisibleUntilOffscreen) throw()
  32998. {
  32999. enable = enable && isMouseButtonDown();
  33000. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  33001. if (enable != isUnboundedMouseModeOn)
  33002. {
  33003. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  33004. || unboundedMouseOffsetX != 0
  33005. || unboundedMouseOffsetY != 0))
  33006. {
  33007. // when released, return the mouse to within the component's bounds
  33008. int mx, my;
  33009. getMouseXYRelative (mx, my);
  33010. mx = jlimit (0, getWidth(), mx);
  33011. my = jlimit (0, getHeight(), my);
  33012. relativePositionToGlobal (mx, my);
  33013. Desktop::setMousePosition (mx, my);
  33014. }
  33015. isUnboundedMouseModeOn = enable;
  33016. unboundedMouseOffsetX = 0;
  33017. unboundedMouseOffsetY = 0;
  33018. internalUpdateMouseCursor (true);
  33019. }
  33020. }
  33021. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  33022. {
  33023. return componentUnderMouse;
  33024. }
  33025. const Rectangle Component::getParentMonitorArea() const throw()
  33026. {
  33027. int centreX = getWidth() / 2;
  33028. int centreY = getHeight() / 2;
  33029. relativePositionToGlobal (centreX, centreY);
  33030. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  33031. }
  33032. void Component::addKeyListener (KeyListener* const newListener) throw()
  33033. {
  33034. if (keyListeners_ == 0)
  33035. keyListeners_ = new VoidArray (4);
  33036. keyListeners_->addIfNotAlreadyThere (newListener);
  33037. }
  33038. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  33039. {
  33040. if (keyListeners_ != 0)
  33041. keyListeners_->removeValue (listenerToRemove);
  33042. }
  33043. bool Component::keyPressed (const KeyPress&)
  33044. {
  33045. return false;
  33046. }
  33047. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  33048. {
  33049. return false;
  33050. }
  33051. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  33052. {
  33053. if (parentComponent_ != 0)
  33054. parentComponent_->modifierKeysChanged (modifiers);
  33055. }
  33056. void Component::internalModifierKeysChanged()
  33057. {
  33058. sendFakeMouseMove();
  33059. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  33060. }
  33061. ComponentPeer* Component::getPeer() const throw()
  33062. {
  33063. if (flags.hasHeavyweightPeerFlag)
  33064. return ComponentPeer::getPeerFor (this);
  33065. else if (parentComponent_ != 0)
  33066. return parentComponent_->getPeer();
  33067. else
  33068. return 0;
  33069. }
  33070. const String Component::getComponentProperty (const String& keyName,
  33071. const bool useParentComponentIfNotFound,
  33072. const String& defaultReturnValue) const throw()
  33073. {
  33074. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33075. return propertySet_->getValue (keyName, defaultReturnValue);
  33076. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33077. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  33078. return defaultReturnValue;
  33079. }
  33080. int Component::getComponentPropertyInt (const String& keyName,
  33081. const bool useParentComponentIfNotFound,
  33082. const int defaultReturnValue) const throw()
  33083. {
  33084. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33085. return propertySet_->getIntValue (keyName, defaultReturnValue);
  33086. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33087. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  33088. return defaultReturnValue;
  33089. }
  33090. double Component::getComponentPropertyDouble (const String& keyName,
  33091. const bool useParentComponentIfNotFound,
  33092. const double defaultReturnValue) const throw()
  33093. {
  33094. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33095. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  33096. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33097. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  33098. return defaultReturnValue;
  33099. }
  33100. bool Component::getComponentPropertyBool (const String& keyName,
  33101. const bool useParentComponentIfNotFound,
  33102. const bool defaultReturnValue) const throw()
  33103. {
  33104. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  33105. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  33106. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  33107. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  33108. return defaultReturnValue;
  33109. }
  33110. const Colour Component::getComponentPropertyColour (const String& keyName,
  33111. const bool useParentComponentIfNotFound,
  33112. const Colour& defaultReturnValue) const throw()
  33113. {
  33114. return Colour ((uint32) getComponentPropertyInt (keyName,
  33115. useParentComponentIfNotFound,
  33116. defaultReturnValue.getARGB()));
  33117. }
  33118. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  33119. {
  33120. if (propertySet_ == 0)
  33121. propertySet_ = new PropertySet();
  33122. propertySet_->setValue (keyName, value);
  33123. }
  33124. void Component::setComponentProperty (const String& keyName, const int value) throw()
  33125. {
  33126. if (propertySet_ == 0)
  33127. propertySet_ = new PropertySet();
  33128. propertySet_->setValue (keyName, value);
  33129. }
  33130. void Component::setComponentProperty (const String& keyName, const double value) throw()
  33131. {
  33132. if (propertySet_ == 0)
  33133. propertySet_ = new PropertySet();
  33134. propertySet_->setValue (keyName, value);
  33135. }
  33136. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  33137. {
  33138. if (propertySet_ == 0)
  33139. propertySet_ = new PropertySet();
  33140. propertySet_->setValue (keyName, value);
  33141. }
  33142. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  33143. {
  33144. setComponentProperty (keyName, (int) colour.getARGB());
  33145. }
  33146. void Component::removeComponentProperty (const String& keyName) throw()
  33147. {
  33148. if (propertySet_ != 0)
  33149. propertySet_->removeValue (keyName);
  33150. }
  33151. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  33152. : componentToWatch (componentToWatch_),
  33153. componentUID (componentToWatch_->getComponentUID())
  33154. {
  33155. // not possible to check on an already-deleted object..
  33156. jassert (componentToWatch_->isValidComponent());
  33157. }
  33158. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  33159. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  33160. {
  33161. return ! (componentToWatch->isValidComponent()
  33162. && componentToWatch->getComponentUID() == componentUID);
  33163. }
  33164. const Component* ComponentDeletionWatcher::getComponent() const throw()
  33165. {
  33166. return hasBeenDeleted() ? 0 : componentToWatch;
  33167. }
  33168. END_JUCE_NAMESPACE
  33169. /********* End of inlined file: juce_Component.cpp *********/
  33170. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  33171. BEGIN_JUCE_NAMESPACE
  33172. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  33173. {
  33174. }
  33175. void ComponentListener::componentBroughtToFront (Component&)
  33176. {
  33177. }
  33178. void ComponentListener::componentVisibilityChanged (Component&)
  33179. {
  33180. }
  33181. void ComponentListener::componentChildrenChanged (Component&)
  33182. {
  33183. }
  33184. void ComponentListener::componentParentHierarchyChanged (Component&)
  33185. {
  33186. }
  33187. void ComponentListener::componentNameChanged (Component&)
  33188. {
  33189. }
  33190. END_JUCE_NAMESPACE
  33191. /********* End of inlined file: juce_ComponentListener.cpp *********/
  33192. /********* Start of inlined file: juce_Desktop.cpp *********/
  33193. BEGIN_JUCE_NAMESPACE
  33194. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  33195. const bool clipToWorkArea) throw();
  33196. static Desktop* juce_desktopInstance = 0;
  33197. Desktop::Desktop() throw()
  33198. : mouseListeners (2),
  33199. desktopComponents (4),
  33200. monitorCoordsClipped (2),
  33201. monitorCoordsUnclipped (2),
  33202. lastMouseX (0),
  33203. lastMouseY (0),
  33204. kioskModeComponent (0)
  33205. {
  33206. refreshMonitorSizes();
  33207. }
  33208. Desktop::~Desktop() throw()
  33209. {
  33210. jassert (juce_desktopInstance == this);
  33211. juce_desktopInstance = 0;
  33212. // doh! If you don't delete all your windows before exiting, you're going to
  33213. // be leaking memory!
  33214. jassert (desktopComponents.size() == 0);
  33215. }
  33216. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  33217. {
  33218. if (juce_desktopInstance == 0)
  33219. juce_desktopInstance = new Desktop();
  33220. return *juce_desktopInstance;
  33221. }
  33222. void Desktop::refreshMonitorSizes() throw()
  33223. {
  33224. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  33225. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  33226. monitorCoordsClipped.clear();
  33227. monitorCoordsUnclipped.clear();
  33228. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  33229. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  33230. jassert (monitorCoordsClipped.size() > 0
  33231. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  33232. if (oldClipped != monitorCoordsClipped
  33233. || oldUnclipped != monitorCoordsUnclipped)
  33234. {
  33235. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  33236. {
  33237. ComponentPeer* const p = ComponentPeer::getPeer (i);
  33238. if (p != 0)
  33239. p->handleScreenSizeChange();
  33240. }
  33241. }
  33242. }
  33243. int Desktop::getNumDisplayMonitors() const throw()
  33244. {
  33245. return monitorCoordsClipped.size();
  33246. }
  33247. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  33248. {
  33249. return clippedToWorkArea ? monitorCoordsClipped [index]
  33250. : monitorCoordsUnclipped [index];
  33251. }
  33252. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  33253. {
  33254. RectangleList rl;
  33255. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  33256. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33257. return rl;
  33258. }
  33259. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  33260. {
  33261. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  33262. }
  33263. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  33264. {
  33265. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  33266. double bestDistance = 1.0e10;
  33267. for (int i = getNumDisplayMonitors(); --i >= 0;)
  33268. {
  33269. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  33270. if (rect.contains (cx, cy))
  33271. return rect;
  33272. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  33273. (double) (rect.getCentreY() - cy));
  33274. if (distance < bestDistance)
  33275. {
  33276. bestDistance = distance;
  33277. best = rect;
  33278. }
  33279. }
  33280. return best;
  33281. }
  33282. int Desktop::getNumComponents() const throw()
  33283. {
  33284. return desktopComponents.size();
  33285. }
  33286. Component* Desktop::getComponent (const int index) const throw()
  33287. {
  33288. return (Component*) desktopComponents [index];
  33289. }
  33290. Component* Desktop::findComponentAt (const int screenX,
  33291. const int screenY) const
  33292. {
  33293. for (int i = desktopComponents.size(); --i >= 0;)
  33294. {
  33295. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  33296. int x = screenX, y = screenY;
  33297. c->globalPositionToRelative (x, y);
  33298. if (c->contains (x, y))
  33299. return c->getComponentAt (x, y);
  33300. }
  33301. return 0;
  33302. }
  33303. void Desktop::addDesktopComponent (Component* const c) throw()
  33304. {
  33305. jassert (c != 0);
  33306. jassert (! desktopComponents.contains (c));
  33307. desktopComponents.addIfNotAlreadyThere (c);
  33308. }
  33309. void Desktop::removeDesktopComponent (Component* const c) throw()
  33310. {
  33311. desktopComponents.removeValue (c);
  33312. }
  33313. void Desktop::componentBroughtToFront (Component* const c) throw()
  33314. {
  33315. const int index = desktopComponents.indexOf (c);
  33316. jassert (index >= 0);
  33317. if (index >= 0)
  33318. desktopComponents.move (index, -1);
  33319. }
  33320. // from Component.cpp
  33321. extern int juce_recentMouseDownX [4];
  33322. extern int juce_recentMouseDownY [4];
  33323. extern int juce_MouseClickCounter;
  33324. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  33325. {
  33326. x = juce_recentMouseDownX [0];
  33327. y = juce_recentMouseDownY [0];
  33328. }
  33329. int Desktop::getMouseButtonClickCounter() throw()
  33330. {
  33331. return juce_MouseClickCounter;
  33332. }
  33333. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  33334. {
  33335. jassert (listener != 0);
  33336. if (listener != 0)
  33337. {
  33338. mouseListeners.add (listener);
  33339. resetTimer();
  33340. }
  33341. }
  33342. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  33343. {
  33344. mouseListeners.removeValue (listener);
  33345. resetTimer();
  33346. }
  33347. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  33348. {
  33349. jassert (listener != 0);
  33350. if (listener != 0)
  33351. focusListeners.add (listener);
  33352. }
  33353. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  33354. {
  33355. focusListeners.removeValue (listener);
  33356. }
  33357. void Desktop::triggerFocusCallback() throw()
  33358. {
  33359. triggerAsyncUpdate();
  33360. }
  33361. void Desktop::handleAsyncUpdate()
  33362. {
  33363. for (int i = focusListeners.size(); --i >= 0;)
  33364. {
  33365. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  33366. i = jmin (i, focusListeners.size());
  33367. }
  33368. }
  33369. void Desktop::timerCallback()
  33370. {
  33371. int x, y;
  33372. getMousePosition (x, y);
  33373. if (lastMouseX != x || lastMouseY != y)
  33374. sendMouseMove();
  33375. }
  33376. void Desktop::sendMouseMove()
  33377. {
  33378. if (mouseListeners.size() > 0)
  33379. {
  33380. startTimer (20);
  33381. int x, y;
  33382. getMousePosition (x, y);
  33383. lastMouseX = x;
  33384. lastMouseY = y;
  33385. Component* const target = findComponentAt (x, y);
  33386. if (target != 0)
  33387. {
  33388. target->globalPositionToRelative (x, y);
  33389. ComponentDeletionWatcher deletionChecker (target);
  33390. const MouseEvent me (x, y,
  33391. ModifierKeys::getCurrentModifiers(),
  33392. target,
  33393. Time::getCurrentTime(),
  33394. x, y,
  33395. Time::getCurrentTime(),
  33396. 0, false);
  33397. for (int i = mouseListeners.size(); --i >= 0;)
  33398. {
  33399. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  33400. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  33401. else
  33402. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  33403. if (deletionChecker.hasBeenDeleted())
  33404. return;
  33405. i = jmin (i, mouseListeners.size());
  33406. }
  33407. }
  33408. }
  33409. }
  33410. void Desktop::resetTimer() throw()
  33411. {
  33412. if (mouseListeners.size() == 0)
  33413. stopTimer();
  33414. else
  33415. startTimer (100);
  33416. getMousePosition (lastMouseX, lastMouseY);
  33417. }
  33418. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  33419. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  33420. {
  33421. if (kioskModeComponent != componentToUse)
  33422. {
  33423. // agh! Don't delete a component without first stopping it being the kiosk comp
  33424. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  33425. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  33426. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  33427. if (kioskModeComponent->isValidComponent())
  33428. {
  33429. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  33430. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  33431. }
  33432. kioskModeComponent = componentToUse;
  33433. if (kioskModeComponent != 0)
  33434. {
  33435. jassert (kioskModeComponent->isValidComponent());
  33436. // Only components that are already on the desktop can be put into kiosk mode!
  33437. jassert (kioskModeComponent->isOnDesktop());
  33438. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  33439. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  33440. }
  33441. }
  33442. }
  33443. END_JUCE_NAMESPACE
  33444. /********* End of inlined file: juce_Desktop.cpp *********/
  33445. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  33446. BEGIN_JUCE_NAMESPACE
  33447. ArrowButton::ArrowButton (const String& name,
  33448. float arrowDirectionInRadians,
  33449. const Colour& arrowColour)
  33450. : Button (name),
  33451. colour (arrowColour)
  33452. {
  33453. path.lineTo (0.0f, 1.0f);
  33454. path.lineTo (1.0f, 0.5f);
  33455. path.closeSubPath();
  33456. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  33457. 0.5f, 0.5f));
  33458. setComponentEffect (&shadow);
  33459. buttonStateChanged();
  33460. }
  33461. ArrowButton::~ArrowButton()
  33462. {
  33463. }
  33464. void ArrowButton::paintButton (Graphics& g,
  33465. bool /*isMouseOverButton*/,
  33466. bool /*isButtonDown*/)
  33467. {
  33468. g.setColour (colour);
  33469. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  33470. (float) offset,
  33471. (float) (getWidth() - 3),
  33472. (float) (getHeight() - 3),
  33473. false));
  33474. }
  33475. void ArrowButton::buttonStateChanged()
  33476. {
  33477. offset = (isDown()) ? 1 : 0;
  33478. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  33479. 0.3f, -1, 0);
  33480. }
  33481. END_JUCE_NAMESPACE
  33482. /********* End of inlined file: juce_ArrowButton.cpp *********/
  33483. /********* Start of inlined file: juce_Button.cpp *********/
  33484. BEGIN_JUCE_NAMESPACE
  33485. Button::Button (const String& name)
  33486. : Component (name),
  33487. shortcuts (2),
  33488. keySource (0),
  33489. text (name),
  33490. buttonListeners (2),
  33491. repeatTimer (0),
  33492. buttonPressTime (0),
  33493. lastTimeCallbackTime (0),
  33494. commandManagerToUse (0),
  33495. autoRepeatDelay (-1),
  33496. autoRepeatSpeed (0),
  33497. autoRepeatMinimumDelay (-1),
  33498. radioGroupId (0),
  33499. commandID (0),
  33500. connectedEdgeFlags (0),
  33501. buttonState (buttonNormal),
  33502. isOn (false),
  33503. clickTogglesState (false),
  33504. needsToRelease (false),
  33505. needsRepainting (false),
  33506. isKeyDown (false),
  33507. triggerOnMouseDown (false),
  33508. generateTooltip (false)
  33509. {
  33510. setWantsKeyboardFocus (true);
  33511. }
  33512. Button::~Button()
  33513. {
  33514. if (commandManagerToUse != 0)
  33515. commandManagerToUse->removeListener (this);
  33516. delete repeatTimer;
  33517. clearShortcuts();
  33518. }
  33519. void Button::setButtonText (const String& newText) throw()
  33520. {
  33521. if (text != newText)
  33522. {
  33523. text = newText;
  33524. repaint();
  33525. }
  33526. }
  33527. void Button::setTooltip (const String& newTooltip)
  33528. {
  33529. SettableTooltipClient::setTooltip (newTooltip);
  33530. generateTooltip = false;
  33531. }
  33532. const String Button::getTooltip()
  33533. {
  33534. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  33535. {
  33536. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  33537. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  33538. for (int i = 0; i < keyPresses.size(); ++i)
  33539. {
  33540. const String key (keyPresses.getReference(i).getTextDescription());
  33541. if (key.length() == 1)
  33542. tt << " [shortcut: '" << key << "']";
  33543. else
  33544. tt << " [" << key << ']';
  33545. }
  33546. return tt;
  33547. }
  33548. return SettableTooltipClient::getTooltip();
  33549. }
  33550. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  33551. {
  33552. if (connectedEdgeFlags != connectedEdgeFlags_)
  33553. {
  33554. connectedEdgeFlags = connectedEdgeFlags_;
  33555. repaint();
  33556. }
  33557. }
  33558. void Button::setToggleState (const bool shouldBeOn,
  33559. const bool sendChangeNotification)
  33560. {
  33561. if (shouldBeOn != isOn)
  33562. {
  33563. const ComponentDeletionWatcher deletionWatcher (this);
  33564. isOn = shouldBeOn;
  33565. repaint();
  33566. if (sendChangeNotification)
  33567. sendClickMessage (ModifierKeys());
  33568. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  33569. turnOffOtherButtonsInGroup (sendChangeNotification);
  33570. }
  33571. }
  33572. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  33573. {
  33574. clickTogglesState = shouldToggle;
  33575. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33576. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33577. // it is that this button represents, and the button will update its state to reflect this
  33578. // in the applicationCommandListChanged() method.
  33579. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33580. }
  33581. bool Button::getClickingTogglesState() const throw()
  33582. {
  33583. return clickTogglesState;
  33584. }
  33585. void Button::setRadioGroupId (const int newGroupId)
  33586. {
  33587. if (radioGroupId != newGroupId)
  33588. {
  33589. radioGroupId = newGroupId;
  33590. if (isOn)
  33591. turnOffOtherButtonsInGroup (true);
  33592. }
  33593. }
  33594. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  33595. {
  33596. Component* const p = getParentComponent();
  33597. if (p != 0 && radioGroupId != 0)
  33598. {
  33599. const ComponentDeletionWatcher deletionWatcher (this);
  33600. for (int i = p->getNumChildComponents(); --i >= 0;)
  33601. {
  33602. Component* const c = p->getChildComponent (i);
  33603. if (c != this)
  33604. {
  33605. Button* const b = dynamic_cast <Button*> (c);
  33606. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  33607. {
  33608. b->setToggleState (false, sendChangeNotification);
  33609. if (deletionWatcher.hasBeenDeleted())
  33610. return;
  33611. }
  33612. }
  33613. }
  33614. }
  33615. }
  33616. void Button::enablementChanged()
  33617. {
  33618. updateState (0);
  33619. repaint();
  33620. }
  33621. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  33622. {
  33623. ButtonState state = buttonNormal;
  33624. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  33625. {
  33626. int mx, my;
  33627. if (e == 0)
  33628. {
  33629. getMouseXYRelative (mx, my);
  33630. }
  33631. else
  33632. {
  33633. const MouseEvent e2 (e->getEventRelativeTo (this));
  33634. mx = e2.x;
  33635. my = e2.y;
  33636. }
  33637. const bool over = reallyContains (mx, my, true);
  33638. const bool down = isMouseButtonDown();
  33639. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  33640. state = buttonDown;
  33641. else if (over)
  33642. state = buttonOver;
  33643. }
  33644. setState (state);
  33645. return state;
  33646. }
  33647. void Button::setState (const ButtonState newState)
  33648. {
  33649. if (buttonState != newState)
  33650. {
  33651. buttonState = newState;
  33652. repaint();
  33653. if (buttonState == buttonDown)
  33654. {
  33655. buttonPressTime = Time::getApproximateMillisecondCounter();
  33656. lastTimeCallbackTime = buttonPressTime;
  33657. }
  33658. sendStateMessage();
  33659. }
  33660. }
  33661. bool Button::isDown() const throw()
  33662. {
  33663. return buttonState == buttonDown;
  33664. }
  33665. bool Button::isOver() const throw()
  33666. {
  33667. return buttonState != buttonNormal;
  33668. }
  33669. void Button::buttonStateChanged()
  33670. {
  33671. }
  33672. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  33673. {
  33674. const uint32 now = Time::getApproximateMillisecondCounter();
  33675. return now > buttonPressTime ? now - buttonPressTime : 0;
  33676. }
  33677. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  33678. {
  33679. triggerOnMouseDown = isTriggeredOnMouseDown;
  33680. }
  33681. void Button::clicked()
  33682. {
  33683. }
  33684. void Button::clicked (const ModifierKeys& /*modifiers*/)
  33685. {
  33686. clicked();
  33687. }
  33688. static const int clickMessageId = 0x2f3f4f99;
  33689. void Button::triggerClick()
  33690. {
  33691. postCommandMessage (clickMessageId);
  33692. }
  33693. void Button::internalClickCallback (const ModifierKeys& modifiers)
  33694. {
  33695. if (clickTogglesState)
  33696. setToggleState ((radioGroupId != 0) || ! isOn, false);
  33697. sendClickMessage (modifiers);
  33698. }
  33699. void Button::flashButtonState() throw()
  33700. {
  33701. if (isEnabled())
  33702. {
  33703. needsToRelease = true;
  33704. setState (buttonDown);
  33705. getRepeatTimer().startTimer (100);
  33706. }
  33707. }
  33708. void Button::handleCommandMessage (int commandId)
  33709. {
  33710. if (commandId == clickMessageId)
  33711. {
  33712. if (isEnabled())
  33713. {
  33714. flashButtonState();
  33715. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33716. }
  33717. }
  33718. else
  33719. {
  33720. Component::handleCommandMessage (commandId);
  33721. }
  33722. }
  33723. void Button::addButtonListener (ButtonListener* const newListener) throw()
  33724. {
  33725. jassert (newListener != 0);
  33726. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  33727. if (newListener != 0)
  33728. buttonListeners.add (newListener);
  33729. }
  33730. void Button::removeButtonListener (ButtonListener* const listener) throw()
  33731. {
  33732. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  33733. buttonListeners.removeValue (listener);
  33734. }
  33735. void Button::sendClickMessage (const ModifierKeys& modifiers)
  33736. {
  33737. const ComponentDeletionWatcher cdw (this);
  33738. if (commandManagerToUse != 0 && commandID != 0)
  33739. {
  33740. ApplicationCommandTarget::InvocationInfo info (commandID);
  33741. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  33742. info.originatingComponent = this;
  33743. commandManagerToUse->invoke (info, true);
  33744. }
  33745. clicked (modifiers);
  33746. if (! cdw.hasBeenDeleted())
  33747. {
  33748. for (int i = buttonListeners.size(); --i >= 0;)
  33749. {
  33750. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33751. if (bl != 0)
  33752. {
  33753. bl->buttonClicked (this);
  33754. if (cdw.hasBeenDeleted())
  33755. return;
  33756. }
  33757. }
  33758. }
  33759. }
  33760. void Button::sendStateMessage()
  33761. {
  33762. const ComponentDeletionWatcher cdw (this);
  33763. buttonStateChanged();
  33764. if (cdw.hasBeenDeleted())
  33765. return;
  33766. for (int i = buttonListeners.size(); --i >= 0;)
  33767. {
  33768. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  33769. if (bl != 0)
  33770. {
  33771. bl->buttonStateChanged (this);
  33772. if (cdw.hasBeenDeleted())
  33773. return;
  33774. }
  33775. }
  33776. }
  33777. void Button::paint (Graphics& g)
  33778. {
  33779. if (needsToRelease && isEnabled())
  33780. {
  33781. needsToRelease = false;
  33782. needsRepainting = true;
  33783. }
  33784. paintButton (g, isOver(), isDown());
  33785. }
  33786. void Button::mouseEnter (const MouseEvent& e)
  33787. {
  33788. updateState (&e);
  33789. }
  33790. void Button::mouseExit (const MouseEvent& e)
  33791. {
  33792. updateState (&e);
  33793. }
  33794. void Button::mouseDown (const MouseEvent& e)
  33795. {
  33796. updateState (&e);
  33797. if (isDown())
  33798. {
  33799. if (autoRepeatDelay >= 0)
  33800. getRepeatTimer().startTimer (autoRepeatDelay);
  33801. if (triggerOnMouseDown)
  33802. internalClickCallback (e.mods);
  33803. }
  33804. }
  33805. void Button::mouseUp (const MouseEvent& e)
  33806. {
  33807. const bool wasDown = isDown();
  33808. updateState (&e);
  33809. if (wasDown && isOver() && ! triggerOnMouseDown)
  33810. internalClickCallback (e.mods);
  33811. }
  33812. void Button::mouseDrag (const MouseEvent& e)
  33813. {
  33814. const ButtonState oldState = buttonState;
  33815. updateState (&e);
  33816. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  33817. getRepeatTimer().startTimer (autoRepeatSpeed);
  33818. }
  33819. void Button::focusGained (FocusChangeType)
  33820. {
  33821. updateState (0);
  33822. repaint();
  33823. }
  33824. void Button::focusLost (FocusChangeType)
  33825. {
  33826. updateState (0);
  33827. repaint();
  33828. }
  33829. void Button::setVisible (bool shouldBeVisible)
  33830. {
  33831. if (shouldBeVisible != isVisible())
  33832. {
  33833. Component::setVisible (shouldBeVisible);
  33834. if (! shouldBeVisible)
  33835. needsToRelease = false;
  33836. updateState (0);
  33837. }
  33838. else
  33839. {
  33840. Component::setVisible (shouldBeVisible);
  33841. }
  33842. }
  33843. void Button::parentHierarchyChanged()
  33844. {
  33845. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  33846. if (newKeySource != keySource)
  33847. {
  33848. if (keySource->isValidComponent())
  33849. keySource->removeKeyListener (this);
  33850. keySource = newKeySource;
  33851. if (keySource->isValidComponent())
  33852. keySource->addKeyListener (this);
  33853. }
  33854. }
  33855. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  33856. const int commandID_,
  33857. const bool generateTooltip_)
  33858. {
  33859. commandID = commandID_;
  33860. generateTooltip = generateTooltip_;
  33861. if (commandManagerToUse != commandManagerToUse_)
  33862. {
  33863. if (commandManagerToUse != 0)
  33864. commandManagerToUse->removeListener (this);
  33865. commandManagerToUse = commandManagerToUse_;
  33866. if (commandManagerToUse != 0)
  33867. commandManagerToUse->addListener (this);
  33868. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  33869. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  33870. // it is that this button represents, and the button will update its state to reflect this
  33871. // in the applicationCommandListChanged() method.
  33872. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  33873. }
  33874. if (commandManagerToUse != 0)
  33875. applicationCommandListChanged();
  33876. else
  33877. setEnabled (true);
  33878. }
  33879. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  33880. {
  33881. if (info.commandID == commandID
  33882. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  33883. {
  33884. flashButtonState();
  33885. }
  33886. }
  33887. void Button::applicationCommandListChanged()
  33888. {
  33889. if (commandManagerToUse != 0)
  33890. {
  33891. ApplicationCommandInfo info (0);
  33892. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  33893. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  33894. if (target != 0)
  33895. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  33896. }
  33897. }
  33898. void Button::addShortcut (const KeyPress& key)
  33899. {
  33900. if (key.isValid())
  33901. {
  33902. jassert (! isRegisteredForShortcut (key)); // already registered!
  33903. shortcuts.add (key);
  33904. parentHierarchyChanged();
  33905. }
  33906. }
  33907. void Button::clearShortcuts()
  33908. {
  33909. shortcuts.clear();
  33910. parentHierarchyChanged();
  33911. }
  33912. bool Button::isShortcutPressed() const throw()
  33913. {
  33914. if (! isCurrentlyBlockedByAnotherModalComponent())
  33915. {
  33916. for (int i = shortcuts.size(); --i >= 0;)
  33917. if (shortcuts.getReference(i).isCurrentlyDown())
  33918. return true;
  33919. }
  33920. return false;
  33921. }
  33922. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  33923. {
  33924. for (int i = shortcuts.size(); --i >= 0;)
  33925. if (key == shortcuts.getReference(i))
  33926. return true;
  33927. return false;
  33928. }
  33929. bool Button::keyStateChanged (const bool, Component*)
  33930. {
  33931. if (! isEnabled())
  33932. return false;
  33933. const bool wasDown = isKeyDown;
  33934. isKeyDown = isShortcutPressed();
  33935. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  33936. getRepeatTimer().startTimer (autoRepeatDelay);
  33937. updateState (0);
  33938. if (isEnabled() && wasDown && ! isKeyDown)
  33939. {
  33940. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33941. // (return immediately - this button may now have been deleted)
  33942. return true;
  33943. }
  33944. return wasDown || isKeyDown;
  33945. }
  33946. bool Button::keyPressed (const KeyPress&, Component*)
  33947. {
  33948. // returning true will avoid forwarding events for keys that we're using as shortcuts
  33949. return isShortcutPressed();
  33950. }
  33951. bool Button::keyPressed (const KeyPress& key)
  33952. {
  33953. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  33954. {
  33955. triggerClick();
  33956. return true;
  33957. }
  33958. return false;
  33959. }
  33960. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  33961. const int repeatMillisecs,
  33962. const int minimumDelayInMillisecs) throw()
  33963. {
  33964. autoRepeatDelay = initialDelayMillisecs;
  33965. autoRepeatSpeed = repeatMillisecs;
  33966. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  33967. }
  33968. void Button::repeatTimerCallback() throw()
  33969. {
  33970. if (needsRepainting)
  33971. {
  33972. getRepeatTimer().stopTimer();
  33973. updateState (0);
  33974. needsRepainting = false;
  33975. }
  33976. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  33977. {
  33978. int repeatSpeed = autoRepeatSpeed;
  33979. if (autoRepeatMinimumDelay >= 0)
  33980. {
  33981. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  33982. timeHeldDown *= timeHeldDown;
  33983. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  33984. }
  33985. repeatSpeed = jmax (1, repeatSpeed);
  33986. getRepeatTimer().startTimer (repeatSpeed);
  33987. const uint32 now = Time::getApproximateMillisecondCounter();
  33988. const int numTimesToCallback
  33989. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  33990. lastTimeCallbackTime = now;
  33991. const ComponentDeletionWatcher cdw (this);
  33992. for (int i = numTimesToCallback; --i >= 0;)
  33993. {
  33994. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33995. if (cdw.hasBeenDeleted() || ! isDown())
  33996. return;
  33997. }
  33998. }
  33999. else if (! needsToRelease)
  34000. {
  34001. getRepeatTimer().stopTimer();
  34002. }
  34003. }
  34004. class InternalButtonRepeatTimer : public Timer
  34005. {
  34006. public:
  34007. InternalButtonRepeatTimer (Button& owner_) throw()
  34008. : owner (owner_)
  34009. {
  34010. }
  34011. ~InternalButtonRepeatTimer()
  34012. {
  34013. }
  34014. void timerCallback()
  34015. {
  34016. owner.repeatTimerCallback();
  34017. }
  34018. private:
  34019. Button& owner;
  34020. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  34021. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  34022. };
  34023. Timer& Button::getRepeatTimer() throw()
  34024. {
  34025. if (repeatTimer == 0)
  34026. repeatTimer = new InternalButtonRepeatTimer (*this);
  34027. return *repeatTimer;
  34028. }
  34029. END_JUCE_NAMESPACE
  34030. /********* End of inlined file: juce_Button.cpp *********/
  34031. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  34032. BEGIN_JUCE_NAMESPACE
  34033. DrawableButton::DrawableButton (const String& name,
  34034. const DrawableButton::ButtonStyle buttonStyle)
  34035. : Button (name),
  34036. style (buttonStyle),
  34037. normalImage (0),
  34038. overImage (0),
  34039. downImage (0),
  34040. disabledImage (0),
  34041. normalImageOn (0),
  34042. overImageOn (0),
  34043. downImageOn (0),
  34044. disabledImageOn (0),
  34045. edgeIndent (3)
  34046. {
  34047. if (buttonStyle == ImageOnButtonBackground)
  34048. {
  34049. backgroundOff = Colour (0xffbbbbff);
  34050. backgroundOn = Colour (0xff3333ff);
  34051. }
  34052. else
  34053. {
  34054. backgroundOff = Colours::transparentBlack;
  34055. backgroundOn = Colour (0xaabbbbff);
  34056. }
  34057. }
  34058. DrawableButton::~DrawableButton()
  34059. {
  34060. deleteImages();
  34061. }
  34062. void DrawableButton::deleteImages()
  34063. {
  34064. deleteAndZero (normalImage);
  34065. deleteAndZero (overImage);
  34066. deleteAndZero (downImage);
  34067. deleteAndZero (disabledImage);
  34068. deleteAndZero (normalImageOn);
  34069. deleteAndZero (overImageOn);
  34070. deleteAndZero (downImageOn);
  34071. deleteAndZero (disabledImageOn);
  34072. }
  34073. void DrawableButton::setImages (const Drawable* normal,
  34074. const Drawable* over,
  34075. const Drawable* down,
  34076. const Drawable* disabled,
  34077. const Drawable* normalOn,
  34078. const Drawable* overOn,
  34079. const Drawable* downOn,
  34080. const Drawable* disabledOn)
  34081. {
  34082. deleteImages();
  34083. jassert (normal != 0); // you really need to give it at least a normal image..
  34084. if (normal != 0)
  34085. normalImage = normal->createCopy();
  34086. if (over != 0)
  34087. overImage = over->createCopy();
  34088. if (down != 0)
  34089. downImage = down->createCopy();
  34090. if (disabled != 0)
  34091. disabledImage = disabled->createCopy();
  34092. if (normalOn != 0)
  34093. normalImageOn = normalOn->createCopy();
  34094. if (overOn != 0)
  34095. overImageOn = overOn->createCopy();
  34096. if (downOn != 0)
  34097. downImageOn = downOn->createCopy();
  34098. if (disabledOn != 0)
  34099. disabledImageOn = disabledOn->createCopy();
  34100. repaint();
  34101. }
  34102. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  34103. {
  34104. if (style != newStyle)
  34105. {
  34106. style = newStyle;
  34107. repaint();
  34108. }
  34109. }
  34110. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  34111. const Colour& toggledOnColour)
  34112. {
  34113. if (backgroundOff != toggledOffColour
  34114. || backgroundOn != toggledOnColour)
  34115. {
  34116. backgroundOff = toggledOffColour;
  34117. backgroundOn = toggledOnColour;
  34118. repaint();
  34119. }
  34120. }
  34121. const Colour& DrawableButton::getBackgroundColour() const throw()
  34122. {
  34123. return getToggleState() ? backgroundOn
  34124. : backgroundOff;
  34125. }
  34126. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  34127. {
  34128. edgeIndent = numPixelsIndent;
  34129. repaint();
  34130. }
  34131. void DrawableButton::paintButton (Graphics& g,
  34132. bool isMouseOverButton,
  34133. bool isButtonDown)
  34134. {
  34135. Rectangle imageSpace;
  34136. if (style == ImageOnButtonBackground)
  34137. {
  34138. const int insetX = getWidth() / 4;
  34139. const int insetY = getHeight() / 4;
  34140. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  34141. getLookAndFeel().drawButtonBackground (g, *this,
  34142. getBackgroundColour(),
  34143. isMouseOverButton,
  34144. isButtonDown);
  34145. }
  34146. else
  34147. {
  34148. g.fillAll (getBackgroundColour());
  34149. const int textH = (style == ImageAboveTextLabel)
  34150. ? jmin (16, proportionOfHeight (0.25f))
  34151. : 0;
  34152. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  34153. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  34154. imageSpace.setBounds (indentX, indentY,
  34155. getWidth() - indentX * 2,
  34156. getHeight() - indentY * 2 - textH);
  34157. if (textH > 0)
  34158. {
  34159. g.setFont ((float) textH);
  34160. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  34161. g.drawFittedText (getButtonText(),
  34162. 2, getHeight() - textH - 1,
  34163. getWidth() - 4, textH,
  34164. Justification::centred, 1);
  34165. }
  34166. }
  34167. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  34168. g.setOpacity (1.0f);
  34169. const Drawable* imageToDraw = 0;
  34170. if (isEnabled())
  34171. {
  34172. imageToDraw = getCurrentImage();
  34173. }
  34174. else
  34175. {
  34176. imageToDraw = getToggleState() ? disabledImageOn
  34177. : disabledImage;
  34178. if (imageToDraw == 0)
  34179. {
  34180. g.setOpacity (0.4f);
  34181. imageToDraw = getNormalImage();
  34182. }
  34183. }
  34184. if (imageToDraw != 0)
  34185. {
  34186. if (style == ImageRaw)
  34187. {
  34188. imageToDraw->draw (g);
  34189. }
  34190. else
  34191. {
  34192. imageToDraw->drawWithin (g,
  34193. imageSpace.getX(),
  34194. imageSpace.getY(),
  34195. imageSpace.getWidth(),
  34196. imageSpace.getHeight(),
  34197. RectanglePlacement::centred);
  34198. }
  34199. }
  34200. }
  34201. const Drawable* DrawableButton::getCurrentImage() const throw()
  34202. {
  34203. if (isDown())
  34204. return getDownImage();
  34205. if (isOver())
  34206. return getOverImage();
  34207. return getNormalImage();
  34208. }
  34209. const Drawable* DrawableButton::getNormalImage() const throw()
  34210. {
  34211. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  34212. : normalImage;
  34213. }
  34214. const Drawable* DrawableButton::getOverImage() const throw()
  34215. {
  34216. const Drawable* d = normalImage;
  34217. if (getToggleState())
  34218. {
  34219. if (overImageOn != 0)
  34220. d = overImageOn;
  34221. else if (normalImageOn != 0)
  34222. d = normalImageOn;
  34223. else if (overImage != 0)
  34224. d = overImage;
  34225. }
  34226. else
  34227. {
  34228. if (overImage != 0)
  34229. d = overImage;
  34230. }
  34231. return d;
  34232. }
  34233. const Drawable* DrawableButton::getDownImage() const throw()
  34234. {
  34235. const Drawable* d = normalImage;
  34236. if (getToggleState())
  34237. {
  34238. if (downImageOn != 0)
  34239. d = downImageOn;
  34240. else if (overImageOn != 0)
  34241. d = overImageOn;
  34242. else if (normalImageOn != 0)
  34243. d = normalImageOn;
  34244. else if (downImage != 0)
  34245. d = downImage;
  34246. else
  34247. d = getOverImage();
  34248. }
  34249. else
  34250. {
  34251. if (downImage != 0)
  34252. d = downImage;
  34253. else
  34254. d = getOverImage();
  34255. }
  34256. return d;
  34257. }
  34258. END_JUCE_NAMESPACE
  34259. /********* End of inlined file: juce_DrawableButton.cpp *********/
  34260. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  34261. BEGIN_JUCE_NAMESPACE
  34262. HyperlinkButton::HyperlinkButton (const String& linkText,
  34263. const URL& linkURL)
  34264. : Button (linkText),
  34265. url (linkURL),
  34266. font (14.0f, Font::underlined),
  34267. resizeFont (true),
  34268. justification (Justification::centred)
  34269. {
  34270. setMouseCursor (MouseCursor::PointingHandCursor);
  34271. setTooltip (linkURL.toString (false));
  34272. }
  34273. HyperlinkButton::~HyperlinkButton()
  34274. {
  34275. }
  34276. void HyperlinkButton::setFont (const Font& newFont,
  34277. const bool resizeToMatchComponentHeight,
  34278. const Justification& justificationType)
  34279. {
  34280. font = newFont;
  34281. resizeFont = resizeToMatchComponentHeight;
  34282. justification = justificationType;
  34283. repaint();
  34284. }
  34285. void HyperlinkButton::setURL (const URL& newURL) throw()
  34286. {
  34287. url = newURL;
  34288. setTooltip (newURL.toString (false));
  34289. }
  34290. const Font HyperlinkButton::getFontToUse() const
  34291. {
  34292. Font f (font);
  34293. if (resizeFont)
  34294. f.setHeight (getHeight() * 0.7f);
  34295. return f;
  34296. }
  34297. void HyperlinkButton::changeWidthToFitText()
  34298. {
  34299. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  34300. }
  34301. void HyperlinkButton::colourChanged()
  34302. {
  34303. repaint();
  34304. }
  34305. void HyperlinkButton::clicked()
  34306. {
  34307. if (url.isWellFormed())
  34308. url.launchInDefaultBrowser();
  34309. }
  34310. void HyperlinkButton::paintButton (Graphics& g,
  34311. bool isMouseOverButton,
  34312. bool isButtonDown)
  34313. {
  34314. const Colour textColour (findColour (textColourId));
  34315. if (isEnabled())
  34316. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  34317. : textColour);
  34318. else
  34319. g.setColour (textColour.withMultipliedAlpha (0.4f));
  34320. g.setFont (getFontToUse());
  34321. g.drawText (getButtonText(),
  34322. 2, 0, getWidth() - 2, getHeight(),
  34323. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  34324. true);
  34325. }
  34326. END_JUCE_NAMESPACE
  34327. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  34328. /********* Start of inlined file: juce_ImageButton.cpp *********/
  34329. BEGIN_JUCE_NAMESPACE
  34330. ImageButton::ImageButton (const String& text_)
  34331. : Button (text_),
  34332. scaleImageToFit (true),
  34333. preserveProportions (true),
  34334. alphaThreshold (0),
  34335. imageX (0),
  34336. imageY (0),
  34337. imageW (0),
  34338. imageH (0),
  34339. normalImage (0),
  34340. overImage (0),
  34341. downImage (0)
  34342. {
  34343. }
  34344. ImageButton::~ImageButton()
  34345. {
  34346. deleteImages();
  34347. }
  34348. void ImageButton::deleteImages()
  34349. {
  34350. if (normalImage != 0)
  34351. {
  34352. if (ImageCache::isImageInCache (normalImage))
  34353. ImageCache::release (normalImage);
  34354. else
  34355. delete normalImage;
  34356. }
  34357. if (overImage != 0)
  34358. {
  34359. if (ImageCache::isImageInCache (overImage))
  34360. ImageCache::release (overImage);
  34361. else
  34362. delete overImage;
  34363. }
  34364. if (downImage != 0)
  34365. {
  34366. if (ImageCache::isImageInCache (downImage))
  34367. ImageCache::release (downImage);
  34368. else
  34369. delete downImage;
  34370. }
  34371. }
  34372. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  34373. const bool rescaleImagesWhenButtonSizeChanges,
  34374. const bool preserveImageProportions,
  34375. Image* const normalImage_,
  34376. const float imageOpacityWhenNormal,
  34377. const Colour& overlayColourWhenNormal,
  34378. Image* const overImage_,
  34379. const float imageOpacityWhenOver,
  34380. const Colour& overlayColourWhenOver,
  34381. Image* const downImage_,
  34382. const float imageOpacityWhenDown,
  34383. const Colour& overlayColourWhenDown,
  34384. const float hitTestAlphaThreshold)
  34385. {
  34386. deleteImages();
  34387. normalImage = normalImage_;
  34388. overImage = overImage_;
  34389. downImage = downImage_;
  34390. if (resizeButtonNowToFitThisImage && normalImage != 0)
  34391. {
  34392. imageW = normalImage->getWidth();
  34393. imageH = normalImage->getHeight();
  34394. setSize (imageW, imageH);
  34395. }
  34396. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  34397. preserveProportions = preserveImageProportions;
  34398. normalOpacity = imageOpacityWhenNormal;
  34399. normalOverlay = overlayColourWhenNormal;
  34400. overOpacity = imageOpacityWhenOver;
  34401. overOverlay = overlayColourWhenOver;
  34402. downOpacity = imageOpacityWhenDown;
  34403. downOverlay = overlayColourWhenDown;
  34404. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  34405. repaint();
  34406. }
  34407. Image* ImageButton::getCurrentImage() const
  34408. {
  34409. if (isDown() || getToggleState())
  34410. return getDownImage();
  34411. if (isOver())
  34412. return getOverImage();
  34413. return getNormalImage();
  34414. }
  34415. Image* ImageButton::getNormalImage() const throw()
  34416. {
  34417. return normalImage;
  34418. }
  34419. Image* ImageButton::getOverImage() const throw()
  34420. {
  34421. return (overImage != 0) ? overImage
  34422. : normalImage;
  34423. }
  34424. Image* ImageButton::getDownImage() const throw()
  34425. {
  34426. return (downImage != 0) ? downImage
  34427. : getOverImage();
  34428. }
  34429. void ImageButton::paintButton (Graphics& g,
  34430. bool isMouseOverButton,
  34431. bool isButtonDown)
  34432. {
  34433. if (! isEnabled())
  34434. {
  34435. isMouseOverButton = false;
  34436. isButtonDown = false;
  34437. }
  34438. Image* const im = getCurrentImage();
  34439. if (im != 0)
  34440. {
  34441. const int iw = im->getWidth();
  34442. const int ih = im->getHeight();
  34443. imageW = getWidth();
  34444. imageH = getHeight();
  34445. imageX = (imageW - iw) >> 1;
  34446. imageY = (imageH - ih) >> 1;
  34447. if (scaleImageToFit)
  34448. {
  34449. if (preserveProportions)
  34450. {
  34451. int newW, newH;
  34452. const float imRatio = ih / (float)iw;
  34453. const float destRatio = imageH / (float)imageW;
  34454. if (imRatio > destRatio)
  34455. {
  34456. newW = roundFloatToInt (imageH / imRatio);
  34457. newH = imageH;
  34458. }
  34459. else
  34460. {
  34461. newW = imageW;
  34462. newH = roundFloatToInt (imageW * imRatio);
  34463. }
  34464. imageX = (imageW - newW) / 2;
  34465. imageY = (imageH - newH) / 2;
  34466. imageW = newW;
  34467. imageH = newH;
  34468. }
  34469. else
  34470. {
  34471. imageX = 0;
  34472. imageY = 0;
  34473. }
  34474. }
  34475. if (! scaleImageToFit)
  34476. {
  34477. imageW = iw;
  34478. imageH = ih;
  34479. }
  34480. getLookAndFeel().drawImageButton (g, im, imageX, imageY, imageW, imageH,
  34481. isButtonDown ? downOverlay
  34482. : (isMouseOverButton ? overOverlay
  34483. : normalOverlay),
  34484. isButtonDown ? downOpacity
  34485. : (isMouseOverButton ? overOpacity
  34486. : normalOpacity),
  34487. *this);
  34488. }
  34489. }
  34490. bool ImageButton::hitTest (int x, int y)
  34491. {
  34492. if (alphaThreshold == 0)
  34493. return true;
  34494. Image* const im = getCurrentImage();
  34495. return im == 0
  34496. || (imageW > 0 && imageH > 0
  34497. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  34498. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  34499. }
  34500. END_JUCE_NAMESPACE
  34501. /********* End of inlined file: juce_ImageButton.cpp *********/
  34502. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  34503. BEGIN_JUCE_NAMESPACE
  34504. ShapeButton::ShapeButton (const String& text,
  34505. const Colour& normalColour_,
  34506. const Colour& overColour_,
  34507. const Colour& downColour_)
  34508. : Button (text),
  34509. normalColour (normalColour_),
  34510. overColour (overColour_),
  34511. downColour (downColour_),
  34512. maintainShapeProportions (false),
  34513. outlineWidth (0.0f)
  34514. {
  34515. }
  34516. ShapeButton::~ShapeButton()
  34517. {
  34518. }
  34519. void ShapeButton::setColours (const Colour& newNormalColour,
  34520. const Colour& newOverColour,
  34521. const Colour& newDownColour)
  34522. {
  34523. normalColour = newNormalColour;
  34524. overColour = newOverColour;
  34525. downColour = newDownColour;
  34526. }
  34527. void ShapeButton::setOutline (const Colour& newOutlineColour,
  34528. const float newOutlineWidth)
  34529. {
  34530. outlineColour = newOutlineColour;
  34531. outlineWidth = newOutlineWidth;
  34532. }
  34533. void ShapeButton::setShape (const Path& newShape,
  34534. const bool resizeNowToFitThisShape,
  34535. const bool maintainShapeProportions_,
  34536. const bool hasShadow)
  34537. {
  34538. shape = newShape;
  34539. maintainShapeProportions = maintainShapeProportions_;
  34540. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  34541. setComponentEffect ((hasShadow) ? &shadow : 0);
  34542. if (resizeNowToFitThisShape)
  34543. {
  34544. float x, y, w, h;
  34545. shape.getBounds (x, y, w, h);
  34546. shape.applyTransform (AffineTransform::translation (-x, -y));
  34547. if (hasShadow)
  34548. {
  34549. w += 4.0f;
  34550. h += 4.0f;
  34551. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  34552. }
  34553. setSize (1 + (int) (w + outlineWidth),
  34554. 1 + (int) (h + outlineWidth));
  34555. }
  34556. }
  34557. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  34558. {
  34559. if (! isEnabled())
  34560. {
  34561. isMouseOverButton = false;
  34562. isButtonDown = false;
  34563. }
  34564. g.setColour ((isButtonDown) ? downColour
  34565. : (isMouseOverButton) ? overColour
  34566. : normalColour);
  34567. int w = getWidth();
  34568. int h = getHeight();
  34569. if (getComponentEffect() != 0)
  34570. {
  34571. w -= 4;
  34572. h -= 4;
  34573. }
  34574. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  34575. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  34576. w - offset - outlineWidth,
  34577. h - offset - outlineWidth,
  34578. maintainShapeProportions));
  34579. g.fillPath (shape, trans);
  34580. if (outlineWidth > 0.0f)
  34581. {
  34582. g.setColour (outlineColour);
  34583. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  34584. }
  34585. }
  34586. END_JUCE_NAMESPACE
  34587. /********* End of inlined file: juce_ShapeButton.cpp *********/
  34588. /********* Start of inlined file: juce_TextButton.cpp *********/
  34589. BEGIN_JUCE_NAMESPACE
  34590. TextButton::TextButton (const String& name,
  34591. const String& toolTip)
  34592. : Button (name)
  34593. {
  34594. setTooltip (toolTip);
  34595. }
  34596. TextButton::~TextButton()
  34597. {
  34598. }
  34599. void TextButton::paintButton (Graphics& g,
  34600. bool isMouseOverButton,
  34601. bool isButtonDown)
  34602. {
  34603. getLookAndFeel().drawButtonBackground (g, *this,
  34604. findColour (getToggleState() ? buttonOnColourId
  34605. : buttonColourId),
  34606. isMouseOverButton,
  34607. isButtonDown);
  34608. getLookAndFeel().drawButtonText (g, *this,
  34609. isMouseOverButton,
  34610. isButtonDown);
  34611. }
  34612. void TextButton::colourChanged()
  34613. {
  34614. repaint();
  34615. }
  34616. const Font TextButton::getFont()
  34617. {
  34618. return Font (jmin (15.0f, getHeight() * 0.6f));
  34619. }
  34620. void TextButton::changeWidthToFitText (const int newHeight)
  34621. {
  34622. if (newHeight >= 0)
  34623. setSize (jmax (1, getWidth()), newHeight);
  34624. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  34625. getHeight());
  34626. }
  34627. END_JUCE_NAMESPACE
  34628. /********* End of inlined file: juce_TextButton.cpp *********/
  34629. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  34630. BEGIN_JUCE_NAMESPACE
  34631. ToggleButton::ToggleButton (const String& buttonText)
  34632. : Button (buttonText)
  34633. {
  34634. setClickingTogglesState (true);
  34635. }
  34636. ToggleButton::~ToggleButton()
  34637. {
  34638. }
  34639. void ToggleButton::paintButton (Graphics& g,
  34640. bool isMouseOverButton,
  34641. bool isButtonDown)
  34642. {
  34643. getLookAndFeel().drawToggleButton (g, *this,
  34644. isMouseOverButton,
  34645. isButtonDown);
  34646. }
  34647. void ToggleButton::changeWidthToFitText()
  34648. {
  34649. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  34650. }
  34651. void ToggleButton::colourChanged()
  34652. {
  34653. repaint();
  34654. }
  34655. END_JUCE_NAMESPACE
  34656. /********* End of inlined file: juce_ToggleButton.cpp *********/
  34657. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  34658. BEGIN_JUCE_NAMESPACE
  34659. ToolbarButton::ToolbarButton (const int itemId_,
  34660. const String& buttonText,
  34661. Drawable* const normalImage_,
  34662. Drawable* const toggledOnImage_)
  34663. : ToolbarItemComponent (itemId_, buttonText, true),
  34664. normalImage (normalImage_),
  34665. toggledOnImage (toggledOnImage_)
  34666. {
  34667. }
  34668. ToolbarButton::~ToolbarButton()
  34669. {
  34670. delete normalImage;
  34671. delete toggledOnImage;
  34672. }
  34673. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  34674. bool /*isToolbarVertical*/,
  34675. int& preferredSize,
  34676. int& minSize, int& maxSize)
  34677. {
  34678. preferredSize = minSize = maxSize = toolbarDepth;
  34679. return true;
  34680. }
  34681. void ToolbarButton::paintButtonArea (Graphics& g,
  34682. int width, int height,
  34683. bool /*isMouseOver*/,
  34684. bool /*isMouseDown*/)
  34685. {
  34686. Drawable* d = normalImage;
  34687. if (getToggleState() && toggledOnImage != 0)
  34688. d = toggledOnImage;
  34689. if (! isEnabled())
  34690. {
  34691. Image im (Image::ARGB, width, height, true);
  34692. Graphics g2 (im);
  34693. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  34694. im.desaturate();
  34695. g.drawImageAt (&im, 0, 0);
  34696. }
  34697. else
  34698. {
  34699. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  34700. }
  34701. }
  34702. void ToolbarButton::contentAreaChanged (const Rectangle&)
  34703. {
  34704. }
  34705. END_JUCE_NAMESPACE
  34706. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  34707. /********* Start of inlined file: juce_ComboBox.cpp *********/
  34708. BEGIN_JUCE_NAMESPACE
  34709. ComboBox::ComboBox (const String& name)
  34710. : Component (name),
  34711. items (4),
  34712. currentIndex (-1),
  34713. isButtonDown (false),
  34714. separatorPending (false),
  34715. menuActive (false),
  34716. listeners (2),
  34717. label (0)
  34718. {
  34719. noChoicesMessage = TRANS("(no choices)");
  34720. setRepaintsOnMouseActivity (true);
  34721. lookAndFeelChanged();
  34722. }
  34723. ComboBox::~ComboBox()
  34724. {
  34725. if (menuActive)
  34726. PopupMenu::dismissAllActiveMenus();
  34727. deleteAllChildren();
  34728. }
  34729. void ComboBox::setEditableText (const bool isEditable)
  34730. {
  34731. label->setEditable (isEditable, isEditable, false);
  34732. setWantsKeyboardFocus (! isEditable);
  34733. resized();
  34734. }
  34735. bool ComboBox::isTextEditable() const throw()
  34736. {
  34737. return label->isEditable();
  34738. }
  34739. void ComboBox::setJustificationType (const Justification& justification) throw()
  34740. {
  34741. label->setJustificationType (justification);
  34742. }
  34743. const Justification ComboBox::getJustificationType() const throw()
  34744. {
  34745. return label->getJustificationType();
  34746. }
  34747. void ComboBox::setTooltip (const String& newTooltip)
  34748. {
  34749. SettableTooltipClient::setTooltip (newTooltip);
  34750. label->setTooltip (newTooltip);
  34751. }
  34752. void ComboBox::addItem (const String& newItemText,
  34753. const int newItemId) throw()
  34754. {
  34755. // you can't add empty strings to the list..
  34756. jassert (newItemText.isNotEmpty());
  34757. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  34758. jassert (newItemId != 0);
  34759. // you shouldn't use duplicate item IDs!
  34760. jassert (getItemForId (newItemId) == 0);
  34761. if (newItemText.isNotEmpty() && newItemId != 0)
  34762. {
  34763. if (separatorPending)
  34764. {
  34765. separatorPending = false;
  34766. ItemInfo* const item = new ItemInfo();
  34767. item->itemId = 0;
  34768. item->isEnabled = false;
  34769. item->isHeading = false;
  34770. items.add (item);
  34771. }
  34772. ItemInfo* const item = new ItemInfo();
  34773. item->name = newItemText;
  34774. item->itemId = newItemId;
  34775. item->isEnabled = true;
  34776. item->isHeading = false;
  34777. items.add (item);
  34778. }
  34779. }
  34780. void ComboBox::addSeparator() throw()
  34781. {
  34782. separatorPending = (items.size() > 0);
  34783. }
  34784. void ComboBox::addSectionHeading (const String& headingName) throw()
  34785. {
  34786. // you can't add empty strings to the list..
  34787. jassert (headingName.isNotEmpty());
  34788. if (headingName.isNotEmpty())
  34789. {
  34790. if (separatorPending)
  34791. {
  34792. separatorPending = false;
  34793. ItemInfo* const item = new ItemInfo();
  34794. item->itemId = 0;
  34795. item->isEnabled = false;
  34796. item->isHeading = false;
  34797. items.add (item);
  34798. }
  34799. ItemInfo* const item = new ItemInfo();
  34800. item->name = headingName;
  34801. item->itemId = 0;
  34802. item->isEnabled = true;
  34803. item->isHeading = true;
  34804. items.add (item);
  34805. }
  34806. }
  34807. void ComboBox::setItemEnabled (const int itemId,
  34808. const bool isEnabled) throw()
  34809. {
  34810. ItemInfo* const item = getItemForId (itemId);
  34811. if (item != 0)
  34812. item->isEnabled = isEnabled;
  34813. }
  34814. void ComboBox::changeItemText (const int itemId,
  34815. const String& newText) throw()
  34816. {
  34817. ItemInfo* const item = getItemForId (itemId);
  34818. jassert (item != 0);
  34819. if (item != 0)
  34820. item->name = newText;
  34821. }
  34822. void ComboBox::clear (const bool dontSendChangeMessage)
  34823. {
  34824. items.clear();
  34825. separatorPending = false;
  34826. if (! label->isEditable())
  34827. setSelectedItemIndex (-1, dontSendChangeMessage);
  34828. }
  34829. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  34830. {
  34831. jassert (itemId != 0);
  34832. if (itemId != 0)
  34833. {
  34834. for (int i = items.size(); --i >= 0;)
  34835. if (items.getUnchecked(i)->itemId == itemId)
  34836. return items.getUnchecked(i);
  34837. }
  34838. return 0;
  34839. }
  34840. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  34841. {
  34842. int n = 0;
  34843. for (int i = 0; i < items.size(); ++i)
  34844. {
  34845. ItemInfo* const item = items.getUnchecked(i);
  34846. if (item->isRealItem())
  34847. {
  34848. if (n++ == index)
  34849. return item;
  34850. }
  34851. }
  34852. return 0;
  34853. }
  34854. int ComboBox::getNumItems() const throw()
  34855. {
  34856. int n = 0;
  34857. for (int i = items.size(); --i >= 0;)
  34858. {
  34859. ItemInfo* const item = items.getUnchecked(i);
  34860. if (item->isRealItem())
  34861. ++n;
  34862. }
  34863. return n;
  34864. }
  34865. const String ComboBox::getItemText (const int index) const throw()
  34866. {
  34867. ItemInfo* const item = getItemForIndex (index);
  34868. if (item != 0)
  34869. return item->name;
  34870. return String::empty;
  34871. }
  34872. int ComboBox::getItemId (const int index) const throw()
  34873. {
  34874. ItemInfo* const item = getItemForIndex (index);
  34875. return (item != 0) ? item->itemId : 0;
  34876. }
  34877. bool ComboBox::ItemInfo::isSeparator() const throw()
  34878. {
  34879. return name.isEmpty();
  34880. }
  34881. bool ComboBox::ItemInfo::isRealItem() const throw()
  34882. {
  34883. return ! (isHeading || name.isEmpty());
  34884. }
  34885. int ComboBox::getSelectedItemIndex() const throw()
  34886. {
  34887. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  34888. ? currentIndex
  34889. : -1;
  34890. }
  34891. void ComboBox::setSelectedItemIndex (const int index,
  34892. const bool dontSendChangeMessage) throw()
  34893. {
  34894. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  34895. {
  34896. if (((unsigned int) index) < (unsigned int) getNumItems())
  34897. currentIndex = index;
  34898. else
  34899. currentIndex = -1;
  34900. label->setText (getItemText (currentIndex), false);
  34901. if (! dontSendChangeMessage)
  34902. triggerAsyncUpdate();
  34903. }
  34904. }
  34905. void ComboBox::setSelectedId (const int newItemId,
  34906. const bool dontSendChangeMessage) throw()
  34907. {
  34908. for (int i = getNumItems(); --i >= 0;)
  34909. {
  34910. if (getItemId(i) == newItemId)
  34911. {
  34912. setSelectedItemIndex (i, dontSendChangeMessage);
  34913. break;
  34914. }
  34915. }
  34916. }
  34917. int ComboBox::getSelectedId() const throw()
  34918. {
  34919. const ItemInfo* const item = getItemForIndex (currentIndex);
  34920. return (item != 0 && getText() == item->name)
  34921. ? item->itemId
  34922. : 0;
  34923. }
  34924. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  34925. {
  34926. jassert (listener != 0);
  34927. if (listener != 0)
  34928. listeners.add (listener);
  34929. }
  34930. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  34931. {
  34932. listeners.removeValue (listener);
  34933. }
  34934. void ComboBox::handleAsyncUpdate()
  34935. {
  34936. for (int i = listeners.size(); --i >= 0;)
  34937. {
  34938. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  34939. i = jmin (i, listeners.size());
  34940. }
  34941. }
  34942. const String ComboBox::getText() const throw()
  34943. {
  34944. return label->getText();
  34945. }
  34946. void ComboBox::setText (const String& newText,
  34947. const bool dontSendChangeMessage) throw()
  34948. {
  34949. for (int i = items.size(); --i >= 0;)
  34950. {
  34951. ItemInfo* const item = items.getUnchecked(i);
  34952. if (item->isRealItem()
  34953. && item->name == newText)
  34954. {
  34955. setSelectedId (item->itemId, dontSendChangeMessage);
  34956. return;
  34957. }
  34958. }
  34959. currentIndex = -1;
  34960. if (label->getText() != newText)
  34961. {
  34962. label->setText (newText, false);
  34963. if (! dontSendChangeMessage)
  34964. triggerAsyncUpdate();
  34965. }
  34966. repaint();
  34967. }
  34968. void ComboBox::showEditor()
  34969. {
  34970. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  34971. label->showEditor();
  34972. }
  34973. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  34974. {
  34975. textWhenNothingSelected = newMessage;
  34976. repaint();
  34977. }
  34978. const String ComboBox::getTextWhenNothingSelected() const throw()
  34979. {
  34980. return textWhenNothingSelected;
  34981. }
  34982. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  34983. {
  34984. noChoicesMessage = newMessage;
  34985. }
  34986. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  34987. {
  34988. return noChoicesMessage;
  34989. }
  34990. void ComboBox::paint (Graphics& g)
  34991. {
  34992. getLookAndFeel().drawComboBox (g,
  34993. getWidth(),
  34994. getHeight(),
  34995. isButtonDown,
  34996. label->getRight(),
  34997. 0,
  34998. getWidth() - label->getRight(),
  34999. getHeight(),
  35000. *this);
  35001. if (textWhenNothingSelected.isNotEmpty()
  35002. && label->getText().isEmpty()
  35003. && ! label->isBeingEdited())
  35004. {
  35005. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  35006. g.setFont (label->getFont());
  35007. g.drawFittedText (textWhenNothingSelected,
  35008. label->getX() + 2, label->getY() + 1,
  35009. label->getWidth() - 4, label->getHeight() - 2,
  35010. label->getJustificationType(),
  35011. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  35012. }
  35013. }
  35014. void ComboBox::resized()
  35015. {
  35016. if (getHeight() > 0 && getWidth() > 0)
  35017. getLookAndFeel().positionComboBoxText (*this, *label);
  35018. }
  35019. void ComboBox::enablementChanged()
  35020. {
  35021. repaint();
  35022. }
  35023. void ComboBox::lookAndFeelChanged()
  35024. {
  35025. repaint();
  35026. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  35027. if (label != 0)
  35028. {
  35029. newLabel->setEditable (label->isEditable());
  35030. newLabel->setJustificationType (label->getJustificationType());
  35031. newLabel->setTooltip (label->getTooltip());
  35032. newLabel->setText (label->getText(), false);
  35033. }
  35034. delete label;
  35035. label = newLabel;
  35036. addAndMakeVisible (newLabel);
  35037. newLabel->addListener (this);
  35038. newLabel->addMouseListener (this, false);
  35039. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  35040. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  35041. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  35042. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35043. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  35044. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35045. resized();
  35046. }
  35047. void ComboBox::colourChanged()
  35048. {
  35049. lookAndFeelChanged();
  35050. }
  35051. bool ComboBox::keyPressed (const KeyPress& key)
  35052. {
  35053. bool used = false;
  35054. if (key.isKeyCode (KeyPress::upKey)
  35055. || key.isKeyCode (KeyPress::leftKey))
  35056. {
  35057. setSelectedItemIndex (jmax (0, currentIndex - 1));
  35058. used = true;
  35059. }
  35060. else if (key.isKeyCode (KeyPress::downKey)
  35061. || key.isKeyCode (KeyPress::rightKey))
  35062. {
  35063. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  35064. used = true;
  35065. }
  35066. else if (key.isKeyCode (KeyPress::returnKey))
  35067. {
  35068. showPopup();
  35069. used = true;
  35070. }
  35071. return used;
  35072. }
  35073. bool ComboBox::keyStateChanged (const bool isKeyDown)
  35074. {
  35075. // only forward key events that aren't used by this component
  35076. return isKeyDown
  35077. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35078. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  35079. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35080. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  35081. }
  35082. void ComboBox::focusGained (FocusChangeType)
  35083. {
  35084. repaint();
  35085. }
  35086. void ComboBox::focusLost (FocusChangeType)
  35087. {
  35088. repaint();
  35089. }
  35090. void ComboBox::labelTextChanged (Label*)
  35091. {
  35092. triggerAsyncUpdate();
  35093. }
  35094. void ComboBox::showPopup()
  35095. {
  35096. if (! menuActive)
  35097. {
  35098. const int currentId = getSelectedId();
  35099. ComponentDeletionWatcher deletionWatcher (this);
  35100. PopupMenu menu;
  35101. menu.setLookAndFeel (&getLookAndFeel());
  35102. for (int i = 0; i < items.size(); ++i)
  35103. {
  35104. const ItemInfo* const item = items.getUnchecked(i);
  35105. if (item->isSeparator())
  35106. menu.addSeparator();
  35107. else if (item->isHeading)
  35108. menu.addSectionHeader (item->name);
  35109. else
  35110. menu.addItem (item->itemId, item->name,
  35111. item->isEnabled, item->itemId == currentId);
  35112. }
  35113. if (items.size() == 0)
  35114. menu.addItem (1, noChoicesMessage, false);
  35115. const int itemHeight = jlimit (12, 24, getHeight());
  35116. menuActive = true;
  35117. const int resultId = menu.showAt (this, currentId,
  35118. getWidth(), 1, itemHeight);
  35119. if (deletionWatcher.hasBeenDeleted())
  35120. return;
  35121. menuActive = false;
  35122. if (resultId != 0)
  35123. setSelectedId (resultId);
  35124. }
  35125. }
  35126. void ComboBox::mouseDown (const MouseEvent& e)
  35127. {
  35128. beginDragAutoRepeat (300);
  35129. isButtonDown = isEnabled();
  35130. if (isButtonDown
  35131. && (e.eventComponent == this || ! label->isEditable()))
  35132. {
  35133. showPopup();
  35134. }
  35135. }
  35136. void ComboBox::mouseDrag (const MouseEvent& e)
  35137. {
  35138. beginDragAutoRepeat (50);
  35139. if (isButtonDown && ! e.mouseWasClicked())
  35140. showPopup();
  35141. }
  35142. void ComboBox::mouseUp (const MouseEvent& e2)
  35143. {
  35144. if (isButtonDown)
  35145. {
  35146. isButtonDown = false;
  35147. repaint();
  35148. const MouseEvent e (e2.getEventRelativeTo (this));
  35149. if (reallyContains (e.x, e.y, true)
  35150. && (e2.eventComponent == this || ! label->isEditable()))
  35151. {
  35152. showPopup();
  35153. }
  35154. }
  35155. }
  35156. END_JUCE_NAMESPACE
  35157. /********* End of inlined file: juce_ComboBox.cpp *********/
  35158. /********* Start of inlined file: juce_Label.cpp *********/
  35159. BEGIN_JUCE_NAMESPACE
  35160. Label::Label (const String& componentName,
  35161. const String& labelText)
  35162. : Component (componentName),
  35163. text (labelText),
  35164. font (15.0f),
  35165. justification (Justification::centredLeft),
  35166. editor (0),
  35167. listeners (2),
  35168. ownerComponent (0),
  35169. deletionWatcher (0),
  35170. horizontalBorderSize (3),
  35171. verticalBorderSize (1),
  35172. minimumHorizontalScale (0.7f),
  35173. editSingleClick (false),
  35174. editDoubleClick (false),
  35175. lossOfFocusDiscardsChanges (false)
  35176. {
  35177. setColour (TextEditor::textColourId, Colours::black);
  35178. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  35179. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  35180. }
  35181. Label::~Label()
  35182. {
  35183. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35184. ownerComponent->removeComponentListener (this);
  35185. deleteAndZero (deletionWatcher);
  35186. if (editor != 0)
  35187. delete editor;
  35188. }
  35189. void Label::setText (const String& newText,
  35190. const bool broadcastChangeMessage)
  35191. {
  35192. hideEditor (true);
  35193. if (text != newText)
  35194. {
  35195. text = newText;
  35196. repaint();
  35197. textWasChanged();
  35198. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35199. componentMovedOrResized (*ownerComponent, true, true);
  35200. if (broadcastChangeMessage)
  35201. callChangeListeners();
  35202. }
  35203. }
  35204. const String Label::getText (const bool returnActiveEditorContents) const throw()
  35205. {
  35206. return (returnActiveEditorContents && isBeingEdited())
  35207. ? editor->getText()
  35208. : text;
  35209. }
  35210. void Label::setFont (const Font& newFont) throw()
  35211. {
  35212. font = newFont;
  35213. repaint();
  35214. }
  35215. const Font& Label::getFont() const throw()
  35216. {
  35217. return font;
  35218. }
  35219. void Label::setEditable (const bool editOnSingleClick,
  35220. const bool editOnDoubleClick,
  35221. const bool lossOfFocusDiscardsChanges_) throw()
  35222. {
  35223. editSingleClick = editOnSingleClick;
  35224. editDoubleClick = editOnDoubleClick;
  35225. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  35226. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  35227. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  35228. }
  35229. void Label::setJustificationType (const Justification& justification_) throw()
  35230. {
  35231. justification = justification_;
  35232. repaint();
  35233. }
  35234. void Label::setBorderSize (int h, int v)
  35235. {
  35236. horizontalBorderSize = h;
  35237. verticalBorderSize = v;
  35238. repaint();
  35239. }
  35240. void Label::attachToComponent (Component* owner,
  35241. const bool onLeft)
  35242. {
  35243. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35244. ownerComponent->removeComponentListener (this);
  35245. deleteAndZero (deletionWatcher);
  35246. ownerComponent = owner;
  35247. leftOfOwnerComp = onLeft;
  35248. if (ownerComponent != 0)
  35249. {
  35250. deletionWatcher = new ComponentDeletionWatcher (owner);
  35251. setVisible (owner->isVisible());
  35252. ownerComponent->addComponentListener (this);
  35253. componentParentHierarchyChanged (*ownerComponent);
  35254. componentMovedOrResized (*ownerComponent, true, true);
  35255. }
  35256. }
  35257. void Label::componentMovedOrResized (Component& component,
  35258. bool /*wasMoved*/,
  35259. bool /*wasResized*/)
  35260. {
  35261. if (leftOfOwnerComp)
  35262. {
  35263. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  35264. component.getHeight());
  35265. setTopRightPosition (component.getX(), component.getY());
  35266. }
  35267. else
  35268. {
  35269. setSize (component.getWidth(),
  35270. 8 + roundFloatToInt (getFont().getHeight()));
  35271. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  35272. }
  35273. }
  35274. void Label::componentParentHierarchyChanged (Component& component)
  35275. {
  35276. if (component.getParentComponent() != 0)
  35277. component.getParentComponent()->addChildComponent (this);
  35278. }
  35279. void Label::componentVisibilityChanged (Component& component)
  35280. {
  35281. setVisible (component.isVisible());
  35282. }
  35283. void Label::textWasEdited()
  35284. {
  35285. }
  35286. void Label::textWasChanged()
  35287. {
  35288. }
  35289. void Label::showEditor()
  35290. {
  35291. if (editor == 0)
  35292. {
  35293. addAndMakeVisible (editor = createEditorComponent());
  35294. editor->setText (getText(), false);
  35295. editor->addListener (this);
  35296. editor->grabKeyboardFocus();
  35297. editor->setHighlightedRegion (0, text.length());
  35298. editor->addListener (this);
  35299. resized();
  35300. repaint();
  35301. editorShown (editor);
  35302. enterModalState();
  35303. editor->grabKeyboardFocus();
  35304. }
  35305. }
  35306. void Label::editorShown (TextEditor* editorComponent)
  35307. {
  35308. }
  35309. void Label::editorAboutToBeHidden (TextEditor* editorComponent)
  35310. {
  35311. }
  35312. bool Label::updateFromTextEditorContents()
  35313. {
  35314. jassert (editor != 0);
  35315. const String newText (editor->getText());
  35316. if (text != newText)
  35317. {
  35318. text = newText;
  35319. repaint();
  35320. textWasChanged();
  35321. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  35322. componentMovedOrResized (*ownerComponent, true, true);
  35323. return true;
  35324. }
  35325. return false;
  35326. }
  35327. void Label::hideEditor (const bool discardCurrentEditorContents)
  35328. {
  35329. if (editor != 0)
  35330. {
  35331. editorAboutToBeHidden (editor);
  35332. const bool changed = (! discardCurrentEditorContents)
  35333. && updateFromTextEditorContents();
  35334. deleteAndZero (editor);
  35335. repaint();
  35336. if (changed)
  35337. textWasEdited();
  35338. exitModalState (0);
  35339. if (changed && isValidComponent())
  35340. callChangeListeners();
  35341. }
  35342. }
  35343. void Label::inputAttemptWhenModal()
  35344. {
  35345. if (editor != 0)
  35346. {
  35347. if (lossOfFocusDiscardsChanges)
  35348. textEditorEscapeKeyPressed (*editor);
  35349. else
  35350. textEditorReturnKeyPressed (*editor);
  35351. }
  35352. }
  35353. bool Label::isBeingEdited() const throw()
  35354. {
  35355. return editor != 0;
  35356. }
  35357. TextEditor* Label::createEditorComponent()
  35358. {
  35359. TextEditor* const ed = new TextEditor (getName());
  35360. ed->setFont (font);
  35361. // copy these colours from our own settings..
  35362. const int cols[] = { TextEditor::backgroundColourId,
  35363. TextEditor::textColourId,
  35364. TextEditor::highlightColourId,
  35365. TextEditor::highlightedTextColourId,
  35366. TextEditor::caretColourId,
  35367. TextEditor::outlineColourId,
  35368. TextEditor::focusedOutlineColourId,
  35369. TextEditor::shadowColourId };
  35370. for (int i = 0; i < numElementsInArray (cols); ++i)
  35371. ed->setColour (cols[i], findColour (cols[i]));
  35372. return ed;
  35373. }
  35374. void Label::paint (Graphics& g)
  35375. {
  35376. getLookAndFeel().drawLabel (g, *this);
  35377. }
  35378. void Label::mouseUp (const MouseEvent& e)
  35379. {
  35380. if (editSingleClick
  35381. && e.mouseWasClicked()
  35382. && contains (e.x, e.y)
  35383. && ! e.mods.isPopupMenu())
  35384. {
  35385. showEditor();
  35386. }
  35387. }
  35388. void Label::mouseDoubleClick (const MouseEvent& e)
  35389. {
  35390. if (editDoubleClick && ! e.mods.isPopupMenu())
  35391. showEditor();
  35392. }
  35393. void Label::resized()
  35394. {
  35395. if (editor != 0)
  35396. editor->setBoundsInset (BorderSize (0));
  35397. }
  35398. void Label::focusGained (FocusChangeType cause)
  35399. {
  35400. if (editSingleClick && cause == focusChangedByTabKey)
  35401. showEditor();
  35402. }
  35403. void Label::enablementChanged()
  35404. {
  35405. repaint();
  35406. }
  35407. void Label::colourChanged()
  35408. {
  35409. repaint();
  35410. }
  35411. void Label::setMinimumHorizontalScale (const float newScale)
  35412. {
  35413. if (minimumHorizontalScale != newScale)
  35414. {
  35415. minimumHorizontalScale = newScale;
  35416. repaint();
  35417. }
  35418. }
  35419. // We'll use a custom focus traverser here to make sure focus goes from the
  35420. // text editor to another component rather than back to the label itself.
  35421. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  35422. {
  35423. public:
  35424. LabelKeyboardFocusTraverser() {}
  35425. Component* getNextComponent (Component* current)
  35426. {
  35427. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  35428. ? current->getParentComponent() : current);
  35429. }
  35430. Component* getPreviousComponent (Component* current)
  35431. {
  35432. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  35433. ? current->getParentComponent() : current);
  35434. }
  35435. };
  35436. KeyboardFocusTraverser* Label::createFocusTraverser()
  35437. {
  35438. return new LabelKeyboardFocusTraverser();
  35439. }
  35440. void Label::addListener (LabelListener* const listener) throw()
  35441. {
  35442. jassert (listener != 0);
  35443. if (listener != 0)
  35444. listeners.add (listener);
  35445. }
  35446. void Label::removeListener (LabelListener* const listener) throw()
  35447. {
  35448. listeners.removeValue (listener);
  35449. }
  35450. void Label::callChangeListeners()
  35451. {
  35452. for (int i = listeners.size(); --i >= 0;)
  35453. {
  35454. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  35455. i = jmin (i, listeners.size());
  35456. }
  35457. }
  35458. void Label::textEditorTextChanged (TextEditor& ed)
  35459. {
  35460. if (editor != 0)
  35461. {
  35462. jassert (&ed == editor);
  35463. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  35464. {
  35465. if (lossOfFocusDiscardsChanges)
  35466. textEditorEscapeKeyPressed (ed);
  35467. else
  35468. textEditorReturnKeyPressed (ed);
  35469. }
  35470. }
  35471. }
  35472. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  35473. {
  35474. if (editor != 0)
  35475. {
  35476. jassert (&ed == editor);
  35477. (void) ed;
  35478. const bool changed = updateFromTextEditorContents();
  35479. hideEditor (true);
  35480. if (changed)
  35481. {
  35482. textWasEdited();
  35483. if (isValidComponent())
  35484. callChangeListeners();
  35485. }
  35486. }
  35487. }
  35488. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  35489. {
  35490. if (editor != 0)
  35491. {
  35492. jassert (&ed == editor);
  35493. (void) ed;
  35494. editor->setText (text, false);
  35495. hideEditor (true);
  35496. }
  35497. }
  35498. void Label::textEditorFocusLost (TextEditor& ed)
  35499. {
  35500. textEditorTextChanged (ed);
  35501. }
  35502. END_JUCE_NAMESPACE
  35503. /********* End of inlined file: juce_Label.cpp *********/
  35504. /********* Start of inlined file: juce_ListBox.cpp *********/
  35505. BEGIN_JUCE_NAMESPACE
  35506. class ListBoxRowComponent : public Component
  35507. {
  35508. public:
  35509. ListBoxRowComponent (ListBox& owner_)
  35510. : owner (owner_),
  35511. row (-1),
  35512. selected (false),
  35513. isDragging (false)
  35514. {
  35515. }
  35516. ~ListBoxRowComponent()
  35517. {
  35518. deleteAllChildren();
  35519. }
  35520. void paint (Graphics& g)
  35521. {
  35522. if (owner.getModel() != 0)
  35523. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  35524. }
  35525. void update (const int row_, const bool selected_)
  35526. {
  35527. if (row != row_ || selected != selected_)
  35528. {
  35529. repaint();
  35530. row = row_;
  35531. selected = selected_;
  35532. }
  35533. if (owner.getModel() != 0)
  35534. {
  35535. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  35536. if (customComp != 0)
  35537. {
  35538. addAndMakeVisible (customComp);
  35539. customComp->setBounds (0, 0, getWidth(), getHeight());
  35540. for (int i = getNumChildComponents(); --i >= 0;)
  35541. if (getChildComponent (i) != customComp)
  35542. delete getChildComponent (i);
  35543. }
  35544. else
  35545. {
  35546. deleteAllChildren();
  35547. }
  35548. }
  35549. }
  35550. void mouseDown (const MouseEvent& e)
  35551. {
  35552. isDragging = false;
  35553. selectRowOnMouseUp = false;
  35554. if (isEnabled())
  35555. {
  35556. if (! selected)
  35557. {
  35558. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35559. if (owner.getModel() != 0)
  35560. owner.getModel()->listBoxItemClicked (row, e);
  35561. }
  35562. else
  35563. {
  35564. selectRowOnMouseUp = true;
  35565. }
  35566. }
  35567. }
  35568. void mouseUp (const MouseEvent& e)
  35569. {
  35570. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  35571. {
  35572. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  35573. if (owner.getModel() != 0)
  35574. owner.getModel()->listBoxItemClicked (row, e);
  35575. }
  35576. }
  35577. void mouseDoubleClick (const MouseEvent& e)
  35578. {
  35579. if (owner.getModel() != 0 && isEnabled())
  35580. owner.getModel()->listBoxItemDoubleClicked (row, e);
  35581. }
  35582. void mouseDrag (const MouseEvent& e)
  35583. {
  35584. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  35585. {
  35586. const SparseSet <int> selectedRows (owner.getSelectedRows());
  35587. if (selectedRows.size() > 0)
  35588. {
  35589. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  35590. if (dragDescription.isNotEmpty())
  35591. {
  35592. isDragging = true;
  35593. DragAndDropContainer* const dragContainer
  35594. = DragAndDropContainer::findParentDragContainerFor (this);
  35595. if (dragContainer != 0)
  35596. {
  35597. Image* dragImage = owner.createSnapshotOfSelectedRows();
  35598. dragImage->multiplyAllAlphas (0.6f);
  35599. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  35600. }
  35601. else
  35602. {
  35603. // to be able to do a drag-and-drop operation, the listbox needs to
  35604. // be inside a component which is also a DragAndDropContainer.
  35605. jassertfalse
  35606. }
  35607. }
  35608. }
  35609. }
  35610. }
  35611. void resized()
  35612. {
  35613. if (getNumChildComponents() > 0)
  35614. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  35615. }
  35616. juce_UseDebuggingNewOperator
  35617. bool neededFlag;
  35618. private:
  35619. ListBox& owner;
  35620. int row;
  35621. bool selected, isDragging, selectRowOnMouseUp;
  35622. ListBoxRowComponent (const ListBoxRowComponent&);
  35623. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  35624. };
  35625. class ListViewport : public Viewport
  35626. {
  35627. public:
  35628. int firstIndex, firstWholeIndex, lastWholeIndex;
  35629. bool hasUpdated;
  35630. ListViewport (ListBox& owner_)
  35631. : owner (owner_)
  35632. {
  35633. setWantsKeyboardFocus (false);
  35634. setViewedComponent (new Component());
  35635. getViewedComponent()->addMouseListener (this, false);
  35636. getViewedComponent()->setWantsKeyboardFocus (false);
  35637. }
  35638. ~ListViewport()
  35639. {
  35640. getViewedComponent()->removeMouseListener (this);
  35641. getViewedComponent()->deleteAllChildren();
  35642. }
  35643. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  35644. {
  35645. return (ListBoxRowComponent*) getViewedComponent()
  35646. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  35647. }
  35648. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  35649. {
  35650. const int index = getIndexOfChildComponent (rowComponent);
  35651. const int num = getViewedComponent()->getNumChildComponents();
  35652. for (int i = num; --i >= 0;)
  35653. if (((firstIndex + i) % jmax (1, num)) == index)
  35654. return firstIndex + i;
  35655. return -1;
  35656. }
  35657. Component* getComponentForRowIfOnscreen (const int row) const throw()
  35658. {
  35659. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  35660. ? getComponentForRow (row) : 0;
  35661. }
  35662. void visibleAreaChanged (int, int, int, int)
  35663. {
  35664. updateVisibleArea (true);
  35665. if (owner.getModel() != 0)
  35666. owner.getModel()->listWasScrolled();
  35667. }
  35668. void updateVisibleArea (const bool makeSureItUpdatesContent)
  35669. {
  35670. hasUpdated = false;
  35671. const int newX = getViewedComponent()->getX();
  35672. int newY = getViewedComponent()->getY();
  35673. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  35674. const int newH = owner.totalItems * owner.getRowHeight();
  35675. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  35676. newY = getMaximumVisibleHeight() - newH;
  35677. getViewedComponent()->setBounds (newX, newY, newW, newH);
  35678. if (makeSureItUpdatesContent && ! hasUpdated)
  35679. updateContents();
  35680. }
  35681. void updateContents()
  35682. {
  35683. hasUpdated = true;
  35684. const int rowHeight = owner.getRowHeight();
  35685. if (rowHeight > 0)
  35686. {
  35687. const int y = getViewPositionY();
  35688. const int w = getViewedComponent()->getWidth();
  35689. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  35690. while (numNeeded > getViewedComponent()->getNumChildComponents())
  35691. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  35692. jassert (numNeeded >= 0);
  35693. while (numNeeded < getViewedComponent()->getNumChildComponents())
  35694. {
  35695. Component* const rowToRemove
  35696. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  35697. delete rowToRemove;
  35698. }
  35699. firstIndex = y / rowHeight;
  35700. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  35701. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  35702. for (int i = 0; i < numNeeded; ++i)
  35703. {
  35704. const int row = i + firstIndex;
  35705. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  35706. if (rowComp != 0)
  35707. {
  35708. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  35709. rowComp->update (row, owner.isRowSelected (row));
  35710. }
  35711. }
  35712. }
  35713. if (owner.headerComponent != 0)
  35714. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  35715. owner.outlineThickness,
  35716. jmax (owner.getWidth() - owner.outlineThickness * 2,
  35717. getViewedComponent()->getWidth()),
  35718. owner.headerComponent->getHeight());
  35719. }
  35720. void paint (Graphics& g)
  35721. {
  35722. if (isOpaque())
  35723. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  35724. }
  35725. bool keyPressed (const KeyPress& key)
  35726. {
  35727. if (key.isKeyCode (KeyPress::upKey)
  35728. || key.isKeyCode (KeyPress::downKey)
  35729. || key.isKeyCode (KeyPress::pageUpKey)
  35730. || key.isKeyCode (KeyPress::pageDownKey)
  35731. || key.isKeyCode (KeyPress::homeKey)
  35732. || key.isKeyCode (KeyPress::endKey))
  35733. {
  35734. // we want to avoid these keypresses going to the viewport, and instead allow
  35735. // them to pass up to our listbox..
  35736. return false;
  35737. }
  35738. return Viewport::keyPressed (key);
  35739. }
  35740. juce_UseDebuggingNewOperator
  35741. private:
  35742. ListBox& owner;
  35743. ListViewport (const ListViewport&);
  35744. const ListViewport& operator= (const ListViewport&);
  35745. };
  35746. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  35747. : Component (name),
  35748. model (model_),
  35749. headerComponent (0),
  35750. totalItems (0),
  35751. rowHeight (22),
  35752. minimumRowWidth (0),
  35753. outlineThickness (0),
  35754. lastRowSelected (-1),
  35755. mouseMoveSelects (false),
  35756. multipleSelection (false),
  35757. hasDoneInitialUpdate (false)
  35758. {
  35759. addAndMakeVisible (viewport = new ListViewport (*this));
  35760. setWantsKeyboardFocus (true);
  35761. colourChanged();
  35762. }
  35763. ListBox::~ListBox()
  35764. {
  35765. deleteAllChildren();
  35766. }
  35767. void ListBox::setModel (ListBoxModel* const newModel)
  35768. {
  35769. if (model != newModel)
  35770. {
  35771. model = newModel;
  35772. updateContent();
  35773. }
  35774. }
  35775. void ListBox::setMultipleSelectionEnabled (bool b)
  35776. {
  35777. multipleSelection = b;
  35778. }
  35779. void ListBox::setMouseMoveSelectsRows (bool b)
  35780. {
  35781. mouseMoveSelects = b;
  35782. if (b)
  35783. addMouseListener (this, true);
  35784. }
  35785. void ListBox::paint (Graphics& g)
  35786. {
  35787. if (! hasDoneInitialUpdate)
  35788. updateContent();
  35789. g.fillAll (findColour (backgroundColourId));
  35790. }
  35791. void ListBox::paintOverChildren (Graphics& g)
  35792. {
  35793. if (outlineThickness > 0)
  35794. {
  35795. g.setColour (findColour (outlineColourId));
  35796. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  35797. }
  35798. }
  35799. void ListBox::resized()
  35800. {
  35801. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  35802. outlineThickness,
  35803. outlineThickness,
  35804. outlineThickness));
  35805. viewport->setSingleStepSizes (20, getRowHeight());
  35806. viewport->updateVisibleArea (false);
  35807. }
  35808. void ListBox::visibilityChanged()
  35809. {
  35810. viewport->updateVisibleArea (true);
  35811. }
  35812. Viewport* ListBox::getViewport() const throw()
  35813. {
  35814. return viewport;
  35815. }
  35816. void ListBox::updateContent()
  35817. {
  35818. hasDoneInitialUpdate = true;
  35819. totalItems = (model != 0) ? model->getNumRows() : 0;
  35820. bool selectionChanged = false;
  35821. if (selected [selected.size() - 1] >= totalItems)
  35822. {
  35823. selected.removeRange (totalItems, INT_MAX - totalItems);
  35824. lastRowSelected = getSelectedRow (0);
  35825. selectionChanged = true;
  35826. }
  35827. viewport->updateVisibleArea (isVisible());
  35828. viewport->resized();
  35829. if (selectionChanged && model != 0)
  35830. model->selectedRowsChanged (lastRowSelected);
  35831. }
  35832. void ListBox::selectRow (const int row,
  35833. bool dontScroll,
  35834. bool deselectOthersFirst)
  35835. {
  35836. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  35837. }
  35838. void ListBox::selectRowInternal (const int row,
  35839. bool dontScroll,
  35840. bool deselectOthersFirst,
  35841. bool isMouseClick)
  35842. {
  35843. if (! multipleSelection)
  35844. deselectOthersFirst = true;
  35845. if ((! isRowSelected (row))
  35846. || (deselectOthersFirst && getNumSelectedRows() > 1))
  35847. {
  35848. if (((unsigned int) row) < (unsigned int) totalItems)
  35849. {
  35850. if (deselectOthersFirst)
  35851. selected.clear();
  35852. selected.addRange (row, 1);
  35853. if (getHeight() == 0 || getWidth() == 0)
  35854. dontScroll = true;
  35855. viewport->hasUpdated = false;
  35856. if (row < viewport->firstWholeIndex && ! dontScroll)
  35857. {
  35858. viewport->setViewPosition (viewport->getViewPositionX(),
  35859. row * getRowHeight());
  35860. }
  35861. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  35862. {
  35863. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  35864. if (row >= lastRowSelected + rowsOnScreen
  35865. && rowsOnScreen < totalItems - 1
  35866. && ! isMouseClick)
  35867. {
  35868. viewport->setViewPosition (viewport->getViewPositionX(),
  35869. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  35870. * getRowHeight());
  35871. }
  35872. else
  35873. {
  35874. viewport->setViewPosition (viewport->getViewPositionX(),
  35875. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35876. }
  35877. }
  35878. if (! viewport->hasUpdated)
  35879. viewport->updateContents();
  35880. lastRowSelected = row;
  35881. model->selectedRowsChanged (row);
  35882. }
  35883. else
  35884. {
  35885. if (deselectOthersFirst)
  35886. deselectAllRows();
  35887. }
  35888. }
  35889. }
  35890. void ListBox::deselectRow (const int row)
  35891. {
  35892. if (selected.contains (row))
  35893. {
  35894. selected.removeRange (row, 1);
  35895. if (row == lastRowSelected)
  35896. lastRowSelected = getSelectedRow (0);
  35897. viewport->updateContents();
  35898. model->selectedRowsChanged (lastRowSelected);
  35899. }
  35900. }
  35901. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  35902. const bool sendNotificationEventToModel)
  35903. {
  35904. selected = setOfRowsToBeSelected;
  35905. selected.removeRange (totalItems, INT_MAX - totalItems);
  35906. if (! isRowSelected (lastRowSelected))
  35907. lastRowSelected = getSelectedRow (0);
  35908. viewport->updateContents();
  35909. if ((model != 0) && sendNotificationEventToModel)
  35910. model->selectedRowsChanged (lastRowSelected);
  35911. }
  35912. const SparseSet<int> ListBox::getSelectedRows() const
  35913. {
  35914. return selected;
  35915. }
  35916. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  35917. {
  35918. if (multipleSelection && (firstRow != lastRow))
  35919. {
  35920. const int numRows = totalItems - 1;
  35921. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  35922. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  35923. selected.addRange (jmin (firstRow, lastRow),
  35924. abs (firstRow - lastRow) + 1);
  35925. selected.removeRange (lastRow, 1);
  35926. }
  35927. selectRowInternal (lastRow, false, false, true);
  35928. }
  35929. void ListBox::flipRowSelection (const int row)
  35930. {
  35931. if (isRowSelected (row))
  35932. deselectRow (row);
  35933. else
  35934. selectRowInternal (row, false, false, true);
  35935. }
  35936. void ListBox::deselectAllRows()
  35937. {
  35938. if (! selected.isEmpty())
  35939. {
  35940. selected.clear();
  35941. lastRowSelected = -1;
  35942. viewport->updateContents();
  35943. if (model != 0)
  35944. model->selectedRowsChanged (lastRowSelected);
  35945. }
  35946. }
  35947. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  35948. const ModifierKeys& mods)
  35949. {
  35950. if (multipleSelection && mods.isCommandDown())
  35951. {
  35952. flipRowSelection (row);
  35953. }
  35954. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  35955. {
  35956. selectRangeOfRows (lastRowSelected, row);
  35957. }
  35958. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  35959. {
  35960. selectRowInternal (row, false, true, true);
  35961. }
  35962. }
  35963. int ListBox::getNumSelectedRows() const
  35964. {
  35965. return selected.size();
  35966. }
  35967. int ListBox::getSelectedRow (const int index) const
  35968. {
  35969. return (((unsigned int) index) < (unsigned int) selected.size())
  35970. ? selected [index] : -1;
  35971. }
  35972. bool ListBox::isRowSelected (const int row) const
  35973. {
  35974. return selected.contains (row);
  35975. }
  35976. int ListBox::getLastRowSelected() const
  35977. {
  35978. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  35979. }
  35980. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  35981. {
  35982. if (((unsigned int) x) < (unsigned int) getWidth())
  35983. {
  35984. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  35985. if (((unsigned int) row) < (unsigned int) totalItems)
  35986. return row;
  35987. }
  35988. return -1;
  35989. }
  35990. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  35991. {
  35992. if (((unsigned int) x) < (unsigned int) getWidth())
  35993. {
  35994. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  35995. return jlimit (0, totalItems, row);
  35996. }
  35997. return -1;
  35998. }
  35999. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  36000. {
  36001. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  36002. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  36003. }
  36004. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  36005. {
  36006. return viewport->getRowNumberOfComponent (rowComponent);
  36007. }
  36008. const Rectangle ListBox::getRowPosition (const int rowNumber,
  36009. const bool relativeToComponentTopLeft) const throw()
  36010. {
  36011. const int rowHeight = getRowHeight();
  36012. int y = viewport->getY() + rowHeight * rowNumber;
  36013. if (relativeToComponentTopLeft)
  36014. y -= viewport->getViewPositionY();
  36015. return Rectangle (viewport->getX(), y,
  36016. viewport->getViewedComponent()->getWidth(), rowHeight);
  36017. }
  36018. void ListBox::setVerticalPosition (const double proportion)
  36019. {
  36020. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36021. viewport->setViewPosition (viewport->getViewPositionX(),
  36022. jmax (0, roundDoubleToInt (proportion * offscreen)));
  36023. }
  36024. double ListBox::getVerticalPosition() const
  36025. {
  36026. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  36027. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  36028. : 0;
  36029. }
  36030. int ListBox::getVisibleRowWidth() const throw()
  36031. {
  36032. return viewport->getViewWidth();
  36033. }
  36034. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  36035. {
  36036. if (row < viewport->firstWholeIndex)
  36037. {
  36038. viewport->setViewPosition (viewport->getViewPositionX(),
  36039. row * getRowHeight());
  36040. }
  36041. else if (row >= viewport->lastWholeIndex)
  36042. {
  36043. viewport->setViewPosition (viewport->getViewPositionX(),
  36044. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  36045. }
  36046. }
  36047. bool ListBox::keyPressed (const KeyPress& key)
  36048. {
  36049. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  36050. const bool multiple = multipleSelection
  36051. && (lastRowSelected >= 0)
  36052. && (key.getModifiers().isShiftDown()
  36053. || key.getModifiers().isCtrlDown()
  36054. || key.getModifiers().isCommandDown());
  36055. if (key.isKeyCode (KeyPress::upKey))
  36056. {
  36057. if (multiple)
  36058. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  36059. else
  36060. selectRow (jmax (0, lastRowSelected - 1));
  36061. }
  36062. else if (key.isKeyCode (KeyPress::returnKey)
  36063. && isRowSelected (lastRowSelected))
  36064. {
  36065. if (model != 0)
  36066. model->returnKeyPressed (lastRowSelected);
  36067. }
  36068. else if (key.isKeyCode (KeyPress::pageUpKey))
  36069. {
  36070. if (multiple)
  36071. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  36072. else
  36073. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  36074. }
  36075. else if (key.isKeyCode (KeyPress::pageDownKey))
  36076. {
  36077. if (multiple)
  36078. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  36079. else
  36080. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  36081. }
  36082. else if (key.isKeyCode (KeyPress::homeKey))
  36083. {
  36084. if (multiple && key.getModifiers().isShiftDown())
  36085. selectRangeOfRows (lastRowSelected, 0);
  36086. else
  36087. selectRow (0);
  36088. }
  36089. else if (key.isKeyCode (KeyPress::endKey))
  36090. {
  36091. if (multiple && key.getModifiers().isShiftDown())
  36092. selectRangeOfRows (lastRowSelected, totalItems - 1);
  36093. else
  36094. selectRow (totalItems - 1);
  36095. }
  36096. else if (key.isKeyCode (KeyPress::downKey))
  36097. {
  36098. if (multiple)
  36099. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  36100. else
  36101. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  36102. }
  36103. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  36104. && isRowSelected (lastRowSelected))
  36105. {
  36106. if (model != 0)
  36107. model->deleteKeyPressed (lastRowSelected);
  36108. }
  36109. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  36110. {
  36111. selectRangeOfRows (0, INT_MAX);
  36112. }
  36113. else
  36114. {
  36115. return false;
  36116. }
  36117. return true;
  36118. }
  36119. bool ListBox::keyStateChanged (const bool isKeyDown)
  36120. {
  36121. return isKeyDown
  36122. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  36123. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  36124. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  36125. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  36126. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  36127. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  36128. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  36129. }
  36130. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36131. {
  36132. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  36133. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  36134. }
  36135. void ListBox::mouseMove (const MouseEvent& e)
  36136. {
  36137. if (mouseMoveSelects)
  36138. {
  36139. const MouseEvent e2 (e.getEventRelativeTo (this));
  36140. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  36141. lastMouseX = e2.x;
  36142. lastMouseY = e2.y;
  36143. }
  36144. }
  36145. void ListBox::mouseExit (const MouseEvent& e)
  36146. {
  36147. mouseMove (e);
  36148. }
  36149. void ListBox::mouseUp (const MouseEvent& e)
  36150. {
  36151. if (e.mouseWasClicked() && model != 0)
  36152. model->backgroundClicked();
  36153. }
  36154. void ListBox::setRowHeight (const int newHeight)
  36155. {
  36156. rowHeight = jmax (1, newHeight);
  36157. viewport->setSingleStepSizes (20, rowHeight);
  36158. updateContent();
  36159. }
  36160. int ListBox::getNumRowsOnScreen() const throw()
  36161. {
  36162. return viewport->getMaximumVisibleHeight() / rowHeight;
  36163. }
  36164. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  36165. {
  36166. minimumRowWidth = newMinimumWidth;
  36167. updateContent();
  36168. }
  36169. int ListBox::getVisibleContentWidth() const throw()
  36170. {
  36171. return viewport->getMaximumVisibleWidth();
  36172. }
  36173. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  36174. {
  36175. return viewport->getVerticalScrollBar();
  36176. }
  36177. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  36178. {
  36179. return viewport->getHorizontalScrollBar();
  36180. }
  36181. void ListBox::colourChanged()
  36182. {
  36183. setOpaque (findColour (backgroundColourId).isOpaque());
  36184. viewport->setOpaque (isOpaque());
  36185. repaint();
  36186. }
  36187. void ListBox::setOutlineThickness (const int outlineThickness_)
  36188. {
  36189. outlineThickness = outlineThickness_;
  36190. resized();
  36191. }
  36192. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  36193. {
  36194. if (headerComponent != newHeaderComponent)
  36195. {
  36196. if (headerComponent != 0)
  36197. delete headerComponent;
  36198. headerComponent = newHeaderComponent;
  36199. addAndMakeVisible (newHeaderComponent);
  36200. ListBox::resized();
  36201. }
  36202. }
  36203. void ListBox::repaintRow (const int rowNumber) throw()
  36204. {
  36205. const Rectangle r (getRowPosition (rowNumber, true));
  36206. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  36207. }
  36208. Image* ListBox::createSnapshotOfSelectedRows()
  36209. {
  36210. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  36211. Graphics g (*snapshot);
  36212. const int firstRow = getRowContainingPosition (0, 0);
  36213. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  36214. {
  36215. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  36216. if (rowComp != 0 && isRowSelected (firstRow + i))
  36217. {
  36218. g.saveState();
  36219. int x = 0, y = 0;
  36220. rowComp->relativePositionToOtherComponent (this, x, y);
  36221. g.setOrigin (x, y);
  36222. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  36223. rowComp->paintEntireComponent (g);
  36224. g.restoreState();
  36225. }
  36226. }
  36227. return snapshot;
  36228. }
  36229. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  36230. {
  36231. (void) existingComponentToUpdate;
  36232. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36233. return 0;
  36234. }
  36235. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  36236. {
  36237. }
  36238. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  36239. {
  36240. }
  36241. void ListBoxModel::backgroundClicked()
  36242. {
  36243. }
  36244. void ListBoxModel::selectedRowsChanged (int)
  36245. {
  36246. }
  36247. void ListBoxModel::deleteKeyPressed (int)
  36248. {
  36249. }
  36250. void ListBoxModel::returnKeyPressed (int)
  36251. {
  36252. }
  36253. void ListBoxModel::listWasScrolled()
  36254. {
  36255. }
  36256. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36257. {
  36258. return String::empty;
  36259. }
  36260. END_JUCE_NAMESPACE
  36261. /********* End of inlined file: juce_ListBox.cpp *********/
  36262. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  36263. BEGIN_JUCE_NAMESPACE
  36264. ProgressBar::ProgressBar (double& progress_)
  36265. : progress (progress_),
  36266. displayPercentage (true),
  36267. lastCallbackTime (0)
  36268. {
  36269. currentValue = jlimit (0.0, 1.0, progress);
  36270. }
  36271. ProgressBar::~ProgressBar()
  36272. {
  36273. }
  36274. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  36275. {
  36276. displayPercentage = shouldDisplayPercentage;
  36277. repaint();
  36278. }
  36279. void ProgressBar::setTextToDisplay (const String& text)
  36280. {
  36281. displayPercentage = false;
  36282. displayedMessage = text;
  36283. }
  36284. void ProgressBar::lookAndFeelChanged()
  36285. {
  36286. setOpaque (findColour (backgroundColourId).isOpaque());
  36287. }
  36288. void ProgressBar::colourChanged()
  36289. {
  36290. lookAndFeelChanged();
  36291. }
  36292. void ProgressBar::paint (Graphics& g)
  36293. {
  36294. String text;
  36295. if (displayPercentage)
  36296. {
  36297. if (currentValue >= 0 && currentValue <= 1.0)
  36298. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  36299. }
  36300. else
  36301. {
  36302. text = displayedMessage;
  36303. }
  36304. getLookAndFeel().drawProgressBar (g, *this,
  36305. getWidth(), getHeight(),
  36306. currentValue, text);
  36307. }
  36308. void ProgressBar::visibilityChanged()
  36309. {
  36310. if (isVisible())
  36311. startTimer (30);
  36312. else
  36313. stopTimer();
  36314. }
  36315. void ProgressBar::timerCallback()
  36316. {
  36317. double newProgress = progress;
  36318. if (currentValue != newProgress
  36319. || newProgress < 0 || newProgress >= 1.0
  36320. || currentMessage != displayedMessage)
  36321. {
  36322. if (currentValue < newProgress
  36323. && newProgress >= 0 && newProgress < 1.0
  36324. && currentValue >= 0 && currentValue < 1.0)
  36325. {
  36326. const uint32 now = Time::getMillisecondCounter();
  36327. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  36328. lastCallbackTime = now;
  36329. newProgress = jmin (currentValue + 0.00018 * timeSinceLastCallback,
  36330. newProgress);
  36331. }
  36332. currentValue = newProgress;
  36333. currentMessage = displayedMessage;
  36334. repaint();
  36335. }
  36336. }
  36337. END_JUCE_NAMESPACE
  36338. /********* End of inlined file: juce_ProgressBar.cpp *********/
  36339. /********* Start of inlined file: juce_Slider.cpp *********/
  36340. BEGIN_JUCE_NAMESPACE
  36341. class SliderPopupDisplayComponent : public BubbleComponent
  36342. {
  36343. public:
  36344. SliderPopupDisplayComponent (Slider* const owner_)
  36345. : owner (owner_),
  36346. font (15.0f, Font::bold)
  36347. {
  36348. setAlwaysOnTop (true);
  36349. }
  36350. ~SliderPopupDisplayComponent()
  36351. {
  36352. }
  36353. void paintContent (Graphics& g, int w, int h)
  36354. {
  36355. g.setFont (font);
  36356. g.setColour (Colours::black);
  36357. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  36358. }
  36359. void getContentSize (int& w, int& h)
  36360. {
  36361. w = font.getStringWidth (text) + 18;
  36362. h = (int) (font.getHeight() * 1.6f);
  36363. }
  36364. void updatePosition (const String& newText)
  36365. {
  36366. if (text != newText)
  36367. {
  36368. text = newText;
  36369. repaint();
  36370. }
  36371. BubbleComponent::setPosition (owner);
  36372. }
  36373. juce_UseDebuggingNewOperator
  36374. private:
  36375. Slider* owner;
  36376. Font font;
  36377. String text;
  36378. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  36379. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  36380. };
  36381. Slider::Slider (const String& name)
  36382. : Component (name),
  36383. listeners (2),
  36384. currentValue (0.0),
  36385. valueMin (0.0),
  36386. valueMax (0.0),
  36387. minimum (0),
  36388. maximum (10),
  36389. interval (0),
  36390. skewFactor (1.0),
  36391. velocityModeSensitivity (1.0),
  36392. velocityModeOffset (0.0),
  36393. velocityModeThreshold (1),
  36394. rotaryStart (float_Pi * 1.2f),
  36395. rotaryEnd (float_Pi * 2.8f),
  36396. numDecimalPlaces (7),
  36397. sliderRegionStart (0),
  36398. sliderRegionSize (1),
  36399. sliderBeingDragged (-1),
  36400. pixelsForFullDragExtent (250),
  36401. style (LinearHorizontal),
  36402. textBoxPos (TextBoxLeft),
  36403. textBoxWidth (80),
  36404. textBoxHeight (20),
  36405. incDecButtonMode (incDecButtonsNotDraggable),
  36406. editableText (true),
  36407. doubleClickToValue (false),
  36408. isVelocityBased (false),
  36409. userKeyOverridesVelocity (true),
  36410. rotaryStop (true),
  36411. incDecButtonsSideBySide (false),
  36412. sendChangeOnlyOnRelease (false),
  36413. popupDisplayEnabled (false),
  36414. menuEnabled (false),
  36415. menuShown (false),
  36416. scrollWheelEnabled (true),
  36417. snapsToMousePos (true),
  36418. valueBox (0),
  36419. incButton (0),
  36420. decButton (0),
  36421. popupDisplay (0),
  36422. parentForPopupDisplay (0)
  36423. {
  36424. setWantsKeyboardFocus (false);
  36425. setRepaintsOnMouseActivity (true);
  36426. lookAndFeelChanged();
  36427. updateText();
  36428. }
  36429. Slider::~Slider()
  36430. {
  36431. deleteAndZero (popupDisplay);
  36432. deleteAllChildren();
  36433. }
  36434. void Slider::handleAsyncUpdate()
  36435. {
  36436. cancelPendingUpdate();
  36437. for (int i = listeners.size(); --i >= 0;)
  36438. {
  36439. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  36440. i = jmin (i, listeners.size());
  36441. }
  36442. }
  36443. void Slider::sendDragStart()
  36444. {
  36445. startedDragging();
  36446. for (int i = listeners.size(); --i >= 0;)
  36447. {
  36448. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  36449. i = jmin (i, listeners.size());
  36450. }
  36451. }
  36452. void Slider::sendDragEnd()
  36453. {
  36454. stoppedDragging();
  36455. sliderBeingDragged = -1;
  36456. for (int i = listeners.size(); --i >= 0;)
  36457. {
  36458. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  36459. i = jmin (i, listeners.size());
  36460. }
  36461. }
  36462. void Slider::addListener (SliderListener* const listener) throw()
  36463. {
  36464. jassert (listener != 0);
  36465. if (listener != 0)
  36466. listeners.add (listener);
  36467. }
  36468. void Slider::removeListener (SliderListener* const listener) throw()
  36469. {
  36470. listeners.removeValue (listener);
  36471. }
  36472. void Slider::setSliderStyle (const SliderStyle newStyle)
  36473. {
  36474. if (style != newStyle)
  36475. {
  36476. style = newStyle;
  36477. repaint();
  36478. lookAndFeelChanged();
  36479. }
  36480. }
  36481. void Slider::setRotaryParameters (const float startAngleRadians,
  36482. const float endAngleRadians,
  36483. const bool stopAtEnd)
  36484. {
  36485. // make sure the values are sensible..
  36486. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  36487. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  36488. jassert (rotaryStart < rotaryEnd);
  36489. rotaryStart = startAngleRadians;
  36490. rotaryEnd = endAngleRadians;
  36491. rotaryStop = stopAtEnd;
  36492. }
  36493. void Slider::setVelocityBasedMode (const bool velBased) throw()
  36494. {
  36495. isVelocityBased = velBased;
  36496. }
  36497. void Slider::setVelocityModeParameters (const double sensitivity,
  36498. const int threshold,
  36499. const double offset,
  36500. const bool userCanPressKeyToSwapMode) throw()
  36501. {
  36502. jassert (threshold >= 0);
  36503. jassert (sensitivity > 0);
  36504. jassert (offset >= 0);
  36505. velocityModeSensitivity = sensitivity;
  36506. velocityModeOffset = offset;
  36507. velocityModeThreshold = threshold;
  36508. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  36509. }
  36510. void Slider::setSkewFactor (const double factor) throw()
  36511. {
  36512. skewFactor = factor;
  36513. }
  36514. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  36515. {
  36516. if (maximum > minimum)
  36517. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  36518. / (maximum - minimum));
  36519. }
  36520. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  36521. {
  36522. jassert (distanceForFullScaleDrag > 0);
  36523. pixelsForFullDragExtent = distanceForFullScaleDrag;
  36524. }
  36525. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  36526. {
  36527. if (incDecButtonMode != mode)
  36528. {
  36529. incDecButtonMode = mode;
  36530. lookAndFeelChanged();
  36531. }
  36532. }
  36533. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  36534. const bool isReadOnly,
  36535. const int textEntryBoxWidth,
  36536. const int textEntryBoxHeight)
  36537. {
  36538. textBoxPos = newPosition;
  36539. editableText = ! isReadOnly;
  36540. textBoxWidth = textEntryBoxWidth;
  36541. textBoxHeight = textEntryBoxHeight;
  36542. repaint();
  36543. lookAndFeelChanged();
  36544. }
  36545. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  36546. {
  36547. editableText = shouldBeEditable;
  36548. if (valueBox != 0)
  36549. valueBox->setEditable (shouldBeEditable && isEnabled());
  36550. }
  36551. void Slider::showTextBox()
  36552. {
  36553. jassert (editableText); // this should probably be avoided in read-only sliders.
  36554. if (valueBox != 0)
  36555. valueBox->showEditor();
  36556. }
  36557. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  36558. {
  36559. if (valueBox != 0)
  36560. {
  36561. valueBox->hideEditor (discardCurrentEditorContents);
  36562. if (discardCurrentEditorContents)
  36563. updateText();
  36564. }
  36565. }
  36566. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  36567. {
  36568. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  36569. }
  36570. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  36571. {
  36572. snapsToMousePos = shouldSnapToMouse;
  36573. }
  36574. void Slider::setPopupDisplayEnabled (const bool enabled,
  36575. Component* const parentComponentToUse) throw()
  36576. {
  36577. popupDisplayEnabled = enabled;
  36578. parentForPopupDisplay = parentComponentToUse;
  36579. }
  36580. void Slider::colourChanged()
  36581. {
  36582. lookAndFeelChanged();
  36583. }
  36584. void Slider::lookAndFeelChanged()
  36585. {
  36586. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  36587. : getTextFromValue (currentValue));
  36588. deleteAllChildren();
  36589. valueBox = 0;
  36590. LookAndFeel& lf = getLookAndFeel();
  36591. if (textBoxPos != NoTextBox)
  36592. {
  36593. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  36594. valueBox->setWantsKeyboardFocus (false);
  36595. valueBox->setText (previousTextBoxContent, false);
  36596. valueBox->setEditable (editableText && isEnabled());
  36597. valueBox->addListener (this);
  36598. if (style == LinearBar)
  36599. valueBox->addMouseListener (this, false);
  36600. valueBox->setTooltip (getTooltip());
  36601. }
  36602. if (style == IncDecButtons)
  36603. {
  36604. addAndMakeVisible (incButton = lf.createSliderButton (true));
  36605. incButton->addButtonListener (this);
  36606. addAndMakeVisible (decButton = lf.createSliderButton (false));
  36607. decButton->addButtonListener (this);
  36608. if (incDecButtonMode != incDecButtonsNotDraggable)
  36609. {
  36610. incButton->addMouseListener (this, false);
  36611. decButton->addMouseListener (this, false);
  36612. }
  36613. else
  36614. {
  36615. incButton->setRepeatSpeed (300, 100, 20);
  36616. incButton->addMouseListener (decButton, false);
  36617. decButton->setRepeatSpeed (300, 100, 20);
  36618. decButton->addMouseListener (incButton, false);
  36619. }
  36620. incButton->setTooltip (getTooltip());
  36621. decButton->setTooltip (getTooltip());
  36622. }
  36623. setComponentEffect (lf.getSliderEffect());
  36624. resized();
  36625. repaint();
  36626. }
  36627. void Slider::setRange (const double newMin,
  36628. const double newMax,
  36629. const double newInt)
  36630. {
  36631. if (minimum != newMin
  36632. || maximum != newMax
  36633. || interval != newInt)
  36634. {
  36635. minimum = newMin;
  36636. maximum = newMax;
  36637. interval = newInt;
  36638. // figure out the number of DPs needed to display all values at this
  36639. // interval setting.
  36640. numDecimalPlaces = 7;
  36641. if (newInt != 0)
  36642. {
  36643. int v = abs ((int) (newInt * 10000000));
  36644. while ((v % 10) == 0)
  36645. {
  36646. --numDecimalPlaces;
  36647. v /= 10;
  36648. }
  36649. }
  36650. // keep the current values inside the new range..
  36651. if (style != TwoValueHorizontal && style != TwoValueVertical)
  36652. {
  36653. setValue (currentValue, false, false);
  36654. }
  36655. else
  36656. {
  36657. setMinValue (getMinValue(), false, false);
  36658. setMaxValue (getMaxValue(), false, false);
  36659. }
  36660. updateText();
  36661. }
  36662. }
  36663. void Slider::triggerChangeMessage (const bool synchronous)
  36664. {
  36665. if (synchronous)
  36666. handleAsyncUpdate();
  36667. else
  36668. triggerAsyncUpdate();
  36669. valueChanged();
  36670. }
  36671. double Slider::getValue() const throw()
  36672. {
  36673. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  36674. // methods to get the two values.
  36675. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36676. return currentValue;
  36677. }
  36678. void Slider::setValue (double newValue,
  36679. const bool sendUpdateMessage,
  36680. const bool sendMessageSynchronously)
  36681. {
  36682. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  36683. // methods to set the two values.
  36684. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  36685. newValue = constrainedValue (newValue);
  36686. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36687. {
  36688. jassert (valueMin <= valueMax);
  36689. newValue = jlimit (valueMin, valueMax, newValue);
  36690. }
  36691. if (currentValue != newValue)
  36692. {
  36693. if (valueBox != 0)
  36694. valueBox->hideEditor (true);
  36695. currentValue = newValue;
  36696. updateText();
  36697. repaint();
  36698. if (popupDisplay != 0)
  36699. {
  36700. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  36701. popupDisplay->repaint();
  36702. }
  36703. if (sendUpdateMessage)
  36704. triggerChangeMessage (sendMessageSynchronously);
  36705. }
  36706. }
  36707. double Slider::getMinValue() const throw()
  36708. {
  36709. // The minimum value only applies to sliders that are in two- or three-value mode.
  36710. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36711. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36712. return valueMin;
  36713. }
  36714. double Slider::getMaxValue() const throw()
  36715. {
  36716. // The maximum value only applies to sliders that are in two- or three-value mode.
  36717. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36718. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36719. return valueMax;
  36720. }
  36721. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  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. newValue = constrainedValue (newValue);
  36727. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36728. {
  36729. if (allowNudgingOfOtherValues && newValue > valueMax)
  36730. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36731. newValue = jmin (valueMax, newValue);
  36732. }
  36733. else
  36734. {
  36735. if (allowNudgingOfOtherValues && newValue > currentValue)
  36736. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36737. newValue = jmin (currentValue, newValue);
  36738. }
  36739. if (valueMin != newValue)
  36740. {
  36741. valueMin = newValue;
  36742. repaint();
  36743. if (popupDisplay != 0)
  36744. {
  36745. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  36746. popupDisplay->repaint();
  36747. }
  36748. if (sendUpdateMessage)
  36749. triggerChangeMessage (sendMessageSynchronously);
  36750. }
  36751. }
  36752. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  36753. {
  36754. // The maximum value only applies to sliders that are in two- or three-value mode.
  36755. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  36756. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  36757. newValue = constrainedValue (newValue);
  36758. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36759. {
  36760. if (allowNudgingOfOtherValues && newValue < valueMin)
  36761. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36762. newValue = jmax (valueMin, newValue);
  36763. }
  36764. else
  36765. {
  36766. if (allowNudgingOfOtherValues && newValue < currentValue)
  36767. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  36768. newValue = jmax (currentValue, newValue);
  36769. }
  36770. if (valueMax != newValue)
  36771. {
  36772. valueMax = newValue;
  36773. repaint();
  36774. if (popupDisplay != 0)
  36775. {
  36776. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  36777. popupDisplay->repaint();
  36778. }
  36779. if (sendUpdateMessage)
  36780. triggerChangeMessage (sendMessageSynchronously);
  36781. }
  36782. }
  36783. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  36784. const double valueToSetOnDoubleClick) throw()
  36785. {
  36786. doubleClickToValue = isDoubleClickEnabled;
  36787. doubleClickReturnValue = valueToSetOnDoubleClick;
  36788. }
  36789. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  36790. {
  36791. isEnabled_ = doubleClickToValue;
  36792. return doubleClickReturnValue;
  36793. }
  36794. void Slider::updateText()
  36795. {
  36796. if (valueBox != 0)
  36797. valueBox->setText (getTextFromValue (currentValue), false);
  36798. }
  36799. void Slider::setTextValueSuffix (const String& suffix)
  36800. {
  36801. if (textSuffix != suffix)
  36802. {
  36803. textSuffix = suffix;
  36804. updateText();
  36805. }
  36806. }
  36807. const String Slider::getTextFromValue (double v)
  36808. {
  36809. if (numDecimalPlaces > 0)
  36810. return String (v, numDecimalPlaces) + textSuffix;
  36811. else
  36812. return String (roundDoubleToInt (v)) + textSuffix;
  36813. }
  36814. double Slider::getValueFromText (const String& text)
  36815. {
  36816. String t (text.trimStart());
  36817. if (t.endsWith (textSuffix))
  36818. t = t.substring (0, t.length() - textSuffix.length());
  36819. while (t.startsWithChar (T('+')))
  36820. t = t.substring (1).trimStart();
  36821. return t.initialSectionContainingOnly (T("0123456789.,-"))
  36822. .getDoubleValue();
  36823. }
  36824. double Slider::proportionOfLengthToValue (double proportion)
  36825. {
  36826. if (skewFactor != 1.0 && proportion > 0.0)
  36827. proportion = exp (log (proportion) / skewFactor);
  36828. return minimum + (maximum - minimum) * proportion;
  36829. }
  36830. double Slider::valueToProportionOfLength (double value)
  36831. {
  36832. const double n = (value - minimum) / (maximum - minimum);
  36833. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  36834. }
  36835. double Slider::snapValue (double attemptedValue, const bool)
  36836. {
  36837. return attemptedValue;
  36838. }
  36839. void Slider::startedDragging()
  36840. {
  36841. }
  36842. void Slider::stoppedDragging()
  36843. {
  36844. }
  36845. void Slider::valueChanged()
  36846. {
  36847. }
  36848. void Slider::enablementChanged()
  36849. {
  36850. repaint();
  36851. }
  36852. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  36853. {
  36854. menuEnabled = menuEnabled_;
  36855. }
  36856. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  36857. {
  36858. scrollWheelEnabled = enabled;
  36859. }
  36860. void Slider::labelTextChanged (Label* label)
  36861. {
  36862. const double newValue = snapValue (getValueFromText (label->getText()), false);
  36863. if (getValue() != newValue)
  36864. {
  36865. sendDragStart();
  36866. setValue (newValue, true, true);
  36867. sendDragEnd();
  36868. }
  36869. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  36870. }
  36871. void Slider::buttonClicked (Button* button)
  36872. {
  36873. if (style == IncDecButtons)
  36874. {
  36875. sendDragStart();
  36876. if (button == incButton)
  36877. setValue (snapValue (getValue() + interval, false), true, true);
  36878. else if (button == decButton)
  36879. setValue (snapValue (getValue() - interval, false), true, true);
  36880. sendDragEnd();
  36881. }
  36882. }
  36883. double Slider::constrainedValue (double value) const throw()
  36884. {
  36885. if (interval > 0)
  36886. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  36887. if (value <= minimum || maximum <= minimum)
  36888. value = minimum;
  36889. else if (value >= maximum)
  36890. value = maximum;
  36891. return value;
  36892. }
  36893. float Slider::getLinearSliderPos (const double value)
  36894. {
  36895. double sliderPosProportional;
  36896. if (maximum > minimum)
  36897. {
  36898. if (value < minimum)
  36899. {
  36900. sliderPosProportional = 0.0;
  36901. }
  36902. else if (value > maximum)
  36903. {
  36904. sliderPosProportional = 1.0;
  36905. }
  36906. else
  36907. {
  36908. sliderPosProportional = valueToProportionOfLength (value);
  36909. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  36910. }
  36911. }
  36912. else
  36913. {
  36914. sliderPosProportional = 0.5;
  36915. }
  36916. if (isVertical() || style == IncDecButtons)
  36917. sliderPosProportional = 1.0 - sliderPosProportional;
  36918. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  36919. }
  36920. bool Slider::isHorizontal() const throw()
  36921. {
  36922. return style == LinearHorizontal
  36923. || style == LinearBar
  36924. || style == TwoValueHorizontal
  36925. || style == ThreeValueHorizontal;
  36926. }
  36927. bool Slider::isVertical() const throw()
  36928. {
  36929. return style == LinearVertical
  36930. || style == TwoValueVertical
  36931. || style == ThreeValueVertical;
  36932. }
  36933. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  36934. {
  36935. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  36936. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  36937. }
  36938. float Slider::getPositionOfValue (const double value)
  36939. {
  36940. if (isHorizontal() || isVertical())
  36941. {
  36942. return getLinearSliderPos (value);
  36943. }
  36944. else
  36945. {
  36946. jassertfalse // not a valid call on a slider that doesn't work linearly!
  36947. return 0.0f;
  36948. }
  36949. }
  36950. void Slider::paint (Graphics& g)
  36951. {
  36952. if (style != IncDecButtons)
  36953. {
  36954. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36955. {
  36956. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  36957. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  36958. getLookAndFeel().drawRotarySlider (g,
  36959. sliderRect.getX(),
  36960. sliderRect.getY(),
  36961. sliderRect.getWidth(),
  36962. sliderRect.getHeight(),
  36963. sliderPos,
  36964. rotaryStart, rotaryEnd,
  36965. *this);
  36966. }
  36967. else
  36968. {
  36969. getLookAndFeel().drawLinearSlider (g,
  36970. sliderRect.getX(),
  36971. sliderRect.getY(),
  36972. sliderRect.getWidth(),
  36973. sliderRect.getHeight(),
  36974. getLinearSliderPos (currentValue),
  36975. getLinearSliderPos (valueMin),
  36976. getLinearSliderPos (valueMax),
  36977. style,
  36978. *this);
  36979. }
  36980. if (style == LinearBar && valueBox == 0)
  36981. {
  36982. g.setColour (findColour (Slider::textBoxOutlineColourId));
  36983. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  36984. }
  36985. }
  36986. }
  36987. void Slider::resized()
  36988. {
  36989. int minXSpace = 0;
  36990. int minYSpace = 0;
  36991. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36992. minXSpace = 30;
  36993. else
  36994. minYSpace = 15;
  36995. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  36996. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  36997. if (style == LinearBar)
  36998. {
  36999. if (valueBox != 0)
  37000. valueBox->setBounds (0, 0, getWidth(), getHeight());
  37001. }
  37002. else
  37003. {
  37004. if (textBoxPos == NoTextBox)
  37005. {
  37006. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  37007. }
  37008. else if (textBoxPos == TextBoxLeft)
  37009. {
  37010. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  37011. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  37012. }
  37013. else if (textBoxPos == TextBoxRight)
  37014. {
  37015. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  37016. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  37017. }
  37018. else if (textBoxPos == TextBoxAbove)
  37019. {
  37020. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  37021. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  37022. }
  37023. else if (textBoxPos == TextBoxBelow)
  37024. {
  37025. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  37026. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  37027. }
  37028. }
  37029. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  37030. if (style == LinearBar)
  37031. {
  37032. const int barIndent = 1;
  37033. sliderRegionStart = barIndent;
  37034. sliderRegionSize = getWidth() - barIndent * 2;
  37035. sliderRect.setBounds (sliderRegionStart, barIndent,
  37036. sliderRegionSize, getHeight() - barIndent * 2);
  37037. }
  37038. else if (isHorizontal())
  37039. {
  37040. sliderRegionStart = sliderRect.getX() + indent;
  37041. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  37042. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  37043. sliderRegionSize, sliderRect.getHeight());
  37044. }
  37045. else if (isVertical())
  37046. {
  37047. sliderRegionStart = sliderRect.getY() + indent;
  37048. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  37049. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  37050. sliderRect.getWidth(), sliderRegionSize);
  37051. }
  37052. else
  37053. {
  37054. sliderRegionStart = 0;
  37055. sliderRegionSize = 100;
  37056. }
  37057. if (style == IncDecButtons)
  37058. {
  37059. Rectangle buttonRect (sliderRect);
  37060. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  37061. buttonRect.expand (-2, 0);
  37062. else
  37063. buttonRect.expand (0, -2);
  37064. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  37065. if (incDecButtonsSideBySide)
  37066. {
  37067. decButton->setBounds (buttonRect.getX(),
  37068. buttonRect.getY(),
  37069. buttonRect.getWidth() / 2,
  37070. buttonRect.getHeight());
  37071. decButton->setConnectedEdges (Button::ConnectedOnRight);
  37072. incButton->setBounds (buttonRect.getCentreX(),
  37073. buttonRect.getY(),
  37074. buttonRect.getWidth() / 2,
  37075. buttonRect.getHeight());
  37076. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  37077. }
  37078. else
  37079. {
  37080. incButton->setBounds (buttonRect.getX(),
  37081. buttonRect.getY(),
  37082. buttonRect.getWidth(),
  37083. buttonRect.getHeight() / 2);
  37084. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  37085. decButton->setBounds (buttonRect.getX(),
  37086. buttonRect.getCentreY(),
  37087. buttonRect.getWidth(),
  37088. buttonRect.getHeight() / 2);
  37089. decButton->setConnectedEdges (Button::ConnectedOnTop);
  37090. }
  37091. }
  37092. }
  37093. void Slider::focusOfChildComponentChanged (FocusChangeType)
  37094. {
  37095. repaint();
  37096. }
  37097. void Slider::mouseDown (const MouseEvent& e)
  37098. {
  37099. mouseWasHidden = false;
  37100. incDecDragged = false;
  37101. mouseXWhenLastDragged = e.x;
  37102. mouseYWhenLastDragged = e.y;
  37103. mouseDragStartX = e.getMouseDownX();
  37104. mouseDragStartY = e.getMouseDownY();
  37105. if (isEnabled())
  37106. {
  37107. if (e.mods.isPopupMenu() && menuEnabled)
  37108. {
  37109. menuShown = true;
  37110. PopupMenu m;
  37111. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  37112. m.addSeparator();
  37113. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37114. {
  37115. PopupMenu rotaryMenu;
  37116. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  37117. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  37118. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  37119. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  37120. }
  37121. const int r = m.show();
  37122. if (r == 1)
  37123. {
  37124. setVelocityBasedMode (! isVelocityBased);
  37125. }
  37126. else if (r == 2)
  37127. {
  37128. setSliderStyle (Rotary);
  37129. }
  37130. else if (r == 3)
  37131. {
  37132. setSliderStyle (RotaryHorizontalDrag);
  37133. }
  37134. else if (r == 4)
  37135. {
  37136. setSliderStyle (RotaryVerticalDrag);
  37137. }
  37138. }
  37139. else if (maximum > minimum)
  37140. {
  37141. menuShown = false;
  37142. if (valueBox != 0)
  37143. valueBox->hideEditor (true);
  37144. sliderBeingDragged = 0;
  37145. if (style == TwoValueHorizontal
  37146. || style == TwoValueVertical
  37147. || style == ThreeValueHorizontal
  37148. || style == ThreeValueVertical)
  37149. {
  37150. const float mousePos = (float) (isVertical() ? e.y : e.x);
  37151. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  37152. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  37153. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  37154. if (style == TwoValueHorizontal || style == TwoValueVertical)
  37155. {
  37156. if (maxPosDistance <= minPosDistance)
  37157. sliderBeingDragged = 2;
  37158. else
  37159. sliderBeingDragged = 1;
  37160. }
  37161. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  37162. {
  37163. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  37164. sliderBeingDragged = 1;
  37165. else if (normalPosDistance >= maxPosDistance)
  37166. sliderBeingDragged = 2;
  37167. }
  37168. }
  37169. minMaxDiff = valueMax - valueMin;
  37170. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  37171. * valueToProportionOfLength (currentValue);
  37172. if (sliderBeingDragged == 2)
  37173. valueWhenLastDragged = valueMax;
  37174. else if (sliderBeingDragged == 1)
  37175. valueWhenLastDragged = valueMin;
  37176. else
  37177. valueWhenLastDragged = currentValue;
  37178. valueOnMouseDown = valueWhenLastDragged;
  37179. if (popupDisplayEnabled)
  37180. {
  37181. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  37182. popupDisplay = popup;
  37183. if (parentForPopupDisplay != 0)
  37184. {
  37185. parentForPopupDisplay->addChildComponent (popup);
  37186. }
  37187. else
  37188. {
  37189. popup->addToDesktop (0);
  37190. }
  37191. popup->setVisible (true);
  37192. }
  37193. sendDragStart();
  37194. mouseDrag (e);
  37195. }
  37196. }
  37197. }
  37198. void Slider::mouseUp (const MouseEvent&)
  37199. {
  37200. if (isEnabled()
  37201. && (! menuShown)
  37202. && (maximum > minimum)
  37203. && (style != IncDecButtons || incDecDragged))
  37204. {
  37205. restoreMouseIfHidden();
  37206. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  37207. triggerChangeMessage (false);
  37208. sendDragEnd();
  37209. deleteAndZero (popupDisplay);
  37210. if (style == IncDecButtons)
  37211. {
  37212. incButton->setState (Button::buttonNormal);
  37213. decButton->setState (Button::buttonNormal);
  37214. }
  37215. }
  37216. }
  37217. void Slider::restoreMouseIfHidden()
  37218. {
  37219. if (mouseWasHidden)
  37220. {
  37221. mouseWasHidden = false;
  37222. Component* c = Component::getComponentUnderMouse();
  37223. if (c == 0)
  37224. c = this;
  37225. c->enableUnboundedMouseMovement (false);
  37226. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  37227. : ((sliderBeingDragged == 1) ? getMinValue()
  37228. : currentValue);
  37229. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  37230. {
  37231. int x, y, downX, downY;
  37232. Desktop::getMousePosition (x, y);
  37233. Desktop::getLastMouseDownPosition (downX, downY);
  37234. if (style == RotaryHorizontalDrag)
  37235. {
  37236. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  37237. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  37238. y = downY;
  37239. }
  37240. else
  37241. {
  37242. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  37243. x = downX;
  37244. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  37245. }
  37246. Desktop::setMousePosition (x, y);
  37247. }
  37248. else
  37249. {
  37250. const int pixelPos = (int) getLinearSliderPos (pos);
  37251. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  37252. int y = isVertical() ? pixelPos : (getHeight() / 2);
  37253. relativePositionToGlobal (x, y);
  37254. Desktop::setMousePosition (x, y);
  37255. }
  37256. }
  37257. }
  37258. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  37259. {
  37260. if (isEnabled()
  37261. && style != IncDecButtons
  37262. && style != Rotary
  37263. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  37264. {
  37265. restoreMouseIfHidden();
  37266. }
  37267. }
  37268. static double smallestAngleBetween (double a1, double a2)
  37269. {
  37270. return jmin (fabs (a1 - a2),
  37271. fabs (a1 + double_Pi * 2.0 - a2),
  37272. fabs (a2 + double_Pi * 2.0 - a1));
  37273. }
  37274. void Slider::mouseDrag (const MouseEvent& e)
  37275. {
  37276. if (isEnabled()
  37277. && (! menuShown)
  37278. && (maximum > minimum))
  37279. {
  37280. if (style == Rotary)
  37281. {
  37282. int dx = e.x - sliderRect.getCentreX();
  37283. int dy = e.y - sliderRect.getCentreY();
  37284. if (dx * dx + dy * dy > 25)
  37285. {
  37286. double angle = atan2 ((double) dx, (double) -dy);
  37287. while (angle < 0.0)
  37288. angle += double_Pi * 2.0;
  37289. if (rotaryStop && ! e.mouseWasClicked())
  37290. {
  37291. if (fabs (angle - lastAngle) > double_Pi)
  37292. {
  37293. if (angle >= lastAngle)
  37294. angle -= double_Pi * 2.0;
  37295. else
  37296. angle += double_Pi * 2.0;
  37297. }
  37298. if (angle >= lastAngle)
  37299. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  37300. else
  37301. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  37302. }
  37303. else
  37304. {
  37305. while (angle < rotaryStart)
  37306. angle += double_Pi * 2.0;
  37307. if (angle > rotaryEnd)
  37308. {
  37309. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  37310. angle = rotaryStart;
  37311. else
  37312. angle = rotaryEnd;
  37313. }
  37314. }
  37315. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  37316. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  37317. lastAngle = angle;
  37318. }
  37319. }
  37320. else
  37321. {
  37322. if (style == LinearBar && e.mouseWasClicked()
  37323. && valueBox != 0 && valueBox->isEditable())
  37324. return;
  37325. if (style == IncDecButtons && ! incDecDragged)
  37326. {
  37327. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  37328. return;
  37329. incDecDragged = true;
  37330. mouseDragStartX = e.x;
  37331. mouseDragStartY = e.y;
  37332. }
  37333. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  37334. : false))
  37335. || ((maximum - minimum) / sliderRegionSize < interval))
  37336. {
  37337. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  37338. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  37339. if (style == RotaryHorizontalDrag
  37340. || style == RotaryVerticalDrag
  37341. || style == IncDecButtons
  37342. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  37343. && ! snapsToMousePos))
  37344. {
  37345. const int mouseDiff = (style == RotaryHorizontalDrag
  37346. || style == LinearHorizontal
  37347. || style == LinearBar
  37348. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37349. ? e.x - mouseDragStartX
  37350. : mouseDragStartY - e.y;
  37351. double newPos = valueToProportionOfLength (valueOnMouseDown)
  37352. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  37353. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  37354. if (style == IncDecButtons)
  37355. {
  37356. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  37357. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  37358. }
  37359. }
  37360. else
  37361. {
  37362. if (isVertical())
  37363. scaledMousePos = 1.0 - scaledMousePos;
  37364. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  37365. }
  37366. }
  37367. else
  37368. {
  37369. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  37370. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  37371. ? e.x - mouseXWhenLastDragged
  37372. : e.y - mouseYWhenLastDragged;
  37373. const double maxSpeed = jmax (200, sliderRegionSize);
  37374. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  37375. if (speed != 0)
  37376. {
  37377. speed = 0.2 * velocityModeSensitivity
  37378. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  37379. + jmax (0.0, (double) (speed - velocityModeThreshold))
  37380. / maxSpeed))));
  37381. if (mouseDiff < 0)
  37382. speed = -speed;
  37383. if (isVertical() || style == RotaryVerticalDrag
  37384. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  37385. speed = -speed;
  37386. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  37387. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  37388. e.originalComponent->enableUnboundedMouseMovement (true, false);
  37389. mouseWasHidden = true;
  37390. }
  37391. }
  37392. }
  37393. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  37394. if (sliderBeingDragged == 0)
  37395. {
  37396. setValue (snapValue (valueWhenLastDragged, true),
  37397. ! sendChangeOnlyOnRelease, true);
  37398. }
  37399. else if (sliderBeingDragged == 1)
  37400. {
  37401. setMinValue (snapValue (valueWhenLastDragged, true),
  37402. ! sendChangeOnlyOnRelease, false, true);
  37403. if (e.mods.isShiftDown())
  37404. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  37405. else
  37406. minMaxDiff = valueMax - valueMin;
  37407. }
  37408. else
  37409. {
  37410. jassert (sliderBeingDragged == 2);
  37411. setMaxValue (snapValue (valueWhenLastDragged, true),
  37412. ! sendChangeOnlyOnRelease, false, true);
  37413. if (e.mods.isShiftDown())
  37414. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  37415. else
  37416. minMaxDiff = valueMax - valueMin;
  37417. }
  37418. mouseXWhenLastDragged = e.x;
  37419. mouseYWhenLastDragged = e.y;
  37420. }
  37421. }
  37422. void Slider::mouseDoubleClick (const MouseEvent&)
  37423. {
  37424. if (doubleClickToValue
  37425. && isEnabled()
  37426. && style != IncDecButtons
  37427. && minimum <= doubleClickReturnValue
  37428. && maximum >= doubleClickReturnValue)
  37429. {
  37430. sendDragStart();
  37431. setValue (doubleClickReturnValue, true, true);
  37432. sendDragEnd();
  37433. }
  37434. }
  37435. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37436. {
  37437. if (scrollWheelEnabled && isEnabled()
  37438. && style != TwoValueHorizontal
  37439. && style != TwoValueVertical)
  37440. {
  37441. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  37442. {
  37443. if (valueBox != 0)
  37444. valueBox->hideEditor (false);
  37445. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  37446. const double currentPos = valueToProportionOfLength (currentValue);
  37447. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  37448. double delta = (newValue != currentValue)
  37449. ? jmax (fabs (newValue - currentValue), interval) : 0;
  37450. if (currentValue > newValue)
  37451. delta = -delta;
  37452. sendDragStart();
  37453. setValue (snapValue (currentValue + delta, false), true, true);
  37454. sendDragEnd();
  37455. }
  37456. }
  37457. else
  37458. {
  37459. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37460. }
  37461. }
  37462. void SliderListener::sliderDragStarted (Slider*)
  37463. {
  37464. }
  37465. void SliderListener::sliderDragEnded (Slider*)
  37466. {
  37467. }
  37468. END_JUCE_NAMESPACE
  37469. /********* End of inlined file: juce_Slider.cpp *********/
  37470. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  37471. BEGIN_JUCE_NAMESPACE
  37472. class DragOverlayComp : public Component
  37473. {
  37474. public:
  37475. DragOverlayComp (Image* const image_)
  37476. : image (image_)
  37477. {
  37478. image->multiplyAllAlphas (0.8f);
  37479. setAlwaysOnTop (true);
  37480. }
  37481. ~DragOverlayComp()
  37482. {
  37483. delete image;
  37484. }
  37485. void paint (Graphics& g)
  37486. {
  37487. g.drawImageAt (image, 0, 0);
  37488. }
  37489. private:
  37490. Image* image;
  37491. DragOverlayComp (const DragOverlayComp&);
  37492. const DragOverlayComp& operator= (const DragOverlayComp&);
  37493. };
  37494. TableHeaderComponent::TableHeaderComponent()
  37495. : listeners (2),
  37496. dragOverlayComp (0),
  37497. columnsChanged (false),
  37498. columnsResized (false),
  37499. sortChanged (false),
  37500. menuActive (true),
  37501. stretchToFit (false),
  37502. columnIdBeingResized (0),
  37503. columnIdBeingDragged (0),
  37504. columnIdUnderMouse (0),
  37505. lastDeliberateWidth (0)
  37506. {
  37507. }
  37508. TableHeaderComponent::~TableHeaderComponent()
  37509. {
  37510. delete dragOverlayComp;
  37511. }
  37512. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  37513. {
  37514. menuActive = hasMenu;
  37515. }
  37516. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  37517. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  37518. {
  37519. if (onlyCountVisibleColumns)
  37520. {
  37521. int num = 0;
  37522. for (int i = columns.size(); --i >= 0;)
  37523. if (columns.getUnchecked(i)->isVisible())
  37524. ++num;
  37525. return num;
  37526. }
  37527. else
  37528. {
  37529. return columns.size();
  37530. }
  37531. }
  37532. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  37533. {
  37534. const ColumnInfo* const ci = getInfoForId (columnId);
  37535. return ci != 0 ? ci->name : String::empty;
  37536. }
  37537. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  37538. {
  37539. ColumnInfo* const ci = getInfoForId (columnId);
  37540. if (ci != 0 && ci->name != newName)
  37541. {
  37542. ci->name = newName;
  37543. sendColumnsChanged();
  37544. }
  37545. }
  37546. void TableHeaderComponent::addColumn (const String& columnName,
  37547. const int columnId,
  37548. const int width,
  37549. const int minimumWidth,
  37550. const int maximumWidth,
  37551. const int propertyFlags,
  37552. const int insertIndex)
  37553. {
  37554. // can't have a duplicate or null ID!
  37555. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  37556. jassert (width > 0);
  37557. ColumnInfo* const ci = new ColumnInfo();
  37558. ci->name = columnName;
  37559. ci->id = columnId;
  37560. ci->width = width;
  37561. ci->lastDeliberateWidth = width;
  37562. ci->minimumWidth = minimumWidth;
  37563. ci->maximumWidth = maximumWidth;
  37564. if (ci->maximumWidth < 0)
  37565. ci->maximumWidth = INT_MAX;
  37566. jassert (ci->maximumWidth >= ci->minimumWidth);
  37567. ci->propertyFlags = propertyFlags;
  37568. columns.insert (insertIndex, ci);
  37569. sendColumnsChanged();
  37570. }
  37571. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  37572. {
  37573. const int index = getIndexOfColumnId (columnIdToRemove, false);
  37574. if (index >= 0)
  37575. {
  37576. columns.remove (index);
  37577. sortChanged = true;
  37578. sendColumnsChanged();
  37579. }
  37580. }
  37581. void TableHeaderComponent::removeAllColumns()
  37582. {
  37583. if (columns.size() > 0)
  37584. {
  37585. columns.clear();
  37586. sendColumnsChanged();
  37587. }
  37588. }
  37589. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  37590. {
  37591. const int currentIndex = getIndexOfColumnId (columnId, false);
  37592. newIndex = visibleIndexToTotalIndex (newIndex);
  37593. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  37594. {
  37595. columns.move (currentIndex, newIndex);
  37596. sendColumnsChanged();
  37597. }
  37598. }
  37599. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  37600. {
  37601. ColumnInfo* const ci = getInfoForId (columnId);
  37602. if (ci != 0 && ci->width != newWidth)
  37603. {
  37604. const int numColumns = getNumColumns (true);
  37605. ci->lastDeliberateWidth = ci->width
  37606. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  37607. if (stretchToFit)
  37608. {
  37609. const int index = getIndexOfColumnId (columnId, true) + 1;
  37610. if (((unsigned int) index) < (unsigned int) numColumns)
  37611. {
  37612. const int x = getColumnPosition (index).getX();
  37613. if (lastDeliberateWidth == 0)
  37614. lastDeliberateWidth = getTotalWidth();
  37615. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  37616. }
  37617. }
  37618. repaint();
  37619. columnsResized = true;
  37620. triggerAsyncUpdate();
  37621. }
  37622. }
  37623. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  37624. {
  37625. int n = 0;
  37626. for (int i = 0; i < columns.size(); ++i)
  37627. {
  37628. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  37629. {
  37630. if (columns.getUnchecked(i)->id == columnId)
  37631. return n;
  37632. ++n;
  37633. }
  37634. }
  37635. return -1;
  37636. }
  37637. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  37638. {
  37639. if (onlyCountVisibleColumns)
  37640. index = visibleIndexToTotalIndex (index);
  37641. const ColumnInfo* const ci = columns [index];
  37642. return (ci != 0) ? ci->id : 0;
  37643. }
  37644. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  37645. {
  37646. int x = 0, width = 0, n = 0;
  37647. for (int i = 0; i < columns.size(); ++i)
  37648. {
  37649. x += width;
  37650. if (columns.getUnchecked(i)->isVisible())
  37651. {
  37652. width = columns.getUnchecked(i)->width;
  37653. if (n++ == index)
  37654. break;
  37655. }
  37656. else
  37657. {
  37658. width = 0;
  37659. }
  37660. }
  37661. return Rectangle (x, 0, width, getHeight());
  37662. }
  37663. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  37664. {
  37665. if (xToFind >= 0)
  37666. {
  37667. int x = 0;
  37668. for (int i = 0; i < columns.size(); ++i)
  37669. {
  37670. const ColumnInfo* const ci = columns.getUnchecked(i);
  37671. if (ci->isVisible())
  37672. {
  37673. x += ci->width;
  37674. if (xToFind < x)
  37675. return ci->id;
  37676. }
  37677. }
  37678. }
  37679. return 0;
  37680. }
  37681. int TableHeaderComponent::getTotalWidth() const throw()
  37682. {
  37683. int w = 0;
  37684. for (int i = columns.size(); --i >= 0;)
  37685. if (columns.getUnchecked(i)->isVisible())
  37686. w += columns.getUnchecked(i)->width;
  37687. return w;
  37688. }
  37689. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  37690. {
  37691. stretchToFit = shouldStretchToFit;
  37692. lastDeliberateWidth = getTotalWidth();
  37693. resized();
  37694. }
  37695. bool TableHeaderComponent::isStretchToFitActive() const throw()
  37696. {
  37697. return stretchToFit;
  37698. }
  37699. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  37700. {
  37701. if (stretchToFit && getWidth() > 0
  37702. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  37703. {
  37704. lastDeliberateWidth = targetTotalWidth;
  37705. resizeColumnsToFit (0, targetTotalWidth);
  37706. }
  37707. }
  37708. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  37709. {
  37710. targetTotalWidth = jmax (targetTotalWidth, 0);
  37711. StretchableObjectResizer sor;
  37712. int i;
  37713. for (i = firstColumnIndex; i < columns.size(); ++i)
  37714. {
  37715. ColumnInfo* const ci = columns.getUnchecked(i);
  37716. if (ci->isVisible())
  37717. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  37718. }
  37719. sor.resizeToFit (targetTotalWidth);
  37720. int visIndex = 0;
  37721. for (i = firstColumnIndex; i < columns.size(); ++i)
  37722. {
  37723. ColumnInfo* const ci = columns.getUnchecked(i);
  37724. if (ci->isVisible())
  37725. {
  37726. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  37727. (int) floor (sor.getItemSize (visIndex++)));
  37728. if (newWidth != ci->width)
  37729. {
  37730. ci->width = newWidth;
  37731. repaint();
  37732. columnsResized = true;
  37733. triggerAsyncUpdate();
  37734. }
  37735. }
  37736. }
  37737. }
  37738. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  37739. {
  37740. ColumnInfo* const ci = getInfoForId (columnId);
  37741. if (ci != 0 && shouldBeVisible != ci->isVisible())
  37742. {
  37743. if (shouldBeVisible)
  37744. ci->propertyFlags |= visible;
  37745. else
  37746. ci->propertyFlags &= ~visible;
  37747. sendColumnsChanged();
  37748. resized();
  37749. }
  37750. }
  37751. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  37752. {
  37753. const ColumnInfo* const ci = getInfoForId (columnId);
  37754. return ci != 0 && ci->isVisible();
  37755. }
  37756. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  37757. {
  37758. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  37759. {
  37760. for (int i = columns.size(); --i >= 0;)
  37761. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  37762. ColumnInfo* const ci = getInfoForId (columnId);
  37763. if (ci != 0)
  37764. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  37765. reSortTable();
  37766. }
  37767. }
  37768. int TableHeaderComponent::getSortColumnId() const throw()
  37769. {
  37770. for (int i = columns.size(); --i >= 0;)
  37771. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37772. return columns.getUnchecked(i)->id;
  37773. return 0;
  37774. }
  37775. bool TableHeaderComponent::isSortedForwards() const throw()
  37776. {
  37777. for (int i = columns.size(); --i >= 0;)
  37778. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  37779. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  37780. return true;
  37781. }
  37782. void TableHeaderComponent::reSortTable()
  37783. {
  37784. sortChanged = true;
  37785. repaint();
  37786. triggerAsyncUpdate();
  37787. }
  37788. const String TableHeaderComponent::toString() const
  37789. {
  37790. String s;
  37791. XmlElement doc (T("TABLELAYOUT"));
  37792. doc.setAttribute (T("sortedCol"), getSortColumnId());
  37793. doc.setAttribute (T("sortForwards"), isSortedForwards());
  37794. for (int i = 0; i < columns.size(); ++i)
  37795. {
  37796. const ColumnInfo* const ci = columns.getUnchecked (i);
  37797. XmlElement* const e = new XmlElement (T("COLUMN"));
  37798. doc.addChildElement (e);
  37799. e->setAttribute (T("id"), ci->id);
  37800. e->setAttribute (T("visible"), ci->isVisible());
  37801. e->setAttribute (T("width"), ci->width);
  37802. }
  37803. return doc.createDocument (String::empty, true, false);
  37804. }
  37805. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  37806. {
  37807. XmlDocument doc (storedVersion);
  37808. XmlElement* const storedXml = doc.getDocumentElement();
  37809. int index = 0;
  37810. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  37811. {
  37812. forEachXmlChildElement (*storedXml, col)
  37813. {
  37814. const int tabId = col->getIntAttribute (T("id"));
  37815. ColumnInfo* const ci = getInfoForId (tabId);
  37816. if (ci != 0)
  37817. {
  37818. columns.move (columns.indexOf (ci), index);
  37819. ci->width = col->getIntAttribute (T("width"));
  37820. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  37821. }
  37822. ++index;
  37823. }
  37824. columnsResized = true;
  37825. sendColumnsChanged();
  37826. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  37827. storedXml->getBoolAttribute (T("sortForwards"), true));
  37828. }
  37829. delete storedXml;
  37830. }
  37831. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  37832. {
  37833. listeners.addIfNotAlreadyThere (newListener);
  37834. }
  37835. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  37836. {
  37837. listeners.removeValue (listenerToRemove);
  37838. }
  37839. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  37840. {
  37841. const ColumnInfo* const ci = getInfoForId (columnId);
  37842. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  37843. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  37844. }
  37845. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  37846. {
  37847. for (int i = 0; i < columns.size(); ++i)
  37848. {
  37849. const ColumnInfo* const ci = columns.getUnchecked(i);
  37850. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  37851. menu.addItem (ci->id, ci->name,
  37852. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  37853. isColumnVisible (ci->id));
  37854. }
  37855. }
  37856. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  37857. {
  37858. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  37859. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  37860. }
  37861. void TableHeaderComponent::paint (Graphics& g)
  37862. {
  37863. LookAndFeel& lf = getLookAndFeel();
  37864. lf.drawTableHeaderBackground (g, *this);
  37865. const Rectangle clip (g.getClipBounds());
  37866. int x = 0;
  37867. for (int i = 0; i < columns.size(); ++i)
  37868. {
  37869. const ColumnInfo* const ci = columns.getUnchecked(i);
  37870. if (ci->isVisible())
  37871. {
  37872. if (x + ci->width > clip.getX()
  37873. && (ci->id != columnIdBeingDragged
  37874. || dragOverlayComp == 0
  37875. || ! dragOverlayComp->isVisible()))
  37876. {
  37877. g.saveState();
  37878. g.setOrigin (x, 0);
  37879. g.reduceClipRegion (0, 0, ci->width, getHeight());
  37880. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  37881. ci->id == columnIdUnderMouse,
  37882. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  37883. ci->propertyFlags);
  37884. g.restoreState();
  37885. }
  37886. x += ci->width;
  37887. if (x >= clip.getRight())
  37888. break;
  37889. }
  37890. }
  37891. }
  37892. void TableHeaderComponent::resized()
  37893. {
  37894. }
  37895. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  37896. {
  37897. updateColumnUnderMouse (e.x, e.y);
  37898. }
  37899. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  37900. {
  37901. updateColumnUnderMouse (e.x, e.y);
  37902. }
  37903. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  37904. {
  37905. updateColumnUnderMouse (e.x, e.y);
  37906. }
  37907. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  37908. {
  37909. repaint();
  37910. columnIdBeingResized = 0;
  37911. columnIdBeingDragged = 0;
  37912. if (columnIdUnderMouse != 0)
  37913. {
  37914. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  37915. if (e.mods.isPopupMenu())
  37916. columnClicked (columnIdUnderMouse, e.mods);
  37917. }
  37918. if (menuActive && e.mods.isPopupMenu())
  37919. showColumnChooserMenu (columnIdUnderMouse);
  37920. }
  37921. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  37922. {
  37923. if (columnIdBeingResized == 0
  37924. && columnIdBeingDragged == 0
  37925. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  37926. {
  37927. deleteAndZero (dragOverlayComp);
  37928. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  37929. if (columnIdBeingResized != 0)
  37930. {
  37931. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37932. initialColumnWidth = ci->width;
  37933. }
  37934. else
  37935. {
  37936. beginDrag (e);
  37937. }
  37938. }
  37939. if (columnIdBeingResized != 0)
  37940. {
  37941. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  37942. if (ci != 0)
  37943. {
  37944. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  37945. initialColumnWidth + e.getDistanceFromDragStartX());
  37946. if (stretchToFit)
  37947. {
  37948. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  37949. int minWidthOnRight = 0;
  37950. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  37951. if (columns.getUnchecked (i)->isVisible())
  37952. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  37953. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  37954. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  37955. }
  37956. setColumnWidth (columnIdBeingResized, w);
  37957. }
  37958. }
  37959. else if (columnIdBeingDragged != 0)
  37960. {
  37961. if (e.y >= -50 && e.y < getHeight() + 50)
  37962. {
  37963. beginDrag (e);
  37964. if (dragOverlayComp != 0)
  37965. {
  37966. dragOverlayComp->setVisible (true);
  37967. dragOverlayComp->setBounds (jlimit (0,
  37968. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  37969. e.x - draggingColumnOffset),
  37970. 0,
  37971. dragOverlayComp->getWidth(),
  37972. getHeight());
  37973. for (int i = columns.size(); --i >= 0;)
  37974. {
  37975. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37976. int newIndex = currentIndex;
  37977. if (newIndex > 0)
  37978. {
  37979. // if the previous column isn't draggable, we can't move our column
  37980. // past it, because that'd change the undraggable column's position..
  37981. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  37982. if ((previous->propertyFlags & draggable) != 0)
  37983. {
  37984. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  37985. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  37986. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  37987. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  37988. {
  37989. --newIndex;
  37990. }
  37991. }
  37992. }
  37993. if (newIndex < columns.size() - 1)
  37994. {
  37995. // if the next column isn't draggable, we can't move our column
  37996. // past it, because that'd change the undraggable column's position..
  37997. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  37998. if ((nextCol->propertyFlags & draggable) != 0)
  37999. {
  38000. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  38001. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  38002. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  38003. > abs (dragOverlayComp->getRight() - rightOfNext))
  38004. {
  38005. ++newIndex;
  38006. }
  38007. }
  38008. }
  38009. if (newIndex != currentIndex)
  38010. moveColumn (columnIdBeingDragged, newIndex);
  38011. else
  38012. break;
  38013. }
  38014. }
  38015. }
  38016. else
  38017. {
  38018. endDrag (draggingColumnOriginalIndex);
  38019. }
  38020. }
  38021. }
  38022. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  38023. {
  38024. if (columnIdBeingDragged == 0)
  38025. {
  38026. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  38027. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  38028. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  38029. {
  38030. columnIdBeingDragged = 0;
  38031. }
  38032. else
  38033. {
  38034. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  38035. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  38036. const int temp = columnIdBeingDragged;
  38037. columnIdBeingDragged = 0;
  38038. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  38039. columnIdBeingDragged = temp;
  38040. dragOverlayComp->setBounds (columnRect);
  38041. for (int i = listeners.size(); --i >= 0;)
  38042. {
  38043. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  38044. i = jmin (i, listeners.size() - 1);
  38045. }
  38046. }
  38047. }
  38048. }
  38049. void TableHeaderComponent::endDrag (const int finalIndex)
  38050. {
  38051. if (columnIdBeingDragged != 0)
  38052. {
  38053. moveColumn (columnIdBeingDragged, finalIndex);
  38054. columnIdBeingDragged = 0;
  38055. repaint();
  38056. for (int i = listeners.size(); --i >= 0;)
  38057. {
  38058. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  38059. i = jmin (i, listeners.size() - 1);
  38060. }
  38061. }
  38062. }
  38063. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  38064. {
  38065. mouseDrag (e);
  38066. for (int i = columns.size(); --i >= 0;)
  38067. if (columns.getUnchecked (i)->isVisible())
  38068. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  38069. columnIdBeingResized = 0;
  38070. repaint();
  38071. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  38072. updateColumnUnderMouse (e.x, e.y);
  38073. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  38074. columnClicked (columnIdUnderMouse, e.mods);
  38075. deleteAndZero (dragOverlayComp);
  38076. }
  38077. const MouseCursor TableHeaderComponent::getMouseCursor()
  38078. {
  38079. int x, y;
  38080. getMouseXYRelative (x, y);
  38081. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  38082. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  38083. return Component::getMouseCursor();
  38084. }
  38085. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  38086. {
  38087. return (propertyFlags & TableHeaderComponent::visible) != 0;
  38088. }
  38089. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  38090. {
  38091. for (int i = columns.size(); --i >= 0;)
  38092. if (columns.getUnchecked(i)->id == id)
  38093. return columns.getUnchecked(i);
  38094. return 0;
  38095. }
  38096. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  38097. {
  38098. int n = 0;
  38099. for (int i = 0; i < columns.size(); ++i)
  38100. {
  38101. if (columns.getUnchecked(i)->isVisible())
  38102. {
  38103. if (n == visibleIndex)
  38104. return i;
  38105. ++n;
  38106. }
  38107. }
  38108. return -1;
  38109. }
  38110. void TableHeaderComponent::sendColumnsChanged()
  38111. {
  38112. if (stretchToFit && lastDeliberateWidth > 0)
  38113. resizeAllColumnsToFit (lastDeliberateWidth);
  38114. repaint();
  38115. columnsChanged = true;
  38116. triggerAsyncUpdate();
  38117. }
  38118. void TableHeaderComponent::handleAsyncUpdate()
  38119. {
  38120. const bool changed = columnsChanged || sortChanged;
  38121. const bool sized = columnsResized || changed;
  38122. const bool sorted = sortChanged;
  38123. columnsChanged = false;
  38124. columnsResized = false;
  38125. sortChanged = false;
  38126. if (sorted)
  38127. {
  38128. for (int i = listeners.size(); --i >= 0;)
  38129. {
  38130. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  38131. i = jmin (i, listeners.size() - 1);
  38132. }
  38133. }
  38134. if (changed)
  38135. {
  38136. for (int i = listeners.size(); --i >= 0;)
  38137. {
  38138. listeners.getUnchecked(i)->tableColumnsChanged (this);
  38139. i = jmin (i, listeners.size() - 1);
  38140. }
  38141. }
  38142. if (sized)
  38143. {
  38144. for (int i = listeners.size(); --i >= 0;)
  38145. {
  38146. listeners.getUnchecked(i)->tableColumnsResized (this);
  38147. i = jmin (i, listeners.size() - 1);
  38148. }
  38149. }
  38150. }
  38151. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  38152. {
  38153. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  38154. {
  38155. const int draggableDistance = 3;
  38156. int x = 0;
  38157. for (int i = 0; i < columns.size(); ++i)
  38158. {
  38159. const ColumnInfo* const ci = columns.getUnchecked(i);
  38160. if (ci->isVisible())
  38161. {
  38162. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  38163. && (ci->propertyFlags & resizable) != 0)
  38164. return ci->id;
  38165. x += ci->width;
  38166. }
  38167. }
  38168. }
  38169. return 0;
  38170. }
  38171. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  38172. {
  38173. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  38174. ? getColumnIdAtX (x) : 0;
  38175. if (newCol != columnIdUnderMouse)
  38176. {
  38177. columnIdUnderMouse = newCol;
  38178. repaint();
  38179. }
  38180. }
  38181. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  38182. {
  38183. PopupMenu m;
  38184. addMenuItems (m, columnIdClicked);
  38185. if (m.getNumItems() > 0)
  38186. {
  38187. const int result = m.show();
  38188. if (result != 0)
  38189. reactToMenuItem (result, columnIdClicked);
  38190. }
  38191. }
  38192. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  38193. {
  38194. }
  38195. END_JUCE_NAMESPACE
  38196. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  38197. /********* Start of inlined file: juce_TableListBox.cpp *********/
  38198. BEGIN_JUCE_NAMESPACE
  38199. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  38200. class TableListRowComp : public Component
  38201. {
  38202. public:
  38203. TableListRowComp (TableListBox& owner_)
  38204. : owner (owner_),
  38205. row (-1),
  38206. isSelected (false)
  38207. {
  38208. }
  38209. ~TableListRowComp()
  38210. {
  38211. deleteAllChildren();
  38212. }
  38213. void paint (Graphics& g)
  38214. {
  38215. TableListBoxModel* const model = owner.getModel();
  38216. if (model != 0)
  38217. {
  38218. const TableHeaderComponent* const header = owner.getHeader();
  38219. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  38220. const int numColumns = header->getNumColumns (true);
  38221. for (int i = 0; i < numColumns; ++i)
  38222. {
  38223. if (! columnsWithComponents [i])
  38224. {
  38225. const int columnId = header->getColumnIdOfIndex (i, true);
  38226. Rectangle columnRect (header->getColumnPosition (i));
  38227. columnRect.setSize (columnRect.getWidth(), getHeight());
  38228. g.saveState();
  38229. g.reduceClipRegion (columnRect);
  38230. g.setOrigin (columnRect.getX(), 0);
  38231. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  38232. g.restoreState();
  38233. }
  38234. }
  38235. }
  38236. }
  38237. void update (const int newRow, const bool isNowSelected)
  38238. {
  38239. if (newRow != row || isNowSelected != isSelected)
  38240. {
  38241. row = newRow;
  38242. isSelected = isNowSelected;
  38243. repaint();
  38244. }
  38245. if (row < owner.getNumRows())
  38246. {
  38247. jassert (row >= 0);
  38248. const tchar* const tagPropertyName = T("_tableLastUseNum");
  38249. const int newTag = Random::getSystemRandom().nextInt();
  38250. const TableHeaderComponent* const header = owner.getHeader();
  38251. const int numColumns = header->getNumColumns (true);
  38252. int i;
  38253. columnsWithComponents.clear();
  38254. if (owner.getModel() != 0)
  38255. {
  38256. for (i = 0; i < numColumns; ++i)
  38257. {
  38258. const int columnId = header->getColumnIdOfIndex (i, true);
  38259. Component* const newComp
  38260. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  38261. findChildComponentForColumn (columnId));
  38262. if (newComp != 0)
  38263. {
  38264. addAndMakeVisible (newComp);
  38265. newComp->setComponentProperty (tagPropertyName, newTag);
  38266. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  38267. const Rectangle columnRect (header->getColumnPosition (i));
  38268. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38269. columnsWithComponents.setBit (i);
  38270. }
  38271. }
  38272. }
  38273. for (i = getNumChildComponents(); --i >= 0;)
  38274. {
  38275. Component* const c = getChildComponent (i);
  38276. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  38277. delete c;
  38278. }
  38279. }
  38280. else
  38281. {
  38282. columnsWithComponents.clear();
  38283. deleteAllChildren();
  38284. }
  38285. }
  38286. void resized()
  38287. {
  38288. for (int i = getNumChildComponents(); --i >= 0;)
  38289. {
  38290. Component* const c = getChildComponent (i);
  38291. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  38292. if (columnId != 0)
  38293. {
  38294. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  38295. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  38296. }
  38297. }
  38298. }
  38299. void mouseDown (const MouseEvent& e)
  38300. {
  38301. isDragging = false;
  38302. selectRowOnMouseUp = false;
  38303. if (isEnabled())
  38304. {
  38305. if (! isSelected)
  38306. {
  38307. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38308. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38309. if (columnId != 0 && owner.getModel() != 0)
  38310. owner.getModel()->cellClicked (row, columnId, e);
  38311. }
  38312. else
  38313. {
  38314. selectRowOnMouseUp = true;
  38315. }
  38316. }
  38317. }
  38318. void mouseDrag (const MouseEvent& e)
  38319. {
  38320. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  38321. {
  38322. const SparseSet <int> selectedRows (owner.getSelectedRows());
  38323. if (selectedRows.size() > 0)
  38324. {
  38325. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  38326. if (dragDescription.isNotEmpty())
  38327. {
  38328. isDragging = true;
  38329. DragAndDropContainer* const dragContainer
  38330. = DragAndDropContainer::findParentDragContainerFor (this);
  38331. if (dragContainer != 0)
  38332. {
  38333. Image* dragImage = owner.createSnapshotOfSelectedRows();
  38334. dragImage->multiplyAllAlphas (0.6f);
  38335. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  38336. }
  38337. else
  38338. {
  38339. // to be able to do a drag-and-drop operation, the listbox needs to
  38340. // be inside a component which is also a DragAndDropContainer.
  38341. jassertfalse
  38342. }
  38343. }
  38344. }
  38345. }
  38346. }
  38347. void mouseUp (const MouseEvent& e)
  38348. {
  38349. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  38350. {
  38351. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  38352. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38353. if (columnId != 0 && owner.getModel() != 0)
  38354. owner.getModel()->cellClicked (row, columnId, e);
  38355. }
  38356. }
  38357. void mouseDoubleClick (const MouseEvent& e)
  38358. {
  38359. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  38360. if (columnId != 0 && owner.getModel() != 0)
  38361. owner.getModel()->cellDoubleClicked (row, columnId, e);
  38362. }
  38363. juce_UseDebuggingNewOperator
  38364. private:
  38365. TableListBox& owner;
  38366. int row;
  38367. bool isSelected, isDragging, selectRowOnMouseUp;
  38368. BitArray columnsWithComponents;
  38369. Component* findChildComponentForColumn (const int columnId) const
  38370. {
  38371. for (int i = getNumChildComponents(); --i >= 0;)
  38372. {
  38373. Component* const c = getChildComponent (i);
  38374. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  38375. return c;
  38376. }
  38377. return 0;
  38378. }
  38379. TableListRowComp (const TableListRowComp&);
  38380. const TableListRowComp& operator= (const TableListRowComp&);
  38381. };
  38382. class TableListBoxHeader : public TableHeaderComponent
  38383. {
  38384. public:
  38385. TableListBoxHeader (TableListBox& owner_)
  38386. : owner (owner_)
  38387. {
  38388. }
  38389. ~TableListBoxHeader()
  38390. {
  38391. }
  38392. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  38393. {
  38394. if (owner.isAutoSizeMenuOptionShown())
  38395. {
  38396. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  38397. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  38398. menu.addSeparator();
  38399. }
  38400. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  38401. }
  38402. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  38403. {
  38404. if (menuReturnId == 0xf836743)
  38405. {
  38406. owner.autoSizeColumn (columnIdClicked);
  38407. }
  38408. else if (menuReturnId == 0xf836744)
  38409. {
  38410. owner.autoSizeAllColumns();
  38411. }
  38412. else
  38413. {
  38414. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  38415. }
  38416. }
  38417. juce_UseDebuggingNewOperator
  38418. private:
  38419. TableListBox& owner;
  38420. TableListBoxHeader (const TableListBoxHeader&);
  38421. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  38422. };
  38423. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  38424. : ListBox (name, 0),
  38425. model (model_),
  38426. autoSizeOptionsShown (true)
  38427. {
  38428. ListBox::model = this;
  38429. header = new TableListBoxHeader (*this);
  38430. header->setSize (100, 28);
  38431. header->addListener (this);
  38432. setHeaderComponent (header);
  38433. }
  38434. TableListBox::~TableListBox()
  38435. {
  38436. deleteAllChildren();
  38437. }
  38438. void TableListBox::setModel (TableListBoxModel* const newModel)
  38439. {
  38440. if (model != newModel)
  38441. {
  38442. model = newModel;
  38443. updateContent();
  38444. }
  38445. }
  38446. int TableListBox::getHeaderHeight() const throw()
  38447. {
  38448. return header->getHeight();
  38449. }
  38450. void TableListBox::setHeaderHeight (const int newHeight)
  38451. {
  38452. header->setSize (header->getWidth(), newHeight);
  38453. resized();
  38454. }
  38455. void TableListBox::autoSizeColumn (const int columnId)
  38456. {
  38457. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  38458. if (width > 0)
  38459. header->setColumnWidth (columnId, width);
  38460. }
  38461. void TableListBox::autoSizeAllColumns()
  38462. {
  38463. for (int i = 0; i < header->getNumColumns (true); ++i)
  38464. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  38465. }
  38466. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  38467. {
  38468. autoSizeOptionsShown = shouldBeShown;
  38469. }
  38470. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  38471. {
  38472. return autoSizeOptionsShown;
  38473. }
  38474. const Rectangle TableListBox::getCellPosition (const int columnId,
  38475. const int rowNumber,
  38476. const bool relativeToComponentTopLeft) const
  38477. {
  38478. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38479. if (relativeToComponentTopLeft)
  38480. headerCell.translate (header->getX(), 0);
  38481. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  38482. return Rectangle (headerCell.getX(), row.getY(),
  38483. headerCell.getWidth(), row.getHeight());
  38484. }
  38485. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  38486. {
  38487. ScrollBar* const scrollbar = getHorizontalScrollBar();
  38488. if (scrollbar != 0)
  38489. {
  38490. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  38491. double x = scrollbar->getCurrentRangeStart();
  38492. const double w = scrollbar->getCurrentRangeSize();
  38493. if (pos.getX() < x)
  38494. x = pos.getX();
  38495. else if (pos.getRight() > x + w)
  38496. x += jmax (0.0, pos.getRight() - (x + w));
  38497. scrollbar->setCurrentRangeStart (x);
  38498. }
  38499. }
  38500. int TableListBox::getNumRows()
  38501. {
  38502. return model != 0 ? model->getNumRows() : 0;
  38503. }
  38504. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  38505. {
  38506. }
  38507. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  38508. {
  38509. if (existingComponentToUpdate == 0)
  38510. existingComponentToUpdate = new TableListRowComp (*this);
  38511. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  38512. return existingComponentToUpdate;
  38513. }
  38514. void TableListBox::selectedRowsChanged (int row)
  38515. {
  38516. if (model != 0)
  38517. model->selectedRowsChanged (row);
  38518. }
  38519. void TableListBox::deleteKeyPressed (int row)
  38520. {
  38521. if (model != 0)
  38522. model->deleteKeyPressed (row);
  38523. }
  38524. void TableListBox::returnKeyPressed (int row)
  38525. {
  38526. if (model != 0)
  38527. model->returnKeyPressed (row);
  38528. }
  38529. void TableListBox::backgroundClicked()
  38530. {
  38531. if (model != 0)
  38532. model->backgroundClicked();
  38533. }
  38534. void TableListBox::listWasScrolled()
  38535. {
  38536. if (model != 0)
  38537. model->listWasScrolled();
  38538. }
  38539. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  38540. {
  38541. setMinimumContentWidth (header->getTotalWidth());
  38542. repaint();
  38543. updateColumnComponents();
  38544. }
  38545. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  38546. {
  38547. setMinimumContentWidth (header->getTotalWidth());
  38548. repaint();
  38549. updateColumnComponents();
  38550. }
  38551. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  38552. {
  38553. if (model != 0)
  38554. model->sortOrderChanged (header->getSortColumnId(),
  38555. header->isSortedForwards());
  38556. }
  38557. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  38558. {
  38559. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  38560. repaint();
  38561. }
  38562. void TableListBox::resized()
  38563. {
  38564. ListBox::resized();
  38565. header->resizeAllColumnsToFit (getVisibleContentWidth());
  38566. setMinimumContentWidth (header->getTotalWidth());
  38567. }
  38568. void TableListBox::updateColumnComponents() const
  38569. {
  38570. const int firstRow = getRowContainingPosition (0, 0);
  38571. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  38572. {
  38573. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  38574. if (rowComp != 0)
  38575. rowComp->resized();
  38576. }
  38577. }
  38578. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  38579. {
  38580. }
  38581. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  38582. {
  38583. }
  38584. void TableListBoxModel::backgroundClicked()
  38585. {
  38586. }
  38587. void TableListBoxModel::sortOrderChanged (int, const bool)
  38588. {
  38589. }
  38590. int TableListBoxModel::getColumnAutoSizeWidth (int)
  38591. {
  38592. return 0;
  38593. }
  38594. void TableListBoxModel::selectedRowsChanged (int)
  38595. {
  38596. }
  38597. void TableListBoxModel::deleteKeyPressed (int)
  38598. {
  38599. }
  38600. void TableListBoxModel::returnKeyPressed (int)
  38601. {
  38602. }
  38603. void TableListBoxModel::listWasScrolled()
  38604. {
  38605. }
  38606. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  38607. {
  38608. return String::empty;
  38609. }
  38610. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  38611. {
  38612. (void) existingComponentToUpdate;
  38613. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  38614. return 0;
  38615. }
  38616. END_JUCE_NAMESPACE
  38617. /********* End of inlined file: juce_TableListBox.cpp *********/
  38618. /********* Start of inlined file: juce_TextEditor.cpp *********/
  38619. BEGIN_JUCE_NAMESPACE
  38620. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  38621. // a word or space that can't be broken down any further
  38622. struct TextAtom
  38623. {
  38624. String atomText;
  38625. float width;
  38626. uint16 numChars;
  38627. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  38628. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  38629. const String getText (const tchar passwordCharacter) const throw()
  38630. {
  38631. if (passwordCharacter == 0)
  38632. return atomText;
  38633. else
  38634. return String::repeatedString (String::charToString (passwordCharacter),
  38635. atomText.length());
  38636. }
  38637. const String getTrimmedText (const tchar passwordCharacter) const throw()
  38638. {
  38639. if (passwordCharacter == 0)
  38640. return atomText.substring (0, numChars);
  38641. else if (isNewLine())
  38642. return String::empty;
  38643. else
  38644. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  38645. }
  38646. };
  38647. // a run of text with a single font and colour
  38648. class UniformTextSection
  38649. {
  38650. public:
  38651. UniformTextSection (const String& text,
  38652. const Font& font_,
  38653. const Colour& colour_,
  38654. const tchar passwordCharacter) throw()
  38655. : font (font_),
  38656. colour (colour_),
  38657. atoms (64)
  38658. {
  38659. initialiseAtoms (text, passwordCharacter);
  38660. }
  38661. UniformTextSection (const UniformTextSection& other) throw()
  38662. : font (other.font),
  38663. colour (other.colour),
  38664. atoms (64)
  38665. {
  38666. for (int i = 0; i < other.atoms.size(); ++i)
  38667. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  38668. }
  38669. ~UniformTextSection() throw()
  38670. {
  38671. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  38672. }
  38673. void clear() throw()
  38674. {
  38675. for (int i = atoms.size(); --i >= 0;)
  38676. {
  38677. TextAtom* const atom = getAtom(i);
  38678. delete atom;
  38679. }
  38680. atoms.clear();
  38681. }
  38682. int getNumAtoms() const throw()
  38683. {
  38684. return atoms.size();
  38685. }
  38686. TextAtom* getAtom (const int index) const throw()
  38687. {
  38688. return (TextAtom*) atoms.getUnchecked (index);
  38689. }
  38690. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  38691. {
  38692. if (other.atoms.size() > 0)
  38693. {
  38694. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  38695. int i = 0;
  38696. if (lastAtom != 0)
  38697. {
  38698. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  38699. {
  38700. TextAtom* const first = other.getAtom(0);
  38701. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  38702. {
  38703. lastAtom->atomText += first->atomText;
  38704. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  38705. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  38706. delete first;
  38707. ++i;
  38708. }
  38709. }
  38710. }
  38711. while (i < other.atoms.size())
  38712. {
  38713. atoms.add (other.getAtom(i));
  38714. ++i;
  38715. }
  38716. }
  38717. }
  38718. UniformTextSection* split (const int indexToBreakAt,
  38719. const tchar passwordCharacter) throw()
  38720. {
  38721. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  38722. font, colour,
  38723. passwordCharacter);
  38724. int index = 0;
  38725. for (int i = 0; i < atoms.size(); ++i)
  38726. {
  38727. TextAtom* const atom = getAtom(i);
  38728. const int nextIndex = index + atom->numChars;
  38729. if (index == indexToBreakAt)
  38730. {
  38731. int j;
  38732. for (j = i; j < atoms.size(); ++j)
  38733. section2->atoms.add (getAtom (j));
  38734. for (j = atoms.size(); --j >= i;)
  38735. atoms.remove (j);
  38736. break;
  38737. }
  38738. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  38739. {
  38740. TextAtom* const secondAtom = new TextAtom();
  38741. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  38742. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  38743. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  38744. section2->atoms.add (secondAtom);
  38745. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  38746. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38747. atom->numChars = (uint16) (indexToBreakAt - index);
  38748. int j;
  38749. for (j = i + 1; j < atoms.size(); ++j)
  38750. section2->atoms.add (getAtom (j));
  38751. for (j = atoms.size(); --j > i;)
  38752. atoms.remove (j);
  38753. break;
  38754. }
  38755. index = nextIndex;
  38756. }
  38757. return section2;
  38758. }
  38759. const String getAllText() const throw()
  38760. {
  38761. String s;
  38762. s.preallocateStorage (getTotalLength());
  38763. tchar* endOfString = (tchar*) &(s[0]);
  38764. for (int i = 0; i < atoms.size(); ++i)
  38765. {
  38766. const TextAtom* const atom = getAtom(i);
  38767. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  38768. endOfString += atom->numChars;
  38769. }
  38770. *endOfString = 0;
  38771. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  38772. return s;
  38773. }
  38774. const String getTextSubstring (const int startCharacter,
  38775. const int endCharacter) const throw()
  38776. {
  38777. int index = 0;
  38778. int totalLen = 0;
  38779. int i;
  38780. for (i = 0; i < atoms.size(); ++i)
  38781. {
  38782. const TextAtom* const atom = getAtom (i);
  38783. const int nextIndex = index + atom->numChars;
  38784. if (startCharacter < nextIndex)
  38785. {
  38786. if (endCharacter <= index)
  38787. break;
  38788. const int start = jmax (0, startCharacter - index);
  38789. const int end = jmin (endCharacter - index, atom->numChars);
  38790. jassert (end >= start);
  38791. totalLen += end - start;
  38792. }
  38793. index = nextIndex;
  38794. }
  38795. String s;
  38796. s.preallocateStorage (totalLen + 1);
  38797. tchar* psz = (tchar*) (const tchar*) s;
  38798. index = 0;
  38799. for (i = 0; i < atoms.size(); ++i)
  38800. {
  38801. const TextAtom* const atom = getAtom (i);
  38802. const int nextIndex = index + atom->numChars;
  38803. if (startCharacter < nextIndex)
  38804. {
  38805. if (endCharacter <= index)
  38806. break;
  38807. const int start = jmax (0, startCharacter - index);
  38808. const int len = jmin (endCharacter - index, atom->numChars) - start;
  38809. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  38810. psz += len;
  38811. *psz = 0;
  38812. }
  38813. index = nextIndex;
  38814. }
  38815. return s;
  38816. }
  38817. int getTotalLength() const throw()
  38818. {
  38819. int c = 0;
  38820. for (int i = atoms.size(); --i >= 0;)
  38821. c += getAtom(i)->numChars;
  38822. return c;
  38823. }
  38824. void setFont (const Font& newFont,
  38825. const tchar passwordCharacter) throw()
  38826. {
  38827. if (font != newFont)
  38828. {
  38829. font = newFont;
  38830. for (int i = atoms.size(); --i >= 0;)
  38831. {
  38832. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  38833. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  38834. }
  38835. }
  38836. }
  38837. juce_UseDebuggingNewOperator
  38838. Font font;
  38839. Colour colour;
  38840. private:
  38841. VoidArray atoms;
  38842. void initialiseAtoms (const String& textToParse,
  38843. const tchar passwordCharacter) throw()
  38844. {
  38845. int i = 0;
  38846. const int len = textToParse.length();
  38847. const tchar* const text = (const tchar*) textToParse;
  38848. while (i < len)
  38849. {
  38850. int start = i;
  38851. // create a whitespace atom unless it starts with non-ws
  38852. if (CharacterFunctions::isWhitespace (text[i])
  38853. && text[i] != T('\r')
  38854. && text[i] != T('\n'))
  38855. {
  38856. while (i < len
  38857. && CharacterFunctions::isWhitespace (text[i])
  38858. && text[i] != T('\r')
  38859. && text[i] != T('\n'))
  38860. {
  38861. ++i;
  38862. }
  38863. }
  38864. else
  38865. {
  38866. if (text[i] == T('\r'))
  38867. {
  38868. ++i;
  38869. if ((i < len) && (text[i] == T('\n')))
  38870. {
  38871. ++start;
  38872. ++i;
  38873. }
  38874. }
  38875. else if (text[i] == T('\n'))
  38876. {
  38877. ++i;
  38878. }
  38879. else
  38880. {
  38881. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  38882. ++i;
  38883. }
  38884. }
  38885. TextAtom* const atom = new TextAtom();
  38886. atom->atomText = String (text + start, i - start);
  38887. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  38888. atom->numChars = (uint16) (i - start);
  38889. atoms.add (atom);
  38890. }
  38891. }
  38892. const UniformTextSection& operator= (const UniformTextSection& other);
  38893. };
  38894. class TextEditorIterator
  38895. {
  38896. public:
  38897. TextEditorIterator (const VoidArray& sections_,
  38898. const float wordWrapWidth_,
  38899. const tchar passwordCharacter_) throw()
  38900. : indexInText (0),
  38901. lineY (0),
  38902. lineHeight (0),
  38903. maxDescent (0),
  38904. atomX (0),
  38905. atomRight (0),
  38906. atom (0),
  38907. currentSection (0),
  38908. sections (sections_),
  38909. sectionIndex (0),
  38910. atomIndex (0),
  38911. wordWrapWidth (wordWrapWidth_),
  38912. passwordCharacter (passwordCharacter_)
  38913. {
  38914. jassert (wordWrapWidth_ > 0);
  38915. if (sections.size() > 0)
  38916. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38917. if (currentSection != 0)
  38918. {
  38919. lineHeight = currentSection->font.getHeight();
  38920. maxDescent = currentSection->font.getDescent();
  38921. }
  38922. }
  38923. TextEditorIterator (const TextEditorIterator& other) throw()
  38924. : indexInText (other.indexInText),
  38925. lineY (other.lineY),
  38926. lineHeight (other.lineHeight),
  38927. maxDescent (other.maxDescent),
  38928. atomX (other.atomX),
  38929. atomRight (other.atomRight),
  38930. atom (other.atom),
  38931. currentSection (other.currentSection),
  38932. sections (other.sections),
  38933. sectionIndex (other.sectionIndex),
  38934. atomIndex (other.atomIndex),
  38935. wordWrapWidth (other.wordWrapWidth),
  38936. passwordCharacter (other.passwordCharacter),
  38937. tempAtom (other.tempAtom)
  38938. {
  38939. }
  38940. ~TextEditorIterator() throw()
  38941. {
  38942. }
  38943. bool next() throw()
  38944. {
  38945. if (atom == &tempAtom)
  38946. {
  38947. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  38948. if (numRemaining > 0)
  38949. {
  38950. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  38951. atomX = 0;
  38952. if (tempAtom.numChars > 0)
  38953. lineY += lineHeight;
  38954. indexInText += tempAtom.numChars;
  38955. GlyphArrangement g;
  38956. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  38957. int split;
  38958. for (split = 0; split < g.getNumGlyphs(); ++split)
  38959. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  38960. break;
  38961. if (split > 0 && split <= numRemaining)
  38962. {
  38963. tempAtom.numChars = (uint16) split;
  38964. tempAtom.width = g.getGlyph (split - 1).getRight();
  38965. atomRight = atomX + tempAtom.width;
  38966. return true;
  38967. }
  38968. }
  38969. }
  38970. bool forceNewLine = false;
  38971. if (sectionIndex >= sections.size())
  38972. {
  38973. moveToEndOfLastAtom();
  38974. return false;
  38975. }
  38976. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  38977. {
  38978. if (atomIndex >= currentSection->getNumAtoms())
  38979. {
  38980. if (++sectionIndex >= sections.size())
  38981. {
  38982. moveToEndOfLastAtom();
  38983. return false;
  38984. }
  38985. atomIndex = 0;
  38986. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38987. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  38988. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  38989. }
  38990. else
  38991. {
  38992. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  38993. if (! lastAtom->isWhitespace())
  38994. {
  38995. // handle the case where the last atom in a section is actually part of the same
  38996. // word as the first atom of the next section...
  38997. float right = atomRight + lastAtom->width;
  38998. float lineHeight2 = lineHeight;
  38999. float maxDescent2 = maxDescent;
  39000. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  39001. {
  39002. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  39003. if (s->getNumAtoms() == 0)
  39004. break;
  39005. const TextAtom* const nextAtom = s->getAtom (0);
  39006. if (nextAtom->isWhitespace())
  39007. break;
  39008. right += nextAtom->width;
  39009. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  39010. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  39011. if (SHOULD_WRAP (right, wordWrapWidth))
  39012. {
  39013. lineHeight = lineHeight2;
  39014. maxDescent = maxDescent2;
  39015. forceNewLine = true;
  39016. break;
  39017. }
  39018. if (s->getNumAtoms() > 1)
  39019. break;
  39020. }
  39021. }
  39022. }
  39023. }
  39024. if (atom != 0)
  39025. {
  39026. atomX = atomRight;
  39027. indexInText += atom->numChars;
  39028. if (atom->isNewLine())
  39029. {
  39030. atomX = 0;
  39031. lineY += lineHeight;
  39032. }
  39033. }
  39034. atom = currentSection->getAtom (atomIndex);
  39035. atomRight = atomX + atom->width;
  39036. ++atomIndex;
  39037. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  39038. {
  39039. if (atom->isWhitespace())
  39040. {
  39041. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  39042. atomRight = jmin (atomRight, wordWrapWidth);
  39043. }
  39044. else
  39045. {
  39046. return wrapCurrentAtom();
  39047. }
  39048. }
  39049. return true;
  39050. }
  39051. bool wrapCurrentAtom() throw()
  39052. {
  39053. atomRight = atom->width;
  39054. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  39055. {
  39056. tempAtom = *atom;
  39057. tempAtom.width = 0;
  39058. tempAtom.numChars = 0;
  39059. atom = &tempAtom;
  39060. if (atomX > 0)
  39061. {
  39062. atomX = 0;
  39063. lineY += lineHeight;
  39064. }
  39065. return next();
  39066. }
  39067. atomX = 0;
  39068. lineY += lineHeight;
  39069. return true;
  39070. }
  39071. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  39072. {
  39073. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39074. {
  39075. if (lastSection != currentSection)
  39076. {
  39077. lastSection = currentSection;
  39078. g.setColour (currentSection->colour);
  39079. g.setFont (currentSection->font);
  39080. }
  39081. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  39082. GlyphArrangement ga;
  39083. ga.addLineOfText (currentSection->font,
  39084. atom->getTrimmedText (passwordCharacter),
  39085. atomX,
  39086. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39087. ga.draw (g);
  39088. }
  39089. }
  39090. void drawSelection (Graphics& g,
  39091. const int selectionStart,
  39092. const int selectionEnd) const throw()
  39093. {
  39094. const int startX = roundFloatToInt (indexToX (selectionStart));
  39095. const int endX = roundFloatToInt (indexToX (selectionEnd));
  39096. const int y = roundFloatToInt (lineY);
  39097. const int nextY = roundFloatToInt (lineY + lineHeight);
  39098. g.fillRect (startX, y, endX - startX, nextY - y);
  39099. }
  39100. void drawSelectedText (Graphics& g,
  39101. const int selectionStart,
  39102. const int selectionEnd,
  39103. const Colour& selectedTextColour) const throw()
  39104. {
  39105. if (passwordCharacter != 0 || ! atom->isWhitespace())
  39106. {
  39107. GlyphArrangement ga;
  39108. ga.addLineOfText (currentSection->font,
  39109. atom->getTrimmedText (passwordCharacter),
  39110. atomX,
  39111. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  39112. if (selectionEnd < indexInText + atom->numChars)
  39113. {
  39114. GlyphArrangement ga2 (ga);
  39115. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  39116. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  39117. g.setColour (currentSection->colour);
  39118. ga2.draw (g);
  39119. }
  39120. if (selectionStart > indexInText)
  39121. {
  39122. GlyphArrangement ga2 (ga);
  39123. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  39124. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  39125. g.setColour (currentSection->colour);
  39126. ga2.draw (g);
  39127. }
  39128. g.setColour (selectedTextColour);
  39129. ga.draw (g);
  39130. }
  39131. }
  39132. float indexToX (const int indexToFind) const throw()
  39133. {
  39134. if (indexToFind <= indexInText)
  39135. return atomX;
  39136. if (indexToFind >= indexInText + atom->numChars)
  39137. return atomRight;
  39138. GlyphArrangement g;
  39139. g.addLineOfText (currentSection->font,
  39140. atom->getText (passwordCharacter),
  39141. atomX, 0.0f);
  39142. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  39143. }
  39144. int xToIndex (const float xToFind) const throw()
  39145. {
  39146. if (xToFind <= atomX || atom->isNewLine())
  39147. return indexInText;
  39148. if (xToFind >= atomRight)
  39149. return indexInText + atom->numChars;
  39150. GlyphArrangement g;
  39151. g.addLineOfText (currentSection->font,
  39152. atom->getText (passwordCharacter),
  39153. atomX, 0.0f);
  39154. int j;
  39155. for (j = 0; j < atom->numChars; ++j)
  39156. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  39157. break;
  39158. return indexInText + j;
  39159. }
  39160. void updateLineHeight() throw()
  39161. {
  39162. float x = atomRight;
  39163. int tempSectionIndex = sectionIndex;
  39164. int tempAtomIndex = atomIndex;
  39165. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39166. while (! SHOULD_WRAP (x, wordWrapWidth))
  39167. {
  39168. if (tempSectionIndex >= sections.size())
  39169. break;
  39170. bool checkSize = false;
  39171. if (tempAtomIndex >= currentSection->getNumAtoms())
  39172. {
  39173. if (++tempSectionIndex >= sections.size())
  39174. break;
  39175. tempAtomIndex = 0;
  39176. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  39177. checkSize = true;
  39178. }
  39179. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  39180. if (atom == 0)
  39181. break;
  39182. x += atom->width;
  39183. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  39184. break;
  39185. if (checkSize)
  39186. {
  39187. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  39188. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  39189. }
  39190. ++tempAtomIndex;
  39191. }
  39192. }
  39193. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  39194. {
  39195. while (next())
  39196. {
  39197. if (indexInText + atom->numChars >= index)
  39198. {
  39199. updateLineHeight();
  39200. if (indexInText + atom->numChars > index)
  39201. {
  39202. cx = indexToX (index);
  39203. cy = lineY;
  39204. lineHeight_ = lineHeight;
  39205. return true;
  39206. }
  39207. }
  39208. }
  39209. cx = atomX;
  39210. cy = lineY;
  39211. lineHeight_ = lineHeight;
  39212. return false;
  39213. }
  39214. juce_UseDebuggingNewOperator
  39215. int indexInText;
  39216. float lineY, lineHeight, maxDescent;
  39217. float atomX, atomRight;
  39218. const TextAtom* atom;
  39219. const UniformTextSection* currentSection;
  39220. private:
  39221. const VoidArray& sections;
  39222. int sectionIndex, atomIndex;
  39223. const float wordWrapWidth;
  39224. const tchar passwordCharacter;
  39225. TextAtom tempAtom;
  39226. const TextEditorIterator& operator= (const TextEditorIterator&);
  39227. void moveToEndOfLastAtom() throw()
  39228. {
  39229. if (atom != 0)
  39230. {
  39231. atomX = atomRight;
  39232. if (atom->isNewLine())
  39233. {
  39234. atomX = 0.0f;
  39235. lineY += lineHeight;
  39236. }
  39237. }
  39238. }
  39239. };
  39240. class TextEditorInsertAction : public UndoableAction
  39241. {
  39242. TextEditor& owner;
  39243. const String text;
  39244. const int insertIndex, oldCaretPos, newCaretPos;
  39245. const Font font;
  39246. const Colour colour;
  39247. TextEditorInsertAction (const TextEditorInsertAction&);
  39248. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  39249. public:
  39250. TextEditorInsertAction (TextEditor& owner_,
  39251. const String& text_,
  39252. const int insertIndex_,
  39253. const Font& font_,
  39254. const Colour& colour_,
  39255. const int oldCaretPos_,
  39256. const int newCaretPos_) throw()
  39257. : owner (owner_),
  39258. text (text_),
  39259. insertIndex (insertIndex_),
  39260. oldCaretPos (oldCaretPos_),
  39261. newCaretPos (newCaretPos_),
  39262. font (font_),
  39263. colour (colour_)
  39264. {
  39265. }
  39266. ~TextEditorInsertAction()
  39267. {
  39268. }
  39269. bool perform()
  39270. {
  39271. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  39272. return true;
  39273. }
  39274. bool undo()
  39275. {
  39276. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  39277. return true;
  39278. }
  39279. int getSizeInUnits()
  39280. {
  39281. return text.length() + 16;
  39282. }
  39283. };
  39284. class TextEditorRemoveAction : public UndoableAction
  39285. {
  39286. TextEditor& owner;
  39287. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  39288. VoidArray removedSections;
  39289. TextEditorRemoveAction (const TextEditorRemoveAction&);
  39290. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  39291. public:
  39292. TextEditorRemoveAction (TextEditor& owner_,
  39293. const int startIndex_,
  39294. const int endIndex_,
  39295. const int oldCaretPos_,
  39296. const int newCaretPos_,
  39297. const VoidArray& removedSections_) throw()
  39298. : owner (owner_),
  39299. startIndex (startIndex_),
  39300. endIndex (endIndex_),
  39301. oldCaretPos (oldCaretPos_),
  39302. newCaretPos (newCaretPos_),
  39303. removedSections (removedSections_)
  39304. {
  39305. }
  39306. ~TextEditorRemoveAction()
  39307. {
  39308. for (int i = removedSections.size(); --i >= 0;)
  39309. {
  39310. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39311. section->clear();
  39312. delete section;
  39313. }
  39314. }
  39315. bool perform()
  39316. {
  39317. owner.remove (startIndex, endIndex, 0, newCaretPos);
  39318. return true;
  39319. }
  39320. bool undo()
  39321. {
  39322. owner.reinsert (startIndex, removedSections);
  39323. owner.moveCursorTo (oldCaretPos, false);
  39324. return true;
  39325. }
  39326. int getSizeInUnits()
  39327. {
  39328. int n = 0;
  39329. for (int i = removedSections.size(); --i >= 0;)
  39330. {
  39331. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  39332. n += section->getTotalLength();
  39333. }
  39334. return n + 16;
  39335. }
  39336. };
  39337. class TextHolderComponent : public Component,
  39338. public Timer
  39339. {
  39340. TextEditor* const owner;
  39341. TextHolderComponent (const TextHolderComponent&);
  39342. const TextHolderComponent& operator= (const TextHolderComponent&);
  39343. public:
  39344. TextHolderComponent (TextEditor* const owner_)
  39345. : owner (owner_)
  39346. {
  39347. setWantsKeyboardFocus (false);
  39348. setInterceptsMouseClicks (false, true);
  39349. }
  39350. ~TextHolderComponent()
  39351. {
  39352. }
  39353. void paint (Graphics& g)
  39354. {
  39355. owner->drawContent (g);
  39356. }
  39357. void timerCallback()
  39358. {
  39359. owner->timerCallbackInt();
  39360. }
  39361. const MouseCursor getMouseCursor()
  39362. {
  39363. return owner->getMouseCursor();
  39364. }
  39365. };
  39366. class TextEditorViewport : public Viewport
  39367. {
  39368. TextEditor* const owner;
  39369. float lastWordWrapWidth;
  39370. TextEditorViewport (const TextEditorViewport&);
  39371. const TextEditorViewport& operator= (const TextEditorViewport&);
  39372. public:
  39373. TextEditorViewport (TextEditor* const owner_)
  39374. : owner (owner_),
  39375. lastWordWrapWidth (0)
  39376. {
  39377. }
  39378. ~TextEditorViewport()
  39379. {
  39380. }
  39381. void visibleAreaChanged (int, int, int, int)
  39382. {
  39383. const float wordWrapWidth = owner->getWordWrapWidth();
  39384. if (wordWrapWidth != lastWordWrapWidth)
  39385. {
  39386. lastWordWrapWidth = wordWrapWidth;
  39387. owner->updateTextHolderSize();
  39388. }
  39389. }
  39390. };
  39391. const int flashSpeedIntervalMs = 380;
  39392. const int textChangeMessageId = 0x10003001;
  39393. const int returnKeyMessageId = 0x10003002;
  39394. const int escapeKeyMessageId = 0x10003003;
  39395. const int focusLossMessageId = 0x10003004;
  39396. TextEditor::TextEditor (const String& name,
  39397. const tchar passwordCharacter_)
  39398. : Component (name),
  39399. borderSize (1, 1, 1, 3),
  39400. readOnly (false),
  39401. multiline (false),
  39402. wordWrap (false),
  39403. returnKeyStartsNewLine (false),
  39404. caretVisible (true),
  39405. popupMenuEnabled (true),
  39406. selectAllTextWhenFocused (false),
  39407. scrollbarVisible (true),
  39408. wasFocused (false),
  39409. caretFlashState (true),
  39410. keepCursorOnScreen (true),
  39411. tabKeyUsed (false),
  39412. menuActive (false),
  39413. cursorX (0),
  39414. cursorY (0),
  39415. cursorHeight (0),
  39416. maxTextLength (0),
  39417. selectionStart (0),
  39418. selectionEnd (0),
  39419. leftIndent (4),
  39420. topIndent (4),
  39421. lastTransactionTime (0),
  39422. currentFont (14.0f),
  39423. totalNumChars (0),
  39424. caretPosition (0),
  39425. sections (8),
  39426. passwordCharacter (passwordCharacter_),
  39427. dragType (notDragging),
  39428. listeners (2)
  39429. {
  39430. setOpaque (true);
  39431. addAndMakeVisible (viewport = new TextEditorViewport (this));
  39432. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  39433. viewport->setWantsKeyboardFocus (false);
  39434. viewport->setScrollBarsShown (false, false);
  39435. setMouseCursor (MouseCursor::IBeamCursor);
  39436. setWantsKeyboardFocus (true);
  39437. }
  39438. TextEditor::~TextEditor()
  39439. {
  39440. clearInternal (0);
  39441. delete viewport;
  39442. }
  39443. void TextEditor::newTransaction() throw()
  39444. {
  39445. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39446. undoManager.beginNewTransaction();
  39447. }
  39448. void TextEditor::doUndoRedo (const bool isRedo)
  39449. {
  39450. if (! isReadOnly())
  39451. {
  39452. if ((isRedo) ? undoManager.redo()
  39453. : undoManager.undo())
  39454. {
  39455. scrollToMakeSureCursorIsVisible();
  39456. repaint();
  39457. textChanged();
  39458. }
  39459. }
  39460. }
  39461. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  39462. const bool shouldWordWrap)
  39463. {
  39464. multiline = shouldBeMultiLine;
  39465. wordWrap = shouldWordWrap && shouldBeMultiLine;
  39466. setScrollbarsShown (scrollbarVisible);
  39467. viewport->setViewPosition (0, 0);
  39468. resized();
  39469. scrollToMakeSureCursorIsVisible();
  39470. }
  39471. bool TextEditor::isMultiLine() const throw()
  39472. {
  39473. return multiline;
  39474. }
  39475. void TextEditor::setScrollbarsShown (bool enabled) throw()
  39476. {
  39477. scrollbarVisible = enabled;
  39478. enabled = enabled && isMultiLine();
  39479. viewport->setScrollBarsShown (enabled, enabled);
  39480. }
  39481. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  39482. {
  39483. readOnly = shouldBeReadOnly;
  39484. enablementChanged();
  39485. }
  39486. bool TextEditor::isReadOnly() const throw()
  39487. {
  39488. return readOnly || ! isEnabled();
  39489. }
  39490. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  39491. {
  39492. returnKeyStartsNewLine = shouldStartNewLine;
  39493. }
  39494. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  39495. {
  39496. tabKeyUsed = shouldTabKeyBeUsed;
  39497. }
  39498. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  39499. {
  39500. popupMenuEnabled = b;
  39501. }
  39502. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  39503. {
  39504. selectAllTextWhenFocused = b;
  39505. }
  39506. const Font TextEditor::getFont() const throw()
  39507. {
  39508. return currentFont;
  39509. }
  39510. void TextEditor::setFont (const Font& newFont) throw()
  39511. {
  39512. currentFont = newFont;
  39513. scrollToMakeSureCursorIsVisible();
  39514. }
  39515. void TextEditor::applyFontToAllText (const Font& newFont)
  39516. {
  39517. currentFont = newFont;
  39518. const Colour overallColour (findColour (textColourId));
  39519. for (int i = sections.size(); --i >= 0;)
  39520. {
  39521. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  39522. uts->setFont (newFont, passwordCharacter);
  39523. uts->colour = overallColour;
  39524. }
  39525. coalesceSimilarSections();
  39526. updateTextHolderSize();
  39527. scrollToMakeSureCursorIsVisible();
  39528. repaint();
  39529. }
  39530. void TextEditor::colourChanged()
  39531. {
  39532. setOpaque (findColour (backgroundColourId).isOpaque());
  39533. repaint();
  39534. }
  39535. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  39536. {
  39537. caretVisible = shouldCaretBeVisible;
  39538. if (shouldCaretBeVisible)
  39539. textHolder->startTimer (flashSpeedIntervalMs);
  39540. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  39541. : MouseCursor::NormalCursor);
  39542. }
  39543. void TextEditor::setInputRestrictions (const int maxLen,
  39544. const String& chars) throw()
  39545. {
  39546. maxTextLength = jmax (0, maxLen);
  39547. allowedCharacters = chars;
  39548. }
  39549. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  39550. {
  39551. textToShowWhenEmpty = text;
  39552. colourForTextWhenEmpty = colourToUse;
  39553. }
  39554. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  39555. {
  39556. if (passwordCharacter != newPasswordCharacter)
  39557. {
  39558. passwordCharacter = newPasswordCharacter;
  39559. resized();
  39560. repaint();
  39561. }
  39562. }
  39563. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  39564. {
  39565. viewport->setScrollBarThickness (newThicknessPixels);
  39566. }
  39567. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  39568. {
  39569. viewport->setScrollBarButtonVisibility (buttonsVisible);
  39570. }
  39571. void TextEditor::clear()
  39572. {
  39573. clearInternal (0);
  39574. updateTextHolderSize();
  39575. undoManager.clearUndoHistory();
  39576. }
  39577. void TextEditor::setText (const String& newText,
  39578. const bool sendTextChangeMessage)
  39579. {
  39580. const int newLength = newText.length();
  39581. if (newLength != getTotalNumChars() || getText() != newText)
  39582. {
  39583. const int oldCursorPos = caretPosition;
  39584. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  39585. clearInternal (0);
  39586. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  39587. // if you're adding text with line-feeds to a single-line text editor, it
  39588. // ain't gonna look right!
  39589. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  39590. if (cursorWasAtEnd && ! isMultiLine())
  39591. moveCursorTo (getTotalNumChars(), false);
  39592. else
  39593. moveCursorTo (oldCursorPos, false);
  39594. if (sendTextChangeMessage)
  39595. textChanged();
  39596. repaint();
  39597. }
  39598. updateTextHolderSize();
  39599. scrollToMakeSureCursorIsVisible();
  39600. undoManager.clearUndoHistory();
  39601. }
  39602. void TextEditor::textChanged() throw()
  39603. {
  39604. updateTextHolderSize();
  39605. postCommandMessage (textChangeMessageId);
  39606. }
  39607. void TextEditor::returnPressed()
  39608. {
  39609. postCommandMessage (returnKeyMessageId);
  39610. }
  39611. void TextEditor::escapePressed()
  39612. {
  39613. postCommandMessage (escapeKeyMessageId);
  39614. }
  39615. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  39616. {
  39617. jassert (newListener != 0)
  39618. if (newListener != 0)
  39619. listeners.add (newListener);
  39620. }
  39621. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  39622. {
  39623. listeners.removeValue (listenerToRemove);
  39624. }
  39625. void TextEditor::timerCallbackInt()
  39626. {
  39627. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  39628. if (caretFlashState != newState)
  39629. {
  39630. caretFlashState = newState;
  39631. if (caretFlashState)
  39632. wasFocused = true;
  39633. if (caretVisible
  39634. && hasKeyboardFocus (false)
  39635. && ! isReadOnly())
  39636. {
  39637. repaintCaret();
  39638. }
  39639. }
  39640. const unsigned int now = Time::getApproximateMillisecondCounter();
  39641. if (now > lastTransactionTime + 200)
  39642. newTransaction();
  39643. }
  39644. void TextEditor::repaintCaret()
  39645. {
  39646. if (! findColour (caretColourId).isTransparent())
  39647. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  39648. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  39649. 4,
  39650. roundFloatToInt (cursorHeight) + 2);
  39651. }
  39652. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  39653. {
  39654. if (textStartIndex > textEndIndex && textEndIndex > 0)
  39655. swapVariables (textStartIndex, textEndIndex);
  39656. float x = 0, y = 0, lh = currentFont.getHeight();
  39657. const float wordWrapWidth = getWordWrapWidth();
  39658. if (wordWrapWidth > 0)
  39659. {
  39660. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39661. i.getCharPosition (textStartIndex, x, y, lh);
  39662. const int y1 = (int) y;
  39663. int y2;
  39664. if (textEndIndex >= 0)
  39665. {
  39666. i.getCharPosition (textEndIndex, x, y, lh);
  39667. y2 = (int) (y + lh * 2.0f);
  39668. }
  39669. else
  39670. {
  39671. y2 = textHolder->getHeight();
  39672. }
  39673. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  39674. }
  39675. }
  39676. void TextEditor::moveCaret (int newCaretPos) throw()
  39677. {
  39678. if (newCaretPos < 0)
  39679. newCaretPos = 0;
  39680. else if (newCaretPos > getTotalNumChars())
  39681. newCaretPos = getTotalNumChars();
  39682. if (newCaretPos != getCaretPosition())
  39683. {
  39684. repaintCaret();
  39685. caretFlashState = true;
  39686. caretPosition = newCaretPos;
  39687. textHolder->startTimer (flashSpeedIntervalMs);
  39688. scrollToMakeSureCursorIsVisible();
  39689. repaintCaret();
  39690. }
  39691. }
  39692. void TextEditor::setCaretPosition (const int newIndex) throw()
  39693. {
  39694. moveCursorTo (newIndex, false);
  39695. }
  39696. int TextEditor::getCaretPosition() const throw()
  39697. {
  39698. return caretPosition;
  39699. }
  39700. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  39701. const int desiredCaretY) throw()
  39702. {
  39703. updateCaretPosition();
  39704. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  39705. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  39706. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  39707. {
  39708. vx += desiredCaretX - proportionOfWidth (0.2f);
  39709. }
  39710. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39711. {
  39712. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39713. }
  39714. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  39715. if (! isMultiLine())
  39716. {
  39717. vy = viewport->getViewPositionY();
  39718. }
  39719. else
  39720. {
  39721. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  39722. const int curH = roundFloatToInt (cursorHeight);
  39723. if (desiredCaretY < 0)
  39724. {
  39725. vy = jmax (0, desiredCaretY + vy);
  39726. }
  39727. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39728. {
  39729. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39730. }
  39731. }
  39732. viewport->setViewPosition (vx, vy);
  39733. }
  39734. const Rectangle TextEditor::getCaretRectangle() throw()
  39735. {
  39736. updateCaretPosition();
  39737. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  39738. roundFloatToInt (cursorY) - viewport->getY(),
  39739. 1, roundFloatToInt (cursorHeight));
  39740. }
  39741. float TextEditor::getWordWrapWidth() const throw()
  39742. {
  39743. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  39744. : 1.0e10f;
  39745. }
  39746. void TextEditor::updateTextHolderSize() throw()
  39747. {
  39748. const float wordWrapWidth = getWordWrapWidth();
  39749. if (wordWrapWidth > 0)
  39750. {
  39751. float maxWidth = 0.0f;
  39752. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39753. while (i.next())
  39754. maxWidth = jmax (maxWidth, i.atomRight);
  39755. const int w = leftIndent + roundFloatToInt (maxWidth);
  39756. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  39757. currentFont.getHeight()));
  39758. textHolder->setSize (w + 1, h + 1);
  39759. }
  39760. }
  39761. int TextEditor::getTextWidth() const throw()
  39762. {
  39763. return textHolder->getWidth();
  39764. }
  39765. int TextEditor::getTextHeight() const throw()
  39766. {
  39767. return textHolder->getHeight();
  39768. }
  39769. void TextEditor::setIndents (const int newLeftIndent,
  39770. const int newTopIndent) throw()
  39771. {
  39772. leftIndent = newLeftIndent;
  39773. topIndent = newTopIndent;
  39774. }
  39775. void TextEditor::setBorder (const BorderSize& border) throw()
  39776. {
  39777. borderSize = border;
  39778. resized();
  39779. }
  39780. const BorderSize TextEditor::getBorder() const throw()
  39781. {
  39782. return borderSize;
  39783. }
  39784. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  39785. {
  39786. keepCursorOnScreen = shouldScrollToShowCursor;
  39787. }
  39788. void TextEditor::updateCaretPosition() throw()
  39789. {
  39790. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  39791. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  39792. }
  39793. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  39794. {
  39795. updateCaretPosition();
  39796. if (keepCursorOnScreen)
  39797. {
  39798. int x = viewport->getViewPositionX();
  39799. int y = viewport->getViewPositionY();
  39800. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  39801. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  39802. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  39803. {
  39804. x += relativeCursorX - proportionOfWidth (0.2f);
  39805. }
  39806. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  39807. {
  39808. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  39809. }
  39810. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  39811. if (! isMultiLine())
  39812. {
  39813. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  39814. }
  39815. else
  39816. {
  39817. const int curH = roundFloatToInt (cursorHeight);
  39818. if (relativeCursorY < 0)
  39819. {
  39820. y = jmax (0, relativeCursorY + y);
  39821. }
  39822. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  39823. {
  39824. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  39825. }
  39826. }
  39827. viewport->setViewPosition (x, y);
  39828. }
  39829. }
  39830. void TextEditor::moveCursorTo (const int newPosition,
  39831. const bool isSelecting) throw()
  39832. {
  39833. if (isSelecting)
  39834. {
  39835. moveCaret (newPosition);
  39836. const int oldSelStart = selectionStart;
  39837. const int oldSelEnd = selectionEnd;
  39838. if (dragType == notDragging)
  39839. {
  39840. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  39841. dragType = draggingSelectionStart;
  39842. else
  39843. dragType = draggingSelectionEnd;
  39844. }
  39845. if (dragType == draggingSelectionStart)
  39846. {
  39847. selectionStart = getCaretPosition();
  39848. if (selectionEnd < selectionStart)
  39849. {
  39850. swapVariables (selectionStart, selectionEnd);
  39851. dragType = draggingSelectionEnd;
  39852. }
  39853. }
  39854. else
  39855. {
  39856. selectionEnd = getCaretPosition();
  39857. if (selectionEnd < selectionStart)
  39858. {
  39859. swapVariables (selectionStart, selectionEnd);
  39860. dragType = draggingSelectionStart;
  39861. }
  39862. }
  39863. jassert (selectionStart <= selectionEnd);
  39864. jassert (oldSelStart <= oldSelEnd);
  39865. repaintText (jmin (oldSelStart, selectionStart),
  39866. jmax (oldSelEnd, selectionEnd));
  39867. }
  39868. else
  39869. {
  39870. dragType = notDragging;
  39871. if (selectionEnd > selectionStart)
  39872. repaintText (selectionStart, selectionEnd);
  39873. moveCaret (newPosition);
  39874. selectionStart = getCaretPosition();
  39875. selectionEnd = getCaretPosition();
  39876. }
  39877. }
  39878. int TextEditor::getTextIndexAt (const int x,
  39879. const int y) throw()
  39880. {
  39881. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  39882. (float) (y + viewport->getViewPositionY() - topIndent));
  39883. }
  39884. void TextEditor::insertTextAtCursor (String newText)
  39885. {
  39886. if (allowedCharacters.isNotEmpty())
  39887. newText = newText.retainCharacters (allowedCharacters);
  39888. if (! isMultiLine())
  39889. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  39890. else
  39891. newText = newText.replace (T("\r\n"), T("\n"));
  39892. const int newCaretPos = selectionStart + newText.length();
  39893. const int insertIndex = selectionStart;
  39894. remove (selectionStart, selectionEnd,
  39895. &undoManager,
  39896. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  39897. if (maxTextLength > 0)
  39898. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  39899. if (newText.isNotEmpty())
  39900. insert (newText,
  39901. insertIndex,
  39902. currentFont,
  39903. findColour (textColourId),
  39904. &undoManager,
  39905. newCaretPos);
  39906. textChanged();
  39907. }
  39908. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  39909. {
  39910. moveCursorTo (startPos, false);
  39911. moveCursorTo (startPos + numChars, true);
  39912. }
  39913. void TextEditor::copy()
  39914. {
  39915. if (passwordCharacter == 0)
  39916. {
  39917. const String selection (getTextSubstring (selectionStart, selectionEnd));
  39918. if (selection.isNotEmpty())
  39919. SystemClipboard::copyTextToClipboard (selection);
  39920. }
  39921. }
  39922. void TextEditor::paste()
  39923. {
  39924. if (! isReadOnly())
  39925. {
  39926. const String clip (SystemClipboard::getTextFromClipboard());
  39927. if (clip.isNotEmpty())
  39928. insertTextAtCursor (clip);
  39929. }
  39930. }
  39931. void TextEditor::cut()
  39932. {
  39933. if (! isReadOnly())
  39934. {
  39935. moveCaret (selectionEnd);
  39936. insertTextAtCursor (String::empty);
  39937. }
  39938. }
  39939. void TextEditor::drawContent (Graphics& g)
  39940. {
  39941. const float wordWrapWidth = getWordWrapWidth();
  39942. if (wordWrapWidth > 0)
  39943. {
  39944. g.setOrigin (leftIndent, topIndent);
  39945. const Rectangle clip (g.getClipBounds());
  39946. Colour selectedTextColour;
  39947. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39948. while (i.lineY + 200.0 < clip.getY() && i.next())
  39949. {}
  39950. if (selectionStart < selectionEnd)
  39951. {
  39952. g.setColour (findColour (highlightColourId)
  39953. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  39954. selectedTextColour = findColour (highlightedTextColourId);
  39955. TextEditorIterator i2 (i);
  39956. while (i2.next() && i2.lineY < clip.getBottom())
  39957. {
  39958. i2.updateLineHeight();
  39959. if (i2.lineY + i2.lineHeight >= clip.getY()
  39960. && selectionEnd >= i2.indexInText
  39961. && selectionStart <= i2.indexInText + i2.atom->numChars)
  39962. {
  39963. i2.drawSelection (g, selectionStart, selectionEnd);
  39964. }
  39965. }
  39966. }
  39967. const UniformTextSection* lastSection = 0;
  39968. while (i.next() && i.lineY < clip.getBottom())
  39969. {
  39970. i.updateLineHeight();
  39971. if (i.lineY + i.lineHeight >= clip.getY())
  39972. {
  39973. if (selectionEnd >= i.indexInText
  39974. && selectionStart <= i.indexInText + i.atom->numChars)
  39975. {
  39976. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  39977. lastSection = 0;
  39978. }
  39979. else
  39980. {
  39981. i.draw (g, lastSection);
  39982. }
  39983. }
  39984. }
  39985. }
  39986. }
  39987. void TextEditor::paint (Graphics& g)
  39988. {
  39989. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  39990. }
  39991. void TextEditor::paintOverChildren (Graphics& g)
  39992. {
  39993. if (caretFlashState
  39994. && hasKeyboardFocus (false)
  39995. && caretVisible
  39996. && ! isReadOnly())
  39997. {
  39998. g.setColour (findColour (caretColourId));
  39999. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  40000. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  40001. 2.0f, cursorHeight);
  40002. }
  40003. if (textToShowWhenEmpty.isNotEmpty()
  40004. && (! hasKeyboardFocus (false))
  40005. && getTotalNumChars() == 0)
  40006. {
  40007. g.setColour (colourForTextWhenEmpty);
  40008. g.setFont (getFont());
  40009. if (isMultiLine())
  40010. {
  40011. g.drawText (textToShowWhenEmpty,
  40012. 0, 0, getWidth(), getHeight(),
  40013. Justification::centred, true);
  40014. }
  40015. else
  40016. {
  40017. g.drawText (textToShowWhenEmpty,
  40018. leftIndent, topIndent,
  40019. viewport->getWidth() - leftIndent,
  40020. viewport->getHeight() - topIndent,
  40021. Justification::centredLeft, true);
  40022. }
  40023. }
  40024. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  40025. }
  40026. void TextEditor::mouseDown (const MouseEvent& e)
  40027. {
  40028. beginDragAutoRepeat (100);
  40029. newTransaction();
  40030. if (wasFocused || ! selectAllTextWhenFocused)
  40031. {
  40032. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40033. {
  40034. moveCursorTo (getTextIndexAt (e.x, e.y),
  40035. e.mods.isShiftDown());
  40036. }
  40037. else
  40038. {
  40039. PopupMenu m;
  40040. addPopupMenuItems (m, &e);
  40041. menuActive = true;
  40042. const int result = m.show();
  40043. menuActive = false;
  40044. if (result != 0)
  40045. performPopupMenuAction (result);
  40046. }
  40047. }
  40048. }
  40049. void TextEditor::mouseDrag (const MouseEvent& e)
  40050. {
  40051. if (wasFocused || ! selectAllTextWhenFocused)
  40052. {
  40053. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40054. {
  40055. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  40056. }
  40057. }
  40058. }
  40059. void TextEditor::mouseUp (const MouseEvent& e)
  40060. {
  40061. newTransaction();
  40062. textHolder->startTimer (flashSpeedIntervalMs);
  40063. if (wasFocused || ! selectAllTextWhenFocused)
  40064. {
  40065. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  40066. {
  40067. moveCaret (getTextIndexAt (e.x, e.y));
  40068. }
  40069. }
  40070. wasFocused = true;
  40071. }
  40072. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  40073. {
  40074. int tokenEnd = getTextIndexAt (e.x, e.y);
  40075. int tokenStart = tokenEnd;
  40076. if (e.getNumberOfClicks() > 3)
  40077. {
  40078. tokenStart = 0;
  40079. tokenEnd = getTotalNumChars();
  40080. }
  40081. else
  40082. {
  40083. const String t (getText());
  40084. const int totalLength = getTotalNumChars();
  40085. while (tokenEnd < totalLength)
  40086. {
  40087. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  40088. ++tokenEnd;
  40089. else
  40090. break;
  40091. }
  40092. tokenStart = tokenEnd;
  40093. while (tokenStart > 0)
  40094. {
  40095. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  40096. --tokenStart;
  40097. else
  40098. break;
  40099. }
  40100. if (e.getNumberOfClicks() > 2)
  40101. {
  40102. while (tokenEnd < totalLength)
  40103. {
  40104. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  40105. ++tokenEnd;
  40106. else
  40107. break;
  40108. }
  40109. while (tokenStart > 0)
  40110. {
  40111. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  40112. --tokenStart;
  40113. else
  40114. break;
  40115. }
  40116. }
  40117. }
  40118. moveCursorTo (tokenEnd, false);
  40119. moveCursorTo (tokenStart, true);
  40120. }
  40121. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40122. {
  40123. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  40124. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  40125. }
  40126. bool TextEditor::keyPressed (const KeyPress& key)
  40127. {
  40128. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  40129. return false;
  40130. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  40131. if (key.isKeyCode (KeyPress::leftKey)
  40132. || key.isKeyCode (KeyPress::upKey))
  40133. {
  40134. newTransaction();
  40135. int newPos;
  40136. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  40137. newPos = indexAtPosition (cursorX, cursorY - 1);
  40138. else if (moveInWholeWordSteps)
  40139. newPos = findWordBreakBefore (getCaretPosition());
  40140. else
  40141. newPos = getCaretPosition() - 1;
  40142. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40143. }
  40144. else if (key.isKeyCode (KeyPress::rightKey)
  40145. || key.isKeyCode (KeyPress::downKey))
  40146. {
  40147. newTransaction();
  40148. int newPos;
  40149. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  40150. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  40151. else if (moveInWholeWordSteps)
  40152. newPos = findWordBreakAfter (getCaretPosition());
  40153. else
  40154. newPos = getCaretPosition() + 1;
  40155. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  40156. }
  40157. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  40158. {
  40159. newTransaction();
  40160. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  40161. key.getModifiers().isShiftDown());
  40162. }
  40163. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  40164. {
  40165. newTransaction();
  40166. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  40167. key.getModifiers().isShiftDown());
  40168. }
  40169. else if (key.isKeyCode (KeyPress::homeKey))
  40170. {
  40171. newTransaction();
  40172. if (isMultiLine() && ! moveInWholeWordSteps)
  40173. moveCursorTo (indexAtPosition (0.0f, cursorY),
  40174. key.getModifiers().isShiftDown());
  40175. else
  40176. moveCursorTo (0, key.getModifiers().isShiftDown());
  40177. }
  40178. else if (key.isKeyCode (KeyPress::endKey))
  40179. {
  40180. newTransaction();
  40181. if (isMultiLine() && ! moveInWholeWordSteps)
  40182. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  40183. key.getModifiers().isShiftDown());
  40184. else
  40185. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  40186. }
  40187. else if (key.isKeyCode (KeyPress::backspaceKey))
  40188. {
  40189. if (moveInWholeWordSteps)
  40190. {
  40191. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  40192. }
  40193. else
  40194. {
  40195. if (selectionStart == selectionEnd && selectionStart > 0)
  40196. --selectionStart;
  40197. }
  40198. cut();
  40199. }
  40200. else if (key.isKeyCode (KeyPress::deleteKey))
  40201. {
  40202. if (key.getModifiers().isShiftDown())
  40203. copy();
  40204. if (selectionStart == selectionEnd
  40205. && selectionEnd < getTotalNumChars())
  40206. {
  40207. ++selectionEnd;
  40208. }
  40209. cut();
  40210. }
  40211. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  40212. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  40213. {
  40214. newTransaction();
  40215. copy();
  40216. }
  40217. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  40218. {
  40219. newTransaction();
  40220. copy();
  40221. cut();
  40222. }
  40223. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  40224. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  40225. {
  40226. newTransaction();
  40227. paste();
  40228. }
  40229. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  40230. {
  40231. newTransaction();
  40232. doUndoRedo (false);
  40233. }
  40234. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  40235. {
  40236. newTransaction();
  40237. doUndoRedo (true);
  40238. }
  40239. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  40240. {
  40241. newTransaction();
  40242. moveCursorTo (getTotalNumChars(), false);
  40243. moveCursorTo (0, true);
  40244. }
  40245. else if (key == KeyPress::returnKey)
  40246. {
  40247. newTransaction();
  40248. if (returnKeyStartsNewLine)
  40249. insertTextAtCursor (T("\n"));
  40250. else
  40251. returnPressed();
  40252. }
  40253. else if (key.isKeyCode (KeyPress::escapeKey))
  40254. {
  40255. newTransaction();
  40256. moveCursorTo (getCaretPosition(), false);
  40257. escapePressed();
  40258. }
  40259. else if (key.getTextCharacter() >= ' '
  40260. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  40261. {
  40262. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  40263. lastTransactionTime = Time::getApproximateMillisecondCounter();
  40264. }
  40265. else
  40266. {
  40267. return false;
  40268. }
  40269. return true;
  40270. }
  40271. bool TextEditor::keyStateChanged (const bool isKeyDown)
  40272. {
  40273. if (! isKeyDown)
  40274. return false;
  40275. #if JUCE_WIN32
  40276. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  40277. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  40278. #endif
  40279. // (overridden to avoid forwarding key events to the parent)
  40280. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  40281. }
  40282. const int baseMenuItemID = 0x7fff0000;
  40283. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  40284. {
  40285. const bool writable = ! isReadOnly();
  40286. if (passwordCharacter == 0)
  40287. {
  40288. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  40289. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  40290. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  40291. }
  40292. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  40293. m.addSeparator();
  40294. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  40295. m.addSeparator();
  40296. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  40297. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  40298. }
  40299. void TextEditor::performPopupMenuAction (const int menuItemID)
  40300. {
  40301. switch (menuItemID)
  40302. {
  40303. case baseMenuItemID + 1:
  40304. copy();
  40305. cut();
  40306. break;
  40307. case baseMenuItemID + 2:
  40308. copy();
  40309. break;
  40310. case baseMenuItemID + 3:
  40311. paste();
  40312. break;
  40313. case baseMenuItemID + 4:
  40314. cut();
  40315. break;
  40316. case baseMenuItemID + 5:
  40317. moveCursorTo (getTotalNumChars(), false);
  40318. moveCursorTo (0, true);
  40319. break;
  40320. case baseMenuItemID + 6:
  40321. doUndoRedo (false);
  40322. break;
  40323. case baseMenuItemID + 7:
  40324. doUndoRedo (true);
  40325. break;
  40326. default:
  40327. break;
  40328. }
  40329. }
  40330. void TextEditor::focusGained (FocusChangeType)
  40331. {
  40332. newTransaction();
  40333. caretFlashState = true;
  40334. if (selectAllTextWhenFocused)
  40335. {
  40336. moveCursorTo (0, false);
  40337. moveCursorTo (getTotalNumChars(), true);
  40338. }
  40339. repaint();
  40340. if (caretVisible)
  40341. textHolder->startTimer (flashSpeedIntervalMs);
  40342. ComponentPeer* const peer = getPeer();
  40343. if (peer != 0)
  40344. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  40345. getScreenY() - peer->getScreenY());
  40346. }
  40347. void TextEditor::focusLost (FocusChangeType)
  40348. {
  40349. newTransaction();
  40350. wasFocused = false;
  40351. textHolder->stopTimer();
  40352. caretFlashState = false;
  40353. postCommandMessage (focusLossMessageId);
  40354. repaint();
  40355. }
  40356. void TextEditor::resized()
  40357. {
  40358. viewport->setBoundsInset (borderSize);
  40359. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  40360. updateTextHolderSize();
  40361. if (! isMultiLine())
  40362. {
  40363. scrollToMakeSureCursorIsVisible();
  40364. }
  40365. else
  40366. {
  40367. updateCaretPosition();
  40368. }
  40369. }
  40370. void TextEditor::handleCommandMessage (const int commandId)
  40371. {
  40372. const ComponentDeletionWatcher deletionChecker (this);
  40373. for (int i = listeners.size(); --i >= 0;)
  40374. {
  40375. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  40376. if (tl != 0)
  40377. {
  40378. switch (commandId)
  40379. {
  40380. case textChangeMessageId:
  40381. tl->textEditorTextChanged (*this);
  40382. break;
  40383. case returnKeyMessageId:
  40384. tl->textEditorReturnKeyPressed (*this);
  40385. break;
  40386. case escapeKeyMessageId:
  40387. tl->textEditorEscapeKeyPressed (*this);
  40388. break;
  40389. case focusLossMessageId:
  40390. tl->textEditorFocusLost (*this);
  40391. break;
  40392. default:
  40393. jassertfalse
  40394. break;
  40395. }
  40396. if (i > 0 && deletionChecker.hasBeenDeleted())
  40397. return;
  40398. }
  40399. }
  40400. }
  40401. void TextEditor::enablementChanged()
  40402. {
  40403. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  40404. : MouseCursor::IBeamCursor));
  40405. repaint();
  40406. }
  40407. void TextEditor::clearInternal (UndoManager* const um) throw()
  40408. {
  40409. remove (0, getTotalNumChars(), um, caretPosition);
  40410. }
  40411. void TextEditor::insert (const String& text,
  40412. const int insertIndex,
  40413. const Font& font,
  40414. const Colour& colour,
  40415. UndoManager* const um,
  40416. const int caretPositionToMoveTo) throw()
  40417. {
  40418. if (text.isNotEmpty())
  40419. {
  40420. if (um != 0)
  40421. {
  40422. um->perform (new TextEditorInsertAction (*this,
  40423. text,
  40424. insertIndex,
  40425. font,
  40426. colour,
  40427. caretPosition,
  40428. caretPositionToMoveTo));
  40429. }
  40430. else
  40431. {
  40432. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  40433. // a line gets moved due to word wrap
  40434. int index = 0;
  40435. int nextIndex = 0;
  40436. for (int i = 0; i < sections.size(); ++i)
  40437. {
  40438. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40439. if (insertIndex == index)
  40440. {
  40441. sections.insert (i, new UniformTextSection (text,
  40442. font, colour,
  40443. passwordCharacter));
  40444. break;
  40445. }
  40446. else if (insertIndex > index && insertIndex < nextIndex)
  40447. {
  40448. splitSection (i, insertIndex - index);
  40449. sections.insert (i + 1, new UniformTextSection (text,
  40450. font, colour,
  40451. passwordCharacter));
  40452. break;
  40453. }
  40454. index = nextIndex;
  40455. }
  40456. if (nextIndex == insertIndex)
  40457. sections.add (new UniformTextSection (text,
  40458. font, colour,
  40459. passwordCharacter));
  40460. coalesceSimilarSections();
  40461. totalNumChars = -1;
  40462. moveCursorTo (caretPositionToMoveTo, false);
  40463. repaintText (insertIndex, -1);
  40464. }
  40465. }
  40466. }
  40467. void TextEditor::reinsert (const int insertIndex,
  40468. const VoidArray& sectionsToInsert) throw()
  40469. {
  40470. int index = 0;
  40471. int nextIndex = 0;
  40472. for (int i = 0; i < sections.size(); ++i)
  40473. {
  40474. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40475. if (insertIndex == index)
  40476. {
  40477. for (int j = sectionsToInsert.size(); --j >= 0;)
  40478. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40479. break;
  40480. }
  40481. else if (insertIndex > index && insertIndex < nextIndex)
  40482. {
  40483. splitSection (i, insertIndex - index);
  40484. for (int j = sectionsToInsert.size(); --j >= 0;)
  40485. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40486. break;
  40487. }
  40488. index = nextIndex;
  40489. }
  40490. if (nextIndex == insertIndex)
  40491. {
  40492. for (int j = 0; j < sectionsToInsert.size(); ++j)
  40493. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  40494. }
  40495. coalesceSimilarSections();
  40496. totalNumChars = -1;
  40497. }
  40498. void TextEditor::remove (const int startIndex,
  40499. int endIndex,
  40500. UndoManager* const um,
  40501. const int caretPositionToMoveTo) throw()
  40502. {
  40503. if (endIndex > startIndex)
  40504. {
  40505. int index = 0;
  40506. for (int i = 0; i < sections.size(); ++i)
  40507. {
  40508. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  40509. if (startIndex > index && startIndex < nextIndex)
  40510. {
  40511. splitSection (i, startIndex - index);
  40512. --i;
  40513. }
  40514. else if (endIndex > index && endIndex < nextIndex)
  40515. {
  40516. splitSection (i, endIndex - index);
  40517. --i;
  40518. }
  40519. else
  40520. {
  40521. index = nextIndex;
  40522. if (index > endIndex)
  40523. break;
  40524. }
  40525. }
  40526. index = 0;
  40527. if (um != 0)
  40528. {
  40529. VoidArray removedSections;
  40530. for (int i = 0; i < sections.size(); ++i)
  40531. {
  40532. if (endIndex <= startIndex)
  40533. break;
  40534. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40535. const int nextIndex = index + section->getTotalLength();
  40536. if (startIndex <= index && endIndex >= nextIndex)
  40537. removedSections.add (new UniformTextSection (*section));
  40538. index = nextIndex;
  40539. }
  40540. um->perform (new TextEditorRemoveAction (*this,
  40541. startIndex,
  40542. endIndex,
  40543. caretPosition,
  40544. caretPositionToMoveTo,
  40545. removedSections));
  40546. }
  40547. else
  40548. {
  40549. for (int i = 0; i < sections.size(); ++i)
  40550. {
  40551. if (endIndex <= startIndex)
  40552. break;
  40553. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  40554. const int nextIndex = index + section->getTotalLength();
  40555. if (startIndex <= index && endIndex >= nextIndex)
  40556. {
  40557. sections.remove(i);
  40558. endIndex -= (nextIndex - index);
  40559. section->clear();
  40560. delete section;
  40561. --i;
  40562. }
  40563. else
  40564. {
  40565. index = nextIndex;
  40566. }
  40567. }
  40568. coalesceSimilarSections();
  40569. totalNumChars = -1;
  40570. moveCursorTo (caretPositionToMoveTo, false);
  40571. repaintText (startIndex, -1);
  40572. }
  40573. }
  40574. }
  40575. const String TextEditor::getText() const throw()
  40576. {
  40577. String t;
  40578. for (int i = 0; i < sections.size(); ++i)
  40579. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  40580. return t;
  40581. }
  40582. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  40583. {
  40584. String t;
  40585. int index = 0;
  40586. for (int i = 0; i < sections.size(); ++i)
  40587. {
  40588. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  40589. const int nextIndex = index + s->getTotalLength();
  40590. if (startCharacter < nextIndex)
  40591. {
  40592. if (endCharacter <= index)
  40593. break;
  40594. const int start = jmax (index, startCharacter);
  40595. t += s->getTextSubstring (start - index, endCharacter - index);
  40596. }
  40597. index = nextIndex;
  40598. }
  40599. return t;
  40600. }
  40601. const String TextEditor::getHighlightedText() const throw()
  40602. {
  40603. return getTextSubstring (getHighlightedRegionStart(),
  40604. getHighlightedRegionStart() + getHighlightedRegionLength());
  40605. }
  40606. int TextEditor::getTotalNumChars() throw()
  40607. {
  40608. if (totalNumChars < 0)
  40609. {
  40610. totalNumChars = 0;
  40611. for (int i = sections.size(); --i >= 0;)
  40612. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  40613. }
  40614. return totalNumChars;
  40615. }
  40616. bool TextEditor::isEmpty() const throw()
  40617. {
  40618. if (totalNumChars != 0)
  40619. {
  40620. for (int i = sections.size(); --i >= 0;)
  40621. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  40622. return false;
  40623. }
  40624. return true;
  40625. }
  40626. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  40627. {
  40628. const float wordWrapWidth = getWordWrapWidth();
  40629. if (wordWrapWidth > 0 && sections.size() > 0)
  40630. {
  40631. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40632. i.getCharPosition (index, cx, cy, lineHeight);
  40633. }
  40634. else
  40635. {
  40636. cx = cy = 0;
  40637. lineHeight = currentFont.getHeight();
  40638. }
  40639. }
  40640. int TextEditor::indexAtPosition (const float x, const float y) throw()
  40641. {
  40642. const float wordWrapWidth = getWordWrapWidth();
  40643. if (wordWrapWidth > 0)
  40644. {
  40645. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  40646. while (i.next())
  40647. {
  40648. if (i.lineY + getHeight() > y)
  40649. i.updateLineHeight();
  40650. if (i.lineY + i.lineHeight > y)
  40651. {
  40652. if (i.lineY > y)
  40653. return jmax (0, i.indexInText - 1);
  40654. if (i.atomX >= x)
  40655. return i.indexInText;
  40656. if (x < i.atomRight)
  40657. return i.xToIndex (x);
  40658. }
  40659. }
  40660. }
  40661. return getTotalNumChars();
  40662. }
  40663. static int getCharacterCategory (const tchar character) throw()
  40664. {
  40665. return CharacterFunctions::isLetterOrDigit (character)
  40666. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  40667. }
  40668. int TextEditor::findWordBreakAfter (const int position) const throw()
  40669. {
  40670. const String t (getTextSubstring (position, position + 512));
  40671. const int totalLength = t.length();
  40672. int i = 0;
  40673. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40674. ++i;
  40675. const int type = getCharacterCategory (t[i]);
  40676. while (i < totalLength && type == getCharacterCategory (t[i]))
  40677. ++i;
  40678. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  40679. ++i;
  40680. return position + i;
  40681. }
  40682. int TextEditor::findWordBreakBefore (const int position) const throw()
  40683. {
  40684. if (position <= 0)
  40685. return 0;
  40686. const int startOfBuffer = jmax (0, position - 512);
  40687. const String t (getTextSubstring (startOfBuffer, position));
  40688. int i = position - startOfBuffer;
  40689. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  40690. --i;
  40691. if (i > 0)
  40692. {
  40693. const int type = getCharacterCategory (t [i - 1]);
  40694. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  40695. --i;
  40696. }
  40697. jassert (startOfBuffer + i >= 0);
  40698. return startOfBuffer + i;
  40699. }
  40700. void TextEditor::splitSection (const int sectionIndex,
  40701. const int charToSplitAt) throw()
  40702. {
  40703. jassert (sections[sectionIndex] != 0);
  40704. sections.insert (sectionIndex + 1,
  40705. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  40706. ->split (charToSplitAt, passwordCharacter));
  40707. }
  40708. void TextEditor::coalesceSimilarSections() throw()
  40709. {
  40710. for (int i = 0; i < sections.size() - 1; ++i)
  40711. {
  40712. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  40713. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  40714. if (s1->font == s2->font
  40715. && s1->colour == s2->colour)
  40716. {
  40717. s1->append (*s2, passwordCharacter);
  40718. sections.remove (i + 1);
  40719. delete s2;
  40720. --i;
  40721. }
  40722. }
  40723. }
  40724. END_JUCE_NAMESPACE
  40725. /********* End of inlined file: juce_TextEditor.cpp *********/
  40726. /********* Start of inlined file: juce_Toolbar.cpp *********/
  40727. BEGIN_JUCE_NAMESPACE
  40728. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  40729. class ToolbarSpacerComp : public ToolbarItemComponent
  40730. {
  40731. public:
  40732. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  40733. : ToolbarItemComponent (itemId, String::empty, false),
  40734. fixedSize (fixedSize_),
  40735. drawBar (drawBar_)
  40736. {
  40737. }
  40738. ~ToolbarSpacerComp()
  40739. {
  40740. }
  40741. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  40742. int& preferredSize, int& minSize, int& maxSize)
  40743. {
  40744. if (fixedSize <= 0)
  40745. {
  40746. preferredSize = toolbarThickness * 2;
  40747. minSize = 4;
  40748. maxSize = 32768;
  40749. }
  40750. else
  40751. {
  40752. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  40753. minSize = drawBar ? maxSize : jmin (4, maxSize);
  40754. preferredSize = maxSize;
  40755. if (getEditingMode() == editableOnPalette)
  40756. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  40757. }
  40758. return true;
  40759. }
  40760. void paintButtonArea (Graphics&, int, int, bool, bool)
  40761. {
  40762. }
  40763. void contentAreaChanged (const Rectangle&)
  40764. {
  40765. }
  40766. int getResizeOrder() const throw()
  40767. {
  40768. return fixedSize <= 0 ? 0 : 1;
  40769. }
  40770. void paint (Graphics& g)
  40771. {
  40772. const int w = getWidth();
  40773. const int h = getHeight();
  40774. if (drawBar)
  40775. {
  40776. g.setColour (findColour (Toolbar::separatorColourId, true));
  40777. const float thickness = 0.2f;
  40778. if (isToolbarVertical())
  40779. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  40780. else
  40781. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  40782. }
  40783. if (getEditingMode() != normalMode && ! drawBar)
  40784. {
  40785. g.setColour (findColour (Toolbar::separatorColourId, true));
  40786. const int indentX = jmin (2, (w - 3) / 2);
  40787. const int indentY = jmin (2, (h - 3) / 2);
  40788. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  40789. if (fixedSize <= 0)
  40790. {
  40791. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  40792. if (isToolbarVertical())
  40793. {
  40794. x1 = w * 0.5f;
  40795. y1 = h * 0.4f;
  40796. x2 = x1;
  40797. y2 = indentX * 2.0f;
  40798. x3 = x1;
  40799. y3 = h * 0.6f;
  40800. x4 = x1;
  40801. y4 = h - y2;
  40802. hw = w * 0.15f;
  40803. hl = w * 0.2f;
  40804. }
  40805. else
  40806. {
  40807. x1 = w * 0.4f;
  40808. y1 = h * 0.5f;
  40809. x2 = indentX * 2.0f;
  40810. y2 = y1;
  40811. x3 = w * 0.6f;
  40812. y3 = y1;
  40813. x4 = w - x2;
  40814. y4 = y1;
  40815. hw = h * 0.15f;
  40816. hl = h * 0.2f;
  40817. }
  40818. Path p;
  40819. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  40820. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  40821. g.fillPath (p);
  40822. }
  40823. }
  40824. }
  40825. juce_UseDebuggingNewOperator
  40826. private:
  40827. const float fixedSize;
  40828. const bool drawBar;
  40829. ToolbarSpacerComp (const ToolbarSpacerComp&);
  40830. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  40831. };
  40832. class MissingItemsComponent : public PopupMenuCustomComponent
  40833. {
  40834. public:
  40835. MissingItemsComponent (Toolbar& owner_, const int height_)
  40836. : PopupMenuCustomComponent (true),
  40837. owner (owner_),
  40838. height (height_)
  40839. {
  40840. for (int i = owner_.items.size(); --i >= 0;)
  40841. {
  40842. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  40843. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  40844. {
  40845. oldIndexes.insert (0, i);
  40846. addAndMakeVisible (tc, 0);
  40847. }
  40848. }
  40849. layout (400);
  40850. }
  40851. ~MissingItemsComponent()
  40852. {
  40853. // deleting the toolbar while its menu it open??
  40854. jassert (owner.isValidComponent());
  40855. for (int i = 0; i < getNumChildComponents(); ++i)
  40856. {
  40857. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40858. if (tc != 0)
  40859. {
  40860. tc->setVisible (false);
  40861. const int index = oldIndexes.remove (i);
  40862. owner.addChildComponent (tc, index);
  40863. --i;
  40864. }
  40865. }
  40866. owner.resized();
  40867. }
  40868. void layout (const int preferredWidth)
  40869. {
  40870. const int indent = 8;
  40871. int x = indent;
  40872. int y = indent;
  40873. int maxX = 0;
  40874. for (int i = 0; i < getNumChildComponents(); ++i)
  40875. {
  40876. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  40877. if (tc != 0)
  40878. {
  40879. int preferredSize = 1, minSize = 1, maxSize = 1;
  40880. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  40881. {
  40882. if (x + preferredSize > preferredWidth && x > indent)
  40883. {
  40884. x = indent;
  40885. y += height;
  40886. }
  40887. tc->setBounds (x, y, preferredSize, height);
  40888. x += preferredSize;
  40889. maxX = jmax (maxX, x);
  40890. }
  40891. }
  40892. }
  40893. setSize (maxX + 8, y + height + 8);
  40894. }
  40895. void getIdealSize (int& idealWidth, int& idealHeight)
  40896. {
  40897. idealWidth = getWidth();
  40898. idealHeight = getHeight();
  40899. }
  40900. juce_UseDebuggingNewOperator
  40901. private:
  40902. Toolbar& owner;
  40903. const int height;
  40904. Array <int> oldIndexes;
  40905. MissingItemsComponent (const MissingItemsComponent&);
  40906. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  40907. };
  40908. Toolbar::Toolbar()
  40909. : vertical (false),
  40910. isEditingActive (false),
  40911. toolbarStyle (Toolbar::iconsOnly)
  40912. {
  40913. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  40914. missingItemsButton->setAlwaysOnTop (true);
  40915. missingItemsButton->addButtonListener (this);
  40916. }
  40917. Toolbar::~Toolbar()
  40918. {
  40919. animator.cancelAllAnimations (true);
  40920. deleteAllChildren();
  40921. }
  40922. void Toolbar::setVertical (const bool shouldBeVertical)
  40923. {
  40924. if (vertical != shouldBeVertical)
  40925. {
  40926. vertical = shouldBeVertical;
  40927. resized();
  40928. }
  40929. }
  40930. void Toolbar::clear()
  40931. {
  40932. for (int i = items.size(); --i >= 0;)
  40933. {
  40934. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40935. items.remove (i);
  40936. delete tc;
  40937. }
  40938. resized();
  40939. }
  40940. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  40941. {
  40942. if (itemId == ToolbarItemFactory::separatorBarId)
  40943. return new ToolbarSpacerComp (itemId, 0.1f, true);
  40944. else if (itemId == ToolbarItemFactory::spacerId)
  40945. return new ToolbarSpacerComp (itemId, 0.5f, false);
  40946. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  40947. return new ToolbarSpacerComp (itemId, 0, false);
  40948. return factory.createItem (itemId);
  40949. }
  40950. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  40951. const int itemId,
  40952. const int insertIndex)
  40953. {
  40954. // An ID can't be zero - this might indicate a mistake somewhere?
  40955. jassert (itemId != 0);
  40956. ToolbarItemComponent* const tc = createItem (factory, itemId);
  40957. if (tc != 0)
  40958. {
  40959. #ifdef JUCE_DEBUG
  40960. Array <int> allowedIds;
  40961. factory.getAllToolbarItemIds (allowedIds);
  40962. // If your factory can create an item for a given ID, it must also return
  40963. // that ID from its getAllToolbarItemIds() method!
  40964. jassert (allowedIds.contains (itemId));
  40965. #endif
  40966. items.insert (insertIndex, tc);
  40967. addAndMakeVisible (tc, insertIndex);
  40968. }
  40969. }
  40970. void Toolbar::addItem (ToolbarItemFactory& factory,
  40971. const int itemId,
  40972. const int insertIndex)
  40973. {
  40974. addItemInternal (factory, itemId, insertIndex);
  40975. resized();
  40976. }
  40977. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  40978. {
  40979. Array <int> ids;
  40980. factoryToUse.getDefaultItemSet (ids);
  40981. clear();
  40982. for (int i = 0; i < ids.size(); ++i)
  40983. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  40984. resized();
  40985. }
  40986. void Toolbar::removeToolbarItem (const int itemIndex)
  40987. {
  40988. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  40989. if (tc != 0)
  40990. {
  40991. items.removeValue (tc);
  40992. delete tc;
  40993. resized();
  40994. }
  40995. }
  40996. int Toolbar::getNumItems() const throw()
  40997. {
  40998. return items.size();
  40999. }
  41000. int Toolbar::getItemId (const int itemIndex) const throw()
  41001. {
  41002. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  41003. return tc != 0 ? tc->getItemId() : 0;
  41004. }
  41005. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  41006. {
  41007. return items [itemIndex];
  41008. }
  41009. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  41010. {
  41011. for (;;)
  41012. {
  41013. index += delta;
  41014. ToolbarItemComponent* const tc = getItemComponent (index);
  41015. if (tc == 0)
  41016. break;
  41017. if (tc->isActive)
  41018. return tc;
  41019. }
  41020. return 0;
  41021. }
  41022. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  41023. {
  41024. if (toolbarStyle != newStyle)
  41025. {
  41026. toolbarStyle = newStyle;
  41027. updateAllItemPositions (false);
  41028. }
  41029. }
  41030. const String Toolbar::toString() const
  41031. {
  41032. String s (T("TB:"));
  41033. for (int i = 0; i < getNumItems(); ++i)
  41034. s << getItemId(i) << T(' ');
  41035. return s.trimEnd();
  41036. }
  41037. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  41038. const String& savedVersion)
  41039. {
  41040. if (! savedVersion.startsWith (T("TB:")))
  41041. return false;
  41042. StringArray tokens;
  41043. tokens.addTokens (savedVersion.substring (3), false);
  41044. clear();
  41045. for (int i = 0; i < tokens.size(); ++i)
  41046. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  41047. resized();
  41048. return true;
  41049. }
  41050. void Toolbar::paint (Graphics& g)
  41051. {
  41052. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  41053. }
  41054. int Toolbar::getThickness() const throw()
  41055. {
  41056. return vertical ? getWidth() : getHeight();
  41057. }
  41058. int Toolbar::getLength() const throw()
  41059. {
  41060. return vertical ? getHeight() : getWidth();
  41061. }
  41062. void Toolbar::setEditingActive (const bool active)
  41063. {
  41064. if (isEditingActive != active)
  41065. {
  41066. isEditingActive = active;
  41067. updateAllItemPositions (false);
  41068. }
  41069. }
  41070. void Toolbar::resized()
  41071. {
  41072. updateAllItemPositions (false);
  41073. }
  41074. void Toolbar::updateAllItemPositions (const bool animate)
  41075. {
  41076. if (getWidth() > 0 && getHeight() > 0)
  41077. {
  41078. StretchableObjectResizer resizer;
  41079. int i;
  41080. for (i = 0; i < items.size(); ++i)
  41081. {
  41082. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41083. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  41084. : ToolbarItemComponent::normalMode);
  41085. tc->setStyle (toolbarStyle);
  41086. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  41087. int preferredSize = 1, minSize = 1, maxSize = 1;
  41088. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  41089. preferredSize, minSize, maxSize))
  41090. {
  41091. tc->isActive = true;
  41092. resizer.addItem (preferredSize, minSize, maxSize,
  41093. spacer != 0 ? spacer->getResizeOrder() : 2);
  41094. }
  41095. else
  41096. {
  41097. tc->isActive = false;
  41098. tc->setVisible (false);
  41099. }
  41100. }
  41101. resizer.resizeToFit (getLength());
  41102. int totalLength = 0;
  41103. for (i = 0; i < resizer.getNumItems(); ++i)
  41104. totalLength += (int) resizer.getItemSize (i);
  41105. const bool itemsOffTheEnd = totalLength > getLength();
  41106. const int extrasButtonSize = getThickness() / 2;
  41107. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  41108. missingItemsButton->setVisible (itemsOffTheEnd);
  41109. missingItemsButton->setEnabled (! isEditingActive);
  41110. if (vertical)
  41111. missingItemsButton->setCentrePosition (getWidth() / 2,
  41112. getHeight() - 4 - extrasButtonSize / 2);
  41113. else
  41114. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  41115. getHeight() / 2);
  41116. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  41117. : missingItemsButton->getX()) - 4
  41118. : getLength();
  41119. int pos = 0, activeIndex = 0;
  41120. for (i = 0; i < items.size(); ++i)
  41121. {
  41122. ToolbarItemComponent* const tc = items.getUnchecked(i);
  41123. if (tc->isActive)
  41124. {
  41125. const int size = (int) resizer.getItemSize (activeIndex++);
  41126. Rectangle newBounds;
  41127. if (vertical)
  41128. newBounds.setBounds (0, pos, getWidth(), size);
  41129. else
  41130. newBounds.setBounds (pos, 0, size, getHeight());
  41131. if (animate)
  41132. {
  41133. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  41134. }
  41135. else
  41136. {
  41137. animator.cancelAnimation (tc, false);
  41138. tc->setBounds (newBounds);
  41139. }
  41140. pos += size;
  41141. tc->setVisible (pos <= maxLength
  41142. && ((! tc->isBeingDragged)
  41143. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  41144. }
  41145. }
  41146. }
  41147. }
  41148. void Toolbar::buttonClicked (Button*)
  41149. {
  41150. jassert (missingItemsButton->isShowing());
  41151. if (missingItemsButton->isShowing())
  41152. {
  41153. PopupMenu m;
  41154. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  41155. m.showAt (missingItemsButton);
  41156. }
  41157. }
  41158. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  41159. Component* /*sourceComponent*/)
  41160. {
  41161. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  41162. }
  41163. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  41164. {
  41165. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41166. if (tc != 0)
  41167. {
  41168. if (getNumItems() == 0)
  41169. {
  41170. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41171. {
  41172. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41173. if (palette != 0)
  41174. palette->replaceComponent (tc);
  41175. }
  41176. else
  41177. {
  41178. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41179. }
  41180. items.add (tc);
  41181. addChildComponent (tc);
  41182. updateAllItemPositions (false);
  41183. }
  41184. else
  41185. {
  41186. for (int i = getNumItems(); --i >= 0;)
  41187. {
  41188. int currentIndex = getIndexOfChildComponent (tc);
  41189. if (currentIndex < 0)
  41190. {
  41191. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  41192. {
  41193. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  41194. if (palette != 0)
  41195. palette->replaceComponent (tc);
  41196. }
  41197. else
  41198. {
  41199. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  41200. }
  41201. items.add (tc);
  41202. addChildComponent (tc);
  41203. currentIndex = getIndexOfChildComponent (tc);
  41204. updateAllItemPositions (true);
  41205. }
  41206. int newIndex = currentIndex;
  41207. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  41208. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  41209. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  41210. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  41211. if (prev != 0)
  41212. {
  41213. const Rectangle previousPos (animator.getComponentDestination (prev));
  41214. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  41215. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  41216. {
  41217. newIndex = getIndexOfChildComponent (prev);
  41218. }
  41219. }
  41220. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  41221. if (next != 0)
  41222. {
  41223. const Rectangle nextPos (animator.getComponentDestination (next));
  41224. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  41225. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  41226. {
  41227. newIndex = getIndexOfChildComponent (next) + 1;
  41228. }
  41229. }
  41230. if (newIndex != currentIndex)
  41231. {
  41232. items.removeValue (tc);
  41233. removeChildComponent (tc);
  41234. addChildComponent (tc, newIndex);
  41235. items.insert (newIndex, tc);
  41236. updateAllItemPositions (true);
  41237. }
  41238. else
  41239. {
  41240. break;
  41241. }
  41242. }
  41243. }
  41244. }
  41245. }
  41246. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  41247. {
  41248. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  41249. if (tc != 0)
  41250. {
  41251. if (isParentOf (tc))
  41252. {
  41253. items.removeValue (tc);
  41254. removeChildComponent (tc);
  41255. updateAllItemPositions (true);
  41256. }
  41257. }
  41258. }
  41259. void Toolbar::itemDropped (const String&, Component*, int, int)
  41260. {
  41261. }
  41262. void Toolbar::mouseDown (const MouseEvent& e)
  41263. {
  41264. if (e.mods.isPopupMenu())
  41265. {
  41266. }
  41267. }
  41268. class ToolbarCustomisationDialog : public DialogWindow
  41269. {
  41270. public:
  41271. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  41272. Toolbar* const toolbar_,
  41273. const int optionFlags)
  41274. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  41275. toolbar (toolbar_)
  41276. {
  41277. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  41278. setResizable (true, true);
  41279. setResizeLimits (400, 300, 1500, 1000);
  41280. positionNearBar();
  41281. }
  41282. ~ToolbarCustomisationDialog()
  41283. {
  41284. setContentComponent (0, true);
  41285. }
  41286. void closeButtonPressed()
  41287. {
  41288. setVisible (false);
  41289. }
  41290. bool canModalEventBeSentToComponent (const Component* comp)
  41291. {
  41292. return toolbar->isParentOf (comp);
  41293. }
  41294. void positionNearBar()
  41295. {
  41296. const Rectangle screenSize (toolbar->getParentMonitorArea());
  41297. const int tbx = toolbar->getScreenX();
  41298. const int tby = toolbar->getScreenY();
  41299. const int gap = 8;
  41300. int x, y;
  41301. if (toolbar->isVertical())
  41302. {
  41303. y = tby;
  41304. if (tbx > screenSize.getCentreX())
  41305. x = tbx - getWidth() - gap;
  41306. else
  41307. x = tbx + toolbar->getWidth() + gap;
  41308. }
  41309. else
  41310. {
  41311. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  41312. if (tby > screenSize.getCentreY())
  41313. y = tby - getHeight() - gap;
  41314. else
  41315. y = tby + toolbar->getHeight() + gap;
  41316. }
  41317. setTopLeftPosition (x, y);
  41318. }
  41319. private:
  41320. Toolbar* const toolbar;
  41321. class CustomiserPanel : public Component,
  41322. private ComboBoxListener,
  41323. private ButtonListener
  41324. {
  41325. public:
  41326. CustomiserPanel (ToolbarItemFactory& factory_,
  41327. Toolbar* const toolbar_,
  41328. const int optionFlags)
  41329. : factory (factory_),
  41330. toolbar (toolbar_),
  41331. styleBox (0),
  41332. defaultButton (0)
  41333. {
  41334. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  41335. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  41336. | Toolbar::allowIconsWithTextChoice
  41337. | Toolbar::allowTextOnlyChoice)) != 0)
  41338. {
  41339. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  41340. styleBox->setEditableText (false);
  41341. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  41342. styleBox->addItem (TRANS("Show icons only"), 1);
  41343. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  41344. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  41345. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  41346. styleBox->addItem (TRANS("Show descriptions only"), 3);
  41347. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  41348. styleBox->setSelectedId (1);
  41349. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  41350. styleBox->setSelectedId (2);
  41351. else if (toolbar_->getStyle() == Toolbar::textOnly)
  41352. styleBox->setSelectedId (3);
  41353. styleBox->addListener (this);
  41354. }
  41355. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  41356. {
  41357. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  41358. defaultButton->addButtonListener (this);
  41359. }
  41360. addAndMakeVisible (instructions = new Label (String::empty,
  41361. 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.")));
  41362. instructions->setFont (Font (13.0f));
  41363. setSize (500, 300);
  41364. }
  41365. ~CustomiserPanel()
  41366. {
  41367. deleteAllChildren();
  41368. }
  41369. void comboBoxChanged (ComboBox*)
  41370. {
  41371. if (styleBox->getSelectedId() == 1)
  41372. toolbar->setStyle (Toolbar::iconsOnly);
  41373. else if (styleBox->getSelectedId() == 2)
  41374. toolbar->setStyle (Toolbar::iconsWithText);
  41375. else if (styleBox->getSelectedId() == 3)
  41376. toolbar->setStyle (Toolbar::textOnly);
  41377. palette->resized(); // to make it update the styles
  41378. }
  41379. void buttonClicked (Button*)
  41380. {
  41381. toolbar->addDefaultItems (factory);
  41382. }
  41383. void paint (Graphics& g)
  41384. {
  41385. Colour background;
  41386. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  41387. if (dw != 0)
  41388. background = dw->getBackgroundColour();
  41389. g.setColour (background.contrasting().withAlpha (0.3f));
  41390. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  41391. }
  41392. void resized()
  41393. {
  41394. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  41395. if (styleBox != 0)
  41396. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  41397. if (defaultButton != 0)
  41398. {
  41399. defaultButton->changeWidthToFitText (22);
  41400. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  41401. }
  41402. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  41403. }
  41404. private:
  41405. ToolbarItemFactory& factory;
  41406. Toolbar* const toolbar;
  41407. Label* instructions;
  41408. ToolbarItemPalette* palette;
  41409. ComboBox* styleBox;
  41410. TextButton* defaultButton;
  41411. };
  41412. };
  41413. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  41414. {
  41415. setEditingActive (true);
  41416. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  41417. dw.runModalLoop();
  41418. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  41419. setEditingActive (false);
  41420. }
  41421. END_JUCE_NAMESPACE
  41422. /********* End of inlined file: juce_Toolbar.cpp *********/
  41423. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  41424. BEGIN_JUCE_NAMESPACE
  41425. ToolbarItemFactory::ToolbarItemFactory()
  41426. {
  41427. }
  41428. ToolbarItemFactory::~ToolbarItemFactory()
  41429. {
  41430. }
  41431. class ItemDragAndDropOverlayComponent : public Component
  41432. {
  41433. public:
  41434. ItemDragAndDropOverlayComponent()
  41435. : isDragging (false)
  41436. {
  41437. setAlwaysOnTop (true);
  41438. setRepaintsOnMouseActivity (true);
  41439. setMouseCursor (MouseCursor::DraggingHandCursor);
  41440. }
  41441. ~ItemDragAndDropOverlayComponent()
  41442. {
  41443. }
  41444. void paint (Graphics& g)
  41445. {
  41446. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41447. if (isMouseOverOrDragging()
  41448. && tc != 0
  41449. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41450. {
  41451. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  41452. g.drawRect (0, 0, getWidth(), getHeight(),
  41453. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  41454. }
  41455. }
  41456. void mouseDown (const MouseEvent& e)
  41457. {
  41458. isDragging = false;
  41459. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41460. if (tc != 0)
  41461. {
  41462. tc->dragOffsetX = e.x;
  41463. tc->dragOffsetY = e.y;
  41464. }
  41465. }
  41466. void mouseDrag (const MouseEvent& e)
  41467. {
  41468. if (! (isDragging || e.mouseWasClicked()))
  41469. {
  41470. isDragging = true;
  41471. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  41472. if (dnd != 0)
  41473. {
  41474. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  41475. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41476. if (tc != 0)
  41477. {
  41478. tc->isBeingDragged = true;
  41479. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41480. tc->setVisible (false);
  41481. }
  41482. }
  41483. }
  41484. }
  41485. void mouseUp (const MouseEvent&)
  41486. {
  41487. isDragging = false;
  41488. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  41489. if (tc != 0)
  41490. {
  41491. tc->isBeingDragged = false;
  41492. Toolbar* const tb = tc->getToolbar();
  41493. if (tb != 0)
  41494. tb->updateAllItemPositions (true);
  41495. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  41496. delete tc;
  41497. }
  41498. }
  41499. void parentSizeChanged()
  41500. {
  41501. setBounds (0, 0, getParentWidth(), getParentHeight());
  41502. }
  41503. juce_UseDebuggingNewOperator
  41504. private:
  41505. bool isDragging;
  41506. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  41507. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  41508. };
  41509. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  41510. const String& labelText,
  41511. const bool isBeingUsedAsAButton_)
  41512. : Button (labelText),
  41513. itemId (itemId_),
  41514. mode (normalMode),
  41515. toolbarStyle (Toolbar::iconsOnly),
  41516. overlayComp (0),
  41517. dragOffsetX (0),
  41518. dragOffsetY (0),
  41519. isActive (true),
  41520. isBeingDragged (false),
  41521. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  41522. {
  41523. // Your item ID can't be 0!
  41524. jassert (itemId_ != 0);
  41525. }
  41526. ToolbarItemComponent::~ToolbarItemComponent()
  41527. {
  41528. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41529. delete overlayComp;
  41530. }
  41531. Toolbar* ToolbarItemComponent::getToolbar() const
  41532. {
  41533. return dynamic_cast <Toolbar*> (getParentComponent());
  41534. }
  41535. bool ToolbarItemComponent::isToolbarVertical() const
  41536. {
  41537. const Toolbar* const t = getToolbar();
  41538. return t != 0 && t->isVertical();
  41539. }
  41540. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  41541. {
  41542. if (toolbarStyle != newStyle)
  41543. {
  41544. toolbarStyle = newStyle;
  41545. repaint();
  41546. resized();
  41547. }
  41548. }
  41549. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  41550. {
  41551. if (isBeingUsedAsAButton)
  41552. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  41553. isMouseOver, isMouseDown, *this);
  41554. if (toolbarStyle != Toolbar::iconsOnly)
  41555. {
  41556. const int indent = contentArea.getX();
  41557. int y = indent;
  41558. int h = getHeight() - indent * 2;
  41559. if (toolbarStyle == Toolbar::iconsWithText)
  41560. {
  41561. y = contentArea.getBottom() + indent / 2;
  41562. h -= contentArea.getHeight();
  41563. }
  41564. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  41565. getButtonText(), *this);
  41566. }
  41567. if (! contentArea.isEmpty())
  41568. {
  41569. g.saveState();
  41570. g.setOrigin (contentArea.getX(), contentArea.getY());
  41571. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  41572. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  41573. g.restoreState();
  41574. }
  41575. }
  41576. void ToolbarItemComponent::resized()
  41577. {
  41578. if (toolbarStyle != Toolbar::textOnly)
  41579. {
  41580. const int indent = jmin (proportionOfWidth (0.08f),
  41581. proportionOfHeight (0.08f));
  41582. contentArea = Rectangle (indent, indent,
  41583. getWidth() - indent * 2,
  41584. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  41585. : (getHeight() - indent * 2));
  41586. }
  41587. else
  41588. {
  41589. contentArea = Rectangle();
  41590. }
  41591. contentAreaChanged (contentArea);
  41592. }
  41593. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  41594. {
  41595. if (mode != newMode)
  41596. {
  41597. mode = newMode;
  41598. repaint();
  41599. if (mode == normalMode)
  41600. {
  41601. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  41602. delete overlayComp;
  41603. overlayComp = 0;
  41604. }
  41605. else if (overlayComp == 0)
  41606. {
  41607. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  41608. overlayComp->parentSizeChanged();
  41609. }
  41610. resized();
  41611. }
  41612. }
  41613. END_JUCE_NAMESPACE
  41614. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  41615. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  41616. BEGIN_JUCE_NAMESPACE
  41617. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  41618. Toolbar* const toolbar_)
  41619. : factory (factory_),
  41620. toolbar (toolbar_)
  41621. {
  41622. Component* const itemHolder = new Component();
  41623. Array <int> allIds;
  41624. factory_.getAllToolbarItemIds (allIds);
  41625. for (int i = 0; i < allIds.size(); ++i)
  41626. {
  41627. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  41628. jassert (tc != 0);
  41629. if (tc != 0)
  41630. {
  41631. itemHolder->addAndMakeVisible (tc);
  41632. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  41633. }
  41634. }
  41635. viewport = new Viewport();
  41636. viewport->setViewedComponent (itemHolder);
  41637. addAndMakeVisible (viewport);
  41638. }
  41639. ToolbarItemPalette::~ToolbarItemPalette()
  41640. {
  41641. viewport->getViewedComponent()->deleteAllChildren();
  41642. deleteAllChildren();
  41643. }
  41644. void ToolbarItemPalette::resized()
  41645. {
  41646. viewport->setBoundsInset (BorderSize (1));
  41647. Component* const itemHolder = viewport->getViewedComponent();
  41648. const int indent = 8;
  41649. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  41650. const int height = toolbar->getThickness();
  41651. int x = indent;
  41652. int y = indent;
  41653. int maxX = 0;
  41654. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  41655. {
  41656. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  41657. if (tc != 0)
  41658. {
  41659. tc->setStyle (toolbar->getStyle());
  41660. int preferredSize = 1, minSize = 1, maxSize = 1;
  41661. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  41662. {
  41663. if (x + preferredSize > preferredWidth && x > indent)
  41664. {
  41665. x = indent;
  41666. y += height;
  41667. }
  41668. tc->setBounds (x, y, preferredSize, height);
  41669. x += preferredSize + 8;
  41670. maxX = jmax (maxX, x);
  41671. }
  41672. }
  41673. }
  41674. itemHolder->setSize (maxX, y + height + 8);
  41675. }
  41676. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  41677. {
  41678. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  41679. jassert (tc != 0);
  41680. if (tc != 0)
  41681. {
  41682. tc->setBounds (comp->getBounds());
  41683. tc->setStyle (toolbar->getStyle());
  41684. tc->setEditingMode (comp->getEditingMode());
  41685. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  41686. }
  41687. }
  41688. END_JUCE_NAMESPACE
  41689. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  41690. /********* Start of inlined file: juce_TreeView.cpp *********/
  41691. BEGIN_JUCE_NAMESPACE
  41692. class TreeViewContentComponent : public Component,
  41693. public TooltipClient
  41694. {
  41695. public:
  41696. TreeViewContentComponent (TreeView* const owner_)
  41697. : owner (owner_),
  41698. buttonUnderMouse (0),
  41699. isDragging (false)
  41700. {
  41701. }
  41702. ~TreeViewContentComponent()
  41703. {
  41704. deleteAllChildren();
  41705. }
  41706. void mouseDown (const MouseEvent& e)
  41707. {
  41708. updateButtonUnderMouse (e);
  41709. isDragging = false;
  41710. needSelectionOnMouseUp = false;
  41711. Rectangle pos;
  41712. TreeViewItem* const item = findItemAt (e.y, pos);
  41713. if (item == 0)
  41714. return;
  41715. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  41716. // as selection clicks)
  41717. if (e.x < pos.getX() && owner->openCloseButtonsVisible)
  41718. {
  41719. if (e.x >= pos.getX() - owner->getIndentSize())
  41720. item->setOpen (! item->isOpen());
  41721. // (clicks to the left of an open/close button are ignored)
  41722. }
  41723. else
  41724. {
  41725. // mouse-down inside the body of the item..
  41726. if (! owner->isMultiSelectEnabled())
  41727. item->setSelected (true, true);
  41728. else if (item->isSelected())
  41729. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  41730. else
  41731. selectBasedOnModifiers (item, e.mods);
  41732. MouseEvent e2 (e);
  41733. e2.x -= pos.getX();
  41734. e2.y -= pos.getY();
  41735. if (e2.x >= 0)
  41736. item->itemClicked (e2);
  41737. }
  41738. }
  41739. void mouseUp (const MouseEvent& e)
  41740. {
  41741. updateButtonUnderMouse (e);
  41742. if (needSelectionOnMouseUp && e.mouseWasClicked())
  41743. {
  41744. Rectangle pos;
  41745. TreeViewItem* const item = findItemAt (e.y, pos);
  41746. if (item != 0)
  41747. selectBasedOnModifiers (item, e.mods);
  41748. }
  41749. }
  41750. void mouseDoubleClick (const MouseEvent& e)
  41751. {
  41752. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  41753. {
  41754. Rectangle pos;
  41755. TreeViewItem* const item = findItemAt (e.y, pos);
  41756. if (item != 0 && (e.x >= pos.getX() || ! owner->openCloseButtonsVisible))
  41757. {
  41758. MouseEvent e2 (e);
  41759. e2.x -= pos.getX();
  41760. e2.y -= pos.getY();
  41761. item->itemDoubleClicked (e2);
  41762. }
  41763. }
  41764. }
  41765. void mouseDrag (const MouseEvent& e)
  41766. {
  41767. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  41768. {
  41769. isDragging = true;
  41770. Rectangle pos;
  41771. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  41772. if (item != 0 && e.getMouseDownX() >= pos.getX())
  41773. {
  41774. const String dragDescription (item->getDragSourceDescription());
  41775. if (dragDescription.isNotEmpty())
  41776. {
  41777. DragAndDropContainer* const dragContainer
  41778. = DragAndDropContainer::findParentDragContainerFor (this);
  41779. if (dragContainer != 0)
  41780. {
  41781. pos.setSize (pos.getWidth(), item->itemHeight);
  41782. Image* dragImage = Component::createComponentSnapshot (pos, true);
  41783. dragImage->multiplyAllAlphas (0.6f);
  41784. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  41785. }
  41786. else
  41787. {
  41788. // to be able to do a drag-and-drop operation, the treeview needs to
  41789. // be inside a component which is also a DragAndDropContainer.
  41790. jassertfalse
  41791. }
  41792. }
  41793. }
  41794. }
  41795. }
  41796. void mouseMove (const MouseEvent& e)
  41797. {
  41798. updateButtonUnderMouse (e);
  41799. }
  41800. void mouseExit (const MouseEvent& e)
  41801. {
  41802. updateButtonUnderMouse (e);
  41803. }
  41804. void paint (Graphics& g);
  41805. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  41806. void updateComponents()
  41807. {
  41808. int xAdjust = 0, yAdjust = 0;
  41809. const int visibleTop = -getY();
  41810. const int visibleBottom = visibleTop + getParentHeight();
  41811. BitArray itemsToKeep;
  41812. TreeViewItem* item = owner->rootItem;
  41813. int y = -yAdjust;
  41814. while (item != 0 && y < visibleBottom)
  41815. {
  41816. y += item->itemHeight;
  41817. if (y >= visibleTop)
  41818. {
  41819. const int index = rowComponentIds.indexOf (item->uid);
  41820. if (index < 0)
  41821. {
  41822. Component* const comp = item->createItemComponent();
  41823. if (comp != 0)
  41824. {
  41825. addAndMakeVisible (comp);
  41826. itemsToKeep.setBit (rowComponentItems.size());
  41827. rowComponentItems.add (item);
  41828. rowComponentIds.add (item->uid);
  41829. rowComponents.add (comp);
  41830. }
  41831. }
  41832. else
  41833. {
  41834. itemsToKeep.setBit (index);
  41835. }
  41836. }
  41837. item = item->getNextVisibleItem (true);
  41838. }
  41839. for (int i = rowComponentItems.size(); --i >= 0;)
  41840. {
  41841. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  41842. bool keep = false;
  41843. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  41844. && isParentOf (comp))
  41845. {
  41846. if (itemsToKeep[i])
  41847. {
  41848. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  41849. Rectangle pos (item->getItemPosition (false));
  41850. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  41851. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  41852. {
  41853. keep = true;
  41854. comp->setBounds (pos);
  41855. }
  41856. }
  41857. else
  41858. {
  41859. comp->setSize (0, 0);
  41860. }
  41861. }
  41862. if (! keep)
  41863. {
  41864. delete comp;
  41865. rowComponents.remove (i);
  41866. rowComponentIds.remove (i);
  41867. rowComponentItems.remove (i);
  41868. }
  41869. }
  41870. }
  41871. void updateButtonUnderMouse (const MouseEvent& e)
  41872. {
  41873. TreeViewItem* newItem = 0;
  41874. if (owner->openCloseButtonsVisible)
  41875. {
  41876. Rectangle pos;
  41877. TreeViewItem* item = findItemAt (e.y, pos);
  41878. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner->getIndentSize())
  41879. {
  41880. newItem = item;
  41881. if (! newItem->mightContainSubItems())
  41882. newItem = 0;
  41883. }
  41884. }
  41885. if (buttonUnderMouse != newItem)
  41886. {
  41887. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  41888. {
  41889. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41890. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41891. }
  41892. buttonUnderMouse = newItem;
  41893. if (buttonUnderMouse != 0)
  41894. {
  41895. const Rectangle r (buttonUnderMouse->getItemPosition (false));
  41896. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  41897. }
  41898. }
  41899. }
  41900. bool isMouseOverButton (TreeViewItem* item) const throw()
  41901. {
  41902. return item == buttonUnderMouse;
  41903. }
  41904. void resized()
  41905. {
  41906. owner->itemsChanged();
  41907. }
  41908. const String getTooltip()
  41909. {
  41910. int x, y;
  41911. getMouseXYRelative (x, y);
  41912. Rectangle pos;
  41913. TreeViewItem* const item = findItemAt (y, pos);
  41914. if (item != 0)
  41915. return item->getTooltip();
  41916. return owner->getTooltip();
  41917. }
  41918. juce_UseDebuggingNewOperator
  41919. private:
  41920. TreeView* const owner;
  41921. VoidArray rowComponentItems;
  41922. Array <int> rowComponentIds;
  41923. VoidArray rowComponents;
  41924. TreeViewItem* buttonUnderMouse;
  41925. bool isDragging, needSelectionOnMouseUp;
  41926. TreeViewContentComponent (const TreeViewContentComponent&);
  41927. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  41928. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  41929. {
  41930. TreeViewItem* firstSelected = 0;
  41931. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  41932. {
  41933. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  41934. jassert (lastSelected != 0);
  41935. int rowStart = firstSelected->getRowNumberInTree();
  41936. int rowEnd = lastSelected->getRowNumberInTree();
  41937. if (rowStart > rowEnd)
  41938. swapVariables (rowStart, rowEnd);
  41939. int ourRow = item->getRowNumberInTree();
  41940. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  41941. if (ourRow > otherEnd)
  41942. swapVariables (ourRow, otherEnd);
  41943. for (int i = ourRow; i <= otherEnd; ++i)
  41944. owner->getItemOnRow (i)->setSelected (true, false);
  41945. }
  41946. else
  41947. {
  41948. const bool cmd = modifiers.isCommandDown();
  41949. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  41950. }
  41951. }
  41952. bool containsItem (TreeViewItem* const item) const
  41953. {
  41954. for (int i = rowComponentItems.size(); --i >= 0;)
  41955. if ((TreeViewItem*) rowComponentItems.getUnchecked (i) == item)
  41956. return true;
  41957. return false;
  41958. }
  41959. };
  41960. class TreeViewport : public Viewport
  41961. {
  41962. public:
  41963. TreeViewport() throw() {}
  41964. ~TreeViewport() throw() {}
  41965. void updateComponents()
  41966. {
  41967. if (getViewedComponent() != 0)
  41968. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  41969. repaint();
  41970. }
  41971. void visibleAreaChanged (int, int, int, int)
  41972. {
  41973. updateComponents();
  41974. }
  41975. juce_UseDebuggingNewOperator
  41976. private:
  41977. TreeViewport (const TreeViewport&);
  41978. const TreeViewport& operator= (const TreeViewport&);
  41979. };
  41980. TreeView::TreeView (const String& componentName)
  41981. : Component (componentName),
  41982. rootItem (0),
  41983. indentSize (24),
  41984. defaultOpenness (false),
  41985. needsRecalculating (true),
  41986. rootItemVisible (true),
  41987. multiSelectEnabled (false),
  41988. openCloseButtonsVisible (true)
  41989. {
  41990. addAndMakeVisible (viewport = new TreeViewport());
  41991. viewport->setViewedComponent (new TreeViewContentComponent (this));
  41992. viewport->setWantsKeyboardFocus (false);
  41993. setWantsKeyboardFocus (true);
  41994. }
  41995. TreeView::~TreeView()
  41996. {
  41997. if (rootItem != 0)
  41998. rootItem->setOwnerView (0);
  41999. deleteAllChildren();
  42000. }
  42001. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  42002. {
  42003. if (rootItem != newRootItem)
  42004. {
  42005. if (newRootItem != 0)
  42006. {
  42007. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  42008. if (newRootItem->ownerView != 0)
  42009. newRootItem->ownerView->setRootItem (0);
  42010. }
  42011. if (rootItem != 0)
  42012. rootItem->setOwnerView (0);
  42013. rootItem = newRootItem;
  42014. if (newRootItem != 0)
  42015. newRootItem->setOwnerView (this);
  42016. needsRecalculating = true;
  42017. handleAsyncUpdate();
  42018. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42019. {
  42020. rootItem->setOpen (false); // force a re-open
  42021. rootItem->setOpen (true);
  42022. }
  42023. }
  42024. }
  42025. void TreeView::deleteRootItem()
  42026. {
  42027. TreeViewItem* const oldItem = rootItem;
  42028. setRootItem (0);
  42029. delete oldItem;
  42030. }
  42031. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  42032. {
  42033. rootItemVisible = shouldBeVisible;
  42034. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  42035. {
  42036. rootItem->setOpen (false); // force a re-open
  42037. rootItem->setOpen (true);
  42038. }
  42039. itemsChanged();
  42040. }
  42041. void TreeView::colourChanged()
  42042. {
  42043. setOpaque (findColour (backgroundColourId).isOpaque());
  42044. repaint();
  42045. }
  42046. void TreeView::setIndentSize (const int newIndentSize)
  42047. {
  42048. if (indentSize != newIndentSize)
  42049. {
  42050. indentSize = newIndentSize;
  42051. resized();
  42052. }
  42053. }
  42054. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  42055. {
  42056. if (defaultOpenness != isOpenByDefault)
  42057. {
  42058. defaultOpenness = isOpenByDefault;
  42059. itemsChanged();
  42060. }
  42061. }
  42062. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  42063. {
  42064. multiSelectEnabled = canMultiSelect;
  42065. }
  42066. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  42067. {
  42068. if (openCloseButtonsVisible != shouldBeVisible)
  42069. {
  42070. openCloseButtonsVisible = shouldBeVisible;
  42071. itemsChanged();
  42072. }
  42073. }
  42074. void TreeView::clearSelectedItems()
  42075. {
  42076. if (rootItem != 0)
  42077. rootItem->deselectAllRecursively();
  42078. }
  42079. int TreeView::getNumSelectedItems() const throw()
  42080. {
  42081. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  42082. }
  42083. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  42084. {
  42085. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  42086. }
  42087. int TreeView::getNumRowsInTree() const
  42088. {
  42089. if (rootItem != 0)
  42090. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  42091. return 0;
  42092. }
  42093. TreeViewItem* TreeView::getItemOnRow (int index) const
  42094. {
  42095. if (! rootItemVisible)
  42096. ++index;
  42097. if (rootItem != 0 && index >= 0)
  42098. return rootItem->getItemOnRow (index);
  42099. return 0;
  42100. }
  42101. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  42102. {
  42103. XmlElement* e = 0;
  42104. if (rootItem != 0)
  42105. {
  42106. e = rootItem->createXmlOpenness();
  42107. if (e != 0 && alsoIncludeScrollPosition)
  42108. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  42109. }
  42110. return e;
  42111. }
  42112. void TreeView::restoreOpennessState (const XmlElement& newState)
  42113. {
  42114. if (rootItem != 0)
  42115. {
  42116. rootItem->restoreFromXml (newState);
  42117. if (newState.hasAttribute (T("scrollPos")))
  42118. viewport->setViewPosition (viewport->getViewPositionX(),
  42119. newState.getIntAttribute (T("scrollPos")));
  42120. }
  42121. }
  42122. void TreeView::paint (Graphics& g)
  42123. {
  42124. g.fillAll (findColour (backgroundColourId));
  42125. }
  42126. void TreeView::resized()
  42127. {
  42128. viewport->setBounds (0, 0, getWidth(), getHeight());
  42129. itemsChanged();
  42130. handleAsyncUpdate();
  42131. }
  42132. void TreeView::enablementChanged()
  42133. {
  42134. repaint();
  42135. }
  42136. void TreeView::moveSelectedRow (int delta)
  42137. {
  42138. if (delta == 0)
  42139. return;
  42140. int rowSelected = 0;
  42141. TreeViewItem* const firstSelected = getSelectedItem (0);
  42142. if (firstSelected != 0)
  42143. rowSelected = firstSelected->getRowNumberInTree();
  42144. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  42145. for (;;)
  42146. {
  42147. TreeViewItem* item = getItemOnRow (rowSelected);
  42148. if (item != 0)
  42149. {
  42150. if (! item->canBeSelected())
  42151. {
  42152. // if the row we want to highlight doesn't allow it, try skipping
  42153. // to the next item..
  42154. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  42155. rowSelected + (delta < 0 ? -1 : 1));
  42156. if (rowSelected != nextRowToTry)
  42157. {
  42158. rowSelected = nextRowToTry;
  42159. continue;
  42160. }
  42161. else
  42162. {
  42163. break;
  42164. }
  42165. }
  42166. item->setSelected (true, true);
  42167. scrollToKeepItemVisible (item);
  42168. }
  42169. break;
  42170. }
  42171. }
  42172. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  42173. {
  42174. if (item != 0 && item->ownerView == this)
  42175. {
  42176. handleAsyncUpdate();
  42177. item = item->getDeepestOpenParentItem();
  42178. int y = item->y;
  42179. int viewTop = viewport->getViewPositionY();
  42180. if (y < viewTop)
  42181. {
  42182. viewport->setViewPosition (viewport->getViewPositionX(), y);
  42183. }
  42184. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  42185. {
  42186. viewport->setViewPosition (viewport->getViewPositionX(),
  42187. (y + item->itemHeight) - viewport->getViewHeight());
  42188. }
  42189. }
  42190. }
  42191. bool TreeView::keyPressed (const KeyPress& key)
  42192. {
  42193. if (key.isKeyCode (KeyPress::upKey))
  42194. {
  42195. moveSelectedRow (-1);
  42196. }
  42197. else if (key.isKeyCode (KeyPress::downKey))
  42198. {
  42199. moveSelectedRow (1);
  42200. }
  42201. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  42202. {
  42203. if (rootItem != 0)
  42204. {
  42205. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  42206. if (key.isKeyCode (KeyPress::pageUpKey))
  42207. rowsOnScreen = -rowsOnScreen;
  42208. moveSelectedRow (rowsOnScreen);
  42209. }
  42210. }
  42211. else if (key.isKeyCode (KeyPress::homeKey))
  42212. {
  42213. moveSelectedRow (-0x3fffffff);
  42214. }
  42215. else if (key.isKeyCode (KeyPress::endKey))
  42216. {
  42217. moveSelectedRow (0x3fffffff);
  42218. }
  42219. else if (key.isKeyCode (KeyPress::returnKey))
  42220. {
  42221. TreeViewItem* const firstSelected = getSelectedItem (0);
  42222. if (firstSelected != 0)
  42223. firstSelected->setOpen (! firstSelected->isOpen());
  42224. }
  42225. else if (key.isKeyCode (KeyPress::leftKey))
  42226. {
  42227. TreeViewItem* const firstSelected = getSelectedItem (0);
  42228. if (firstSelected != 0)
  42229. {
  42230. if (firstSelected->isOpen())
  42231. {
  42232. firstSelected->setOpen (false);
  42233. }
  42234. else
  42235. {
  42236. TreeViewItem* parent = firstSelected->parentItem;
  42237. if ((! rootItemVisible) && parent == rootItem)
  42238. parent = 0;
  42239. if (parent != 0)
  42240. {
  42241. parent->setSelected (true, true);
  42242. scrollToKeepItemVisible (parent);
  42243. }
  42244. }
  42245. }
  42246. }
  42247. else if (key.isKeyCode (KeyPress::rightKey))
  42248. {
  42249. TreeViewItem* const firstSelected = getSelectedItem (0);
  42250. if (firstSelected != 0)
  42251. {
  42252. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  42253. moveSelectedRow (1);
  42254. else
  42255. firstSelected->setOpen (true);
  42256. }
  42257. }
  42258. else
  42259. {
  42260. return false;
  42261. }
  42262. return true;
  42263. }
  42264. void TreeView::itemsChanged() throw()
  42265. {
  42266. needsRecalculating = true;
  42267. repaint();
  42268. triggerAsyncUpdate();
  42269. }
  42270. void TreeView::handleAsyncUpdate()
  42271. {
  42272. if (needsRecalculating)
  42273. {
  42274. needsRecalculating = false;
  42275. const ScopedLock sl (nodeAlterationLock);
  42276. if (rootItem != 0)
  42277. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  42278. ((TreeViewport*) viewport)->updateComponents();
  42279. if (rootItem != 0)
  42280. {
  42281. viewport->getViewedComponent()
  42282. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  42283. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  42284. }
  42285. else
  42286. {
  42287. viewport->getViewedComponent()->setSize (0, 0);
  42288. }
  42289. }
  42290. }
  42291. void TreeViewContentComponent::paint (Graphics& g)
  42292. {
  42293. if (owner->rootItem != 0)
  42294. {
  42295. owner->handleAsyncUpdate();
  42296. if (! owner->rootItemVisible)
  42297. g.setOrigin (0, -owner->rootItem->itemHeight);
  42298. owner->rootItem->paintRecursively (g, getWidth());
  42299. }
  42300. }
  42301. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  42302. {
  42303. if (owner->rootItem != 0)
  42304. {
  42305. owner->handleAsyncUpdate();
  42306. if (! owner->rootItemVisible)
  42307. y += owner->rootItem->itemHeight;
  42308. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  42309. if (ti != 0)
  42310. itemPosition = ti->getItemPosition (false);
  42311. return ti;
  42312. }
  42313. return 0;
  42314. }
  42315. #define opennessDefault 0
  42316. #define opennessClosed 1
  42317. #define opennessOpen 2
  42318. TreeViewItem::TreeViewItem()
  42319. : ownerView (0),
  42320. parentItem (0),
  42321. subItems (8),
  42322. y (0),
  42323. itemHeight (0),
  42324. totalHeight (0),
  42325. selected (false),
  42326. redrawNeeded (true),
  42327. drawLinesInside (true),
  42328. drawsInLeftMargin (false),
  42329. openness (opennessDefault)
  42330. {
  42331. static int nextUID = 0;
  42332. uid = nextUID++;
  42333. }
  42334. TreeViewItem::~TreeViewItem()
  42335. {
  42336. }
  42337. const String TreeViewItem::getUniqueName() const
  42338. {
  42339. return String::empty;
  42340. }
  42341. void TreeViewItem::itemOpennessChanged (bool)
  42342. {
  42343. }
  42344. int TreeViewItem::getNumSubItems() const throw()
  42345. {
  42346. return subItems.size();
  42347. }
  42348. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  42349. {
  42350. return subItems [index];
  42351. }
  42352. void TreeViewItem::clearSubItems()
  42353. {
  42354. if (subItems.size() > 0)
  42355. {
  42356. if (ownerView != 0)
  42357. {
  42358. const ScopedLock sl (ownerView->nodeAlterationLock);
  42359. subItems.clear();
  42360. treeHasChanged();
  42361. }
  42362. else
  42363. {
  42364. subItems.clear();
  42365. }
  42366. }
  42367. }
  42368. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  42369. {
  42370. if (newItem != 0)
  42371. {
  42372. newItem->parentItem = this;
  42373. newItem->setOwnerView (ownerView);
  42374. newItem->y = 0;
  42375. newItem->itemHeight = newItem->getItemHeight();
  42376. newItem->totalHeight = 0;
  42377. newItem->itemWidth = newItem->getItemWidth();
  42378. newItem->totalWidth = 0;
  42379. if (ownerView != 0)
  42380. {
  42381. const ScopedLock sl (ownerView->nodeAlterationLock);
  42382. subItems.insert (insertPosition, newItem);
  42383. treeHasChanged();
  42384. if (newItem->isOpen())
  42385. newItem->itemOpennessChanged (true);
  42386. }
  42387. else
  42388. {
  42389. subItems.insert (insertPosition, newItem);
  42390. if (newItem->isOpen())
  42391. newItem->itemOpennessChanged (true);
  42392. }
  42393. }
  42394. }
  42395. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  42396. {
  42397. if (ownerView != 0)
  42398. ownerView->nodeAlterationLock.enter();
  42399. if (((unsigned int) index) < (unsigned int) subItems.size())
  42400. {
  42401. subItems.remove (index, deleteItem);
  42402. treeHasChanged();
  42403. }
  42404. if (ownerView != 0)
  42405. ownerView->nodeAlterationLock.exit();
  42406. }
  42407. bool TreeViewItem::isOpen() const throw()
  42408. {
  42409. if (openness == opennessDefault)
  42410. return ownerView != 0 && ownerView->defaultOpenness;
  42411. else
  42412. return openness == opennessOpen;
  42413. }
  42414. void TreeViewItem::setOpen (const bool shouldBeOpen)
  42415. {
  42416. if (isOpen() != shouldBeOpen)
  42417. {
  42418. openness = shouldBeOpen ? opennessOpen
  42419. : opennessClosed;
  42420. treeHasChanged();
  42421. itemOpennessChanged (isOpen());
  42422. }
  42423. }
  42424. bool TreeViewItem::isSelected() const throw()
  42425. {
  42426. return selected;
  42427. }
  42428. void TreeViewItem::deselectAllRecursively()
  42429. {
  42430. setSelected (false, false);
  42431. for (int i = 0; i < subItems.size(); ++i)
  42432. subItems.getUnchecked(i)->deselectAllRecursively();
  42433. }
  42434. void TreeViewItem::setSelected (const bool shouldBeSelected,
  42435. const bool deselectOtherItemsFirst)
  42436. {
  42437. if (shouldBeSelected && ! canBeSelected())
  42438. return;
  42439. if (deselectOtherItemsFirst)
  42440. getTopLevelItem()->deselectAllRecursively();
  42441. if (shouldBeSelected != selected)
  42442. {
  42443. selected = shouldBeSelected;
  42444. if (ownerView != 0)
  42445. ownerView->repaint();
  42446. itemSelectionChanged (shouldBeSelected);
  42447. }
  42448. }
  42449. void TreeViewItem::paintItem (Graphics&, int, int)
  42450. {
  42451. }
  42452. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  42453. {
  42454. ownerView->getLookAndFeel()
  42455. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  42456. }
  42457. void TreeViewItem::itemClicked (const MouseEvent&)
  42458. {
  42459. }
  42460. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  42461. {
  42462. if (mightContainSubItems())
  42463. setOpen (! isOpen());
  42464. }
  42465. void TreeViewItem::itemSelectionChanged (bool)
  42466. {
  42467. }
  42468. const String TreeViewItem::getTooltip()
  42469. {
  42470. return String::empty;
  42471. }
  42472. const String TreeViewItem::getDragSourceDescription()
  42473. {
  42474. return String::empty;
  42475. }
  42476. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  42477. {
  42478. const int indentX = getIndentX();
  42479. int width = itemWidth;
  42480. if (ownerView != 0 && width < 0)
  42481. width = ownerView->viewport->getViewWidth() - indentX;
  42482. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  42483. if (relativeToTreeViewTopLeft)
  42484. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  42485. r.getY() - ownerView->viewport->getViewPositionY());
  42486. return r;
  42487. }
  42488. void TreeViewItem::treeHasChanged() const throw()
  42489. {
  42490. if (ownerView != 0)
  42491. ownerView->itemsChanged();
  42492. }
  42493. void TreeViewItem::repaintItem() const
  42494. {
  42495. if (ownerView != 0 && areAllParentsOpen())
  42496. {
  42497. const Rectangle r (getItemPosition (true));
  42498. ownerView->viewport->repaint (0, r.getY(), r.getRight(), r.getHeight());
  42499. }
  42500. }
  42501. bool TreeViewItem::areAllParentsOpen() const throw()
  42502. {
  42503. return parentItem == 0
  42504. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  42505. }
  42506. void TreeViewItem::updatePositions (int newY)
  42507. {
  42508. y = newY;
  42509. itemHeight = getItemHeight();
  42510. totalHeight = itemHeight;
  42511. itemWidth = getItemWidth();
  42512. totalWidth = jmax (itemWidth, 0) + getIndentX();
  42513. if (isOpen())
  42514. {
  42515. newY += totalHeight;
  42516. for (int i = 0; i < subItems.size(); ++i)
  42517. {
  42518. TreeViewItem* const ti = subItems.getUnchecked(i);
  42519. ti->updatePositions (newY);
  42520. newY += ti->totalHeight;
  42521. totalHeight += ti->totalHeight;
  42522. totalWidth = jmax (totalWidth, ti->totalWidth);
  42523. }
  42524. }
  42525. }
  42526. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  42527. {
  42528. TreeViewItem* result = this;
  42529. TreeViewItem* item = this;
  42530. while (item->parentItem != 0)
  42531. {
  42532. item = item->parentItem;
  42533. if (! item->isOpen())
  42534. result = item;
  42535. }
  42536. return result;
  42537. }
  42538. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  42539. {
  42540. ownerView = newOwner;
  42541. for (int i = subItems.size(); --i >= 0;)
  42542. subItems.getUnchecked(i)->setOwnerView (newOwner);
  42543. }
  42544. int TreeViewItem::getIndentX() const throw()
  42545. {
  42546. const int indentWidth = ownerView->getIndentSize();
  42547. int x = ownerView->rootItemVisible ? indentWidth : 0;
  42548. if (! ownerView->openCloseButtonsVisible)
  42549. x -= indentWidth;
  42550. TreeViewItem* p = parentItem;
  42551. while (p != 0)
  42552. {
  42553. x += indentWidth;
  42554. p = p->parentItem;
  42555. }
  42556. return x;
  42557. }
  42558. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  42559. {
  42560. drawsInLeftMargin = canDrawInLeftMargin;
  42561. }
  42562. void TreeViewItem::paintRecursively (Graphics& g, int width)
  42563. {
  42564. jassert (ownerView != 0);
  42565. if (ownerView == 0)
  42566. return;
  42567. const int indent = getIndentX();
  42568. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  42569. g.setColour (ownerView->findColour (TreeView::linesColourId));
  42570. const float halfH = itemHeight * 0.5f;
  42571. int depth = 0;
  42572. TreeViewItem* p = parentItem;
  42573. while (p != 0)
  42574. {
  42575. ++depth;
  42576. p = p->parentItem;
  42577. }
  42578. if (! ownerView->rootItemVisible)
  42579. --depth;
  42580. const int indentWidth = ownerView->getIndentSize();
  42581. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  42582. {
  42583. float x = (depth + 0.5f) * indentWidth;
  42584. if (depth >= 0)
  42585. {
  42586. if (parentItem != 0 && parentItem->drawLinesInside)
  42587. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  42588. if ((parentItem != 0 && parentItem->drawLinesInside)
  42589. || (parentItem == 0 && drawLinesInside))
  42590. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  42591. }
  42592. p = parentItem;
  42593. int d = depth;
  42594. while (p != 0 && --d >= 0)
  42595. {
  42596. x -= (float) indentWidth;
  42597. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  42598. && ! p->isLastOfSiblings())
  42599. {
  42600. g.drawLine (x, 0, x, (float) itemHeight);
  42601. }
  42602. p = p->parentItem;
  42603. }
  42604. if (mightContainSubItems())
  42605. {
  42606. g.saveState();
  42607. g.setOrigin (depth * indentWidth, 0);
  42608. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  42609. paintOpenCloseButton (g, indentWidth, itemHeight,
  42610. ((TreeViewContentComponent*) ownerView->viewport->getViewedComponent())
  42611. ->isMouseOverButton (this));
  42612. g.restoreState();
  42613. }
  42614. }
  42615. {
  42616. g.saveState();
  42617. g.setOrigin (indent, 0);
  42618. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  42619. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  42620. paintItem (g, itemW, itemHeight);
  42621. g.restoreState();
  42622. }
  42623. if (isOpen())
  42624. {
  42625. const Rectangle clip (g.getClipBounds());
  42626. for (int i = 0; i < subItems.size(); ++i)
  42627. {
  42628. TreeViewItem* const ti = subItems.getUnchecked(i);
  42629. const int relY = ti->y - y;
  42630. if (relY >= clip.getBottom())
  42631. break;
  42632. if (relY + ti->totalHeight >= clip.getY())
  42633. {
  42634. g.saveState();
  42635. g.setOrigin (0, relY);
  42636. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  42637. ti->paintRecursively (g, width);
  42638. g.restoreState();
  42639. }
  42640. }
  42641. }
  42642. }
  42643. bool TreeViewItem::isLastOfSiblings() const throw()
  42644. {
  42645. return parentItem == 0
  42646. || parentItem->subItems.getLast() == this;
  42647. }
  42648. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  42649. {
  42650. return (parentItem == 0) ? this
  42651. : parentItem->getTopLevelItem();
  42652. }
  42653. int TreeViewItem::getNumRows() const throw()
  42654. {
  42655. int num = 1;
  42656. if (isOpen())
  42657. {
  42658. for (int i = subItems.size(); --i >= 0;)
  42659. num += subItems.getUnchecked(i)->getNumRows();
  42660. }
  42661. return num;
  42662. }
  42663. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  42664. {
  42665. if (index == 0)
  42666. return this;
  42667. if (index > 0 && isOpen())
  42668. {
  42669. --index;
  42670. for (int i = 0; i < subItems.size(); ++i)
  42671. {
  42672. TreeViewItem* const item = subItems.getUnchecked(i);
  42673. if (index == 0)
  42674. return item;
  42675. const int numRows = item->getNumRows();
  42676. if (numRows > index)
  42677. return item->getItemOnRow (index);
  42678. index -= numRows;
  42679. }
  42680. }
  42681. return 0;
  42682. }
  42683. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  42684. {
  42685. if (((unsigned int) y) < (unsigned int) totalHeight)
  42686. {
  42687. const int h = itemHeight;
  42688. if (y < h)
  42689. return this;
  42690. if (isOpen())
  42691. {
  42692. y -= h;
  42693. for (int i = 0; i < subItems.size(); ++i)
  42694. {
  42695. TreeViewItem* const ti = subItems.getUnchecked(i);
  42696. if (ti->totalHeight >= y)
  42697. return ti->findItemRecursively (y);
  42698. y -= ti->totalHeight;
  42699. }
  42700. }
  42701. }
  42702. return 0;
  42703. }
  42704. int TreeViewItem::countSelectedItemsRecursively() const throw()
  42705. {
  42706. int total = 0;
  42707. if (isSelected())
  42708. ++total;
  42709. for (int i = subItems.size(); --i >= 0;)
  42710. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  42711. return total;
  42712. }
  42713. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  42714. {
  42715. if (isSelected())
  42716. {
  42717. if (index == 0)
  42718. return this;
  42719. --index;
  42720. }
  42721. if (index >= 0)
  42722. {
  42723. for (int i = 0; i < subItems.size(); ++i)
  42724. {
  42725. TreeViewItem* const item = subItems.getUnchecked(i);
  42726. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  42727. if (found != 0)
  42728. return found;
  42729. index -= item->countSelectedItemsRecursively();
  42730. }
  42731. }
  42732. return 0;
  42733. }
  42734. int TreeViewItem::getRowNumberInTree() const throw()
  42735. {
  42736. if (parentItem != 0 && ownerView != 0)
  42737. {
  42738. int n = 1 + parentItem->getRowNumberInTree();
  42739. int ourIndex = parentItem->subItems.indexOf (this);
  42740. jassert (ourIndex >= 0);
  42741. while (--ourIndex >= 0)
  42742. n += parentItem->subItems [ourIndex]->getNumRows();
  42743. if (parentItem->parentItem == 0
  42744. && ! ownerView->rootItemVisible)
  42745. --n;
  42746. return n;
  42747. }
  42748. else
  42749. {
  42750. return 0;
  42751. }
  42752. }
  42753. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  42754. {
  42755. drawLinesInside = drawLines;
  42756. }
  42757. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  42758. {
  42759. if (recurse && isOpen() && subItems.size() > 0)
  42760. return subItems [0];
  42761. if (parentItem != 0)
  42762. {
  42763. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  42764. if (nextIndex >= parentItem->subItems.size())
  42765. return parentItem->getNextVisibleItem (false);
  42766. return parentItem->subItems [nextIndex];
  42767. }
  42768. return 0;
  42769. }
  42770. void TreeViewItem::restoreFromXml (const XmlElement& e)
  42771. {
  42772. if (e.hasTagName (T("CLOSED")))
  42773. {
  42774. setOpen (false);
  42775. }
  42776. else if (e.hasTagName (T("OPEN")))
  42777. {
  42778. setOpen (true);
  42779. forEachXmlChildElement (e, n)
  42780. {
  42781. const String id (n->getStringAttribute (T("id")));
  42782. for (int i = 0; i < subItems.size(); ++i)
  42783. {
  42784. TreeViewItem* const ti = subItems.getUnchecked(i);
  42785. if (ti->getUniqueName() == id)
  42786. {
  42787. ti->restoreFromXml (*n);
  42788. break;
  42789. }
  42790. }
  42791. }
  42792. }
  42793. }
  42794. XmlElement* TreeViewItem::createXmlOpenness() const
  42795. {
  42796. if (openness != opennessDefault)
  42797. {
  42798. const String name (getUniqueName());
  42799. if (name.isNotEmpty())
  42800. {
  42801. XmlElement* e;
  42802. if (isOpen())
  42803. {
  42804. e = new XmlElement (T("OPEN"));
  42805. for (int i = 0; i < subItems.size(); ++i)
  42806. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  42807. }
  42808. else
  42809. {
  42810. e = new XmlElement (T("CLOSED"));
  42811. }
  42812. e->setAttribute (T("id"), name);
  42813. return e;
  42814. }
  42815. else
  42816. {
  42817. // trying to save the openness for an element that has no name - this won't
  42818. // work because it needs the names to identify what to open.
  42819. jassertfalse
  42820. }
  42821. }
  42822. return 0;
  42823. }
  42824. END_JUCE_NAMESPACE
  42825. /********* End of inlined file: juce_TreeView.cpp *********/
  42826. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42827. BEGIN_JUCE_NAMESPACE
  42828. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  42829. : fileList (listToShow),
  42830. listeners (2)
  42831. {
  42832. }
  42833. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  42834. {
  42835. }
  42836. FileBrowserListener::~FileBrowserListener()
  42837. {
  42838. }
  42839. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  42840. {
  42841. jassert (listener != 0);
  42842. if (listener != 0)
  42843. listeners.add (listener);
  42844. }
  42845. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  42846. {
  42847. listeners.removeValue (listener);
  42848. }
  42849. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  42850. {
  42851. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42852. for (int i = listeners.size(); --i >= 0;)
  42853. {
  42854. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  42855. if (deletionWatcher.hasBeenDeleted())
  42856. return;
  42857. i = jmin (i, listeners.size() - 1);
  42858. }
  42859. }
  42860. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  42861. {
  42862. if (fileList.getDirectory().exists())
  42863. {
  42864. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42865. for (int i = listeners.size(); --i >= 0;)
  42866. {
  42867. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  42868. if (deletionWatcher.hasBeenDeleted())
  42869. return;
  42870. i = jmin (i, listeners.size() - 1);
  42871. }
  42872. }
  42873. }
  42874. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  42875. {
  42876. if (fileList.getDirectory().exists())
  42877. {
  42878. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  42879. for (int i = listeners.size(); --i >= 0;)
  42880. {
  42881. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  42882. if (deletionWatcher.hasBeenDeleted())
  42883. return;
  42884. i = jmin (i, listeners.size() - 1);
  42885. }
  42886. }
  42887. }
  42888. END_JUCE_NAMESPACE
  42889. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  42890. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  42891. BEGIN_JUCE_NAMESPACE
  42892. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  42893. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  42894. Time* creationTime, bool* isReadOnly) throw();
  42895. bool juce_findFileNext (void* handle, String& resultFile,
  42896. bool* isDirectory, bool* isHidden, int64* fileSize,
  42897. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  42898. void juce_findFileClose (void* handle) throw();
  42899. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  42900. TimeSliceThread& thread_)
  42901. : fileFilter (fileFilter_),
  42902. thread (thread_),
  42903. includeDirectories (false),
  42904. includeFiles (false),
  42905. ignoreHiddenFiles (true),
  42906. fileFindHandle (0),
  42907. shouldStop (true)
  42908. {
  42909. }
  42910. DirectoryContentsList::~DirectoryContentsList()
  42911. {
  42912. clear();
  42913. }
  42914. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  42915. {
  42916. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  42917. }
  42918. const File& DirectoryContentsList::getDirectory() const throw()
  42919. {
  42920. return root;
  42921. }
  42922. void DirectoryContentsList::setDirectory (const File& directory,
  42923. const bool includeDirectories_,
  42924. const bool includeFiles_)
  42925. {
  42926. if (directory != root
  42927. || includeDirectories != includeDirectories_
  42928. || includeFiles != includeFiles_)
  42929. {
  42930. clear();
  42931. root = directory;
  42932. includeDirectories = includeDirectories_;
  42933. includeFiles = includeFiles_;
  42934. refresh();
  42935. }
  42936. }
  42937. void DirectoryContentsList::clear()
  42938. {
  42939. shouldStop = true;
  42940. thread.removeTimeSliceClient (this);
  42941. if (fileFindHandle != 0)
  42942. {
  42943. juce_findFileClose (fileFindHandle);
  42944. fileFindHandle = 0;
  42945. }
  42946. if (files.size() > 0)
  42947. {
  42948. files.clear();
  42949. changed();
  42950. }
  42951. }
  42952. void DirectoryContentsList::refresh()
  42953. {
  42954. clear();
  42955. if (root.isDirectory())
  42956. {
  42957. String fileFound;
  42958. bool fileFoundIsDir, isHidden, isReadOnly;
  42959. int64 fileSize;
  42960. Time modTime, creationTime;
  42961. String path (root.getFullPathName());
  42962. if (! path.endsWithChar (File::separator))
  42963. path += File::separator;
  42964. jassert (fileFindHandle == 0);
  42965. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  42966. &fileFoundIsDir,
  42967. &isHidden,
  42968. &fileSize,
  42969. &modTime,
  42970. &creationTime,
  42971. &isReadOnly);
  42972. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  42973. {
  42974. if (addFile (fileFound, fileFoundIsDir, isHidden,
  42975. fileSize, modTime, creationTime, isReadOnly))
  42976. {
  42977. changed();
  42978. }
  42979. }
  42980. shouldStop = false;
  42981. thread.addTimeSliceClient (this);
  42982. }
  42983. }
  42984. int DirectoryContentsList::getNumFiles() const
  42985. {
  42986. return files.size();
  42987. }
  42988. bool DirectoryContentsList::getFileInfo (const int index,
  42989. FileInfo& result) const
  42990. {
  42991. const ScopedLock sl (fileListLock);
  42992. const FileInfo* const info = files [index];
  42993. if (info != 0)
  42994. {
  42995. result = *info;
  42996. return true;
  42997. }
  42998. return false;
  42999. }
  43000. const File DirectoryContentsList::getFile (const int index) const
  43001. {
  43002. const ScopedLock sl (fileListLock);
  43003. const FileInfo* const info = files [index];
  43004. if (info != 0)
  43005. return root.getChildFile (info->filename);
  43006. return File::nonexistent;
  43007. }
  43008. bool DirectoryContentsList::isStillLoading() const
  43009. {
  43010. return fileFindHandle != 0;
  43011. }
  43012. void DirectoryContentsList::changed()
  43013. {
  43014. sendChangeMessage (this);
  43015. }
  43016. bool DirectoryContentsList::useTimeSlice()
  43017. {
  43018. const uint32 startTime = Time::getApproximateMillisecondCounter();
  43019. bool hasChanged = false;
  43020. for (int i = 100; --i >= 0;)
  43021. {
  43022. if (! checkNextFile (hasChanged))
  43023. {
  43024. if (hasChanged)
  43025. changed();
  43026. return false;
  43027. }
  43028. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  43029. break;
  43030. }
  43031. if (hasChanged)
  43032. changed();
  43033. return true;
  43034. }
  43035. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  43036. {
  43037. if (fileFindHandle != 0)
  43038. {
  43039. String fileFound;
  43040. bool fileFoundIsDir, isHidden, isReadOnly;
  43041. int64 fileSize;
  43042. Time modTime, creationTime;
  43043. if (juce_findFileNext (fileFindHandle, fileFound,
  43044. &fileFoundIsDir, &isHidden,
  43045. &fileSize,
  43046. &modTime,
  43047. &creationTime,
  43048. &isReadOnly))
  43049. {
  43050. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  43051. modTime, creationTime, isReadOnly))
  43052. {
  43053. hasChanged = true;
  43054. }
  43055. return true;
  43056. }
  43057. else
  43058. {
  43059. juce_findFileClose (fileFindHandle);
  43060. fileFindHandle = 0;
  43061. }
  43062. }
  43063. return false;
  43064. }
  43065. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  43066. const DirectoryContentsList::FileInfo* const second) throw()
  43067. {
  43068. #if JUCE_WIN32
  43069. if (first->isDirectory != second->isDirectory)
  43070. return first->isDirectory ? -1 : 1;
  43071. #endif
  43072. return first->filename.compareIgnoreCase (second->filename);
  43073. }
  43074. bool DirectoryContentsList::addFile (const String& filename,
  43075. const bool isDir,
  43076. const bool isHidden,
  43077. const int64 fileSize,
  43078. const Time& modTime,
  43079. const Time& creationTime,
  43080. const bool isReadOnly)
  43081. {
  43082. if (filename == T("..")
  43083. || filename == T(".")
  43084. || (ignoreHiddenFiles && isHidden))
  43085. return false;
  43086. const File file (root.getChildFile (filename));
  43087. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  43088. && (fileFilter == 0
  43089. || ((! isDir) && fileFilter->isFileSuitable (file))
  43090. || (isDir && fileFilter->isDirectorySuitable (file))))
  43091. {
  43092. FileInfo* const info = new FileInfo();
  43093. info->filename = filename;
  43094. info->fileSize = fileSize;
  43095. info->modificationTime = modTime;
  43096. info->creationTime = creationTime;
  43097. info->isDirectory = isDir;
  43098. info->isReadOnly = isReadOnly;
  43099. const ScopedLock sl (fileListLock);
  43100. for (int i = files.size(); --i >= 0;)
  43101. {
  43102. if (files.getUnchecked(i)->filename == info->filename)
  43103. {
  43104. delete info;
  43105. return false;
  43106. }
  43107. }
  43108. files.addSorted (*this, info);
  43109. return true;
  43110. }
  43111. return false;
  43112. }
  43113. END_JUCE_NAMESPACE
  43114. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  43115. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  43116. BEGIN_JUCE_NAMESPACE
  43117. class DirectoriesOnlyFilter : public FileFilter
  43118. {
  43119. public:
  43120. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  43121. bool isFileSuitable (const File&) const { return false; }
  43122. bool isDirectorySuitable (const File&) const { return true; }
  43123. };
  43124. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  43125. const File& initialFileOrDirectory,
  43126. const FileFilter* fileFilter,
  43127. FilePreviewComponent* previewComp_,
  43128. const bool useTreeView,
  43129. const bool filenameTextBoxIsReadOnly)
  43130. : directoriesOnlyFilter (0),
  43131. mode (mode_),
  43132. listeners (2),
  43133. previewComp (previewComp_),
  43134. thread ("Juce FileBrowser")
  43135. {
  43136. String filename;
  43137. if (initialFileOrDirectory == File::nonexistent)
  43138. {
  43139. currentRoot = File::getCurrentWorkingDirectory();
  43140. }
  43141. else if (initialFileOrDirectory.isDirectory())
  43142. {
  43143. currentRoot = initialFileOrDirectory;
  43144. }
  43145. else
  43146. {
  43147. currentRoot = initialFileOrDirectory.getParentDirectory();
  43148. filename = initialFileOrDirectory.getFileName();
  43149. }
  43150. if (mode_ == chooseDirectoryMode)
  43151. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  43152. fileList = new DirectoryContentsList (fileFilter, thread);
  43153. if (useTreeView)
  43154. {
  43155. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  43156. addAndMakeVisible (tree);
  43157. fileListComponent = tree;
  43158. }
  43159. else
  43160. {
  43161. FileListComponent* const list = new FileListComponent (*fileList);
  43162. list->setOutlineThickness (1);
  43163. addAndMakeVisible (list);
  43164. fileListComponent = list;
  43165. }
  43166. fileListComponent->addListener (this);
  43167. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  43168. currentPathBox->setEditableText (true);
  43169. StringArray rootNames, rootPaths;
  43170. const BitArray separators (getRoots (rootNames, rootPaths));
  43171. for (int i = 0; i < rootNames.size(); ++i)
  43172. {
  43173. if (separators [i])
  43174. currentPathBox->addSeparator();
  43175. currentPathBox->addItem (rootNames[i], i + 1);
  43176. }
  43177. currentPathBox->addSeparator();
  43178. currentPathBox->addListener (this);
  43179. addAndMakeVisible (filenameBox = new TextEditor());
  43180. filenameBox->setMultiLine (false);
  43181. filenameBox->setSelectAllWhenFocused (true);
  43182. filenameBox->setText (filename, false);
  43183. filenameBox->addListener (this);
  43184. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  43185. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  43186. : TRANS("file:"));
  43187. addAndMakeVisible (label);
  43188. label->attachToComponent (filenameBox, true);
  43189. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  43190. goUpButton->addButtonListener (this);
  43191. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  43192. if (previewComp != 0)
  43193. addAndMakeVisible (previewComp);
  43194. setRoot (currentRoot);
  43195. thread.startThread (4);
  43196. }
  43197. FileBrowserComponent::~FileBrowserComponent()
  43198. {
  43199. if (previewComp != 0)
  43200. removeChildComponent (previewComp);
  43201. deleteAllChildren();
  43202. deleteAndZero (fileList);
  43203. delete directoriesOnlyFilter;
  43204. thread.stopThread (10000);
  43205. }
  43206. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  43207. {
  43208. jassert (newListener != 0)
  43209. if (newListener != 0)
  43210. listeners.add (newListener);
  43211. }
  43212. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  43213. {
  43214. listeners.removeValue (listener);
  43215. }
  43216. const File FileBrowserComponent::getCurrentFile() const throw()
  43217. {
  43218. return currentRoot.getChildFile (filenameBox->getText());
  43219. }
  43220. bool FileBrowserComponent::currentFileIsValid() const
  43221. {
  43222. if (mode == saveFileMode)
  43223. return ! getCurrentFile().isDirectory();
  43224. else if (mode == loadFileMode)
  43225. return getCurrentFile().existsAsFile();
  43226. else if (mode == chooseDirectoryMode)
  43227. return getCurrentFile().isDirectory();
  43228. jassertfalse
  43229. return false;
  43230. }
  43231. const File FileBrowserComponent::getRoot() const
  43232. {
  43233. return currentRoot;
  43234. }
  43235. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  43236. {
  43237. if (currentRoot != newRootDirectory)
  43238. {
  43239. fileListComponent->scrollToTop();
  43240. if (mode == chooseDirectoryMode)
  43241. filenameBox->setText (String::empty, false);
  43242. String path (newRootDirectory.getFullPathName());
  43243. if (path.isEmpty())
  43244. path += File::separator;
  43245. StringArray rootNames, rootPaths;
  43246. getRoots (rootNames, rootPaths);
  43247. if (! rootPaths.contains (path, true))
  43248. {
  43249. bool alreadyListed = false;
  43250. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  43251. {
  43252. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  43253. {
  43254. alreadyListed = true;
  43255. break;
  43256. }
  43257. }
  43258. if (! alreadyListed)
  43259. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  43260. }
  43261. }
  43262. currentRoot = newRootDirectory;
  43263. fileList->setDirectory (currentRoot, true, true);
  43264. String currentRootName (currentRoot.getFullPathName());
  43265. if (currentRootName.isEmpty())
  43266. currentRootName += File::separator;
  43267. currentPathBox->setText (currentRootName, true);
  43268. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  43269. && currentRoot.getParentDirectory() != currentRoot);
  43270. }
  43271. void FileBrowserComponent::goUp()
  43272. {
  43273. setRoot (getRoot().getParentDirectory());
  43274. }
  43275. void FileBrowserComponent::refresh()
  43276. {
  43277. fileList->refresh();
  43278. }
  43279. const String FileBrowserComponent::getActionVerb() const
  43280. {
  43281. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  43282. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  43283. }
  43284. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  43285. {
  43286. return previewComp;
  43287. }
  43288. void FileBrowserComponent::resized()
  43289. {
  43290. getLookAndFeel()
  43291. .layoutFileBrowserComponent (*this, fileListComponent,
  43292. previewComp, currentPathBox,
  43293. filenameBox, goUpButton);
  43294. }
  43295. void FileBrowserComponent::sendListenerChangeMessage()
  43296. {
  43297. ComponentDeletionWatcher deletionWatcher (this);
  43298. if (previewComp != 0)
  43299. previewComp->selectedFileChanged (getCurrentFile());
  43300. jassert (! deletionWatcher.hasBeenDeleted());
  43301. for (int i = listeners.size(); --i >= 0;)
  43302. {
  43303. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  43304. if (deletionWatcher.hasBeenDeleted())
  43305. return;
  43306. i = jmin (i, listeners.size() - 1);
  43307. }
  43308. }
  43309. void FileBrowserComponent::selectionChanged()
  43310. {
  43311. const File selected (fileListComponent->getSelectedFile());
  43312. if ((mode == chooseDirectoryMode && selected.isDirectory())
  43313. || selected.existsAsFile())
  43314. {
  43315. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  43316. }
  43317. sendListenerChangeMessage();
  43318. }
  43319. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  43320. {
  43321. ComponentDeletionWatcher deletionWatcher (this);
  43322. for (int i = listeners.size(); --i >= 0;)
  43323. {
  43324. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  43325. if (deletionWatcher.hasBeenDeleted())
  43326. return;
  43327. i = jmin (i, listeners.size() - 1);
  43328. }
  43329. }
  43330. void FileBrowserComponent::fileDoubleClicked (const File& f)
  43331. {
  43332. if (f.isDirectory())
  43333. {
  43334. setRoot (f);
  43335. }
  43336. else
  43337. {
  43338. ComponentDeletionWatcher deletionWatcher (this);
  43339. for (int i = listeners.size(); --i >= 0;)
  43340. {
  43341. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  43342. if (deletionWatcher.hasBeenDeleted())
  43343. return;
  43344. i = jmin (i, listeners.size() - 1);
  43345. }
  43346. }
  43347. }
  43348. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  43349. {
  43350. #if JUCE_LINUX || JUCE_WIN32
  43351. if (key.getModifiers().isCommandDown()
  43352. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  43353. {
  43354. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  43355. fileList->refresh();
  43356. return true;
  43357. }
  43358. #endif
  43359. return false;
  43360. }
  43361. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  43362. {
  43363. sendListenerChangeMessage();
  43364. }
  43365. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  43366. {
  43367. if (filenameBox->getText().containsChar (File::separator))
  43368. {
  43369. const File f (currentRoot.getChildFile (filenameBox->getText()));
  43370. if (f.isDirectory())
  43371. {
  43372. setRoot (f);
  43373. filenameBox->setText (String::empty);
  43374. }
  43375. else
  43376. {
  43377. setRoot (f.getParentDirectory());
  43378. filenameBox->setText (f.getFileName());
  43379. }
  43380. }
  43381. else
  43382. {
  43383. fileDoubleClicked (getCurrentFile());
  43384. }
  43385. }
  43386. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  43387. {
  43388. }
  43389. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  43390. {
  43391. if (mode != saveFileMode)
  43392. selectionChanged();
  43393. }
  43394. void FileBrowserComponent::buttonClicked (Button*)
  43395. {
  43396. goUp();
  43397. }
  43398. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  43399. {
  43400. const String newText (currentPathBox->getText().trim().unquoted());
  43401. if (newText.isNotEmpty())
  43402. {
  43403. const int index = currentPathBox->getSelectedId() - 1;
  43404. StringArray rootNames, rootPaths;
  43405. getRoots (rootNames, rootPaths);
  43406. if (rootPaths [index].isNotEmpty())
  43407. {
  43408. setRoot (File (rootPaths [index]));
  43409. }
  43410. else
  43411. {
  43412. File f (newText);
  43413. for (;;)
  43414. {
  43415. if (f.isDirectory())
  43416. {
  43417. setRoot (f);
  43418. break;
  43419. }
  43420. if (f.getParentDirectory() == f)
  43421. break;
  43422. f = f.getParentDirectory();
  43423. }
  43424. }
  43425. }
  43426. }
  43427. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  43428. {
  43429. BitArray separators;
  43430. #if JUCE_WIN32
  43431. OwnedArray<File> roots;
  43432. File::findFileSystemRoots (roots);
  43433. rootPaths.clear();
  43434. for (int i = 0; i < roots.size(); ++i)
  43435. {
  43436. const File* const drive = roots.getUnchecked(i);
  43437. String name (drive->getFullPathName());
  43438. rootPaths.add (name);
  43439. if (drive->isOnHardDisk())
  43440. {
  43441. String volume (drive->getVolumeLabel());
  43442. if (volume.isEmpty())
  43443. volume = TRANS("Hard Drive");
  43444. name << " [" << drive->getVolumeLabel() << ']';
  43445. }
  43446. else if (drive->isOnCDRomDrive())
  43447. {
  43448. name << TRANS(" [CD/DVD drive]");
  43449. }
  43450. rootNames.add (name);
  43451. }
  43452. separators.setBit (rootPaths.size());
  43453. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43454. rootNames.add ("Documents");
  43455. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43456. rootNames.add ("Desktop");
  43457. #endif
  43458. #if JUCE_MAC
  43459. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43460. rootNames.add ("Home folder");
  43461. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  43462. rootNames.add ("Documents");
  43463. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43464. rootNames.add ("Desktop");
  43465. separators.setBit (rootPaths.size());
  43466. OwnedArray <File> volumes;
  43467. File vol ("/Volumes");
  43468. vol.findChildFiles (volumes, File::findDirectories, false);
  43469. for (int i = 0; i < volumes.size(); ++i)
  43470. {
  43471. const File* const volume = volumes.getUnchecked(i);
  43472. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  43473. {
  43474. rootPaths.add (volume->getFullPathName());
  43475. rootNames.add (volume->getFileName());
  43476. }
  43477. }
  43478. #endif
  43479. #if JUCE_LINUX
  43480. rootPaths.add ("/");
  43481. rootNames.add ("/");
  43482. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  43483. rootNames.add ("Home folder");
  43484. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  43485. rootNames.add ("Desktop");
  43486. #endif
  43487. return separators;
  43488. }
  43489. END_JUCE_NAMESPACE
  43490. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  43491. /********* Start of inlined file: juce_FileChooser.cpp *********/
  43492. BEGIN_JUCE_NAMESPACE
  43493. FileChooser::FileChooser (const String& chooserBoxTitle,
  43494. const File& currentFileOrDirectory,
  43495. const String& fileFilters,
  43496. const bool useNativeDialogBox_)
  43497. : title (chooserBoxTitle),
  43498. filters (fileFilters),
  43499. startingFile (currentFileOrDirectory),
  43500. useNativeDialogBox (useNativeDialogBox_)
  43501. {
  43502. #if JUCE_LINUX
  43503. useNativeDialogBox = false;
  43504. #endif
  43505. if (! fileFilters.containsNonWhitespaceChars())
  43506. filters = T("*");
  43507. }
  43508. FileChooser::~FileChooser()
  43509. {
  43510. }
  43511. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  43512. {
  43513. return showDialog (false, false, false, false, previewComponent);
  43514. }
  43515. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  43516. {
  43517. return showDialog (false, false, false, true, previewComponent);
  43518. }
  43519. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  43520. {
  43521. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  43522. }
  43523. bool FileChooser::browseForDirectory()
  43524. {
  43525. return showDialog (true, false, false, false, 0);
  43526. }
  43527. const File FileChooser::getResult() const
  43528. {
  43529. // if you've used a multiple-file select, you should use the getResults() method
  43530. // to retrieve all the files that were chosen.
  43531. jassert (results.size() <= 1);
  43532. const File* const f = results.getFirst();
  43533. if (f != 0)
  43534. return *f;
  43535. return File::nonexistent;
  43536. }
  43537. const OwnedArray <File>& FileChooser::getResults() const
  43538. {
  43539. return results;
  43540. }
  43541. bool FileChooser::showDialog (const bool isDirectory,
  43542. const bool isSave,
  43543. const bool warnAboutOverwritingExistingFiles,
  43544. const bool selectMultipleFiles,
  43545. FilePreviewComponent* const previewComponent)
  43546. {
  43547. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  43548. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  43549. if (currentlyFocused != 0)
  43550. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  43551. results.clear();
  43552. // the preview component needs to be the right size before you pass it in here..
  43553. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  43554. && previewComponent->getHeight() > 10));
  43555. #if JUCE_WIN32
  43556. if (useNativeDialogBox)
  43557. #else
  43558. if (useNativeDialogBox && (previewComponent == 0))
  43559. #endif
  43560. {
  43561. showPlatformDialog (results, title, startingFile, filters,
  43562. isDirectory, isSave,
  43563. warnAboutOverwritingExistingFiles,
  43564. selectMultipleFiles,
  43565. previewComponent);
  43566. }
  43567. else
  43568. {
  43569. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  43570. WildcardFileFilter wildcard (filters, String::empty);
  43571. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  43572. : (isSave ? FileBrowserComponent::saveFileMode
  43573. : FileBrowserComponent::loadFileMode),
  43574. startingFile, &wildcard, previewComponent);
  43575. FileChooserDialogBox box (title, String::empty,
  43576. browserComponent,
  43577. warnAboutOverwritingExistingFiles,
  43578. browserComponent.findColour (AlertWindow::backgroundColourId));
  43579. if (box.show())
  43580. results.add (new File (browserComponent.getCurrentFile()));
  43581. }
  43582. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  43583. currentlyFocused->grabKeyboardFocus();
  43584. delete currentlyFocusedChecker;
  43585. return results.size() > 0;
  43586. }
  43587. FilePreviewComponent::FilePreviewComponent()
  43588. {
  43589. }
  43590. FilePreviewComponent::~FilePreviewComponent()
  43591. {
  43592. }
  43593. END_JUCE_NAMESPACE
  43594. /********* End of inlined file: juce_FileChooser.cpp *********/
  43595. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  43596. BEGIN_JUCE_NAMESPACE
  43597. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  43598. const String& instructions,
  43599. FileBrowserComponent& chooserComponent,
  43600. const bool warnAboutOverwritingExistingFiles_,
  43601. const Colour& backgroundColour)
  43602. : ResizableWindow (name, backgroundColour, true),
  43603. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  43604. {
  43605. content = new ContentComponent();
  43606. content->setName (name);
  43607. content->instructions = instructions;
  43608. content->chooserComponent = &chooserComponent;
  43609. content->addAndMakeVisible (&chooserComponent);
  43610. content->okButton = new TextButton (chooserComponent.getActionVerb());
  43611. content->addAndMakeVisible (content->okButton);
  43612. content->okButton->addButtonListener (this);
  43613. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  43614. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  43615. content->cancelButton = new TextButton (TRANS("Cancel"));
  43616. content->addAndMakeVisible (content->cancelButton);
  43617. content->cancelButton->addButtonListener (this);
  43618. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  43619. setContentComponent (content);
  43620. setResizable (true, true);
  43621. setResizeLimits (300, 300, 1200, 1000);
  43622. content->chooserComponent->addListener (this);
  43623. }
  43624. FileChooserDialogBox::~FileChooserDialogBox()
  43625. {
  43626. content->chooserComponent->removeListener (this);
  43627. }
  43628. bool FileChooserDialogBox::show (int w, int h)
  43629. {
  43630. if (w <= 0)
  43631. {
  43632. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  43633. if (previewComp != 0)
  43634. w = 400 + previewComp->getWidth();
  43635. else
  43636. w = 600;
  43637. }
  43638. if (h <= 0)
  43639. h = 500;
  43640. centreWithSize (w, h);
  43641. const bool ok = (runModalLoop() != 0);
  43642. setVisible (false);
  43643. return ok;
  43644. }
  43645. void FileChooserDialogBox::buttonClicked (Button* button)
  43646. {
  43647. if (button == content->okButton)
  43648. {
  43649. if (warnAboutOverwritingExistingFiles
  43650. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  43651. && content->chooserComponent->getCurrentFile().exists())
  43652. {
  43653. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43654. TRANS("File already exists"),
  43655. TRANS("There's already a file called:\n\n")
  43656. + content->chooserComponent->getCurrentFile().getFullPathName()
  43657. + T("\n\nAre you sure you want to overwrite it?"),
  43658. TRANS("overwrite"),
  43659. TRANS("cancel")))
  43660. {
  43661. return;
  43662. }
  43663. }
  43664. exitModalState (1);
  43665. }
  43666. else if (button == content->cancelButton)
  43667. closeButtonPressed();
  43668. }
  43669. void FileChooserDialogBox::closeButtonPressed()
  43670. {
  43671. setVisible (false);
  43672. }
  43673. void FileChooserDialogBox::selectionChanged()
  43674. {
  43675. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  43676. }
  43677. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  43678. {
  43679. }
  43680. void FileChooserDialogBox::fileDoubleClicked (const File&)
  43681. {
  43682. selectionChanged();
  43683. content->okButton->triggerClick();
  43684. }
  43685. FileChooserDialogBox::ContentComponent::ContentComponent()
  43686. {
  43687. setInterceptsMouseClicks (false, true);
  43688. }
  43689. FileChooserDialogBox::ContentComponent::~ContentComponent()
  43690. {
  43691. delete okButton;
  43692. delete cancelButton;
  43693. }
  43694. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  43695. {
  43696. g.setColour (Colours::black);
  43697. text.draw (g);
  43698. }
  43699. void FileChooserDialogBox::ContentComponent::resized()
  43700. {
  43701. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  43702. float left, top, right, bottom;
  43703. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  43704. const int y = roundFloatToInt (bottom) + 10;
  43705. const int buttonHeight = 26;
  43706. const int buttonY = getHeight() - buttonHeight - 8;
  43707. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  43708. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  43709. proportionOfWidth (0.2f), buttonHeight);
  43710. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  43711. proportionOfWidth (0.2f), buttonHeight);
  43712. }
  43713. END_JUCE_NAMESPACE
  43714. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  43715. /********* Start of inlined file: juce_FileFilter.cpp *********/
  43716. BEGIN_JUCE_NAMESPACE
  43717. FileFilter::FileFilter (const String& filterDescription)
  43718. : description (filterDescription)
  43719. {
  43720. }
  43721. FileFilter::~FileFilter()
  43722. {
  43723. }
  43724. const String& FileFilter::getDescription() const throw()
  43725. {
  43726. return description;
  43727. }
  43728. END_JUCE_NAMESPACE
  43729. /********* End of inlined file: juce_FileFilter.cpp *********/
  43730. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  43731. BEGIN_JUCE_NAMESPACE
  43732. Image* juce_createIconForFile (const File& file);
  43733. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  43734. : ListBox (String::empty, 0),
  43735. DirectoryContentsDisplayComponent (listToShow)
  43736. {
  43737. setModel (this);
  43738. fileList.addChangeListener (this);
  43739. }
  43740. FileListComponent::~FileListComponent()
  43741. {
  43742. fileList.removeChangeListener (this);
  43743. deleteAllChildren();
  43744. }
  43745. const File FileListComponent::getSelectedFile() const
  43746. {
  43747. return fileList.getFile (getSelectedRow());
  43748. }
  43749. void FileListComponent::scrollToTop()
  43750. {
  43751. getVerticalScrollBar()->setCurrentRangeStart (0);
  43752. }
  43753. void FileListComponent::changeListenerCallback (void*)
  43754. {
  43755. updateContent();
  43756. if (lastDirectory != fileList.getDirectory())
  43757. {
  43758. lastDirectory = fileList.getDirectory();
  43759. deselectAllRows();
  43760. }
  43761. }
  43762. class FileListItemComponent : public Component,
  43763. public TimeSliceClient,
  43764. public AsyncUpdater
  43765. {
  43766. public:
  43767. FileListItemComponent (FileListComponent& owner_,
  43768. TimeSliceThread& thread_) throw()
  43769. : owner (owner_),
  43770. thread (thread_),
  43771. icon (0)
  43772. {
  43773. }
  43774. ~FileListItemComponent() throw()
  43775. {
  43776. thread.removeTimeSliceClient (this);
  43777. clearIcon();
  43778. }
  43779. void paint (Graphics& g)
  43780. {
  43781. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  43782. file.getFileName(),
  43783. icon,
  43784. fileSize, modTime,
  43785. isDirectory, highlighted,
  43786. index);
  43787. }
  43788. void mouseDown (const MouseEvent& e)
  43789. {
  43790. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  43791. owner.sendMouseClickMessage (file, e);
  43792. }
  43793. void mouseDoubleClick (const MouseEvent&)
  43794. {
  43795. owner.sendDoubleClickMessage (file);
  43796. }
  43797. void update (const File& root,
  43798. const DirectoryContentsList::FileInfo* const fileInfo,
  43799. const int index_,
  43800. const bool highlighted_) throw()
  43801. {
  43802. thread.removeTimeSliceClient (this);
  43803. if (highlighted_ != highlighted
  43804. || index_ != index)
  43805. {
  43806. index = index_;
  43807. highlighted = highlighted_;
  43808. repaint();
  43809. }
  43810. File newFile;
  43811. String newFileSize;
  43812. String newModTime;
  43813. if (fileInfo != 0)
  43814. {
  43815. newFile = root.getChildFile (fileInfo->filename);
  43816. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  43817. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  43818. }
  43819. if (newFile != file
  43820. || fileSize != newFileSize
  43821. || modTime != newModTime)
  43822. {
  43823. file = newFile;
  43824. fileSize = newFileSize;
  43825. modTime = newModTime;
  43826. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  43827. repaint();
  43828. clearIcon();
  43829. }
  43830. if (file != File::nonexistent
  43831. && icon == 0 && ! isDirectory)
  43832. {
  43833. updateIcon (true);
  43834. if (icon == 0)
  43835. thread.addTimeSliceClient (this);
  43836. }
  43837. }
  43838. bool useTimeSlice()
  43839. {
  43840. updateIcon (false);
  43841. return false;
  43842. }
  43843. void handleAsyncUpdate()
  43844. {
  43845. repaint();
  43846. }
  43847. juce_UseDebuggingNewOperator
  43848. private:
  43849. FileListComponent& owner;
  43850. TimeSliceThread& thread;
  43851. bool highlighted;
  43852. int index;
  43853. File file;
  43854. String fileSize;
  43855. String modTime;
  43856. Image* icon;
  43857. bool isDirectory;
  43858. void clearIcon() throw()
  43859. {
  43860. ImageCache::release (icon);
  43861. icon = 0;
  43862. }
  43863. void updateIcon (const bool onlyUpdateIfCached) throw()
  43864. {
  43865. if (icon == 0)
  43866. {
  43867. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  43868. Image* im = ImageCache::getFromHashCode (hashCode);
  43869. if (im == 0 && ! onlyUpdateIfCached)
  43870. {
  43871. im = juce_createIconForFile (file);
  43872. if (im != 0)
  43873. ImageCache::addImageToCache (im, hashCode);
  43874. }
  43875. if (im != 0)
  43876. {
  43877. icon = im;
  43878. triggerAsyncUpdate();
  43879. }
  43880. }
  43881. }
  43882. };
  43883. int FileListComponent::getNumRows()
  43884. {
  43885. return fileList.getNumFiles();
  43886. }
  43887. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  43888. {
  43889. }
  43890. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  43891. {
  43892. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  43893. if (comp == 0)
  43894. {
  43895. delete existingComponentToUpdate;
  43896. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  43897. }
  43898. DirectoryContentsList::FileInfo fileInfo;
  43899. if (fileList.getFileInfo (row, fileInfo))
  43900. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  43901. else
  43902. comp->update (fileList.getDirectory(), 0, row, isSelected);
  43903. return comp;
  43904. }
  43905. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  43906. {
  43907. sendSelectionChangeMessage();
  43908. }
  43909. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  43910. {
  43911. }
  43912. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  43913. {
  43914. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  43915. }
  43916. END_JUCE_NAMESPACE
  43917. /********* End of inlined file: juce_FileListComponent.cpp *********/
  43918. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  43919. BEGIN_JUCE_NAMESPACE
  43920. FilenameComponent::FilenameComponent (const String& name,
  43921. const File& currentFile,
  43922. const bool canEditFilename,
  43923. const bool isDirectory,
  43924. const bool isForSaving,
  43925. const String& fileBrowserWildcard,
  43926. const String& enforcedSuffix_,
  43927. const String& textWhenNothingSelected)
  43928. : Component (name),
  43929. maxRecentFiles (30),
  43930. isDir (isDirectory),
  43931. isSaving (isForSaving),
  43932. isFileDragOver (false),
  43933. wildcard (fileBrowserWildcard),
  43934. enforcedSuffix (enforcedSuffix_)
  43935. {
  43936. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  43937. filenameBox->setEditableText (canEditFilename);
  43938. filenameBox->addListener (this);
  43939. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  43940. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  43941. browseButton = 0;
  43942. setBrowseButtonText (T("..."));
  43943. setCurrentFile (currentFile, true);
  43944. }
  43945. FilenameComponent::~FilenameComponent()
  43946. {
  43947. deleteAllChildren();
  43948. }
  43949. void FilenameComponent::paintOverChildren (Graphics& g)
  43950. {
  43951. if (isFileDragOver)
  43952. {
  43953. g.setColour (Colours::red.withAlpha (0.2f));
  43954. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  43955. }
  43956. }
  43957. void FilenameComponent::resized()
  43958. {
  43959. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  43960. }
  43961. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  43962. {
  43963. browseButtonText = newBrowseButtonText;
  43964. lookAndFeelChanged();
  43965. }
  43966. void FilenameComponent::lookAndFeelChanged()
  43967. {
  43968. deleteAndZero (browseButton);
  43969. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  43970. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  43971. resized();
  43972. browseButton->addButtonListener (this);
  43973. }
  43974. void FilenameComponent::setTooltip (const String& newTooltip)
  43975. {
  43976. SettableTooltipClient::setTooltip (newTooltip);
  43977. filenameBox->setTooltip (newTooltip);
  43978. }
  43979. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  43980. {
  43981. defaultBrowseFile = newDefaultDirectory;
  43982. }
  43983. void FilenameComponent::buttonClicked (Button*)
  43984. {
  43985. FileChooser fc (TRANS("Choose a new file"),
  43986. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  43987. : getCurrentFile(),
  43988. wildcard);
  43989. if (isDir ? fc.browseForDirectory()
  43990. : (isSaving ? fc.browseForFileToSave (false)
  43991. : fc.browseForFileToOpen()))
  43992. {
  43993. setCurrentFile (fc.getResult(), true);
  43994. }
  43995. }
  43996. void FilenameComponent::comboBoxChanged (ComboBox*)
  43997. {
  43998. setCurrentFile (getCurrentFile(), true);
  43999. }
  44000. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  44001. {
  44002. return true;
  44003. }
  44004. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  44005. {
  44006. isFileDragOver = false;
  44007. repaint();
  44008. const File f (filenames[0]);
  44009. if (f.exists() && (f.isDirectory() == isDir))
  44010. setCurrentFile (f, true);
  44011. }
  44012. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  44013. {
  44014. isFileDragOver = true;
  44015. repaint();
  44016. }
  44017. void FilenameComponent::fileDragExit (const StringArray&)
  44018. {
  44019. isFileDragOver = false;
  44020. repaint();
  44021. }
  44022. const File FilenameComponent::getCurrentFile() const
  44023. {
  44024. File f (filenameBox->getText());
  44025. if (enforcedSuffix.isNotEmpty())
  44026. f = f.withFileExtension (enforcedSuffix);
  44027. return f;
  44028. }
  44029. void FilenameComponent::setCurrentFile (File newFile,
  44030. const bool addToRecentlyUsedList,
  44031. const bool sendChangeNotification)
  44032. {
  44033. if (enforcedSuffix.isNotEmpty())
  44034. newFile = newFile.withFileExtension (enforcedSuffix);
  44035. if (newFile.getFullPathName() != lastFilename)
  44036. {
  44037. lastFilename = newFile.getFullPathName();
  44038. if (addToRecentlyUsedList)
  44039. addRecentlyUsedFile (newFile);
  44040. filenameBox->setText (lastFilename, true);
  44041. if (sendChangeNotification)
  44042. triggerAsyncUpdate();
  44043. }
  44044. }
  44045. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  44046. {
  44047. filenameBox->setEditableText (shouldBeEditable);
  44048. }
  44049. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  44050. {
  44051. StringArray names;
  44052. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  44053. names.add (filenameBox->getItemText (i));
  44054. return names;
  44055. }
  44056. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  44057. {
  44058. if (filenames != getRecentlyUsedFilenames())
  44059. {
  44060. filenameBox->clear();
  44061. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  44062. filenameBox->addItem (filenames[i], i + 1);
  44063. }
  44064. }
  44065. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  44066. {
  44067. maxRecentFiles = jmax (1, newMaximum);
  44068. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  44069. }
  44070. void FilenameComponent::addRecentlyUsedFile (const File& file)
  44071. {
  44072. StringArray files (getRecentlyUsedFilenames());
  44073. if (file.getFullPathName().isNotEmpty())
  44074. {
  44075. files.removeString (file.getFullPathName(), true);
  44076. files.insert (0, file.getFullPathName());
  44077. setRecentlyUsedFilenames (files);
  44078. }
  44079. }
  44080. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  44081. {
  44082. jassert (listener != 0);
  44083. if (listener != 0)
  44084. listeners.add (listener);
  44085. }
  44086. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  44087. {
  44088. listeners.removeValue (listener);
  44089. }
  44090. void FilenameComponent::handleAsyncUpdate()
  44091. {
  44092. for (int i = listeners.size(); --i >= 0;)
  44093. {
  44094. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  44095. i = jmin (i, listeners.size());
  44096. }
  44097. }
  44098. END_JUCE_NAMESPACE
  44099. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  44100. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44101. BEGIN_JUCE_NAMESPACE
  44102. FileSearchPathListComponent::FileSearchPathListComponent()
  44103. {
  44104. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  44105. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  44106. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  44107. listBox->setOutlineThickness (1);
  44108. addAndMakeVisible (addButton = new TextButton ("+"));
  44109. addButton->addButtonListener (this);
  44110. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44111. addAndMakeVisible (removeButton = new TextButton ("-"));
  44112. removeButton->addButtonListener (this);
  44113. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  44114. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  44115. changeButton->addButtonListener (this);
  44116. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44117. upButton->addButtonListener (this);
  44118. {
  44119. Path arrowPath;
  44120. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  44121. DrawablePath arrowImage;
  44122. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44123. arrowImage.setPath (arrowPath);
  44124. ((DrawableButton*) upButton)->setImages (&arrowImage);
  44125. }
  44126. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  44127. downButton->addButtonListener (this);
  44128. {
  44129. Path arrowPath;
  44130. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  44131. DrawablePath arrowImage;
  44132. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  44133. arrowImage.setPath (arrowPath);
  44134. ((DrawableButton*) downButton)->setImages (&arrowImage);
  44135. }
  44136. updateButtons();
  44137. }
  44138. FileSearchPathListComponent::~FileSearchPathListComponent()
  44139. {
  44140. deleteAllChildren();
  44141. }
  44142. void FileSearchPathListComponent::updateButtons() throw()
  44143. {
  44144. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  44145. removeButton->setEnabled (anythingSelected);
  44146. changeButton->setEnabled (anythingSelected);
  44147. upButton->setEnabled (anythingSelected);
  44148. downButton->setEnabled (anythingSelected);
  44149. }
  44150. void FileSearchPathListComponent::changed() throw()
  44151. {
  44152. listBox->updateContent();
  44153. listBox->repaint();
  44154. updateButtons();
  44155. }
  44156. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  44157. {
  44158. if (newPath.toString() != path.toString())
  44159. {
  44160. path = newPath;
  44161. changed();
  44162. }
  44163. }
  44164. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  44165. {
  44166. defaultBrowseTarget = newDefaultDirectory;
  44167. }
  44168. int FileSearchPathListComponent::getNumRows()
  44169. {
  44170. return path.getNumPaths();
  44171. }
  44172. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  44173. {
  44174. if (rowIsSelected)
  44175. g.fillAll (findColour (TextEditor::highlightColourId));
  44176. g.setColour (findColour (ListBox::textColourId));
  44177. Font f (height * 0.7f);
  44178. f.setHorizontalScale (0.9f);
  44179. g.setFont (f);
  44180. g.drawText (path [rowNumber].getFullPathName(),
  44181. 4, 0, width - 6, height,
  44182. Justification::centredLeft, true);
  44183. }
  44184. void FileSearchPathListComponent::deleteKeyPressed (int row)
  44185. {
  44186. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  44187. {
  44188. path.remove (row);
  44189. changed();
  44190. }
  44191. }
  44192. void FileSearchPathListComponent::returnKeyPressed (int row)
  44193. {
  44194. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  44195. if (chooser.browseForDirectory())
  44196. {
  44197. path.remove (row);
  44198. path.add (chooser.getResult(), row);
  44199. changed();
  44200. }
  44201. }
  44202. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  44203. {
  44204. returnKeyPressed (row);
  44205. }
  44206. void FileSearchPathListComponent::selectedRowsChanged (int)
  44207. {
  44208. updateButtons();
  44209. }
  44210. void FileSearchPathListComponent::paint (Graphics& g)
  44211. {
  44212. g.fillAll (findColour (backgroundColourId));
  44213. }
  44214. void FileSearchPathListComponent::resized()
  44215. {
  44216. const int buttonH = 22;
  44217. const int buttonY = getHeight() - buttonH - 4;
  44218. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  44219. addButton->setBounds (2, buttonY, buttonH, buttonH);
  44220. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  44221. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  44222. downButton->setSize (buttonH * 2, buttonH);
  44223. upButton->setSize (buttonH * 2, buttonH);
  44224. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  44225. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  44226. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  44227. }
  44228. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  44229. {
  44230. return true;
  44231. }
  44232. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  44233. {
  44234. for (int i = filenames.size(); --i >= 0;)
  44235. {
  44236. const File f (filenames[i]);
  44237. if (f.isDirectory())
  44238. {
  44239. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  44240. path.add (f, row);
  44241. changed();
  44242. }
  44243. }
  44244. }
  44245. void FileSearchPathListComponent::buttonClicked (Button* button)
  44246. {
  44247. const int currentRow = listBox->getSelectedRow();
  44248. if (button == removeButton)
  44249. {
  44250. deleteKeyPressed (currentRow);
  44251. }
  44252. else if (button == addButton)
  44253. {
  44254. File start (defaultBrowseTarget);
  44255. if (start == File::nonexistent)
  44256. start = path [0];
  44257. if (start == File::nonexistent)
  44258. start = File::getCurrentWorkingDirectory();
  44259. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  44260. if (chooser.browseForDirectory())
  44261. {
  44262. path.add (chooser.getResult(), currentRow);
  44263. }
  44264. }
  44265. else if (button == changeButton)
  44266. {
  44267. returnKeyPressed (currentRow);
  44268. }
  44269. else if (button == upButton)
  44270. {
  44271. if (currentRow > 0 && currentRow < path.getNumPaths())
  44272. {
  44273. const File f (path[currentRow]);
  44274. path.remove (currentRow);
  44275. path.add (f, currentRow - 1);
  44276. listBox->selectRow (currentRow - 1);
  44277. }
  44278. }
  44279. else if (button == downButton)
  44280. {
  44281. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  44282. {
  44283. const File f (path[currentRow]);
  44284. path.remove (currentRow);
  44285. path.add (f, currentRow + 1);
  44286. listBox->selectRow (currentRow + 1);
  44287. }
  44288. }
  44289. changed();
  44290. }
  44291. END_JUCE_NAMESPACE
  44292. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  44293. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  44294. BEGIN_JUCE_NAMESPACE
  44295. Image* juce_createIconForFile (const File& file);
  44296. class FileListTreeItem : public TreeViewItem,
  44297. public TimeSliceClient,
  44298. public AsyncUpdater,
  44299. public ChangeListener
  44300. {
  44301. public:
  44302. FileListTreeItem (FileTreeComponent& owner_,
  44303. DirectoryContentsList* const parentContentsList_,
  44304. const int indexInContentsList_,
  44305. const File& file_,
  44306. TimeSliceThread& thread_) throw()
  44307. : file (file_),
  44308. owner (owner_),
  44309. parentContentsList (parentContentsList_),
  44310. indexInContentsList (indexInContentsList_),
  44311. subContentsList (0),
  44312. canDeleteSubContentsList (false),
  44313. thread (thread_),
  44314. icon (0)
  44315. {
  44316. DirectoryContentsList::FileInfo fileInfo;
  44317. if (parentContentsList_ != 0
  44318. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  44319. {
  44320. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  44321. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  44322. isDirectory = fileInfo.isDirectory;
  44323. }
  44324. else
  44325. {
  44326. isDirectory = true;
  44327. }
  44328. }
  44329. ~FileListTreeItem() throw()
  44330. {
  44331. thread.removeTimeSliceClient (this);
  44332. clearSubItems();
  44333. ImageCache::release (icon);
  44334. if (canDeleteSubContentsList)
  44335. delete subContentsList;
  44336. }
  44337. bool mightContainSubItems() { return isDirectory; }
  44338. const String getUniqueName() const { return file.getFullPathName(); }
  44339. int getItemHeight() const { return 22; }
  44340. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  44341. void itemOpennessChanged (bool isNowOpen)
  44342. {
  44343. if (isNowOpen)
  44344. {
  44345. clearSubItems();
  44346. isDirectory = file.isDirectory();
  44347. if (isDirectory)
  44348. {
  44349. if (subContentsList == 0)
  44350. {
  44351. jassert (parentContentsList != 0);
  44352. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  44353. l->setDirectory (file, true, true);
  44354. setSubContentsList (l);
  44355. canDeleteSubContentsList = true;
  44356. }
  44357. changeListenerCallback (0);
  44358. }
  44359. }
  44360. }
  44361. void setSubContentsList (DirectoryContentsList* newList) throw()
  44362. {
  44363. jassert (subContentsList == 0);
  44364. subContentsList = newList;
  44365. newList->addChangeListener (this);
  44366. }
  44367. void changeListenerCallback (void*)
  44368. {
  44369. clearSubItems();
  44370. if (isOpen() && subContentsList != 0)
  44371. {
  44372. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  44373. {
  44374. FileListTreeItem* const item
  44375. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  44376. addSubItem (item);
  44377. }
  44378. }
  44379. }
  44380. void paintItem (Graphics& g, int width, int height)
  44381. {
  44382. if (file != File::nonexistent && ! isDirectory)
  44383. {
  44384. updateIcon (true);
  44385. if (icon == 0)
  44386. thread.addTimeSliceClient (this);
  44387. }
  44388. owner.getLookAndFeel()
  44389. .drawFileBrowserRow (g, width, height,
  44390. file.getFileName(),
  44391. icon,
  44392. fileSize, modTime,
  44393. isDirectory, isSelected(),
  44394. indexInContentsList);
  44395. }
  44396. void itemClicked (const MouseEvent& e)
  44397. {
  44398. owner.sendMouseClickMessage (file, e);
  44399. }
  44400. void itemDoubleClicked (const MouseEvent& e)
  44401. {
  44402. TreeViewItem::itemDoubleClicked (e);
  44403. owner.sendDoubleClickMessage (file);
  44404. }
  44405. void itemSelectionChanged (bool)
  44406. {
  44407. owner.sendSelectionChangeMessage();
  44408. }
  44409. bool useTimeSlice()
  44410. {
  44411. updateIcon (false);
  44412. thread.removeTimeSliceClient (this);
  44413. return false;
  44414. }
  44415. void handleAsyncUpdate()
  44416. {
  44417. owner.repaint();
  44418. }
  44419. const File file;
  44420. juce_UseDebuggingNewOperator
  44421. private:
  44422. FileTreeComponent& owner;
  44423. DirectoryContentsList* parentContentsList;
  44424. int indexInContentsList;
  44425. DirectoryContentsList* subContentsList;
  44426. bool isDirectory, canDeleteSubContentsList;
  44427. TimeSliceThread& thread;
  44428. Image* icon;
  44429. String fileSize;
  44430. String modTime;
  44431. void updateIcon (const bool onlyUpdateIfCached) throw()
  44432. {
  44433. if (icon == 0)
  44434. {
  44435. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  44436. Image* im = ImageCache::getFromHashCode (hashCode);
  44437. if (im == 0 && ! onlyUpdateIfCached)
  44438. {
  44439. im = juce_createIconForFile (file);
  44440. if (im != 0)
  44441. ImageCache::addImageToCache (im, hashCode);
  44442. }
  44443. if (im != 0)
  44444. {
  44445. icon = im;
  44446. triggerAsyncUpdate();
  44447. }
  44448. }
  44449. }
  44450. };
  44451. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  44452. : DirectoryContentsDisplayComponent (listToShow)
  44453. {
  44454. FileListTreeItem* const root
  44455. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  44456. listToShow.getTimeSliceThread());
  44457. root->setSubContentsList (&listToShow);
  44458. setRootItemVisible (false);
  44459. setRootItem (root);
  44460. }
  44461. FileTreeComponent::~FileTreeComponent()
  44462. {
  44463. TreeViewItem* const root = getRootItem();
  44464. setRootItem (0);
  44465. delete root;
  44466. }
  44467. const File FileTreeComponent::getSelectedFile() const
  44468. {
  44469. return getSelectedFile (0);
  44470. }
  44471. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  44472. {
  44473. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  44474. if (item != 0)
  44475. return item->file;
  44476. return File::nonexistent;
  44477. }
  44478. void FileTreeComponent::scrollToTop()
  44479. {
  44480. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  44481. }
  44482. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  44483. {
  44484. dragAndDropDescription = description;
  44485. }
  44486. END_JUCE_NAMESPACE
  44487. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  44488. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  44489. BEGIN_JUCE_NAMESPACE
  44490. ImagePreviewComponent::ImagePreviewComponent()
  44491. : currentThumbnail (0)
  44492. {
  44493. }
  44494. ImagePreviewComponent::~ImagePreviewComponent()
  44495. {
  44496. delete currentThumbnail;
  44497. }
  44498. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  44499. {
  44500. const int availableW = proportionOfWidth (0.97f);
  44501. const int availableH = getHeight() - 13 * 4;
  44502. const double scale = jmin (1.0,
  44503. availableW / (double) w,
  44504. availableH / (double) h);
  44505. w = roundDoubleToInt (scale * w);
  44506. h = roundDoubleToInt (scale * h);
  44507. }
  44508. void ImagePreviewComponent::selectedFileChanged (const File& file)
  44509. {
  44510. if (fileToLoad != file)
  44511. {
  44512. fileToLoad = file;
  44513. startTimer (100);
  44514. }
  44515. }
  44516. void ImagePreviewComponent::timerCallback()
  44517. {
  44518. stopTimer();
  44519. deleteAndZero (currentThumbnail);
  44520. currentDetails = String::empty;
  44521. repaint();
  44522. FileInputStream* const in = fileToLoad.createInputStream();
  44523. if (in != 0)
  44524. {
  44525. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  44526. if (format != 0)
  44527. {
  44528. currentThumbnail = format->decodeImage (*in);
  44529. if (currentThumbnail != 0)
  44530. {
  44531. int w = currentThumbnail->getWidth();
  44532. int h = currentThumbnail->getHeight();
  44533. currentDetails
  44534. << fileToLoad.getFileName() << "\n"
  44535. << format->getFormatName() << "\n"
  44536. << w << " x " << h << " pixels\n"
  44537. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  44538. getThumbSize (w, h);
  44539. Image* const reduced = currentThumbnail->createCopy (w, h);
  44540. delete currentThumbnail;
  44541. currentThumbnail = reduced;
  44542. }
  44543. }
  44544. delete in;
  44545. }
  44546. }
  44547. void ImagePreviewComponent::paint (Graphics& g)
  44548. {
  44549. if (currentThumbnail != 0)
  44550. {
  44551. g.setFont (13.0f);
  44552. int w = currentThumbnail->getWidth();
  44553. int h = currentThumbnail->getHeight();
  44554. getThumbSize (w, h);
  44555. const int numLines = 4;
  44556. const int totalH = 13 * numLines + h + 4;
  44557. const int y = (getHeight() - totalH) / 2;
  44558. g.drawImageWithin (currentThumbnail,
  44559. (getWidth() - w) / 2, y, w, h,
  44560. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  44561. false);
  44562. g.drawFittedText (currentDetails,
  44563. 0, y + h + 4, getWidth(), 100,
  44564. Justification::centredTop, numLines);
  44565. }
  44566. }
  44567. END_JUCE_NAMESPACE
  44568. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  44569. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  44570. BEGIN_JUCE_NAMESPACE
  44571. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  44572. const String& description)
  44573. : FileFilter (description.isEmpty() ? wildcardPatterns
  44574. : (description + T(" (") + wildcardPatterns + T(")")))
  44575. {
  44576. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  44577. wildcards.trim();
  44578. wildcards.removeEmptyStrings();
  44579. // special case for *.*, because people use it to mean "any file", but it
  44580. // would actually ignore files with no extension.
  44581. for (int i = wildcards.size(); --i >= 0;)
  44582. if (wildcards[i] == T("*.*"))
  44583. wildcards.set (i, T("*"));
  44584. }
  44585. WildcardFileFilter::~WildcardFileFilter()
  44586. {
  44587. }
  44588. bool WildcardFileFilter::isFileSuitable (const File& file) const
  44589. {
  44590. const String filename (file.getFileName());
  44591. for (int i = wildcards.size(); --i >= 0;)
  44592. if (filename.matchesWildcard (wildcards[i], true))
  44593. return true;
  44594. return false;
  44595. }
  44596. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  44597. {
  44598. return true;
  44599. }
  44600. END_JUCE_NAMESPACE
  44601. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  44602. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44603. BEGIN_JUCE_NAMESPACE
  44604. KeyboardFocusTraverser::KeyboardFocusTraverser()
  44605. {
  44606. }
  44607. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  44608. {
  44609. }
  44610. // This will sort a set of components, so that they are ordered in terms of
  44611. // left-to-right and then top-to-bottom.
  44612. class ScreenPositionComparator
  44613. {
  44614. public:
  44615. ScreenPositionComparator() {}
  44616. static int compareElements (const Component* const first, const Component* const second) throw()
  44617. {
  44618. int explicitOrder1 = first->getExplicitFocusOrder();
  44619. if (explicitOrder1 <= 0)
  44620. explicitOrder1 = INT_MAX / 2;
  44621. int explicitOrder2 = second->getExplicitFocusOrder();
  44622. if (explicitOrder2 <= 0)
  44623. explicitOrder2 = INT_MAX / 2;
  44624. if (explicitOrder1 != explicitOrder2)
  44625. return explicitOrder1 - explicitOrder2;
  44626. const int diff = first->getY() - second->getY();
  44627. return (diff == 0) ? first->getX() - second->getX()
  44628. : diff;
  44629. }
  44630. };
  44631. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  44632. {
  44633. if (parent->getNumChildComponents() > 0)
  44634. {
  44635. Array <Component*> localComps;
  44636. ScreenPositionComparator comparator;
  44637. int i;
  44638. for (i = parent->getNumChildComponents(); --i >= 0;)
  44639. {
  44640. Component* const c = parent->getChildComponent (i);
  44641. if (c->isVisible() && c->isEnabled())
  44642. localComps.addSorted (comparator, c);
  44643. }
  44644. for (i = 0; i < localComps.size(); ++i)
  44645. {
  44646. Component* const c = localComps.getUnchecked (i);
  44647. if (c->getWantsKeyboardFocus())
  44648. comps.add (c);
  44649. if (! c->isFocusContainer())
  44650. findAllFocusableComponents (c, comps);
  44651. }
  44652. }
  44653. }
  44654. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  44655. {
  44656. Component* focusContainer = current->getParentComponent();
  44657. if (focusContainer != 0)
  44658. {
  44659. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  44660. focusContainer = focusContainer->getParentComponent();
  44661. if (focusContainer != 0)
  44662. {
  44663. Array <Component*> comps;
  44664. findAllFocusableComponents (focusContainer, comps);
  44665. if (comps.size() > 0)
  44666. {
  44667. const int index = comps.indexOf (current);
  44668. return comps [(index + comps.size() + delta) % comps.size()];
  44669. }
  44670. }
  44671. }
  44672. return 0;
  44673. }
  44674. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  44675. {
  44676. return getIncrementedComponent (current, 1);
  44677. }
  44678. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  44679. {
  44680. return getIncrementedComponent (current, -1);
  44681. }
  44682. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  44683. {
  44684. Array <Component*> comps;
  44685. if (parentComponent != 0)
  44686. findAllFocusableComponents (parentComponent, comps);
  44687. return comps.getFirst();
  44688. }
  44689. END_JUCE_NAMESPACE
  44690. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  44691. /********* Start of inlined file: juce_KeyListener.cpp *********/
  44692. BEGIN_JUCE_NAMESPACE
  44693. bool KeyListener::keyStateChanged (const bool, Component*)
  44694. {
  44695. return false;
  44696. }
  44697. END_JUCE_NAMESPACE
  44698. /********* End of inlined file: juce_KeyListener.cpp *********/
  44699. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  44700. BEGIN_JUCE_NAMESPACE
  44701. // N.B. these two includes are put here deliberately to avoid problems with
  44702. // old GCCs failing on long include paths
  44703. const int maxKeys = 3;
  44704. class KeyMappingChangeButton : public Button
  44705. {
  44706. public:
  44707. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  44708. const CommandID commandID_,
  44709. const String& keyName,
  44710. const int keyNum_)
  44711. : Button (keyName),
  44712. owner (owner_),
  44713. commandID (commandID_),
  44714. keyNum (keyNum_)
  44715. {
  44716. setWantsKeyboardFocus (false);
  44717. setTriggeredOnMouseDown (keyNum >= 0);
  44718. if (keyNum_ < 0)
  44719. setTooltip (TRANS("adds a new key-mapping"));
  44720. else
  44721. setTooltip (TRANS("click to change this key-mapping"));
  44722. }
  44723. ~KeyMappingChangeButton()
  44724. {
  44725. }
  44726. void paintButton (Graphics& g, bool isOver, bool isDown)
  44727. {
  44728. if (keyNum >= 0)
  44729. {
  44730. if (isEnabled())
  44731. {
  44732. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  44733. g.fillAll (owner->textColour.withAlpha (alpha));
  44734. g.setOpacity (0.3f);
  44735. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  44736. }
  44737. g.setColour (owner->textColour);
  44738. g.setFont (getHeight() * 0.6f);
  44739. g.drawFittedText (getName(),
  44740. 3, 0, getWidth() - 6, getHeight(),
  44741. Justification::centred, 1);
  44742. }
  44743. else
  44744. {
  44745. const float thickness = 7.0f;
  44746. const float indent = 22.0f;
  44747. Path p;
  44748. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  44749. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  44750. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  44751. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  44752. p.setUsingNonZeroWinding (false);
  44753. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  44754. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  44755. }
  44756. if (hasKeyboardFocus (false))
  44757. {
  44758. g.setColour (owner->textColour.withAlpha (0.4f));
  44759. g.drawRect (0, 0, getWidth(), getHeight());
  44760. }
  44761. }
  44762. void clicked()
  44763. {
  44764. if (keyNum >= 0)
  44765. {
  44766. // existing key clicked..
  44767. PopupMenu m;
  44768. m.addItem (1, TRANS("change this key-mapping"));
  44769. m.addSeparator();
  44770. m.addItem (2, TRANS("remove this key-mapping"));
  44771. const int res = m.show();
  44772. if (res == 1)
  44773. {
  44774. owner->assignNewKey (commandID, keyNum);
  44775. }
  44776. else if (res == 2)
  44777. {
  44778. owner->getMappings()->removeKeyPress (commandID, keyNum);
  44779. }
  44780. }
  44781. else
  44782. {
  44783. // + button pressed..
  44784. owner->assignNewKey (commandID, -1);
  44785. }
  44786. }
  44787. void fitToContent (const int h) throw()
  44788. {
  44789. if (keyNum < 0)
  44790. {
  44791. setSize (h, h);
  44792. }
  44793. else
  44794. {
  44795. Font f (h * 0.6f);
  44796. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  44797. }
  44798. }
  44799. juce_UseDebuggingNewOperator
  44800. private:
  44801. KeyMappingEditorComponent* const owner;
  44802. const CommandID commandID;
  44803. const int keyNum;
  44804. KeyMappingChangeButton (const KeyMappingChangeButton&);
  44805. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  44806. };
  44807. class KeyMappingItemComponent : public Component
  44808. {
  44809. public:
  44810. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  44811. const CommandID commandID_)
  44812. : owner (owner_),
  44813. commandID (commandID_)
  44814. {
  44815. setInterceptsMouseClicks (false, true);
  44816. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  44817. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  44818. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  44819. {
  44820. KeyMappingChangeButton* const kb
  44821. = new KeyMappingChangeButton (owner_, commandID,
  44822. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  44823. kb->setEnabled (! isReadOnly);
  44824. addAndMakeVisible (kb);
  44825. }
  44826. KeyMappingChangeButton* const kb
  44827. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  44828. addChildComponent (kb);
  44829. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  44830. }
  44831. ~KeyMappingItemComponent()
  44832. {
  44833. deleteAllChildren();
  44834. }
  44835. void paint (Graphics& g)
  44836. {
  44837. g.setFont (getHeight() * 0.7f);
  44838. g.setColour (owner->textColour);
  44839. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  44840. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  44841. Justification::centredLeft, true);
  44842. }
  44843. void resized()
  44844. {
  44845. int x = getWidth() - 4;
  44846. for (int i = getNumChildComponents(); --i >= 0;)
  44847. {
  44848. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  44849. kb->fitToContent (getHeight() - 2);
  44850. kb->setTopRightPosition (x, 1);
  44851. x -= kb->getWidth() + 5;
  44852. }
  44853. }
  44854. juce_UseDebuggingNewOperator
  44855. private:
  44856. KeyMappingEditorComponent* const owner;
  44857. const CommandID commandID;
  44858. KeyMappingItemComponent (const KeyMappingItemComponent&);
  44859. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  44860. };
  44861. class KeyMappingTreeViewItem : public TreeViewItem
  44862. {
  44863. public:
  44864. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  44865. const CommandID commandID_)
  44866. : owner (owner_),
  44867. commandID (commandID_)
  44868. {
  44869. }
  44870. ~KeyMappingTreeViewItem()
  44871. {
  44872. }
  44873. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  44874. bool mightContainSubItems() { return false; }
  44875. int getItemHeight() const { return 20; }
  44876. Component* createItemComponent()
  44877. {
  44878. return new KeyMappingItemComponent (owner, commandID);
  44879. }
  44880. juce_UseDebuggingNewOperator
  44881. private:
  44882. KeyMappingEditorComponent* const owner;
  44883. const CommandID commandID;
  44884. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  44885. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  44886. };
  44887. class KeyCategoryTreeViewItem : public TreeViewItem
  44888. {
  44889. public:
  44890. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  44891. const String& name)
  44892. : owner (owner_),
  44893. categoryName (name)
  44894. {
  44895. }
  44896. ~KeyCategoryTreeViewItem()
  44897. {
  44898. }
  44899. const String getUniqueName() const { return categoryName + "_cat"; }
  44900. bool mightContainSubItems() { return true; }
  44901. int getItemHeight() const { return 28; }
  44902. void paintItem (Graphics& g, int width, int height)
  44903. {
  44904. g.setFont (height * 0.6f, Font::bold);
  44905. g.setColour (owner->textColour);
  44906. g.drawText (categoryName,
  44907. 2, 0, width - 2, height,
  44908. Justification::centredLeft, true);
  44909. }
  44910. void itemOpennessChanged (bool isNowOpen)
  44911. {
  44912. if (isNowOpen)
  44913. {
  44914. if (getNumSubItems() == 0)
  44915. {
  44916. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  44917. for (int i = 0; i < commands.size(); ++i)
  44918. {
  44919. if (owner->shouldCommandBeIncluded (commands[i]))
  44920. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  44921. }
  44922. }
  44923. }
  44924. else
  44925. {
  44926. clearSubItems();
  44927. }
  44928. }
  44929. juce_UseDebuggingNewOperator
  44930. private:
  44931. KeyMappingEditorComponent* owner;
  44932. String categoryName;
  44933. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  44934. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  44935. };
  44936. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  44937. const bool showResetToDefaultButton)
  44938. : mappings (mappingManager),
  44939. textColour (Colours::black)
  44940. {
  44941. jassert (mappingManager != 0); // can't be null!
  44942. mappingManager->addChangeListener (this);
  44943. setLinesDrawnForSubItems (false);
  44944. resetButton = 0;
  44945. if (showResetToDefaultButton)
  44946. {
  44947. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  44948. resetButton->addButtonListener (this);
  44949. }
  44950. addAndMakeVisible (tree = new TreeView());
  44951. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44952. tree->setRootItemVisible (false);
  44953. tree->setDefaultOpenness (true);
  44954. tree->setRootItem (this);
  44955. }
  44956. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  44957. {
  44958. mappings->removeChangeListener (this);
  44959. deleteAllChildren();
  44960. }
  44961. bool KeyMappingEditorComponent::mightContainSubItems()
  44962. {
  44963. return true;
  44964. }
  44965. const String KeyMappingEditorComponent::getUniqueName() const
  44966. {
  44967. return T("keys");
  44968. }
  44969. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  44970. const Colour& textColour_)
  44971. {
  44972. backgroundColour = mainBackground;
  44973. textColour = textColour_;
  44974. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  44975. }
  44976. void KeyMappingEditorComponent::parentHierarchyChanged()
  44977. {
  44978. changeListenerCallback (0);
  44979. }
  44980. void KeyMappingEditorComponent::resized()
  44981. {
  44982. int h = getHeight();
  44983. if (resetButton != 0)
  44984. {
  44985. const int buttonHeight = 20;
  44986. h -= buttonHeight + 8;
  44987. int x = getWidth() - 8;
  44988. const int y = h + 6;
  44989. resetButton->changeWidthToFitText (buttonHeight);
  44990. resetButton->setTopRightPosition (x, y);
  44991. }
  44992. tree->setBounds (0, 0, getWidth(), h);
  44993. }
  44994. void KeyMappingEditorComponent::buttonClicked (Button* button)
  44995. {
  44996. if (button == resetButton)
  44997. {
  44998. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  44999. TRANS("Reset to defaults"),
  45000. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  45001. TRANS("Reset")))
  45002. {
  45003. mappings->resetToDefaultMappings();
  45004. }
  45005. }
  45006. }
  45007. void KeyMappingEditorComponent::changeListenerCallback (void*)
  45008. {
  45009. XmlElement* openness = tree->getOpennessState (true);
  45010. clearSubItems();
  45011. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  45012. for (int i = 0; i < categories.size(); ++i)
  45013. {
  45014. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  45015. int count = 0;
  45016. for (int j = 0; j < commands.size(); ++j)
  45017. if (shouldCommandBeIncluded (commands[j]))
  45018. ++count;
  45019. if (count > 0)
  45020. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  45021. }
  45022. if (openness != 0)
  45023. {
  45024. tree->restoreOpennessState (*openness);
  45025. delete openness;
  45026. }
  45027. }
  45028. class KeyEntryWindow : public AlertWindow
  45029. {
  45030. public:
  45031. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  45032. : AlertWindow (TRANS("New key-mapping"),
  45033. TRANS("Please press a key combination now..."),
  45034. AlertWindow::NoIcon),
  45035. owner (owner_)
  45036. {
  45037. addButton (TRANS("ok"), 1);
  45038. addButton (TRANS("cancel"), 0);
  45039. // (avoid return + escape keys getting processed by the buttons..)
  45040. for (int i = getNumChildComponents(); --i >= 0;)
  45041. getChildComponent (i)->setWantsKeyboardFocus (false);
  45042. setWantsKeyboardFocus (true);
  45043. grabKeyboardFocus();
  45044. }
  45045. ~KeyEntryWindow()
  45046. {
  45047. }
  45048. bool keyPressed (const KeyPress& key)
  45049. {
  45050. lastPress = key;
  45051. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  45052. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  45053. if (previousCommand != 0)
  45054. {
  45055. message << "\n\n"
  45056. << TRANS("(Currently assigned to \"")
  45057. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  45058. << "\")";
  45059. }
  45060. setMessage (message);
  45061. return true;
  45062. }
  45063. bool keyStateChanged (const bool)
  45064. {
  45065. return true;
  45066. }
  45067. KeyPress lastPress;
  45068. juce_UseDebuggingNewOperator
  45069. private:
  45070. KeyMappingEditorComponent* owner;
  45071. KeyEntryWindow (const KeyEntryWindow&);
  45072. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  45073. };
  45074. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  45075. {
  45076. KeyEntryWindow entryWindow (this);
  45077. if (entryWindow.runModalLoop() != 0)
  45078. {
  45079. entryWindow.setVisible (false);
  45080. if (entryWindow.lastPress.isValid())
  45081. {
  45082. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  45083. if (previousCommand != 0)
  45084. {
  45085. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  45086. TRANS("Change key-mapping"),
  45087. TRANS("This key is already assigned to the command \"")
  45088. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  45089. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  45090. TRANS("re-assign"),
  45091. TRANS("cancel")))
  45092. {
  45093. return;
  45094. }
  45095. }
  45096. mappings->removeKeyPress (entryWindow.lastPress);
  45097. if (index >= 0)
  45098. mappings->removeKeyPress (commandID, index);
  45099. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  45100. }
  45101. }
  45102. }
  45103. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  45104. {
  45105. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45106. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  45107. }
  45108. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  45109. {
  45110. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  45111. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  45112. }
  45113. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  45114. {
  45115. return key.getTextDescription();
  45116. }
  45117. END_JUCE_NAMESPACE
  45118. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  45119. /********* Start of inlined file: juce_KeyPress.cpp *********/
  45120. BEGIN_JUCE_NAMESPACE
  45121. KeyPress::KeyPress() throw()
  45122. : keyCode (0),
  45123. mods (0),
  45124. textCharacter (0)
  45125. {
  45126. }
  45127. KeyPress::KeyPress (const int keyCode_,
  45128. const ModifierKeys& mods_,
  45129. const juce_wchar textCharacter_) throw()
  45130. : keyCode (keyCode_),
  45131. mods (mods_),
  45132. textCharacter (textCharacter_)
  45133. {
  45134. }
  45135. KeyPress::KeyPress (const int keyCode_) throw()
  45136. : keyCode (keyCode_),
  45137. textCharacter (0)
  45138. {
  45139. }
  45140. KeyPress::KeyPress (const KeyPress& other) throw()
  45141. : keyCode (other.keyCode),
  45142. mods (other.mods),
  45143. textCharacter (other.textCharacter)
  45144. {
  45145. }
  45146. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  45147. {
  45148. keyCode = other.keyCode;
  45149. mods = other.mods;
  45150. textCharacter = other.textCharacter;
  45151. return *this;
  45152. }
  45153. bool KeyPress::operator== (const KeyPress& other) const throw()
  45154. {
  45155. return mods.getRawFlags() == other.mods.getRawFlags()
  45156. && (textCharacter == other.textCharacter
  45157. || textCharacter == 0
  45158. || other.textCharacter == 0)
  45159. && (keyCode == other.keyCode
  45160. || (keyCode < 256
  45161. && other.keyCode < 256
  45162. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  45163. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  45164. }
  45165. bool KeyPress::operator!= (const KeyPress& other) const throw()
  45166. {
  45167. return ! operator== (other);
  45168. }
  45169. bool KeyPress::isCurrentlyDown() const throw()
  45170. {
  45171. return isKeyCurrentlyDown (keyCode)
  45172. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  45173. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  45174. }
  45175. struct KeyNameAndCode
  45176. {
  45177. const char* name;
  45178. int code;
  45179. };
  45180. static const KeyNameAndCode keyNameTranslations[] =
  45181. {
  45182. { "spacebar", KeyPress::spaceKey },
  45183. { "return", KeyPress::returnKey },
  45184. { "escape", KeyPress::escapeKey },
  45185. { "backspace", KeyPress::backspaceKey },
  45186. { "cursor left", KeyPress::leftKey },
  45187. { "cursor right", KeyPress::rightKey },
  45188. { "cursor up", KeyPress::upKey },
  45189. { "cursor down", KeyPress::downKey },
  45190. { "page up", KeyPress::pageUpKey },
  45191. { "page down", KeyPress::pageDownKey },
  45192. { "home", KeyPress::homeKey },
  45193. { "end", KeyPress::endKey },
  45194. { "delete", KeyPress::deleteKey },
  45195. { "insert", KeyPress::insertKey },
  45196. { "tab", KeyPress::tabKey },
  45197. { "play", KeyPress::playKey },
  45198. { "stop", KeyPress::stopKey },
  45199. { "fast forward", KeyPress::fastForwardKey },
  45200. { "rewind", KeyPress::rewindKey }
  45201. };
  45202. static const tchar* const numberPadPrefix = T("numpad ");
  45203. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  45204. {
  45205. int modifiers = 0;
  45206. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  45207. || desc.containsWholeWordIgnoreCase (T("control"))
  45208. || desc.containsWholeWordIgnoreCase (T("ctl")))
  45209. modifiers |= ModifierKeys::ctrlModifier;
  45210. if (desc.containsWholeWordIgnoreCase (T("shift"))
  45211. || desc.containsWholeWordIgnoreCase (T("shft")))
  45212. modifiers |= ModifierKeys::shiftModifier;
  45213. if (desc.containsWholeWordIgnoreCase (T("alt"))
  45214. || desc.containsWholeWordIgnoreCase (T("option")))
  45215. modifiers |= ModifierKeys::altModifier;
  45216. if (desc.containsWholeWordIgnoreCase (T("command"))
  45217. || desc.containsWholeWordIgnoreCase (T("cmd")))
  45218. modifiers |= ModifierKeys::commandModifier;
  45219. int key = 0;
  45220. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45221. {
  45222. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  45223. {
  45224. key = keyNameTranslations[i].code;
  45225. break;
  45226. }
  45227. }
  45228. if (key == 0)
  45229. {
  45230. // see if it's a numpad key..
  45231. if (desc.containsIgnoreCase (numberPadPrefix))
  45232. {
  45233. const tchar lastChar = desc.trimEnd().getLastCharacter();
  45234. if (lastChar >= T('0') && lastChar <= T('9'))
  45235. key = numberPad0 + lastChar - T('0');
  45236. else if (lastChar == T('+'))
  45237. key = numberPadAdd;
  45238. else if (lastChar == T('-'))
  45239. key = numberPadSubtract;
  45240. else if (lastChar == T('*'))
  45241. key = numberPadMultiply;
  45242. else if (lastChar == T('/'))
  45243. key = numberPadDivide;
  45244. else if (lastChar == T('.'))
  45245. key = numberPadDecimalPoint;
  45246. else if (lastChar == T('='))
  45247. key = numberPadEquals;
  45248. else if (desc.endsWith (T("separator")))
  45249. key = numberPadSeparator;
  45250. else if (desc.endsWith (T("delete")))
  45251. key = numberPadDelete;
  45252. }
  45253. if (key == 0)
  45254. {
  45255. // see if it's a function key..
  45256. for (int i = 1; i <= 12; ++i)
  45257. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  45258. key = F1Key + i - 1;
  45259. if (key == 0)
  45260. {
  45261. // give up and use the hex code..
  45262. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  45263. .toLowerCase()
  45264. .retainCharacters (T("0123456789abcdef"))
  45265. .getHexValue32();
  45266. if (hexCode > 0)
  45267. key = hexCode;
  45268. else
  45269. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  45270. }
  45271. }
  45272. }
  45273. return KeyPress (key, ModifierKeys (modifiers), 0);
  45274. }
  45275. const String KeyPress::getTextDescription() const throw()
  45276. {
  45277. String desc;
  45278. if (keyCode > 0)
  45279. {
  45280. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  45281. // want to store it as being a slash, not shift+whatever.
  45282. if (textCharacter == T('/'))
  45283. return "/";
  45284. if (mods.isCtrlDown())
  45285. desc << "ctrl + ";
  45286. if (mods.isShiftDown())
  45287. desc << "shift + ";
  45288. #if JUCE_MAC
  45289. // only do this on the mac, because on Windows ctrl and command are the same,
  45290. // and this would get confusing
  45291. if (mods.isCommandDown())
  45292. desc << "command + ";
  45293. if (mods.isAltDown())
  45294. desc << "option + ";
  45295. #else
  45296. if (mods.isAltDown())
  45297. desc << "alt + ";
  45298. #endif
  45299. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  45300. if (keyCode == keyNameTranslations[i].code)
  45301. return desc + keyNameTranslations[i].name;
  45302. if (keyCode >= F1Key && keyCode <= F16Key)
  45303. desc << 'F' << (1 + keyCode - F1Key);
  45304. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  45305. desc << numberPadPrefix << (keyCode - numberPad0);
  45306. else if (keyCode >= 33 && keyCode < 176)
  45307. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  45308. else if (keyCode == numberPadAdd)
  45309. desc << numberPadPrefix << '+';
  45310. else if (keyCode == numberPadSubtract)
  45311. desc << numberPadPrefix << '-';
  45312. else if (keyCode == numberPadMultiply)
  45313. desc << numberPadPrefix << '*';
  45314. else if (keyCode == numberPadDivide)
  45315. desc << numberPadPrefix << '/';
  45316. else if (keyCode == numberPadSeparator)
  45317. desc << numberPadPrefix << "separator";
  45318. else if (keyCode == numberPadDecimalPoint)
  45319. desc << numberPadPrefix << '.';
  45320. else if (keyCode == numberPadDelete)
  45321. desc << numberPadPrefix << "delete";
  45322. else
  45323. desc << '#' << String::toHexString (keyCode);
  45324. }
  45325. return desc;
  45326. }
  45327. END_JUCE_NAMESPACE
  45328. /********* End of inlined file: juce_KeyPress.cpp *********/
  45329. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  45330. BEGIN_JUCE_NAMESPACE
  45331. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  45332. : commandManager (commandManager_)
  45333. {
  45334. // A manager is needed to get the descriptions of commands, and will be called when
  45335. // a command is invoked. So you can't leave this null..
  45336. jassert (commandManager_ != 0);
  45337. Desktop::getInstance().addFocusChangeListener (this);
  45338. }
  45339. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  45340. : commandManager (other.commandManager)
  45341. {
  45342. Desktop::getInstance().addFocusChangeListener (this);
  45343. }
  45344. KeyPressMappingSet::~KeyPressMappingSet()
  45345. {
  45346. Desktop::getInstance().removeFocusChangeListener (this);
  45347. }
  45348. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  45349. {
  45350. for (int i = 0; i < mappings.size(); ++i)
  45351. if (mappings.getUnchecked(i)->commandID == commandID)
  45352. return mappings.getUnchecked (i)->keypresses;
  45353. return Array <KeyPress> ();
  45354. }
  45355. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  45356. const KeyPress& newKeyPress,
  45357. int insertIndex) throw()
  45358. {
  45359. if (findCommandForKeyPress (newKeyPress) != commandID)
  45360. {
  45361. removeKeyPress (newKeyPress);
  45362. if (newKeyPress.isValid())
  45363. {
  45364. for (int i = mappings.size(); --i >= 0;)
  45365. {
  45366. if (mappings.getUnchecked(i)->commandID == commandID)
  45367. {
  45368. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  45369. sendChangeMessage (this);
  45370. return;
  45371. }
  45372. }
  45373. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45374. if (ci != 0)
  45375. {
  45376. CommandMapping* const cm = new CommandMapping();
  45377. cm->commandID = commandID;
  45378. cm->keypresses.add (newKeyPress);
  45379. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  45380. mappings.add (cm);
  45381. sendChangeMessage (this);
  45382. }
  45383. }
  45384. }
  45385. }
  45386. void KeyPressMappingSet::resetToDefaultMappings() throw()
  45387. {
  45388. mappings.clear();
  45389. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  45390. {
  45391. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  45392. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45393. {
  45394. addKeyPress (ci->commandID,
  45395. ci->defaultKeypresses.getReference (j));
  45396. }
  45397. }
  45398. sendChangeMessage (this);
  45399. }
  45400. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  45401. {
  45402. clearAllKeyPresses (commandID);
  45403. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45404. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  45405. {
  45406. addKeyPress (ci->commandID,
  45407. ci->defaultKeypresses.getReference (j));
  45408. }
  45409. }
  45410. void KeyPressMappingSet::clearAllKeyPresses() throw()
  45411. {
  45412. if (mappings.size() > 0)
  45413. {
  45414. sendChangeMessage (this);
  45415. mappings.clear();
  45416. }
  45417. }
  45418. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  45419. {
  45420. for (int i = mappings.size(); --i >= 0;)
  45421. {
  45422. if (mappings.getUnchecked(i)->commandID == commandID)
  45423. {
  45424. mappings.remove (i);
  45425. sendChangeMessage (this);
  45426. }
  45427. }
  45428. }
  45429. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  45430. {
  45431. if (keypress.isValid())
  45432. {
  45433. for (int i = mappings.size(); --i >= 0;)
  45434. {
  45435. CommandMapping* const cm = mappings.getUnchecked(i);
  45436. for (int j = cm->keypresses.size(); --j >= 0;)
  45437. {
  45438. if (keypress == cm->keypresses [j])
  45439. {
  45440. cm->keypresses.remove (j);
  45441. sendChangeMessage (this);
  45442. }
  45443. }
  45444. }
  45445. }
  45446. }
  45447. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  45448. const int keyPressIndex) throw()
  45449. {
  45450. for (int i = mappings.size(); --i >= 0;)
  45451. {
  45452. if (mappings.getUnchecked(i)->commandID == commandID)
  45453. {
  45454. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  45455. sendChangeMessage (this);
  45456. break;
  45457. }
  45458. }
  45459. }
  45460. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  45461. {
  45462. for (int i = 0; i < mappings.size(); ++i)
  45463. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  45464. return mappings.getUnchecked(i)->commandID;
  45465. return 0;
  45466. }
  45467. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  45468. const KeyPress& keyPress) const throw()
  45469. {
  45470. for (int i = mappings.size(); --i >= 0;)
  45471. if (mappings.getUnchecked(i)->commandID == commandID)
  45472. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  45473. return false;
  45474. }
  45475. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  45476. const KeyPress& key,
  45477. const bool isKeyDown,
  45478. const int millisecsSinceKeyPressed,
  45479. Component* const originatingComponent) const
  45480. {
  45481. ApplicationCommandTarget::InvocationInfo info (commandID);
  45482. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  45483. info.isKeyDown = isKeyDown;
  45484. info.keyPress = key;
  45485. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  45486. info.originatingComponent = originatingComponent;
  45487. commandManager->invoke (info, false);
  45488. }
  45489. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  45490. {
  45491. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  45492. {
  45493. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  45494. {
  45495. // if the XML was created as a set of differences from the default mappings,
  45496. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  45497. resetToDefaultMappings();
  45498. }
  45499. else
  45500. {
  45501. // if the XML was created calling createXml (false), then we need to clear all
  45502. // the keys and treat the xml as describing the entire set of mappings.
  45503. clearAllKeyPresses();
  45504. }
  45505. forEachXmlChildElement (xmlVersion, map)
  45506. {
  45507. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  45508. if (commandId != 0)
  45509. {
  45510. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  45511. if (map->hasTagName (T("MAPPING")))
  45512. {
  45513. addKeyPress (commandId, key);
  45514. }
  45515. else if (map->hasTagName (T("UNMAPPING")))
  45516. {
  45517. if (containsMapping (commandId, key))
  45518. removeKeyPress (key);
  45519. }
  45520. }
  45521. }
  45522. return true;
  45523. }
  45524. return false;
  45525. }
  45526. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  45527. {
  45528. KeyPressMappingSet* defaultSet = 0;
  45529. if (saveDifferencesFromDefaultSet)
  45530. {
  45531. defaultSet = new KeyPressMappingSet (commandManager);
  45532. defaultSet->resetToDefaultMappings();
  45533. }
  45534. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  45535. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  45536. int i;
  45537. for (i = 0; i < mappings.size(); ++i)
  45538. {
  45539. const CommandMapping* const cm = mappings.getUnchecked(i);
  45540. for (int j = 0; j < cm->keypresses.size(); ++j)
  45541. {
  45542. if (defaultSet == 0
  45543. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45544. {
  45545. XmlElement* const map = new XmlElement (T("MAPPING"));
  45546. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45547. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45548. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45549. doc->addChildElement (map);
  45550. }
  45551. }
  45552. }
  45553. if (defaultSet != 0)
  45554. {
  45555. for (i = 0; i < defaultSet->mappings.size(); ++i)
  45556. {
  45557. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  45558. for (int j = 0; j < cm->keypresses.size(); ++j)
  45559. {
  45560. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  45561. {
  45562. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  45563. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  45564. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  45565. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  45566. doc->addChildElement (map);
  45567. }
  45568. }
  45569. }
  45570. delete defaultSet;
  45571. }
  45572. return doc;
  45573. }
  45574. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  45575. Component* originatingComponent)
  45576. {
  45577. bool used = false;
  45578. const CommandID commandID = findCommandForKeyPress (key);
  45579. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  45580. if (ci != 0
  45581. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  45582. {
  45583. ApplicationCommandInfo info (0);
  45584. if (commandManager->getTargetForCommand (commandID, info) != 0
  45585. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  45586. {
  45587. invokeCommand (commandID, key, true, 0, originatingComponent);
  45588. used = true;
  45589. }
  45590. else
  45591. {
  45592. if (originatingComponent != 0)
  45593. originatingComponent->getLookAndFeel().playAlertSound();
  45594. }
  45595. }
  45596. return used;
  45597. }
  45598. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  45599. {
  45600. bool used = false;
  45601. const uint32 now = Time::getMillisecondCounter();
  45602. for (int i = mappings.size(); --i >= 0;)
  45603. {
  45604. CommandMapping* const cm = mappings.getUnchecked(i);
  45605. if (cm->wantsKeyUpDownCallbacks)
  45606. {
  45607. for (int j = cm->keypresses.size(); --j >= 0;)
  45608. {
  45609. const KeyPress key (cm->keypresses.getReference (j));
  45610. const bool isDown = key.isCurrentlyDown();
  45611. int keyPressEntryIndex = 0;
  45612. bool wasDown = false;
  45613. for (int k = keysDown.size(); --k >= 0;)
  45614. {
  45615. if (key == keysDown.getUnchecked(k)->key)
  45616. {
  45617. keyPressEntryIndex = k;
  45618. wasDown = true;
  45619. used = true;
  45620. break;
  45621. }
  45622. }
  45623. if (isDown != wasDown)
  45624. {
  45625. int millisecs = 0;
  45626. if (isDown)
  45627. {
  45628. KeyPressTime* const k = new KeyPressTime();
  45629. k->key = key;
  45630. k->timeWhenPressed = now;
  45631. keysDown.add (k);
  45632. }
  45633. else
  45634. {
  45635. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  45636. if (now > pressTime)
  45637. millisecs = now - pressTime;
  45638. keysDown.remove (keyPressEntryIndex);
  45639. }
  45640. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  45641. used = true;
  45642. }
  45643. }
  45644. }
  45645. }
  45646. return used;
  45647. }
  45648. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  45649. {
  45650. if (focusedComponent != 0)
  45651. focusedComponent->keyStateChanged (false);
  45652. }
  45653. END_JUCE_NAMESPACE
  45654. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  45655. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  45656. BEGIN_JUCE_NAMESPACE
  45657. ModifierKeys::ModifierKeys (const int flags_) throw()
  45658. : flags (flags_)
  45659. {
  45660. }
  45661. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  45662. : flags (other.flags)
  45663. {
  45664. }
  45665. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  45666. {
  45667. flags = other.flags;
  45668. return *this;
  45669. }
  45670. int ModifierKeys::currentModifierFlags = 0;
  45671. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  45672. {
  45673. return ModifierKeys (currentModifierFlags);
  45674. }
  45675. END_JUCE_NAMESPACE
  45676. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  45677. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  45678. BEGIN_JUCE_NAMESPACE
  45679. struct AnimationTask
  45680. {
  45681. AnimationTask (Component* const comp)
  45682. : component (comp),
  45683. watcher (comp)
  45684. {
  45685. }
  45686. Component* component;
  45687. ComponentDeletionWatcher watcher;
  45688. Rectangle destination;
  45689. int msElapsed, msTotal;
  45690. double startSpeed, midSpeed, endSpeed, lastProgress;
  45691. double left, top, right, bottom;
  45692. bool useTimeslice (const int elapsed)
  45693. {
  45694. if (watcher.hasBeenDeleted())
  45695. return false;
  45696. msElapsed += elapsed;
  45697. double newProgress = msElapsed / (double) msTotal;
  45698. if (newProgress >= 0 && newProgress < 1.0)
  45699. {
  45700. newProgress = timeToDistance (newProgress);
  45701. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  45702. jassert (newProgress >= lastProgress);
  45703. lastProgress = newProgress;
  45704. left += (destination.getX() - left) * delta;
  45705. top += (destination.getY() - top) * delta;
  45706. right += (destination.getRight() - right) * delta;
  45707. bottom += (destination.getBottom() - bottom) * delta;
  45708. if (delta < 1.0)
  45709. {
  45710. const Rectangle newBounds (roundDoubleToInt (left),
  45711. roundDoubleToInt (top),
  45712. roundDoubleToInt (right - left),
  45713. roundDoubleToInt (bottom - top));
  45714. if (newBounds != destination)
  45715. {
  45716. component->setBounds (newBounds);
  45717. return true;
  45718. }
  45719. }
  45720. }
  45721. component->setBounds (destination);
  45722. return false;
  45723. }
  45724. void moveToFinalDestination()
  45725. {
  45726. if (! watcher.hasBeenDeleted())
  45727. component->setBounds (destination);
  45728. }
  45729. private:
  45730. inline double timeToDistance (const double time) const
  45731. {
  45732. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  45733. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  45734. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  45735. }
  45736. };
  45737. ComponentAnimator::ComponentAnimator()
  45738. : lastTime (0)
  45739. {
  45740. }
  45741. ComponentAnimator::~ComponentAnimator()
  45742. {
  45743. cancelAllAnimations (false);
  45744. jassert (tasks.size() == 0);
  45745. }
  45746. void* ComponentAnimator::findTaskFor (Component* const component) const
  45747. {
  45748. for (int i = tasks.size(); --i >= 0;)
  45749. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  45750. return tasks.getUnchecked(i);
  45751. return 0;
  45752. }
  45753. void ComponentAnimator::animateComponent (Component* const component,
  45754. const Rectangle& finalPosition,
  45755. const int millisecondsToSpendMoving,
  45756. const double startSpeed,
  45757. const double endSpeed)
  45758. {
  45759. if (component != 0)
  45760. {
  45761. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  45762. if (at == 0)
  45763. {
  45764. at = new AnimationTask (component);
  45765. tasks.add (at);
  45766. sendChangeMessage (this);
  45767. }
  45768. at->msElapsed = 0;
  45769. at->lastProgress = 0;
  45770. at->msTotal = jmax (1, millisecondsToSpendMoving);
  45771. at->destination = finalPosition;
  45772. // the speeds must be 0 or greater!
  45773. jassert (startSpeed >= 0 && endSpeed >= 0)
  45774. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  45775. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  45776. at->midSpeed = invTotalDistance;
  45777. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  45778. at->left = component->getX();
  45779. at->top = component->getY();
  45780. at->right = component->getRight();
  45781. at->bottom = component->getBottom();
  45782. if (! isTimerRunning())
  45783. {
  45784. lastTime = Time::getMillisecondCounter();
  45785. startTimer (1000 / 50);
  45786. }
  45787. }
  45788. }
  45789. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  45790. {
  45791. for (int i = tasks.size(); --i >= 0;)
  45792. {
  45793. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45794. if (moveComponentsToTheirFinalPositions)
  45795. at->moveToFinalDestination();
  45796. delete at;
  45797. tasks.remove (i);
  45798. sendChangeMessage (this);
  45799. }
  45800. }
  45801. void ComponentAnimator::cancelAnimation (Component* const component,
  45802. const bool moveComponentToItsFinalPosition)
  45803. {
  45804. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45805. if (at != 0)
  45806. {
  45807. if (moveComponentToItsFinalPosition)
  45808. at->moveToFinalDestination();
  45809. tasks.removeValue (at);
  45810. delete at;
  45811. sendChangeMessage (this);
  45812. }
  45813. }
  45814. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  45815. {
  45816. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  45817. if (at != 0)
  45818. return at->destination;
  45819. else if (component != 0)
  45820. return component->getBounds();
  45821. return Rectangle();
  45822. }
  45823. bool ComponentAnimator::isAnimating (Component* component) const
  45824. {
  45825. return findTaskFor (component) != 0;
  45826. }
  45827. void ComponentAnimator::timerCallback()
  45828. {
  45829. const uint32 timeNow = Time::getMillisecondCounter();
  45830. if (lastTime == 0 || lastTime == timeNow)
  45831. lastTime = timeNow;
  45832. const int elapsed = timeNow - lastTime;
  45833. for (int i = tasks.size(); --i >= 0;)
  45834. {
  45835. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  45836. if (! at->useTimeslice (elapsed))
  45837. {
  45838. tasks.remove (i);
  45839. delete at;
  45840. sendChangeMessage (this);
  45841. }
  45842. }
  45843. lastTime = timeNow;
  45844. if (tasks.size() == 0)
  45845. stopTimer();
  45846. }
  45847. END_JUCE_NAMESPACE
  45848. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  45849. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  45850. BEGIN_JUCE_NAMESPACE
  45851. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  45852. : minW (0),
  45853. maxW (0x3fffffff),
  45854. minH (0),
  45855. maxH (0x3fffffff),
  45856. minOffTop (0),
  45857. minOffLeft (0),
  45858. minOffBottom (0),
  45859. minOffRight (0),
  45860. aspectRatio (0.0)
  45861. {
  45862. }
  45863. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  45864. {
  45865. }
  45866. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  45867. {
  45868. minW = minimumWidth;
  45869. }
  45870. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  45871. {
  45872. maxW = maximumWidth;
  45873. }
  45874. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  45875. {
  45876. minH = minimumHeight;
  45877. }
  45878. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  45879. {
  45880. maxH = maximumHeight;
  45881. }
  45882. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  45883. {
  45884. jassert (maxW >= minimumWidth);
  45885. jassert (maxH >= minimumHeight);
  45886. jassert (minimumWidth > 0 && minimumHeight > 0);
  45887. minW = minimumWidth;
  45888. minH = minimumHeight;
  45889. if (minW > maxW)
  45890. maxW = minW;
  45891. if (minH > maxH)
  45892. maxH = minH;
  45893. }
  45894. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  45895. {
  45896. jassert (maximumWidth >= minW);
  45897. jassert (maximumHeight >= minH);
  45898. jassert (maximumWidth > 0 && maximumHeight > 0);
  45899. maxW = jmax (minW, maximumWidth);
  45900. maxH = jmax (minH, maximumHeight);
  45901. }
  45902. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  45903. const int minimumHeight,
  45904. const int maximumWidth,
  45905. const int maximumHeight) throw()
  45906. {
  45907. jassert (maximumWidth >= minimumWidth);
  45908. jassert (maximumHeight >= minimumHeight);
  45909. jassert (maximumWidth > 0 && maximumHeight > 0);
  45910. jassert (minimumWidth > 0 && minimumHeight > 0);
  45911. minW = jmax (0, minimumWidth);
  45912. minH = jmax (0, minimumHeight);
  45913. maxW = jmax (minW, maximumWidth);
  45914. maxH = jmax (minH, maximumHeight);
  45915. }
  45916. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  45917. const int minimumWhenOffTheLeft,
  45918. const int minimumWhenOffTheBottom,
  45919. const int minimumWhenOffTheRight) throw()
  45920. {
  45921. minOffTop = minimumWhenOffTheTop;
  45922. minOffLeft = minimumWhenOffTheLeft;
  45923. minOffBottom = minimumWhenOffTheBottom;
  45924. minOffRight = minimumWhenOffTheRight;
  45925. }
  45926. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  45927. {
  45928. aspectRatio = jmax (0.0, widthOverHeight);
  45929. }
  45930. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  45931. {
  45932. return aspectRatio;
  45933. }
  45934. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  45935. int x, int y, int w, int h,
  45936. const bool isStretchingTop,
  45937. const bool isStretchingLeft,
  45938. const bool isStretchingBottom,
  45939. const bool isStretchingRight)
  45940. {
  45941. jassert (component != 0);
  45942. Rectangle limits;
  45943. Component* const p = component->getParentComponent();
  45944. if (p == 0)
  45945. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  45946. else
  45947. limits.setSize (p->getWidth(), p->getHeight());
  45948. if (component->isOnDesktop())
  45949. {
  45950. ComponentPeer* const peer = component->getPeer();
  45951. const BorderSize border (peer->getFrameSize());
  45952. x -= border.getLeft();
  45953. y -= border.getTop();
  45954. w += border.getLeftAndRight();
  45955. h += border.getTopAndBottom();
  45956. checkBounds (x, y, w, h,
  45957. border.addedTo (component->getBounds()), limits,
  45958. isStretchingTop, isStretchingLeft,
  45959. isStretchingBottom, isStretchingRight);
  45960. x += border.getLeft();
  45961. y += border.getTop();
  45962. w -= border.getLeftAndRight();
  45963. h -= border.getTopAndBottom();
  45964. }
  45965. else
  45966. {
  45967. checkBounds (x, y, w, h,
  45968. component->getBounds(), limits,
  45969. isStretchingTop, isStretchingLeft,
  45970. isStretchingBottom, isStretchingRight);
  45971. }
  45972. applyBoundsToComponent (component, x, y, w, h);
  45973. }
  45974. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  45975. {
  45976. setBoundsForComponent (component,
  45977. component->getX(), component->getY(),
  45978. component->getWidth(), component->getHeight(),
  45979. false, false, false, false);
  45980. }
  45981. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  45982. int x, int y, int w, int h)
  45983. {
  45984. component->setBounds (x, y, w, h);
  45985. }
  45986. void ComponentBoundsConstrainer::resizeStart()
  45987. {
  45988. }
  45989. void ComponentBoundsConstrainer::resizeEnd()
  45990. {
  45991. }
  45992. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  45993. const Rectangle& old,
  45994. const Rectangle& limits,
  45995. const bool isStretchingTop,
  45996. const bool isStretchingLeft,
  45997. const bool isStretchingBottom,
  45998. const bool isStretchingRight)
  45999. {
  46000. // constrain the size if it's being stretched..
  46001. if (isStretchingLeft)
  46002. {
  46003. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  46004. w = old.getRight() - x;
  46005. }
  46006. if (isStretchingRight)
  46007. {
  46008. w = jlimit (minW, maxW, w);
  46009. }
  46010. if (isStretchingTop)
  46011. {
  46012. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  46013. h = old.getBottom() - y;
  46014. }
  46015. if (isStretchingBottom)
  46016. {
  46017. h = jlimit (minH, maxH, h);
  46018. }
  46019. // constrain the aspect ratio if one has been specified..
  46020. if (aspectRatio > 0.0 && w > 0 && h > 0)
  46021. {
  46022. bool adjustWidth;
  46023. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46024. {
  46025. adjustWidth = true;
  46026. }
  46027. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46028. {
  46029. adjustWidth = false;
  46030. }
  46031. else
  46032. {
  46033. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  46034. const double newRatio = fabs (w / (double) h);
  46035. adjustWidth = (oldRatio > newRatio);
  46036. }
  46037. if (adjustWidth)
  46038. {
  46039. w = roundDoubleToInt (h * aspectRatio);
  46040. if (w > maxW || w < minW)
  46041. {
  46042. w = jlimit (minW, maxW, w);
  46043. h = roundDoubleToInt (w / aspectRatio);
  46044. }
  46045. }
  46046. else
  46047. {
  46048. h = roundDoubleToInt (w / aspectRatio);
  46049. if (h > maxH || h < minH)
  46050. {
  46051. h = jlimit (minH, maxH, h);
  46052. w = roundDoubleToInt (h * aspectRatio);
  46053. }
  46054. }
  46055. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  46056. {
  46057. x = old.getX() + (old.getWidth() - w) / 2;
  46058. }
  46059. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  46060. {
  46061. y = old.getY() + (old.getHeight() - h) / 2;
  46062. }
  46063. else
  46064. {
  46065. if (isStretchingLeft)
  46066. x = old.getRight() - w;
  46067. if (isStretchingTop)
  46068. y = old.getBottom() - h;
  46069. }
  46070. }
  46071. // ...and constrain the position if limits have been set for that.
  46072. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  46073. {
  46074. if (minOffTop > 0)
  46075. {
  46076. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  46077. if (y < limit)
  46078. {
  46079. if (isStretchingTop)
  46080. h -= (limit - y);
  46081. y = limit;
  46082. }
  46083. }
  46084. if (minOffLeft > 0)
  46085. {
  46086. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  46087. if (x < limit)
  46088. {
  46089. if (isStretchingLeft)
  46090. w -= (limit - x);
  46091. x = limit;
  46092. }
  46093. }
  46094. if (minOffBottom > 0)
  46095. {
  46096. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  46097. if (y > limit)
  46098. {
  46099. if (isStretchingBottom)
  46100. h += (limit - y);
  46101. else
  46102. y = limit;
  46103. }
  46104. }
  46105. if (minOffRight > 0)
  46106. {
  46107. const int limit = limits.getRight() - jmin (minOffRight, w);
  46108. if (x > limit)
  46109. {
  46110. if (isStretchingRight)
  46111. w += (limit - x);
  46112. else
  46113. x = limit;
  46114. }
  46115. }
  46116. }
  46117. jassert (w >= 0 && h >= 0);
  46118. }
  46119. END_JUCE_NAMESPACE
  46120. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  46121. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46122. BEGIN_JUCE_NAMESPACE
  46123. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  46124. : component (component_),
  46125. lastPeer (0),
  46126. registeredParentComps (4),
  46127. reentrant (false)
  46128. {
  46129. jassert (component != 0); // can't use this with a null pointer..
  46130. #ifdef JUCE_DEBUG
  46131. deletionWatcher = new ComponentDeletionWatcher (component_);
  46132. #endif
  46133. component->addComponentListener (this);
  46134. registerWithParentComps();
  46135. }
  46136. ComponentMovementWatcher::~ComponentMovementWatcher()
  46137. {
  46138. component->removeComponentListener (this);
  46139. unregister();
  46140. #ifdef JUCE_DEBUG
  46141. delete deletionWatcher;
  46142. #endif
  46143. }
  46144. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  46145. {
  46146. #ifdef JUCE_DEBUG
  46147. // agh! don't delete the target component without deleting this object first!
  46148. jassert (! deletionWatcher->hasBeenDeleted());
  46149. #endif
  46150. if (! reentrant)
  46151. {
  46152. reentrant = true;
  46153. ComponentPeer* const peer = component->getPeer();
  46154. if (peer != lastPeer)
  46155. {
  46156. ComponentDeletionWatcher watcher (component);
  46157. componentPeerChanged();
  46158. if (watcher.hasBeenDeleted())
  46159. return;
  46160. lastPeer = peer;
  46161. }
  46162. unregister();
  46163. registerWithParentComps();
  46164. reentrant = false;
  46165. componentMovedOrResized (*component, true, true);
  46166. }
  46167. }
  46168. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  46169. {
  46170. #ifdef JUCE_DEBUG
  46171. // agh! don't delete the target component without deleting this object first!
  46172. jassert (! deletionWatcher->hasBeenDeleted());
  46173. #endif
  46174. if (wasMoved)
  46175. {
  46176. int x = 0, y = 0;
  46177. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  46178. wasMoved = (lastX != x || lastY != y);
  46179. lastX = x;
  46180. lastY = y;
  46181. }
  46182. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  46183. lastWidth = component->getWidth();
  46184. lastHeight = component->getHeight();
  46185. if (wasMoved || wasResized)
  46186. componentMovedOrResized (wasMoved, wasResized);
  46187. }
  46188. void ComponentMovementWatcher::registerWithParentComps() throw()
  46189. {
  46190. Component* p = component->getParentComponent();
  46191. while (p != 0)
  46192. {
  46193. p->addComponentListener (this);
  46194. registeredParentComps.add (p);
  46195. p = p->getParentComponent();
  46196. }
  46197. }
  46198. void ComponentMovementWatcher::unregister() throw()
  46199. {
  46200. for (int i = registeredParentComps.size(); --i >= 0;)
  46201. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  46202. registeredParentComps.clear();
  46203. }
  46204. END_JUCE_NAMESPACE
  46205. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  46206. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  46207. BEGIN_JUCE_NAMESPACE
  46208. GroupComponent::GroupComponent (const String& componentName,
  46209. const String& labelText)
  46210. : Component (componentName),
  46211. text (labelText),
  46212. justification (Justification::left)
  46213. {
  46214. setInterceptsMouseClicks (false, true);
  46215. }
  46216. GroupComponent::~GroupComponent()
  46217. {
  46218. }
  46219. void GroupComponent::setText (const String& newText) throw()
  46220. {
  46221. if (text != newText)
  46222. {
  46223. text = newText;
  46224. repaint();
  46225. }
  46226. }
  46227. const String GroupComponent::getText() const throw()
  46228. {
  46229. return text;
  46230. }
  46231. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  46232. {
  46233. if (justification.getFlags() != newJustification.getFlags())
  46234. {
  46235. justification = newJustification;
  46236. repaint();
  46237. }
  46238. }
  46239. void GroupComponent::paint (Graphics& g)
  46240. {
  46241. getLookAndFeel()
  46242. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  46243. text, justification,
  46244. *this);
  46245. }
  46246. void GroupComponent::enablementChanged()
  46247. {
  46248. repaint();
  46249. }
  46250. void GroupComponent::colourChanged()
  46251. {
  46252. repaint();
  46253. }
  46254. END_JUCE_NAMESPACE
  46255. /********* End of inlined file: juce_GroupComponent.cpp *********/
  46256. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  46257. BEGIN_JUCE_NAMESPACE
  46258. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  46259. : DocumentWindow (String::empty, backgroundColour,
  46260. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  46261. {
  46262. }
  46263. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  46264. {
  46265. }
  46266. void MultiDocumentPanelWindow::maximiseButtonPressed()
  46267. {
  46268. MultiDocumentPanel* const owner = getOwner();
  46269. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46270. if (owner != 0)
  46271. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  46272. }
  46273. void MultiDocumentPanelWindow::closeButtonPressed()
  46274. {
  46275. MultiDocumentPanel* const owner = getOwner();
  46276. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  46277. if (owner != 0)
  46278. owner->closeDocument (getContentComponent(), true);
  46279. }
  46280. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  46281. {
  46282. DocumentWindow::activeWindowStatusChanged();
  46283. updateOrder();
  46284. }
  46285. void MultiDocumentPanelWindow::broughtToFront()
  46286. {
  46287. DocumentWindow::broughtToFront();
  46288. updateOrder();
  46289. }
  46290. void MultiDocumentPanelWindow::updateOrder()
  46291. {
  46292. MultiDocumentPanel* const owner = getOwner();
  46293. if (owner != 0)
  46294. owner->updateOrder();
  46295. }
  46296. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  46297. {
  46298. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46299. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46300. }
  46301. class MDITabbedComponentInternal : public TabbedComponent
  46302. {
  46303. public:
  46304. MDITabbedComponentInternal()
  46305. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  46306. {
  46307. }
  46308. ~MDITabbedComponentInternal()
  46309. {
  46310. }
  46311. void currentTabChanged (const int, const String&)
  46312. {
  46313. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  46314. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  46315. if (owner != 0)
  46316. owner->updateOrder();
  46317. }
  46318. };
  46319. MultiDocumentPanel::MultiDocumentPanel()
  46320. : mode (MaximisedWindowsWithTabs),
  46321. tabComponent (0),
  46322. backgroundColour (Colours::lightblue),
  46323. maximumNumDocuments (0),
  46324. numDocsBeforeTabsUsed (0)
  46325. {
  46326. setOpaque (true);
  46327. }
  46328. MultiDocumentPanel::~MultiDocumentPanel()
  46329. {
  46330. closeAllDocuments (false);
  46331. }
  46332. static bool shouldDeleteComp (Component* const c)
  46333. {
  46334. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  46335. }
  46336. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  46337. {
  46338. while (components.size() > 0)
  46339. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  46340. return false;
  46341. return true;
  46342. }
  46343. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  46344. {
  46345. return new MultiDocumentPanelWindow (backgroundColour);
  46346. }
  46347. void MultiDocumentPanel::addWindow (Component* component)
  46348. {
  46349. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  46350. dw->setResizable (true, false);
  46351. dw->setContentComponent (component, false, true);
  46352. dw->setName (component->getName());
  46353. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  46354. int x = 4;
  46355. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  46356. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  46357. x += 16;
  46358. dw->setTopLeftPosition (x, x);
  46359. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  46360. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  46361. addAndMakeVisible (dw);
  46362. dw->toFront (true);
  46363. }
  46364. bool MultiDocumentPanel::addDocument (Component* const component,
  46365. const Colour& docColour,
  46366. const bool deleteWhenRemoved)
  46367. {
  46368. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  46369. // with a frame-within-a-frame! Just pass in the bare content component.
  46370. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  46371. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  46372. return false;
  46373. components.add (component);
  46374. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  46375. component->setComponentProperty (T("mdiDocumentBkg_"), docColour);
  46376. component->addComponentListener (this);
  46377. if (mode == FloatingWindows)
  46378. {
  46379. if (isFullscreenWhenOneDocument())
  46380. {
  46381. if (components.size() == 1)
  46382. {
  46383. addAndMakeVisible (component);
  46384. }
  46385. else
  46386. {
  46387. if (components.size() == 2)
  46388. addWindow (components.getFirst());
  46389. addWindow (component);
  46390. }
  46391. }
  46392. else
  46393. {
  46394. addWindow (component);
  46395. }
  46396. }
  46397. else
  46398. {
  46399. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  46400. {
  46401. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  46402. Array <Component*> temp (components);
  46403. for (int i = 0; i < temp.size(); ++i)
  46404. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  46405. resized();
  46406. }
  46407. else
  46408. {
  46409. if (tabComponent != 0)
  46410. tabComponent->addTab (component->getName(), docColour, component, false);
  46411. else
  46412. addAndMakeVisible (component);
  46413. }
  46414. setActiveDocument (component);
  46415. }
  46416. resized();
  46417. activeDocumentChanged();
  46418. return true;
  46419. }
  46420. bool MultiDocumentPanel::closeDocument (Component* component,
  46421. const bool checkItsOkToCloseFirst)
  46422. {
  46423. if (components.contains (component))
  46424. {
  46425. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  46426. return false;
  46427. component->removeComponentListener (this);
  46428. const bool shouldDelete = shouldDeleteComp (component);
  46429. component->removeComponentProperty (T("mdiDocumentDelete_"));
  46430. component->removeComponentProperty (T("mdiDocumentBkg_"));
  46431. if (mode == FloatingWindows)
  46432. {
  46433. for (int i = getNumChildComponents(); --i >= 0;)
  46434. {
  46435. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46436. if (dw != 0 && dw->getContentComponent() == component)
  46437. {
  46438. dw->setContentComponent (0, false);
  46439. delete dw;
  46440. break;
  46441. }
  46442. }
  46443. if (shouldDelete)
  46444. delete component;
  46445. components.removeValue (component);
  46446. if (isFullscreenWhenOneDocument() && components.size() == 1)
  46447. {
  46448. for (int i = getNumChildComponents(); --i >= 0;)
  46449. {
  46450. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46451. if (dw != 0)
  46452. {
  46453. dw->setContentComponent (0, false);
  46454. delete dw;
  46455. }
  46456. }
  46457. addAndMakeVisible (components.getFirst());
  46458. }
  46459. }
  46460. else
  46461. {
  46462. jassert (components.indexOf (component) >= 0);
  46463. if (tabComponent != 0)
  46464. {
  46465. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46466. if (tabComponent->getTabContentComponent (i) == component)
  46467. tabComponent->removeTab (i);
  46468. }
  46469. else
  46470. {
  46471. removeChildComponent (component);
  46472. }
  46473. if (shouldDelete)
  46474. delete component;
  46475. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  46476. deleteAndZero (tabComponent);
  46477. components.removeValue (component);
  46478. if (components.size() > 0 && tabComponent == 0)
  46479. addAndMakeVisible (components.getFirst());
  46480. }
  46481. resized();
  46482. activeDocumentChanged();
  46483. }
  46484. else
  46485. {
  46486. jassertfalse
  46487. }
  46488. return true;
  46489. }
  46490. int MultiDocumentPanel::getNumDocuments() const throw()
  46491. {
  46492. return components.size();
  46493. }
  46494. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  46495. {
  46496. return components [index];
  46497. }
  46498. Component* MultiDocumentPanel::getActiveDocument() const throw()
  46499. {
  46500. if (mode == FloatingWindows)
  46501. {
  46502. for (int i = getNumChildComponents(); --i >= 0;)
  46503. {
  46504. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46505. if (dw != 0 && dw->isActiveWindow())
  46506. return dw->getContentComponent();
  46507. }
  46508. }
  46509. return components.getLast();
  46510. }
  46511. void MultiDocumentPanel::setActiveDocument (Component* component)
  46512. {
  46513. if (mode == FloatingWindows)
  46514. {
  46515. component = getContainerComp (component);
  46516. if (component != 0)
  46517. component->toFront (true);
  46518. }
  46519. else if (tabComponent != 0)
  46520. {
  46521. jassert (components.indexOf (component) >= 0);
  46522. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46523. {
  46524. if (tabComponent->getTabContentComponent (i) == component)
  46525. {
  46526. tabComponent->setCurrentTabIndex (i);
  46527. break;
  46528. }
  46529. }
  46530. }
  46531. else
  46532. {
  46533. component->grabKeyboardFocus();
  46534. }
  46535. }
  46536. void MultiDocumentPanel::activeDocumentChanged()
  46537. {
  46538. }
  46539. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  46540. {
  46541. maximumNumDocuments = newNumber;
  46542. }
  46543. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  46544. {
  46545. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  46546. }
  46547. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  46548. {
  46549. return numDocsBeforeTabsUsed != 0;
  46550. }
  46551. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  46552. {
  46553. if (mode != newLayoutMode)
  46554. {
  46555. mode = newLayoutMode;
  46556. if (mode == FloatingWindows)
  46557. {
  46558. deleteAndZero (tabComponent);
  46559. }
  46560. else
  46561. {
  46562. for (int i = getNumChildComponents(); --i >= 0;)
  46563. {
  46564. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46565. if (dw != 0)
  46566. {
  46567. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  46568. dw->setContentComponent (0, false);
  46569. delete dw;
  46570. }
  46571. }
  46572. }
  46573. resized();
  46574. const Array <Component*> tempComps (components);
  46575. components.clear();
  46576. for (int i = 0; i < tempComps.size(); ++i)
  46577. {
  46578. Component* const c = tempComps.getUnchecked(i);
  46579. addDocument (c,
  46580. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  46581. shouldDeleteComp (c));
  46582. }
  46583. }
  46584. }
  46585. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  46586. {
  46587. if (backgroundColour != newBackgroundColour)
  46588. {
  46589. backgroundColour = newBackgroundColour;
  46590. setOpaque (newBackgroundColour.isOpaque());
  46591. repaint();
  46592. }
  46593. }
  46594. void MultiDocumentPanel::paint (Graphics& g)
  46595. {
  46596. g.fillAll (backgroundColour);
  46597. }
  46598. void MultiDocumentPanel::resized()
  46599. {
  46600. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  46601. {
  46602. for (int i = getNumChildComponents(); --i >= 0;)
  46603. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  46604. }
  46605. setWantsKeyboardFocus (components.size() == 0);
  46606. }
  46607. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  46608. {
  46609. if (mode == FloatingWindows)
  46610. {
  46611. for (int i = 0; i < getNumChildComponents(); ++i)
  46612. {
  46613. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46614. if (dw != 0 && dw->getContentComponent() == c)
  46615. {
  46616. c = dw;
  46617. break;
  46618. }
  46619. }
  46620. }
  46621. return c;
  46622. }
  46623. void MultiDocumentPanel::componentNameChanged (Component&)
  46624. {
  46625. if (mode == FloatingWindows)
  46626. {
  46627. for (int i = 0; i < getNumChildComponents(); ++i)
  46628. {
  46629. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46630. if (dw != 0)
  46631. dw->setName (dw->getContentComponent()->getName());
  46632. }
  46633. }
  46634. else if (tabComponent != 0)
  46635. {
  46636. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  46637. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  46638. }
  46639. }
  46640. void MultiDocumentPanel::updateOrder()
  46641. {
  46642. const Array <Component*> oldList (components);
  46643. if (mode == FloatingWindows)
  46644. {
  46645. components.clear();
  46646. for (int i = 0; i < getNumChildComponents(); ++i)
  46647. {
  46648. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  46649. if (dw != 0)
  46650. components.add (dw->getContentComponent());
  46651. }
  46652. }
  46653. else
  46654. {
  46655. if (tabComponent != 0)
  46656. {
  46657. Component* const current = tabComponent->getCurrentContentComponent();
  46658. if (current != 0)
  46659. {
  46660. components.removeValue (current);
  46661. components.add (current);
  46662. }
  46663. }
  46664. }
  46665. if (components != oldList)
  46666. activeDocumentChanged();
  46667. }
  46668. END_JUCE_NAMESPACE
  46669. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  46670. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  46671. BEGIN_JUCE_NAMESPACE
  46672. const int zoneL = 1;
  46673. const int zoneR = 2;
  46674. const int zoneT = 4;
  46675. const int zoneB = 8;
  46676. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  46677. ComponentBoundsConstrainer* const constrainer_)
  46678. : component (componentToResize),
  46679. constrainer (constrainer_),
  46680. borderSize (5),
  46681. mouseZone (0)
  46682. {
  46683. }
  46684. ResizableBorderComponent::~ResizableBorderComponent()
  46685. {
  46686. }
  46687. void ResizableBorderComponent::paint (Graphics& g)
  46688. {
  46689. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  46690. }
  46691. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  46692. {
  46693. updateMouseZone (e);
  46694. }
  46695. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  46696. {
  46697. updateMouseZone (e);
  46698. }
  46699. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  46700. {
  46701. if (component->isValidComponent())
  46702. {
  46703. updateMouseZone (e);
  46704. originalX = component->getX();
  46705. originalY = component->getY();
  46706. originalW = component->getWidth();
  46707. originalH = component->getHeight();
  46708. if (constrainer != 0)
  46709. constrainer->resizeStart();
  46710. }
  46711. else
  46712. {
  46713. jassertfalse
  46714. }
  46715. }
  46716. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  46717. {
  46718. if (! component->isValidComponent())
  46719. {
  46720. jassertfalse
  46721. return;
  46722. }
  46723. int x = originalX;
  46724. int y = originalY;
  46725. int w = originalW;
  46726. int h = originalH;
  46727. const int dx = e.getDistanceFromDragStartX();
  46728. const int dy = e.getDistanceFromDragStartY();
  46729. if ((mouseZone & zoneL) != 0)
  46730. {
  46731. x += dx;
  46732. w -= dx;
  46733. }
  46734. if ((mouseZone & zoneT) != 0)
  46735. {
  46736. y += dy;
  46737. h -= dy;
  46738. }
  46739. if ((mouseZone & zoneR) != 0)
  46740. w += dx;
  46741. if ((mouseZone & zoneB) != 0)
  46742. h += dy;
  46743. if (constrainer != 0)
  46744. constrainer->setBoundsForComponent (component,
  46745. x, y, w, h,
  46746. (mouseZone & zoneT) != 0,
  46747. (mouseZone & zoneL) != 0,
  46748. (mouseZone & zoneB) != 0,
  46749. (mouseZone & zoneR) != 0);
  46750. else
  46751. component->setBounds (x, y, w, h);
  46752. }
  46753. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  46754. {
  46755. if (constrainer != 0)
  46756. constrainer->resizeEnd();
  46757. }
  46758. bool ResizableBorderComponent::hitTest (int x, int y)
  46759. {
  46760. return x < borderSize.getLeft()
  46761. || x >= getWidth() - borderSize.getRight()
  46762. || y < borderSize.getTop()
  46763. || y >= getHeight() - borderSize.getBottom();
  46764. }
  46765. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  46766. {
  46767. if (borderSize != newBorderSize)
  46768. {
  46769. borderSize = newBorderSize;
  46770. repaint();
  46771. }
  46772. }
  46773. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  46774. {
  46775. return borderSize;
  46776. }
  46777. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  46778. {
  46779. int newZone = 0;
  46780. if (ResizableBorderComponent::hitTest (e.x, e.y))
  46781. {
  46782. if (e.x < jmax (borderSize.getLeft(),
  46783. proportionOfWidth (0.1f),
  46784. jmin (10, proportionOfWidth (0.33f))))
  46785. newZone |= zoneL;
  46786. else if (e.x >= jmin (getWidth() - borderSize.getRight(),
  46787. proportionOfWidth (0.9f),
  46788. getWidth() - jmin (10, proportionOfWidth (0.33f))))
  46789. newZone |= zoneR;
  46790. if (e.y < jmax (borderSize.getTop(),
  46791. proportionOfHeight (0.1f),
  46792. jmin (10, proportionOfHeight (0.33f))))
  46793. newZone |= zoneT;
  46794. else if (e.y >= jmin (getHeight() - borderSize.getBottom(),
  46795. proportionOfHeight (0.9f),
  46796. getHeight() - jmin (10, proportionOfHeight (0.33f))))
  46797. newZone |= zoneB;
  46798. }
  46799. if (mouseZone != newZone)
  46800. {
  46801. mouseZone = newZone;
  46802. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  46803. switch (newZone)
  46804. {
  46805. case (zoneL | zoneT):
  46806. mc = MouseCursor::TopLeftCornerResizeCursor;
  46807. break;
  46808. case zoneT:
  46809. mc = MouseCursor::TopEdgeResizeCursor;
  46810. break;
  46811. case (zoneR | zoneT):
  46812. mc = MouseCursor::TopRightCornerResizeCursor;
  46813. break;
  46814. case zoneL:
  46815. mc = MouseCursor::LeftEdgeResizeCursor;
  46816. break;
  46817. case zoneR:
  46818. mc = MouseCursor::RightEdgeResizeCursor;
  46819. break;
  46820. case (zoneL | zoneB):
  46821. mc = MouseCursor::BottomLeftCornerResizeCursor;
  46822. break;
  46823. case zoneB:
  46824. mc = MouseCursor::BottomEdgeResizeCursor;
  46825. break;
  46826. case (zoneR | zoneB):
  46827. mc = MouseCursor::BottomRightCornerResizeCursor;
  46828. break;
  46829. default:
  46830. break;
  46831. }
  46832. setMouseCursor (mc);
  46833. }
  46834. }
  46835. END_JUCE_NAMESPACE
  46836. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  46837. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  46838. BEGIN_JUCE_NAMESPACE
  46839. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  46840. ComponentBoundsConstrainer* const constrainer_)
  46841. : component (componentToResize),
  46842. constrainer (constrainer_)
  46843. {
  46844. setRepaintsOnMouseActivity (true);
  46845. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  46846. }
  46847. ResizableCornerComponent::~ResizableCornerComponent()
  46848. {
  46849. }
  46850. void ResizableCornerComponent::paint (Graphics& g)
  46851. {
  46852. getLookAndFeel()
  46853. .drawCornerResizer (g, getWidth(), getHeight(),
  46854. isMouseOverOrDragging(),
  46855. isMouseButtonDown());
  46856. }
  46857. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  46858. {
  46859. if (component->isValidComponent())
  46860. {
  46861. originalX = component->getX();
  46862. originalY = component->getY();
  46863. originalW = component->getWidth();
  46864. originalH = component->getHeight();
  46865. if (constrainer != 0)
  46866. constrainer->resizeStart();
  46867. }
  46868. else
  46869. {
  46870. jassertfalse
  46871. }
  46872. }
  46873. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  46874. {
  46875. if (! component->isValidComponent())
  46876. {
  46877. jassertfalse
  46878. return;
  46879. }
  46880. int x = originalX;
  46881. int y = originalY;
  46882. int w = originalW + e.getDistanceFromDragStartX();
  46883. int h = originalH + e.getDistanceFromDragStartY();
  46884. if (constrainer != 0)
  46885. constrainer->setBoundsForComponent (component, x, y, w, h,
  46886. false, false, true, true);
  46887. else
  46888. component->setBounds (x, y, w, h);
  46889. }
  46890. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  46891. {
  46892. if (constrainer != 0)
  46893. constrainer->resizeStart();
  46894. }
  46895. bool ResizableCornerComponent::hitTest (int x, int y)
  46896. {
  46897. if (getWidth() <= 0)
  46898. return false;
  46899. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  46900. return y >= yAtX - getHeight() / 4;
  46901. }
  46902. END_JUCE_NAMESPACE
  46903. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  46904. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  46905. BEGIN_JUCE_NAMESPACE
  46906. class ScrollbarButton : public Button
  46907. {
  46908. public:
  46909. int direction;
  46910. ScrollbarButton (const int direction_,
  46911. ScrollBar& owner_) throw()
  46912. : Button (String::empty),
  46913. direction (direction_),
  46914. owner (owner_)
  46915. {
  46916. setWantsKeyboardFocus (false);
  46917. }
  46918. ~ScrollbarButton()
  46919. {
  46920. }
  46921. void paintButton (Graphics& g,
  46922. bool isMouseOver,
  46923. bool isMouseDown)
  46924. {
  46925. getLookAndFeel()
  46926. .drawScrollbarButton (g, owner,
  46927. getWidth(), getHeight(),
  46928. direction,
  46929. owner.isVertical(),
  46930. isMouseOver, isMouseDown);
  46931. }
  46932. void clicked()
  46933. {
  46934. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  46935. }
  46936. juce_UseDebuggingNewOperator
  46937. private:
  46938. ScrollBar& owner;
  46939. ScrollbarButton (const ScrollbarButton&);
  46940. const ScrollbarButton& operator= (const ScrollbarButton&);
  46941. };
  46942. ScrollBar::ScrollBar (const bool vertical_,
  46943. const bool buttonsAreVisible)
  46944. : minimum (0.0),
  46945. maximum (1.0),
  46946. rangeStart (0.0),
  46947. rangeSize (0.1),
  46948. singleStepSize (0.1),
  46949. thumbAreaStart (0),
  46950. thumbAreaSize (0),
  46951. thumbStart (0),
  46952. thumbSize (0),
  46953. initialDelayInMillisecs (100),
  46954. repeatDelayInMillisecs (50),
  46955. minimumDelayInMillisecs (10),
  46956. vertical (vertical_),
  46957. isDraggingThumb (false),
  46958. alwaysVisible (false),
  46959. upButton (0),
  46960. downButton (0),
  46961. listeners (2)
  46962. {
  46963. setButtonVisibility (buttonsAreVisible);
  46964. setRepaintsOnMouseActivity (true);
  46965. setFocusContainer (true);
  46966. }
  46967. ScrollBar::~ScrollBar()
  46968. {
  46969. deleteAllChildren();
  46970. }
  46971. void ScrollBar::setRangeLimits (const double newMinimum,
  46972. const double newMaximum) throw()
  46973. {
  46974. minimum = newMinimum;
  46975. maximum = newMaximum;
  46976. jassert (maximum >= minimum); // these can't be the wrong way round!
  46977. setCurrentRangeStart (rangeStart);
  46978. updateThumbPosition();
  46979. }
  46980. void ScrollBar::setCurrentRange (double newStart,
  46981. double newSize) throw()
  46982. {
  46983. newSize = jlimit (0.0, maximum - minimum, newSize);
  46984. newStart = jlimit (minimum, maximum - newSize, newStart);
  46985. if (rangeStart != newStart
  46986. || rangeSize != newSize)
  46987. {
  46988. rangeStart = newStart;
  46989. rangeSize = newSize;
  46990. updateThumbPosition();
  46991. triggerAsyncUpdate();
  46992. }
  46993. }
  46994. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  46995. {
  46996. setCurrentRange (newStart, rangeSize);
  46997. }
  46998. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  46999. {
  47000. singleStepSize = newSingleStepSize;
  47001. }
  47002. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  47003. {
  47004. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  47005. }
  47006. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  47007. {
  47008. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  47009. }
  47010. void ScrollBar::scrollToTop() throw()
  47011. {
  47012. setCurrentRangeStart (minimum);
  47013. }
  47014. void ScrollBar::scrollToBottom() throw()
  47015. {
  47016. setCurrentRangeStart (maximum - rangeSize);
  47017. }
  47018. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  47019. const int repeatDelayInMillisecs_,
  47020. const int minimumDelayInMillisecs_) throw()
  47021. {
  47022. initialDelayInMillisecs = initialDelayInMillisecs_;
  47023. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  47024. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  47025. if (upButton != 0)
  47026. {
  47027. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47028. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47029. }
  47030. }
  47031. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  47032. {
  47033. jassert (listener != 0);
  47034. if (listener != 0)
  47035. listeners.add (listener);
  47036. }
  47037. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  47038. {
  47039. listeners.removeValue (listener);
  47040. }
  47041. void ScrollBar::handleAsyncUpdate()
  47042. {
  47043. const double value = getCurrentRangeStart();
  47044. for (int i = listeners.size(); --i >= 0;)
  47045. {
  47046. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  47047. i = jmin (i, listeners.size());
  47048. }
  47049. }
  47050. void ScrollBar::updateThumbPosition() throw()
  47051. {
  47052. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  47053. : thumbAreaSize);
  47054. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47055. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  47056. if (newThumbSize > thumbAreaSize)
  47057. newThumbSize = thumbAreaSize;
  47058. int newThumbStart = thumbAreaStart;
  47059. if (maximum - minimum > rangeSize)
  47060. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  47061. / ((maximum - minimum) - rangeSize));
  47062. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  47063. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  47064. {
  47065. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  47066. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  47067. if (vertical)
  47068. repaint (0, repaintStart, getWidth(), repaintSize);
  47069. else
  47070. repaint (repaintStart, 0, repaintSize, getHeight());
  47071. thumbStart = newThumbStart;
  47072. thumbSize = newThumbSize;
  47073. }
  47074. }
  47075. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  47076. {
  47077. if (vertical != shouldBeVertical)
  47078. {
  47079. vertical = shouldBeVertical;
  47080. if (upButton != 0)
  47081. {
  47082. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  47083. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  47084. }
  47085. updateThumbPosition();
  47086. }
  47087. }
  47088. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  47089. {
  47090. deleteAndZero (upButton);
  47091. deleteAndZero (downButton);
  47092. if (buttonsAreVisible)
  47093. {
  47094. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  47095. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  47096. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  47097. }
  47098. updateThumbPosition();
  47099. }
  47100. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  47101. {
  47102. alwaysVisible = ! shouldHideWhenFullRange;
  47103. updateThumbPosition();
  47104. }
  47105. void ScrollBar::paint (Graphics& g)
  47106. {
  47107. if (thumbAreaSize > 0)
  47108. {
  47109. LookAndFeel& lf = getLookAndFeel();
  47110. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  47111. ? thumbSize : 0;
  47112. if (vertical)
  47113. {
  47114. lf.drawScrollbar (g, *this,
  47115. 0, thumbAreaStart,
  47116. getWidth(), thumbAreaSize,
  47117. vertical,
  47118. thumbStart, thumb,
  47119. isMouseOver(), isMouseButtonDown());
  47120. }
  47121. else
  47122. {
  47123. lf.drawScrollbar (g, *this,
  47124. thumbAreaStart, 0,
  47125. thumbAreaSize, getHeight(),
  47126. vertical,
  47127. thumbStart, thumb,
  47128. isMouseOver(), isMouseButtonDown());
  47129. }
  47130. }
  47131. }
  47132. void ScrollBar::lookAndFeelChanged()
  47133. {
  47134. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  47135. }
  47136. void ScrollBar::resized()
  47137. {
  47138. const int length = ((vertical) ? getHeight() : getWidth());
  47139. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  47140. : 0;
  47141. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47142. {
  47143. thumbAreaStart = length >> 1;
  47144. thumbAreaSize = 0;
  47145. }
  47146. else
  47147. {
  47148. thumbAreaStart = buttonSize;
  47149. thumbAreaSize = length - (buttonSize << 1);
  47150. }
  47151. if (upButton != 0)
  47152. {
  47153. if (vertical)
  47154. {
  47155. upButton->setBounds (0, 0, getWidth(), buttonSize);
  47156. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  47157. }
  47158. else
  47159. {
  47160. upButton->setBounds (0, 0, buttonSize, getHeight());
  47161. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  47162. }
  47163. }
  47164. updateThumbPosition();
  47165. }
  47166. void ScrollBar::mouseDown (const MouseEvent& e)
  47167. {
  47168. isDraggingThumb = false;
  47169. lastMousePos = vertical ? e.y : e.x;
  47170. dragStartMousePos = lastMousePos;
  47171. dragStartRange = rangeStart;
  47172. if (dragStartMousePos < thumbStart)
  47173. {
  47174. moveScrollbarInPages (-1);
  47175. startTimer (400);
  47176. }
  47177. else if (dragStartMousePos >= thumbStart + thumbSize)
  47178. {
  47179. moveScrollbarInPages (1);
  47180. startTimer (400);
  47181. }
  47182. else
  47183. {
  47184. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  47185. && (thumbAreaSize > thumbSize);
  47186. }
  47187. }
  47188. void ScrollBar::mouseDrag (const MouseEvent& e)
  47189. {
  47190. if (isDraggingThumb)
  47191. {
  47192. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  47193. setCurrentRangeStart (dragStartRange
  47194. + deltaPixels * ((maximum - minimum) - rangeSize)
  47195. / (thumbAreaSize - thumbSize));
  47196. }
  47197. else
  47198. {
  47199. lastMousePos = (vertical) ? e.y : e.x;
  47200. }
  47201. }
  47202. void ScrollBar::mouseUp (const MouseEvent&)
  47203. {
  47204. isDraggingThumb = false;
  47205. stopTimer();
  47206. repaint();
  47207. }
  47208. void ScrollBar::mouseWheelMove (const MouseEvent&,
  47209. float wheelIncrementX,
  47210. float wheelIncrementY)
  47211. {
  47212. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  47213. if (increment < 0)
  47214. increment = jmin (increment * 10.0f, -1.0f);
  47215. else if (increment > 0)
  47216. increment = jmax (increment * 10.0f, 1.0f);
  47217. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  47218. }
  47219. void ScrollBar::timerCallback()
  47220. {
  47221. if (isMouseButtonDown())
  47222. {
  47223. startTimer (40);
  47224. if (lastMousePos < thumbStart)
  47225. setCurrentRangeStart (rangeStart - rangeSize);
  47226. else if (lastMousePos > thumbStart + thumbSize)
  47227. setCurrentRangeStart (rangeStart + rangeSize);
  47228. }
  47229. else
  47230. {
  47231. stopTimer();
  47232. }
  47233. }
  47234. bool ScrollBar::keyPressed (const KeyPress& key)
  47235. {
  47236. if (! isVisible())
  47237. return false;
  47238. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  47239. moveScrollbarInSteps (-1);
  47240. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  47241. moveScrollbarInSteps (1);
  47242. else if (key.isKeyCode (KeyPress::pageUpKey))
  47243. moveScrollbarInPages (-1);
  47244. else if (key.isKeyCode (KeyPress::pageDownKey))
  47245. moveScrollbarInPages (1);
  47246. else if (key.isKeyCode (KeyPress::homeKey))
  47247. scrollToTop();
  47248. else if (key.isKeyCode (KeyPress::endKey))
  47249. scrollToBottom();
  47250. else
  47251. return false;
  47252. return true;
  47253. }
  47254. END_JUCE_NAMESPACE
  47255. /********* End of inlined file: juce_ScrollBar.cpp *********/
  47256. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  47257. BEGIN_JUCE_NAMESPACE
  47258. StretchableLayoutManager::StretchableLayoutManager()
  47259. : totalSize (0)
  47260. {
  47261. }
  47262. StretchableLayoutManager::~StretchableLayoutManager()
  47263. {
  47264. }
  47265. void StretchableLayoutManager::clearAllItems()
  47266. {
  47267. items.clear();
  47268. totalSize = 0;
  47269. }
  47270. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  47271. const double minimumSize,
  47272. const double maximumSize,
  47273. const double preferredSize)
  47274. {
  47275. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  47276. if (layout == 0)
  47277. {
  47278. layout = new ItemLayoutProperties();
  47279. layout->itemIndex = itemIndex;
  47280. int i;
  47281. for (i = 0; i < items.size(); ++i)
  47282. if (items.getUnchecked (i)->itemIndex > itemIndex)
  47283. break;
  47284. items.insert (i, layout);
  47285. }
  47286. layout->minSize = minimumSize;
  47287. layout->maxSize = maximumSize;
  47288. layout->preferredSize = preferredSize;
  47289. layout->currentSize = 0;
  47290. }
  47291. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  47292. double& minimumSize,
  47293. double& maximumSize,
  47294. double& preferredSize) const
  47295. {
  47296. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47297. if (layout != 0)
  47298. {
  47299. minimumSize = layout->minSize;
  47300. maximumSize = layout->maxSize;
  47301. preferredSize = layout->preferredSize;
  47302. return true;
  47303. }
  47304. return false;
  47305. }
  47306. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  47307. {
  47308. totalSize = newTotalSize;
  47309. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  47310. }
  47311. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  47312. {
  47313. int pos = 0;
  47314. for (int i = 0; i < itemIndex; ++i)
  47315. {
  47316. const ItemLayoutProperties* const layout = getInfoFor (i);
  47317. if (layout != 0)
  47318. pos += layout->currentSize;
  47319. }
  47320. return pos;
  47321. }
  47322. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  47323. {
  47324. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47325. if (layout != 0)
  47326. return layout->currentSize;
  47327. return 0;
  47328. }
  47329. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  47330. {
  47331. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  47332. if (layout != 0)
  47333. return -layout->currentSize / (double) totalSize;
  47334. return 0;
  47335. }
  47336. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  47337. int newPosition)
  47338. {
  47339. for (int i = items.size(); --i >= 0;)
  47340. {
  47341. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  47342. if (layout->itemIndex == itemIndex)
  47343. {
  47344. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  47345. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  47346. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  47347. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  47348. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  47349. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  47350. endPos += layout->currentSize;
  47351. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  47352. updatePrefSizesToMatchCurrentPositions();
  47353. break;
  47354. }
  47355. }
  47356. }
  47357. void StretchableLayoutManager::layOutComponents (Component** const components,
  47358. int numComponents,
  47359. int x, int y, int w, int h,
  47360. const bool vertically,
  47361. const bool resizeOtherDimension)
  47362. {
  47363. setTotalSize (vertically ? h : w);
  47364. int pos = vertically ? y : x;
  47365. for (int i = 0; i < numComponents; ++i)
  47366. {
  47367. const ItemLayoutProperties* const layout = getInfoFor (i);
  47368. if (layout != 0)
  47369. {
  47370. Component* const c = components[i];
  47371. if (c != 0)
  47372. {
  47373. if (i == numComponents - 1)
  47374. {
  47375. // if it's the last item, crop it to exactly fit the available space..
  47376. if (resizeOtherDimension)
  47377. {
  47378. if (vertically)
  47379. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  47380. else
  47381. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  47382. }
  47383. else
  47384. {
  47385. if (vertically)
  47386. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  47387. else
  47388. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  47389. }
  47390. }
  47391. else
  47392. {
  47393. if (resizeOtherDimension)
  47394. {
  47395. if (vertically)
  47396. c->setBounds (x, pos, w, layout->currentSize);
  47397. else
  47398. c->setBounds (pos, y, layout->currentSize, h);
  47399. }
  47400. else
  47401. {
  47402. if (vertically)
  47403. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  47404. else
  47405. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  47406. }
  47407. }
  47408. }
  47409. pos += layout->currentSize;
  47410. }
  47411. }
  47412. }
  47413. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  47414. {
  47415. for (int i = items.size(); --i >= 0;)
  47416. if (items.getUnchecked(i)->itemIndex == itemIndex)
  47417. return items.getUnchecked(i);
  47418. return 0;
  47419. }
  47420. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  47421. const int endIndex,
  47422. const int availableSpace,
  47423. int startPos)
  47424. {
  47425. // calculate the total sizes
  47426. int i;
  47427. double totalIdealSize = 0.0;
  47428. int totalMinimums = 0;
  47429. for (i = startIndex; i < endIndex; ++i)
  47430. {
  47431. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47432. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  47433. totalMinimums += layout->currentSize;
  47434. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  47435. }
  47436. if (totalIdealSize <= 0)
  47437. totalIdealSize = 1.0;
  47438. // now calc the best sizes..
  47439. int extraSpace = availableSpace - totalMinimums;
  47440. while (extraSpace > 0)
  47441. {
  47442. int numWantingMoreSpace = 0;
  47443. int numHavingTakenExtraSpace = 0;
  47444. // first figure out how many comps want a slice of the extra space..
  47445. for (i = startIndex; i < endIndex; ++i)
  47446. {
  47447. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47448. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47449. const int bestSize = jlimit (layout->currentSize,
  47450. jmax (layout->currentSize,
  47451. sizeToRealSize (layout->maxSize, totalSize)),
  47452. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47453. if (bestSize > layout->currentSize)
  47454. ++numWantingMoreSpace;
  47455. }
  47456. // ..share out the extra space..
  47457. for (i = startIndex; i < endIndex; ++i)
  47458. {
  47459. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47460. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  47461. int bestSize = jlimit (layout->currentSize,
  47462. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  47463. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  47464. const int extraWanted = bestSize - layout->currentSize;
  47465. if (extraWanted > 0)
  47466. {
  47467. const int extraAllowed = jmin (extraWanted,
  47468. extraSpace / jmax (1, numWantingMoreSpace));
  47469. if (extraAllowed > 0)
  47470. {
  47471. ++numHavingTakenExtraSpace;
  47472. --numWantingMoreSpace;
  47473. layout->currentSize += extraAllowed;
  47474. extraSpace -= extraAllowed;
  47475. }
  47476. }
  47477. }
  47478. if (numHavingTakenExtraSpace <= 0)
  47479. break;
  47480. }
  47481. // ..and calculate the end position
  47482. for (i = startIndex; i < endIndex; ++i)
  47483. {
  47484. ItemLayoutProperties* const layout = items.getUnchecked(i);
  47485. startPos += layout->currentSize;
  47486. }
  47487. return startPos;
  47488. }
  47489. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  47490. const int endIndex) const
  47491. {
  47492. int totalMinimums = 0;
  47493. for (int i = startIndex; i < endIndex; ++i)
  47494. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  47495. return totalMinimums;
  47496. }
  47497. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  47498. {
  47499. int totalMaximums = 0;
  47500. for (int i = startIndex; i < endIndex; ++i)
  47501. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  47502. return totalMaximums;
  47503. }
  47504. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  47505. {
  47506. for (int i = 0; i < items.size(); ++i)
  47507. {
  47508. ItemLayoutProperties* const layout = items.getUnchecked (i);
  47509. layout->preferredSize
  47510. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  47511. : getItemCurrentAbsoluteSize (i);
  47512. }
  47513. }
  47514. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  47515. {
  47516. if (size < 0)
  47517. size *= -totalSpace;
  47518. return roundDoubleToInt (size);
  47519. }
  47520. END_JUCE_NAMESPACE
  47521. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  47522. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47523. BEGIN_JUCE_NAMESPACE
  47524. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  47525. const int itemIndex_,
  47526. const bool isVertical_)
  47527. : layout (layout_),
  47528. itemIndex (itemIndex_),
  47529. isVertical (isVertical_)
  47530. {
  47531. setRepaintsOnMouseActivity (true);
  47532. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  47533. : MouseCursor::UpDownResizeCursor));
  47534. }
  47535. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  47536. {
  47537. }
  47538. void StretchableLayoutResizerBar::paint (Graphics& g)
  47539. {
  47540. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  47541. getWidth(), getHeight(),
  47542. isVertical,
  47543. isMouseOver(),
  47544. isMouseButtonDown());
  47545. }
  47546. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  47547. {
  47548. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  47549. }
  47550. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  47551. {
  47552. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  47553. : e.getDistanceFromDragStartY());
  47554. layout->setItemPosition (itemIndex, desiredPos);
  47555. hasBeenMoved();
  47556. }
  47557. void StretchableLayoutResizerBar::hasBeenMoved()
  47558. {
  47559. if (getParentComponent() != 0)
  47560. getParentComponent()->resized();
  47561. }
  47562. END_JUCE_NAMESPACE
  47563. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  47564. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  47565. BEGIN_JUCE_NAMESPACE
  47566. StretchableObjectResizer::StretchableObjectResizer()
  47567. {
  47568. }
  47569. StretchableObjectResizer::~StretchableObjectResizer()
  47570. {
  47571. }
  47572. void StretchableObjectResizer::addItem (const double size,
  47573. const double minSize, const double maxSize,
  47574. const int order)
  47575. {
  47576. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  47577. Item* const item = new Item();
  47578. item->size = size;
  47579. item->minSize = minSize;
  47580. item->maxSize = maxSize;
  47581. item->order = order;
  47582. items.add (item);
  47583. }
  47584. double StretchableObjectResizer::getItemSize (const int index) const throw()
  47585. {
  47586. const Item* const it = items [index];
  47587. return it != 0 ? it->size : 0;
  47588. }
  47589. void StretchableObjectResizer::resizeToFit (const double targetSize)
  47590. {
  47591. int order = 0;
  47592. for (;;)
  47593. {
  47594. double currentSize = 0;
  47595. double minSize = 0;
  47596. double maxSize = 0;
  47597. int nextHighestOrder = INT_MAX;
  47598. for (int i = 0; i < items.size(); ++i)
  47599. {
  47600. const Item* const it = items.getUnchecked(i);
  47601. currentSize += it->size;
  47602. if (it->order <= order)
  47603. {
  47604. minSize += it->minSize;
  47605. maxSize += it->maxSize;
  47606. }
  47607. else
  47608. {
  47609. minSize += it->size;
  47610. maxSize += it->size;
  47611. nextHighestOrder = jmin (nextHighestOrder, it->order);
  47612. }
  47613. }
  47614. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  47615. if (thisIterationTarget >= currentSize)
  47616. {
  47617. const double availableExtraSpace = maxSize - currentSize;
  47618. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  47619. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  47620. for (int i = 0; i < items.size(); ++i)
  47621. {
  47622. Item* const it = items.getUnchecked(i);
  47623. if (it->order <= order)
  47624. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  47625. }
  47626. }
  47627. else
  47628. {
  47629. const double amountOfSlack = currentSize - minSize;
  47630. const double targetAmountOfSlack = thisIterationTarget - minSize;
  47631. const double scale = targetAmountOfSlack / amountOfSlack;
  47632. for (int i = 0; i < items.size(); ++i)
  47633. {
  47634. Item* const it = items.getUnchecked(i);
  47635. if (it->order <= order)
  47636. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  47637. }
  47638. }
  47639. if (nextHighestOrder < INT_MAX)
  47640. order = nextHighestOrder;
  47641. else
  47642. break;
  47643. }
  47644. }
  47645. END_JUCE_NAMESPACE
  47646. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  47647. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  47648. BEGIN_JUCE_NAMESPACE
  47649. TabBarButton::TabBarButton (const String& name,
  47650. TabbedButtonBar* const owner_,
  47651. const int index)
  47652. : Button (name),
  47653. owner (owner_),
  47654. tabIndex (index),
  47655. overlapPixels (0)
  47656. {
  47657. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  47658. setComponentEffect (&shadow);
  47659. setWantsKeyboardFocus (false);
  47660. }
  47661. TabBarButton::~TabBarButton()
  47662. {
  47663. }
  47664. void TabBarButton::paintButton (Graphics& g,
  47665. bool isMouseOverButton,
  47666. bool isButtonDown)
  47667. {
  47668. int x, y, w, h;
  47669. getActiveArea (x, y, w, h);
  47670. g.setOrigin (x, y);
  47671. getLookAndFeel()
  47672. .drawTabButton (g, w, h,
  47673. owner->getTabBackgroundColour (tabIndex),
  47674. tabIndex, getButtonText(), *this,
  47675. owner->getOrientation(),
  47676. isMouseOverButton, isButtonDown,
  47677. getToggleState());
  47678. }
  47679. void TabBarButton::clicked (const ModifierKeys& mods)
  47680. {
  47681. if (mods.isPopupMenu())
  47682. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  47683. else
  47684. owner->setCurrentTabIndex (tabIndex);
  47685. }
  47686. bool TabBarButton::hitTest (int mx, int my)
  47687. {
  47688. int x, y, w, h;
  47689. getActiveArea (x, y, w, h);
  47690. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  47691. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  47692. {
  47693. if (((unsigned int) mx) < (unsigned int) getWidth()
  47694. && my >= y + overlapPixels
  47695. && my < y + h - overlapPixels)
  47696. return true;
  47697. }
  47698. else
  47699. {
  47700. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  47701. && ((unsigned int) my) < (unsigned int) getHeight())
  47702. return true;
  47703. }
  47704. Path p;
  47705. getLookAndFeel()
  47706. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  47707. owner->getOrientation(),
  47708. false, false, getToggleState());
  47709. return p.contains ((float) (mx - x),
  47710. (float) (my - y));
  47711. }
  47712. int TabBarButton::getBestTabLength (const int depth)
  47713. {
  47714. return jlimit (depth * 2,
  47715. depth * 7,
  47716. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  47717. }
  47718. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  47719. {
  47720. x = 0;
  47721. y = 0;
  47722. int r = getWidth();
  47723. int b = getHeight();
  47724. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  47725. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  47726. r -= spaceAroundImage;
  47727. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  47728. x += spaceAroundImage;
  47729. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  47730. y += spaceAroundImage;
  47731. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  47732. b -= spaceAroundImage;
  47733. w = r - x;
  47734. h = b - y;
  47735. }
  47736. class TabAreaBehindFrontButtonComponent : public Component
  47737. {
  47738. public:
  47739. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  47740. : owner (owner_)
  47741. {
  47742. setInterceptsMouseClicks (false, false);
  47743. }
  47744. ~TabAreaBehindFrontButtonComponent()
  47745. {
  47746. }
  47747. void paint (Graphics& g)
  47748. {
  47749. getLookAndFeel()
  47750. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  47751. *owner, owner->getOrientation());
  47752. }
  47753. void enablementChanged()
  47754. {
  47755. repaint();
  47756. }
  47757. private:
  47758. TabbedButtonBar* const owner;
  47759. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  47760. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  47761. };
  47762. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  47763. : orientation (orientation_),
  47764. currentTabIndex (-1),
  47765. extraTabsButton (0)
  47766. {
  47767. setInterceptsMouseClicks (false, true);
  47768. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  47769. setFocusContainer (true);
  47770. }
  47771. TabbedButtonBar::~TabbedButtonBar()
  47772. {
  47773. deleteAllChildren();
  47774. }
  47775. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  47776. {
  47777. orientation = newOrientation;
  47778. for (int i = getNumChildComponents(); --i >= 0;)
  47779. getChildComponent (i)->resized();
  47780. resized();
  47781. }
  47782. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  47783. {
  47784. return new TabBarButton (name, this, index);
  47785. }
  47786. void TabbedButtonBar::clearTabs()
  47787. {
  47788. tabs.clear();
  47789. tabColours.clear();
  47790. currentTabIndex = -1;
  47791. deleteAndZero (extraTabsButton);
  47792. removeChildComponent (behindFrontTab);
  47793. deleteAllChildren();
  47794. addChildComponent (behindFrontTab);
  47795. setCurrentTabIndex (-1);
  47796. }
  47797. void TabbedButtonBar::addTab (const String& tabName,
  47798. const Colour& tabBackgroundColour,
  47799. int insertIndex)
  47800. {
  47801. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  47802. if (tabName.isNotEmpty())
  47803. {
  47804. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  47805. insertIndex = tabs.size();
  47806. for (int i = tabs.size(); --i >= insertIndex;)
  47807. {
  47808. TabBarButton* const tb = getTabButton (i);
  47809. if (tb != 0)
  47810. tb->tabIndex++;
  47811. }
  47812. tabs.insert (insertIndex, tabName);
  47813. tabColours.insert (insertIndex, tabBackgroundColour);
  47814. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  47815. jassert (tb != 0); // your createTabButton() mustn't return zero!
  47816. addAndMakeVisible (tb, insertIndex);
  47817. resized();
  47818. if (currentTabIndex < 0)
  47819. setCurrentTabIndex (0);
  47820. }
  47821. }
  47822. void TabbedButtonBar::setTabName (const int tabIndex,
  47823. const String& newName)
  47824. {
  47825. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  47826. && tabs[tabIndex] != newName)
  47827. {
  47828. tabs.set (tabIndex, newName);
  47829. TabBarButton* const tb = getTabButton (tabIndex);
  47830. if (tb != 0)
  47831. tb->setButtonText (newName);
  47832. resized();
  47833. }
  47834. }
  47835. void TabbedButtonBar::removeTab (const int tabIndex)
  47836. {
  47837. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  47838. {
  47839. const int oldTabIndex = currentTabIndex;
  47840. if (currentTabIndex == tabIndex)
  47841. currentTabIndex = -1;
  47842. tabs.remove (tabIndex);
  47843. tabColours.remove (tabIndex);
  47844. TabBarButton* const tb = getTabButton (tabIndex);
  47845. if (tb != 0)
  47846. delete tb;
  47847. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  47848. {
  47849. TabBarButton* const tb = getTabButton (i);
  47850. if (tb != 0)
  47851. tb->tabIndex--;
  47852. }
  47853. resized();
  47854. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  47855. }
  47856. }
  47857. void TabbedButtonBar::moveTab (const int currentIndex,
  47858. const int newIndex)
  47859. {
  47860. tabs.move (currentIndex, newIndex);
  47861. tabColours.move (currentIndex, newIndex);
  47862. resized();
  47863. }
  47864. int TabbedButtonBar::getNumTabs() const
  47865. {
  47866. return tabs.size();
  47867. }
  47868. const StringArray TabbedButtonBar::getTabNames() const
  47869. {
  47870. return tabs;
  47871. }
  47872. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  47873. {
  47874. if (currentTabIndex != newIndex)
  47875. {
  47876. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  47877. newIndex = -1;
  47878. currentTabIndex = newIndex;
  47879. for (int i = 0; i < getNumChildComponents(); ++i)
  47880. {
  47881. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47882. if (tb != 0)
  47883. tb->setToggleState (tb->tabIndex == newIndex, false);
  47884. }
  47885. resized();
  47886. if (sendChangeMessage_)
  47887. sendChangeMessage (this);
  47888. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  47889. }
  47890. }
  47891. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  47892. {
  47893. for (int i = getNumChildComponents(); --i >= 0;)
  47894. {
  47895. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47896. if (tb != 0 && tb->tabIndex == index)
  47897. return tb;
  47898. }
  47899. return 0;
  47900. }
  47901. void TabbedButtonBar::lookAndFeelChanged()
  47902. {
  47903. deleteAndZero (extraTabsButton);
  47904. resized();
  47905. }
  47906. void TabbedButtonBar::resized()
  47907. {
  47908. const double minimumScale = 0.7;
  47909. int depth = getWidth();
  47910. int length = getHeight();
  47911. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47912. swapVariables (depth, length);
  47913. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  47914. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  47915. int i, totalLength = overlap;
  47916. int numVisibleButtons = tabs.size();
  47917. for (i = 0; i < getNumChildComponents(); ++i)
  47918. {
  47919. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  47920. if (tb != 0)
  47921. {
  47922. totalLength += tb->getBestTabLength (depth) - overlap;
  47923. tb->overlapPixels = overlap / 2;
  47924. }
  47925. }
  47926. double scale = 1.0;
  47927. if (totalLength > length)
  47928. scale = jmax (minimumScale, length / (double) totalLength);
  47929. const bool isTooBig = totalLength * scale > length;
  47930. int tabsButtonPos = 0;
  47931. if (isTooBig)
  47932. {
  47933. if (extraTabsButton == 0)
  47934. {
  47935. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  47936. extraTabsButton->addButtonListener (this);
  47937. extraTabsButton->setAlwaysOnTop (true);
  47938. extraTabsButton->setTriggeredOnMouseDown (true);
  47939. }
  47940. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  47941. extraTabsButton->setSize (buttonSize, buttonSize);
  47942. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47943. {
  47944. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  47945. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  47946. }
  47947. else
  47948. {
  47949. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  47950. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  47951. }
  47952. totalLength = 0;
  47953. for (i = 0; i < tabs.size(); ++i)
  47954. {
  47955. TabBarButton* const tb = getTabButton (i);
  47956. if (tb != 0)
  47957. {
  47958. const int newLength = totalLength + tb->getBestTabLength (depth);
  47959. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  47960. {
  47961. totalLength += overlap;
  47962. break;
  47963. }
  47964. numVisibleButtons = i + 1;
  47965. totalLength = newLength - overlap;
  47966. }
  47967. }
  47968. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  47969. }
  47970. else
  47971. {
  47972. deleteAndZero (extraTabsButton);
  47973. }
  47974. int pos = 0;
  47975. TabBarButton* frontTab = 0;
  47976. for (i = 0; i < tabs.size(); ++i)
  47977. {
  47978. TabBarButton* const tb = getTabButton (i);
  47979. if (tb != 0)
  47980. {
  47981. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  47982. if (i < numVisibleButtons)
  47983. {
  47984. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  47985. tb->setBounds (pos, 0, bestLength, getHeight());
  47986. else
  47987. tb->setBounds (0, pos, getWidth(), bestLength);
  47988. tb->toBack();
  47989. if (tb->tabIndex == currentTabIndex)
  47990. frontTab = tb;
  47991. tb->setVisible (true);
  47992. }
  47993. else
  47994. {
  47995. tb->setVisible (false);
  47996. }
  47997. pos += bestLength - overlap;
  47998. }
  47999. }
  48000. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  48001. if (frontTab != 0)
  48002. {
  48003. frontTab->toFront (false);
  48004. behindFrontTab->toBehind (frontTab);
  48005. }
  48006. }
  48007. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  48008. {
  48009. return tabColours [tabIndex];
  48010. }
  48011. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48012. {
  48013. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  48014. && tabColours [tabIndex] != newColour)
  48015. {
  48016. tabColours.set (tabIndex, newColour);
  48017. repaint();
  48018. }
  48019. }
  48020. void TabbedButtonBar::buttonClicked (Button* button)
  48021. {
  48022. if (extraTabsButton == button)
  48023. {
  48024. PopupMenu m;
  48025. for (int i = 0; i < tabs.size(); ++i)
  48026. {
  48027. TabBarButton* const tb = getTabButton (i);
  48028. if (tb != 0 && ! tb->isVisible())
  48029. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  48030. }
  48031. const int res = m.showAt (extraTabsButton);
  48032. if (res != 0)
  48033. setCurrentTabIndex (res - 1);
  48034. }
  48035. }
  48036. void TabbedButtonBar::currentTabChanged (const int, const String&)
  48037. {
  48038. }
  48039. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  48040. {
  48041. }
  48042. END_JUCE_NAMESPACE
  48043. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  48044. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  48045. BEGIN_JUCE_NAMESPACE
  48046. class TabCompButtonBar : public TabbedButtonBar
  48047. {
  48048. public:
  48049. TabCompButtonBar (TabbedComponent* const owner_,
  48050. const TabbedButtonBar::Orientation orientation)
  48051. : TabbedButtonBar (orientation),
  48052. owner (owner_)
  48053. {
  48054. }
  48055. ~TabCompButtonBar()
  48056. {
  48057. }
  48058. void currentTabChanged (const int newCurrentTabIndex,
  48059. const String& newTabName)
  48060. {
  48061. owner->changeCallback (newCurrentTabIndex, newTabName);
  48062. }
  48063. void popupMenuClickOnTab (const int tabIndex,
  48064. const String& tabName)
  48065. {
  48066. owner->popupMenuClickOnTab (tabIndex, tabName);
  48067. }
  48068. const Colour getTabBackgroundColour (const int tabIndex)
  48069. {
  48070. return owner->tabs->getTabBackgroundColour (tabIndex);
  48071. }
  48072. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  48073. {
  48074. return owner->createTabButton (tabName, tabIndex);
  48075. }
  48076. juce_UseDebuggingNewOperator
  48077. private:
  48078. TabbedComponent* const owner;
  48079. TabCompButtonBar (const TabCompButtonBar&);
  48080. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  48081. };
  48082. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  48083. : panelComponent (0),
  48084. tabDepth (30),
  48085. outlineThickness (1),
  48086. edgeIndent (0)
  48087. {
  48088. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  48089. }
  48090. TabbedComponent::~TabbedComponent()
  48091. {
  48092. clearTabs();
  48093. delete tabs;
  48094. }
  48095. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  48096. {
  48097. tabs->setOrientation (orientation);
  48098. resized();
  48099. }
  48100. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  48101. {
  48102. return tabs->getOrientation();
  48103. }
  48104. void TabbedComponent::setTabBarDepth (const int newDepth)
  48105. {
  48106. if (tabDepth != newDepth)
  48107. {
  48108. tabDepth = newDepth;
  48109. resized();
  48110. }
  48111. }
  48112. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  48113. {
  48114. return new TabBarButton (tabName, tabs, tabIndex);
  48115. }
  48116. void TabbedComponent::clearTabs()
  48117. {
  48118. if (panelComponent != 0)
  48119. {
  48120. panelComponent->setVisible (false);
  48121. removeChildComponent (panelComponent);
  48122. panelComponent = 0;
  48123. }
  48124. tabs->clearTabs();
  48125. for (int i = contentComponents.size(); --i >= 0;)
  48126. {
  48127. Component* const c = contentComponents.getUnchecked(i);
  48128. // be careful not to delete these components until they've been removed from the tab component
  48129. jassert (c == 0 || c->isValidComponent());
  48130. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48131. delete c;
  48132. }
  48133. contentComponents.clear();
  48134. }
  48135. void TabbedComponent::addTab (const String& tabName,
  48136. const Colour& tabBackgroundColour,
  48137. Component* const contentComponent,
  48138. const bool deleteComponentWhenNotNeeded,
  48139. const int insertIndex)
  48140. {
  48141. contentComponents.insert (insertIndex, contentComponent);
  48142. if (contentComponent != 0)
  48143. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  48144. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  48145. }
  48146. void TabbedComponent::setTabName (const int tabIndex,
  48147. const String& newName)
  48148. {
  48149. tabs->setTabName (tabIndex, newName);
  48150. }
  48151. void TabbedComponent::removeTab (const int tabIndex)
  48152. {
  48153. Component* const c = contentComponents [tabIndex];
  48154. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  48155. {
  48156. if (c == panelComponent)
  48157. panelComponent = 0;
  48158. delete c;
  48159. }
  48160. contentComponents.remove (tabIndex);
  48161. tabs->removeTab (tabIndex);
  48162. }
  48163. int TabbedComponent::getNumTabs() const
  48164. {
  48165. return tabs->getNumTabs();
  48166. }
  48167. const StringArray TabbedComponent::getTabNames() const
  48168. {
  48169. return tabs->getTabNames();
  48170. }
  48171. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  48172. {
  48173. return contentComponents [tabIndex];
  48174. }
  48175. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  48176. {
  48177. return tabs->getTabBackgroundColour (tabIndex);
  48178. }
  48179. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  48180. {
  48181. tabs->setTabBackgroundColour (tabIndex, newColour);
  48182. if (getCurrentTabIndex() == tabIndex)
  48183. repaint();
  48184. }
  48185. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  48186. {
  48187. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  48188. }
  48189. int TabbedComponent::getCurrentTabIndex() const
  48190. {
  48191. return tabs->getCurrentTabIndex();
  48192. }
  48193. const String& TabbedComponent::getCurrentTabName() const
  48194. {
  48195. return tabs->getCurrentTabName();
  48196. }
  48197. void TabbedComponent::setOutline (int thickness)
  48198. {
  48199. outlineThickness = thickness;
  48200. repaint();
  48201. }
  48202. void TabbedComponent::setIndent (const int indentThickness)
  48203. {
  48204. edgeIndent = indentThickness;
  48205. }
  48206. void TabbedComponent::paint (Graphics& g)
  48207. {
  48208. g.fillAll (findColour (backgroundColourId));
  48209. const TabbedButtonBar::Orientation o = getOrientation();
  48210. int x = 0;
  48211. int y = 0;
  48212. int r = getWidth();
  48213. int b = getHeight();
  48214. if (o == TabbedButtonBar::TabsAtTop)
  48215. y += tabDepth;
  48216. else if (o == TabbedButtonBar::TabsAtBottom)
  48217. b -= tabDepth;
  48218. else if (o == TabbedButtonBar::TabsAtLeft)
  48219. x += tabDepth;
  48220. else if (o == TabbedButtonBar::TabsAtRight)
  48221. r -= tabDepth;
  48222. g.reduceClipRegion (x, y, r - x, b - y);
  48223. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  48224. if (outlineThickness > 0)
  48225. {
  48226. if (o == TabbedButtonBar::TabsAtTop)
  48227. --y;
  48228. else if (o == TabbedButtonBar::TabsAtBottom)
  48229. ++b;
  48230. else if (o == TabbedButtonBar::TabsAtLeft)
  48231. --x;
  48232. else if (o == TabbedButtonBar::TabsAtRight)
  48233. ++r;
  48234. g.setColour (findColour (outlineColourId));
  48235. g.drawRect (x, y, r - x, b - y, outlineThickness);
  48236. }
  48237. }
  48238. void TabbedComponent::resized()
  48239. {
  48240. const TabbedButtonBar::Orientation o = getOrientation();
  48241. const int indent = edgeIndent + outlineThickness;
  48242. BorderSize indents (indent);
  48243. if (o == TabbedButtonBar::TabsAtTop)
  48244. {
  48245. tabs->setBounds (0, 0, getWidth(), tabDepth);
  48246. indents.setTop (tabDepth + edgeIndent);
  48247. }
  48248. else if (o == TabbedButtonBar::TabsAtBottom)
  48249. {
  48250. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  48251. indents.setBottom (tabDepth + edgeIndent);
  48252. }
  48253. else if (o == TabbedButtonBar::TabsAtLeft)
  48254. {
  48255. tabs->setBounds (0, 0, tabDepth, getHeight());
  48256. indents.setLeft (tabDepth + edgeIndent);
  48257. }
  48258. else if (o == TabbedButtonBar::TabsAtRight)
  48259. {
  48260. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  48261. indents.setRight (tabDepth + edgeIndent);
  48262. }
  48263. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  48264. for (int i = contentComponents.size(); --i >= 0;)
  48265. if (contentComponents.getUnchecked (i) != 0)
  48266. contentComponents.getUnchecked (i)->setBounds (bounds);
  48267. }
  48268. void TabbedComponent::lookAndFeelChanged()
  48269. {
  48270. for (int i = contentComponents.size(); --i >= 0;)
  48271. if (contentComponents.getUnchecked (i) != 0)
  48272. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  48273. }
  48274. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  48275. const String& newTabName)
  48276. {
  48277. if (panelComponent != 0)
  48278. {
  48279. panelComponent->setVisible (false);
  48280. removeChildComponent (panelComponent);
  48281. panelComponent = 0;
  48282. }
  48283. if (getCurrentTabIndex() >= 0)
  48284. {
  48285. panelComponent = contentComponents [getCurrentTabIndex()];
  48286. if (panelComponent != 0)
  48287. {
  48288. // do these ops as two stages instead of addAndMakeVisible() so that the
  48289. // component has always got a parent when it gets the visibilityChanged() callback
  48290. addChildComponent (panelComponent);
  48291. panelComponent->setVisible (true);
  48292. panelComponent->toFront (true);
  48293. }
  48294. repaint();
  48295. }
  48296. resized();
  48297. currentTabChanged (newCurrentTabIndex, newTabName);
  48298. }
  48299. void TabbedComponent::currentTabChanged (const int, const String&)
  48300. {
  48301. }
  48302. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  48303. {
  48304. }
  48305. END_JUCE_NAMESPACE
  48306. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  48307. /********* Start of inlined file: juce_Viewport.cpp *********/
  48308. BEGIN_JUCE_NAMESPACE
  48309. Viewport::Viewport (const String& componentName)
  48310. : Component (componentName),
  48311. contentComp (0),
  48312. lastVX (0),
  48313. lastVY (0),
  48314. lastVW (0),
  48315. lastVH (0),
  48316. scrollBarThickness (0),
  48317. singleStepX (16),
  48318. singleStepY (16),
  48319. showHScrollbar (true),
  48320. showVScrollbar (true)
  48321. {
  48322. // content holder is used to clip the contents so they don't overlap the scrollbars
  48323. addAndMakeVisible (contentHolder = new Component());
  48324. contentHolder->setInterceptsMouseClicks (false, true);
  48325. verticalScrollBar = new ScrollBar (true);
  48326. horizontalScrollBar = new ScrollBar (false);
  48327. addChildComponent (verticalScrollBar);
  48328. addChildComponent (horizontalScrollBar);
  48329. verticalScrollBar->addListener (this);
  48330. horizontalScrollBar->addListener (this);
  48331. setInterceptsMouseClicks (false, true);
  48332. setWantsKeyboardFocus (true);
  48333. }
  48334. Viewport::~Viewport()
  48335. {
  48336. contentHolder->deleteAllChildren();
  48337. deleteAllChildren();
  48338. }
  48339. void Viewport::visibleAreaChanged (int, int, int, int)
  48340. {
  48341. }
  48342. void Viewport::setViewedComponent (Component* const newViewedComponent)
  48343. {
  48344. if (contentComp != newViewedComponent)
  48345. {
  48346. if (contentComp->isValidComponent())
  48347. {
  48348. Component* const oldComp = contentComp;
  48349. contentComp = 0;
  48350. delete oldComp;
  48351. }
  48352. contentComp = newViewedComponent;
  48353. if (contentComp != 0)
  48354. {
  48355. contentComp->setTopLeftPosition (0, 0);
  48356. contentHolder->addAndMakeVisible (contentComp);
  48357. contentComp->addComponentListener (this);
  48358. }
  48359. updateVisibleRegion();
  48360. }
  48361. }
  48362. int Viewport::getMaximumVisibleWidth() const throw()
  48363. {
  48364. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48365. }
  48366. int Viewport::getMaximumVisibleHeight() const throw()
  48367. {
  48368. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  48369. }
  48370. void Viewport::setViewPosition (const int xPixelsOffset,
  48371. const int yPixelsOffset)
  48372. {
  48373. if (contentComp != 0)
  48374. contentComp->setTopLeftPosition (-xPixelsOffset,
  48375. -yPixelsOffset);
  48376. }
  48377. void Viewport::setViewPositionProportionately (const double x,
  48378. const double y)
  48379. {
  48380. if (contentComp != 0)
  48381. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  48382. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  48383. }
  48384. void Viewport::componentMovedOrResized (Component&, bool, bool)
  48385. {
  48386. updateVisibleRegion();
  48387. }
  48388. void Viewport::resized()
  48389. {
  48390. updateVisibleRegion();
  48391. }
  48392. void Viewport::updateVisibleRegion()
  48393. {
  48394. if (contentComp != 0)
  48395. {
  48396. const int newVX = -contentComp->getX();
  48397. const int newVY = -contentComp->getY();
  48398. if (newVX == 0 && newVY == 0
  48399. && contentComp->getWidth() <= getWidth()
  48400. && contentComp->getHeight() <= getHeight())
  48401. {
  48402. horizontalScrollBar->setVisible (false);
  48403. verticalScrollBar->setVisible (false);
  48404. }
  48405. if ((contentComp->getWidth() > 0) && showHScrollbar
  48406. && getHeight() > getScrollBarThickness())
  48407. {
  48408. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  48409. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48410. horizontalScrollBar->setSingleStepSize (singleStepX);
  48411. }
  48412. else
  48413. {
  48414. horizontalScrollBar->setVisible (false);
  48415. }
  48416. if ((contentComp->getHeight() > 0) && showVScrollbar
  48417. && getWidth() > getScrollBarThickness())
  48418. {
  48419. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  48420. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48421. verticalScrollBar->setSingleStepSize (singleStepY);
  48422. }
  48423. else
  48424. {
  48425. verticalScrollBar->setVisible (false);
  48426. }
  48427. if (verticalScrollBar->isVisible())
  48428. {
  48429. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48430. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  48431. verticalScrollBar
  48432. ->setBounds (getMaximumVisibleWidth(), 0,
  48433. getScrollBarThickness(), getMaximumVisibleHeight());
  48434. }
  48435. if (horizontalScrollBar->isVisible())
  48436. {
  48437. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  48438. horizontalScrollBar
  48439. ->setBounds (0, getMaximumVisibleHeight(),
  48440. getMaximumVisibleWidth(), getScrollBarThickness());
  48441. }
  48442. contentHolder->setSize (getMaximumVisibleWidth(),
  48443. getMaximumVisibleHeight());
  48444. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  48445. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  48446. if (newVX != lastVX
  48447. || newVY != lastVY
  48448. || newVW != lastVW
  48449. || newVH != lastVH)
  48450. {
  48451. lastVX = newVX;
  48452. lastVY = newVY;
  48453. lastVW = newVW;
  48454. lastVH = newVH;
  48455. visibleAreaChanged (newVX, newVY, newVW, newVH);
  48456. }
  48457. horizontalScrollBar->handleUpdateNowIfNeeded();
  48458. verticalScrollBar->handleUpdateNowIfNeeded();
  48459. }
  48460. else
  48461. {
  48462. horizontalScrollBar->setVisible (false);
  48463. verticalScrollBar->setVisible (false);
  48464. }
  48465. }
  48466. void Viewport::setSingleStepSizes (const int stepX,
  48467. const int stepY)
  48468. {
  48469. singleStepX = stepX;
  48470. singleStepY = stepY;
  48471. updateVisibleRegion();
  48472. }
  48473. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  48474. const bool showHorizontalScrollbarIfNeeded)
  48475. {
  48476. showVScrollbar = showVerticalScrollbarIfNeeded;
  48477. showHScrollbar = showHorizontalScrollbarIfNeeded;
  48478. updateVisibleRegion();
  48479. }
  48480. void Viewport::setScrollBarThickness (const int thickness)
  48481. {
  48482. scrollBarThickness = thickness;
  48483. updateVisibleRegion();
  48484. }
  48485. int Viewport::getScrollBarThickness() const throw()
  48486. {
  48487. return (scrollBarThickness > 0) ? scrollBarThickness
  48488. : getLookAndFeel().getDefaultScrollbarWidth();
  48489. }
  48490. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  48491. {
  48492. verticalScrollBar->setButtonVisibility (buttonsVisible);
  48493. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  48494. }
  48495. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  48496. {
  48497. if (scrollBarThatHasMoved == horizontalScrollBar)
  48498. {
  48499. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  48500. }
  48501. else if (scrollBarThatHasMoved == verticalScrollBar)
  48502. {
  48503. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  48504. }
  48505. }
  48506. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48507. {
  48508. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  48509. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  48510. }
  48511. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  48512. {
  48513. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  48514. {
  48515. const bool hasVertBar = verticalScrollBar->isVisible();
  48516. const bool hasHorzBar = horizontalScrollBar->isVisible();
  48517. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  48518. {
  48519. if (wheelIncrementX == 0 && ! hasVertBar)
  48520. wheelIncrementX = wheelIncrementY;
  48521. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  48522. wheelIncrementX, wheelIncrementY);
  48523. return true;
  48524. }
  48525. else if (hasVertBar && wheelIncrementY != 0)
  48526. {
  48527. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  48528. wheelIncrementX, wheelIncrementY);
  48529. return true;
  48530. }
  48531. }
  48532. return false;
  48533. }
  48534. bool Viewport::keyPressed (const KeyPress& key)
  48535. {
  48536. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  48537. || key.isKeyCode (KeyPress::downKey)
  48538. || key.isKeyCode (KeyPress::pageUpKey)
  48539. || key.isKeyCode (KeyPress::pageDownKey)
  48540. || key.isKeyCode (KeyPress::homeKey)
  48541. || key.isKeyCode (KeyPress::endKey);
  48542. if (verticalScrollBar->isVisible() && isUpDownKey)
  48543. return verticalScrollBar->keyPressed (key);
  48544. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  48545. || key.isKeyCode (KeyPress::rightKey);
  48546. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  48547. return horizontalScrollBar->keyPressed (key);
  48548. return false;
  48549. }
  48550. END_JUCE_NAMESPACE
  48551. /********* End of inlined file: juce_Viewport.cpp *********/
  48552. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  48553. BEGIN_JUCE_NAMESPACE
  48554. static const Colour createBaseColour (const Colour& buttonColour,
  48555. const bool hasKeyboardFocus,
  48556. const bool isMouseOverButton,
  48557. const bool isButtonDown) throw()
  48558. {
  48559. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  48560. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  48561. if (isButtonDown)
  48562. return baseColour.contrasting (0.2f);
  48563. else if (isMouseOverButton)
  48564. return baseColour.contrasting (0.1f);
  48565. return baseColour;
  48566. }
  48567. static String defaultSansName, defaultSerifName, defaultFixedName;
  48568. void clearUpDefaultFontNames() throw()
  48569. {
  48570. defaultSansName = String::empty;
  48571. defaultSerifName = String::empty;
  48572. defaultFixedName = String::empty;
  48573. }
  48574. LookAndFeel::LookAndFeel()
  48575. {
  48576. /* if this fails it means you're trying to create a LookAndFeel object before
  48577. the static Colours have been initialised. That ain't gonna work. It probably
  48578. means that you're using a static LookAndFeel object and that your compiler has
  48579. decided to intialise it before the Colours class.
  48580. */
  48581. jassert (Colours::white == Colour (0xffffffff));
  48582. // set up the standard set of colours..
  48583. #define textButtonColour 0xffbbbbff
  48584. #define textHighlightColour 0x401111ee
  48585. #define standardOutlineColour 0xb2808080
  48586. static const int standardColours[] =
  48587. {
  48588. TextButton::buttonColourId, textButtonColour,
  48589. TextButton::buttonOnColourId, 0xff4444ff,
  48590. TextButton::textColourId, 0xff000000,
  48591. ComboBox::buttonColourId, 0xffbbbbff,
  48592. ComboBox::outlineColourId, standardOutlineColour,
  48593. ToggleButton::textColourId, 0xff000000,
  48594. TextEditor::backgroundColourId, 0xffffffff,
  48595. TextEditor::textColourId, 0xff000000,
  48596. TextEditor::highlightColourId, textHighlightColour,
  48597. TextEditor::highlightedTextColourId, 0xff000000,
  48598. TextEditor::caretColourId, 0xff000000,
  48599. TextEditor::outlineColourId, 0x00000000,
  48600. TextEditor::focusedOutlineColourId, textButtonColour,
  48601. TextEditor::shadowColourId, 0x38000000,
  48602. Label::backgroundColourId, 0x00000000,
  48603. Label::textColourId, 0xff000000,
  48604. Label::outlineColourId, 0x00000000,
  48605. ScrollBar::backgroundColourId, 0x00000000,
  48606. ScrollBar::thumbColourId, 0xffffffff,
  48607. ScrollBar::trackColourId, 0xffffffff,
  48608. TreeView::linesColourId, 0x4c000000,
  48609. TreeView::backgroundColourId, 0x00000000,
  48610. PopupMenu::backgroundColourId, 0xffffffff,
  48611. PopupMenu::textColourId, 0xff000000,
  48612. PopupMenu::headerTextColourId, 0xff000000,
  48613. PopupMenu::highlightedTextColourId, 0xffffffff,
  48614. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  48615. ComboBox::textColourId, 0xff000000,
  48616. ComboBox::backgroundColourId, 0xffffffff,
  48617. ComboBox::arrowColourId, 0x99000000,
  48618. ListBox::backgroundColourId, 0xffffffff,
  48619. ListBox::outlineColourId, standardOutlineColour,
  48620. ListBox::textColourId, 0xff000000,
  48621. Slider::backgroundColourId, 0x00000000,
  48622. Slider::thumbColourId, textButtonColour,
  48623. Slider::trackColourId, 0x7fffffff,
  48624. Slider::rotarySliderFillColourId, 0x7f0000ff,
  48625. Slider::rotarySliderOutlineColourId, 0x66000000,
  48626. Slider::textBoxTextColourId, 0xff000000,
  48627. Slider::textBoxBackgroundColourId, 0xffffffff,
  48628. Slider::textBoxHighlightColourId, textHighlightColour,
  48629. Slider::textBoxOutlineColourId, standardOutlineColour,
  48630. ResizableWindow::backgroundColourId, 0xff777777,
  48631. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  48632. AlertWindow::backgroundColourId, 0xffededed,
  48633. AlertWindow::textColourId, 0xff000000,
  48634. AlertWindow::outlineColourId, 0xff666666,
  48635. ProgressBar::backgroundColourId, 0xffeeeeee,
  48636. ProgressBar::foregroundColourId, 0xffaaaaee,
  48637. TooltipWindow::backgroundColourId, 0xffeeeebb,
  48638. TooltipWindow::textColourId, 0xff000000,
  48639. TooltipWindow::outlineColourId, 0x4c000000,
  48640. TabbedComponent::backgroundColourId, 0x00000000,
  48641. TabbedComponent::outlineColourId, 0xff777777,
  48642. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  48643. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  48644. Toolbar::backgroundColourId, 0xfff6f8f9,
  48645. Toolbar::separatorColourId, 0x4c000000,
  48646. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  48647. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  48648. Toolbar::labelTextColourId, 0xff000000,
  48649. Toolbar::editingModeOutlineColourId, 0xffff0000,
  48650. HyperlinkButton::textColourId, 0xcc1111ee,
  48651. GroupComponent::outlineColourId, 0x66000000,
  48652. GroupComponent::textColourId, 0xff000000,
  48653. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  48654. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  48655. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  48656. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  48657. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  48658. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  48659. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  48660. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  48661. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  48662. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  48663. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  48664. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  48665. ColourSelector::backgroundColourId, 0xffe5e5e5,
  48666. ColourSelector::labelTextColourId, 0xff000000,
  48667. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  48668. };
  48669. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  48670. setColour (standardColours [i], Colour (standardColours [i + 1]));
  48671. if (defaultSansName.isEmpty())
  48672. Typeface::getDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  48673. defaultSans = defaultSansName;
  48674. defaultSerif = defaultSerifName;
  48675. defaultFixed = defaultFixedName;
  48676. }
  48677. LookAndFeel::~LookAndFeel()
  48678. {
  48679. }
  48680. const Colour LookAndFeel::findColour (const int colourId) const throw()
  48681. {
  48682. const int index = colourIds.indexOf (colourId);
  48683. if (index >= 0)
  48684. return colours [index];
  48685. jassertfalse
  48686. return Colours::black;
  48687. }
  48688. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  48689. {
  48690. const int index = colourIds.indexOf (colourId);
  48691. if (index >= 0)
  48692. colours.set (index, colour);
  48693. colourIds.add (colourId);
  48694. colours.add (colour);
  48695. }
  48696. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  48697. {
  48698. return colourIds.contains (colourId);
  48699. }
  48700. static LookAndFeel* defaultLF = 0;
  48701. static LookAndFeel* currentDefaultLF = 0;
  48702. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  48703. {
  48704. // if this happens, your app hasn't initialised itself properly.. if you're
  48705. // trying to hack your own main() function, have a look at
  48706. // JUCEApplication::initialiseForGUI()
  48707. jassert (currentDefaultLF != 0);
  48708. return *currentDefaultLF;
  48709. }
  48710. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  48711. {
  48712. if (newDefaultLookAndFeel == 0)
  48713. {
  48714. if (defaultLF == 0)
  48715. defaultLF = new LookAndFeel();
  48716. newDefaultLookAndFeel = defaultLF;
  48717. }
  48718. currentDefaultLF = newDefaultLookAndFeel;
  48719. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  48720. {
  48721. Component* const c = Desktop::getInstance().getComponent (i);
  48722. if (c != 0)
  48723. c->sendLookAndFeelChange();
  48724. }
  48725. }
  48726. void LookAndFeel::clearDefaultLookAndFeel() throw()
  48727. {
  48728. if (currentDefaultLF == defaultLF)
  48729. currentDefaultLF = 0;
  48730. deleteAndZero (defaultLF);
  48731. }
  48732. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  48733. {
  48734. String faceName (font.getTypefaceName());
  48735. if (faceName == Typeface::defaultTypefaceNameSans)
  48736. faceName = defaultSans;
  48737. else if (faceName == Typeface::defaultTypefaceNameSerif)
  48738. faceName = defaultSerif;
  48739. else if (faceName == Typeface::defaultTypefaceNameMono)
  48740. faceName = defaultFixed;
  48741. return new Typeface (faceName, font.isBold(), font.isItalic());
  48742. }
  48743. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  48744. {
  48745. defaultSans = newName;
  48746. }
  48747. void LookAndFeel::drawButtonBackground (Graphics& g,
  48748. Button& button,
  48749. const Colour& backgroundColour,
  48750. bool isMouseOverButton,
  48751. bool isButtonDown)
  48752. {
  48753. const int width = button.getWidth();
  48754. const int height = button.getHeight();
  48755. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  48756. const float halfThickness = outlineThickness * 0.5f;
  48757. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  48758. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  48759. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  48760. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  48761. const Colour baseColour (createBaseColour (backgroundColour,
  48762. button.hasKeyboardFocus (true),
  48763. isMouseOverButton, isButtonDown)
  48764. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48765. drawGlassLozenge (g,
  48766. indentL,
  48767. indentT,
  48768. width - indentL - indentR,
  48769. height - indentT - indentB,
  48770. baseColour, outlineThickness, -1.0f,
  48771. button.isConnectedOnLeft(),
  48772. button.isConnectedOnRight(),
  48773. button.isConnectedOnTop(),
  48774. button.isConnectedOnBottom());
  48775. }
  48776. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  48777. {
  48778. return button.getFont();
  48779. }
  48780. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  48781. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  48782. {
  48783. g.setFont (getFontForTextButton (button));
  48784. g.setColour (button.findColour (TextButton::textColourId)
  48785. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  48786. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  48787. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  48788. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  48789. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  48790. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  48791. g.drawFittedText (button.getButtonText(),
  48792. leftIndent,
  48793. yIndent,
  48794. button.getWidth() - leftIndent - rightIndent,
  48795. button.getHeight() - yIndent * 2,
  48796. Justification::centred, 2);
  48797. }
  48798. void LookAndFeel::drawTickBox (Graphics& g,
  48799. Component& component,
  48800. int x, int y, int w, int h,
  48801. const bool ticked,
  48802. const bool isEnabled,
  48803. const bool isMouseOverButton,
  48804. const bool isButtonDown)
  48805. {
  48806. const float boxSize = w * 0.7f;
  48807. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  48808. createBaseColour (component.findColour (TextButton::buttonColourId)
  48809. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  48810. true,
  48811. isMouseOverButton,
  48812. isButtonDown),
  48813. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  48814. if (ticked)
  48815. {
  48816. Path tick;
  48817. tick.startNewSubPath (1.5f, 3.0f);
  48818. tick.lineTo (3.0f, 6.0f);
  48819. tick.lineTo (6.0f, 0.0f);
  48820. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48821. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48822. .translated ((float) x, (float) y));
  48823. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48824. }
  48825. }
  48826. void LookAndFeel::drawToggleButton (Graphics& g,
  48827. ToggleButton& button,
  48828. bool isMouseOverButton,
  48829. bool isButtonDown)
  48830. {
  48831. if (button.hasKeyboardFocus (true))
  48832. {
  48833. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48834. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48835. }
  48836. const int tickWidth = jmin (20, button.getHeight() - 4);
  48837. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48838. tickWidth, tickWidth,
  48839. button.getToggleState(),
  48840. button.isEnabled(),
  48841. isMouseOverButton,
  48842. isButtonDown);
  48843. g.setColour (button.findColour (ToggleButton::textColourId));
  48844. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48845. if (! button.isEnabled())
  48846. g.setOpacity (0.5f);
  48847. const int textX = tickWidth + 5;
  48848. g.drawFittedText (button.getButtonText(),
  48849. textX, 4,
  48850. button.getWidth() - textX - 2, button.getHeight() - 8,
  48851. Justification::centredLeft, 10);
  48852. }
  48853. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  48854. {
  48855. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  48856. const int tickWidth = jmin (24, button.getHeight());
  48857. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  48858. button.getHeight());
  48859. }
  48860. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  48861. const String& message,
  48862. const String& button1,
  48863. const String& button2,
  48864. const String& button3,
  48865. AlertWindow::AlertIconType iconType,
  48866. int numButtons,
  48867. Component* associatedComponent)
  48868. {
  48869. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  48870. if (numButtons == 1)
  48871. {
  48872. aw->addButton (button1, 0,
  48873. KeyPress (KeyPress::escapeKey, 0, 0),
  48874. KeyPress (KeyPress::returnKey, 0, 0));
  48875. }
  48876. else
  48877. {
  48878. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  48879. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  48880. if (button1ShortCut == button2ShortCut)
  48881. button2ShortCut = KeyPress();
  48882. if (numButtons == 2)
  48883. {
  48884. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  48885. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  48886. }
  48887. else if (numButtons == 3)
  48888. {
  48889. aw->addButton (button1, 1, button1ShortCut);
  48890. aw->addButton (button2, 2, button2ShortCut);
  48891. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  48892. }
  48893. }
  48894. return aw;
  48895. }
  48896. void LookAndFeel::drawAlertBox (Graphics& g,
  48897. AlertWindow& alert,
  48898. const Rectangle& textArea,
  48899. TextLayout& textLayout)
  48900. {
  48901. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  48902. int iconSpaceUsed = 0;
  48903. Justification alignment (Justification::horizontallyCentred);
  48904. const int iconWidth = 80;
  48905. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  48906. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  48907. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  48908. const Rectangle iconRect (iconSize / -10, iconSize / -10,
  48909. iconSize, iconSize);
  48910. if (alert.getAlertType() != AlertWindow::NoIcon)
  48911. {
  48912. Path icon;
  48913. uint32 colour;
  48914. char character;
  48915. if (alert.getAlertType() == AlertWindow::WarningIcon)
  48916. {
  48917. colour = 0x55ff5555;
  48918. character = '!';
  48919. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  48920. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  48921. (float) iconRect.getX(), (float) iconRect.getBottom());
  48922. icon = icon.createPathWithRoundedCorners (5.0f);
  48923. }
  48924. else
  48925. {
  48926. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  48927. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  48928. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  48929. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  48930. }
  48931. GlyphArrangement ga;
  48932. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  48933. String::charToString (character),
  48934. (float) iconRect.getX(), (float) iconRect.getY(),
  48935. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  48936. Justification::centred, false);
  48937. ga.createPath (icon);
  48938. icon.setUsingNonZeroWinding (false);
  48939. g.setColour (Colour (colour));
  48940. g.fillPath (icon);
  48941. iconSpaceUsed = iconWidth;
  48942. alignment = Justification::left;
  48943. }
  48944. g.setColour (alert.findColour (AlertWindow::textColourId));
  48945. textLayout.drawWithin (g,
  48946. textArea.getX() + iconSpaceUsed, textArea.getY(),
  48947. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  48948. alignment.getFlags() | Justification::top);
  48949. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  48950. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  48951. }
  48952. int LookAndFeel::getAlertBoxWindowFlags()
  48953. {
  48954. return ComponentPeer::windowAppearsOnTaskbar
  48955. | ComponentPeer::windowHasDropShadow;
  48956. }
  48957. int LookAndFeel::getAlertWindowButtonHeight()
  48958. {
  48959. return 28;
  48960. }
  48961. const Font LookAndFeel::getAlertWindowFont()
  48962. {
  48963. return Font (12.0f);
  48964. }
  48965. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48966. int width, int height,
  48967. double progress, const String& textToShow)
  48968. {
  48969. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48970. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48971. g.fillAll (background);
  48972. if (progress >= 0.0f && progress < 1.0f)
  48973. {
  48974. drawGlassLozenge (g, 1.0f, 1.0f,
  48975. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  48976. (float) (height - 2),
  48977. foreground,
  48978. 0.5f, 0.0f,
  48979. true, true, true, true);
  48980. }
  48981. else
  48982. {
  48983. // spinning bar..
  48984. g.setColour (foreground);
  48985. const int stripeWidth = height * 2;
  48986. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  48987. Path p;
  48988. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  48989. p.addQuadrilateral (x, 0.0f,
  48990. x + stripeWidth * 0.5f, 0.0f,
  48991. x, (float) height,
  48992. x - stripeWidth * 0.5f, (float) height);
  48993. Image im (Image::ARGB, width, height, true);
  48994. {
  48995. Graphics g (im);
  48996. drawGlassLozenge (g, 1.0f, 1.0f,
  48997. (float) (width - 2),
  48998. (float) (height - 2),
  48999. foreground,
  49000. 0.5f, 0.0f,
  49001. true, true, true, true);
  49002. }
  49003. ImageBrush ib (&im, 0, 0, 0.85f);
  49004. g.setBrush (&ib);
  49005. g.fillPath (p);
  49006. }
  49007. if (textToShow.isNotEmpty())
  49008. {
  49009. g.setColour (Colour::contrasting (background, foreground));
  49010. g.setFont (height * 0.6f);
  49011. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49012. }
  49013. }
  49014. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, int x, int y, int w, int h)
  49015. {
  49016. const float radius = jmin (w, h) * 0.4f;
  49017. const float thickness = radius * 0.15f;
  49018. Path p;
  49019. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  49020. radius * 0.6f, thickness,
  49021. thickness * 0.5f);
  49022. const float cx = x + w * 0.5f;
  49023. const float cy = y + h * 0.5f;
  49024. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  49025. const Colour col (g.getCurrentColour());
  49026. for (int i = 0; i < 12; ++i)
  49027. {
  49028. const int n = (i + 12 - animationIndex) % 12;
  49029. g.setColour (col.withMultipliedAlpha ((n + 1) / 12.0f));
  49030. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  49031. .translated (cx, cy));
  49032. }
  49033. }
  49034. void LookAndFeel::drawScrollbarButton (Graphics& g,
  49035. ScrollBar& scrollbar,
  49036. int width, int height,
  49037. int buttonDirection,
  49038. bool /*isScrollbarVertical*/,
  49039. bool /*isMouseOverButton*/,
  49040. bool isButtonDown)
  49041. {
  49042. Path p;
  49043. if (buttonDirection == 0)
  49044. p.addTriangle (width * 0.5f, height * 0.2f,
  49045. width * 0.1f, height * 0.7f,
  49046. width * 0.9f, height * 0.7f);
  49047. else if (buttonDirection == 1)
  49048. p.addTriangle (width * 0.8f, height * 0.5f,
  49049. width * 0.3f, height * 0.1f,
  49050. width * 0.3f, height * 0.9f);
  49051. else if (buttonDirection == 2)
  49052. p.addTriangle (width * 0.5f, height * 0.8f,
  49053. width * 0.1f, height * 0.3f,
  49054. width * 0.9f, height * 0.3f);
  49055. else if (buttonDirection == 3)
  49056. p.addTriangle (width * 0.2f, height * 0.5f,
  49057. width * 0.7f, height * 0.1f,
  49058. width * 0.7f, height * 0.9f);
  49059. if (isButtonDown)
  49060. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  49061. else
  49062. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  49063. g.fillPath (p);
  49064. g.setColour (Colour (0x80000000));
  49065. g.strokePath (p, PathStrokeType (0.5f));
  49066. }
  49067. void LookAndFeel::drawScrollbar (Graphics& g,
  49068. ScrollBar& scrollbar,
  49069. int x, int y,
  49070. int width, int height,
  49071. bool isScrollbarVertical,
  49072. int thumbStartPosition,
  49073. int thumbSize,
  49074. bool /*isMouseOver*/,
  49075. bool /*isMouseDown*/)
  49076. {
  49077. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  49078. Path slotPath, thumbPath;
  49079. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  49080. const float slotIndentx2 = slotIndent * 2.0f;
  49081. const float thumbIndent = slotIndent + 1.0f;
  49082. const float thumbIndentx2 = thumbIndent * 2.0f;
  49083. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  49084. if (isScrollbarVertical)
  49085. {
  49086. slotPath.addRoundedRectangle (x + slotIndent,
  49087. y + slotIndent,
  49088. width - slotIndentx2,
  49089. height - slotIndentx2,
  49090. (width - slotIndentx2) * 0.5f);
  49091. if (thumbSize > 0)
  49092. thumbPath.addRoundedRectangle (x + thumbIndent,
  49093. thumbStartPosition + thumbIndent,
  49094. width - thumbIndentx2,
  49095. thumbSize - thumbIndentx2,
  49096. (width - thumbIndentx2) * 0.5f);
  49097. gx1 = (float) x;
  49098. gx2 = x + width * 0.7f;
  49099. }
  49100. else
  49101. {
  49102. slotPath.addRoundedRectangle (x + slotIndent,
  49103. y + slotIndent,
  49104. width - slotIndentx2,
  49105. height - slotIndentx2,
  49106. (height - slotIndentx2) * 0.5f);
  49107. if (thumbSize > 0)
  49108. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  49109. y + thumbIndent,
  49110. thumbSize - thumbIndentx2,
  49111. height - thumbIndentx2,
  49112. (height - thumbIndentx2) * 0.5f);
  49113. gy1 = (float) y;
  49114. gy2 = y + height * 0.7f;
  49115. }
  49116. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  49117. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  49118. gx1, gy1,
  49119. thumbColour.overlaidWith (Colour (0x19000000)),
  49120. gx2, gy2, false);
  49121. g.setBrush (&gb);
  49122. g.fillPath (slotPath);
  49123. if (isScrollbarVertical)
  49124. {
  49125. gx1 = x + width * 0.6f;
  49126. gx2 = (float) x + width;
  49127. }
  49128. else
  49129. {
  49130. gy1 = y + height * 0.6f;
  49131. gy2 = (float) y + height;
  49132. }
  49133. GradientBrush gb2 (Colours::transparentBlack,
  49134. gx1, gy1,
  49135. Colour (0x19000000),
  49136. gx2, gy2, false);
  49137. g.setBrush (&gb2);
  49138. g.fillPath (slotPath);
  49139. g.setColour (thumbColour);
  49140. g.fillPath (thumbPath);
  49141. GradientBrush gb3 (Colour (0x10000000),
  49142. gx1, gy1,
  49143. Colours::transparentBlack,
  49144. gx2, gy2, false);
  49145. g.saveState();
  49146. g.setBrush (&gb3);
  49147. if (isScrollbarVertical)
  49148. g.reduceClipRegion (x + width / 2, y, width, height);
  49149. else
  49150. g.reduceClipRegion (x, y + height / 2, width, height);
  49151. g.fillPath (thumbPath);
  49152. g.restoreState();
  49153. g.setColour (Colour (0x4c000000));
  49154. g.strokePath (thumbPath, PathStrokeType (0.4f));
  49155. }
  49156. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  49157. {
  49158. return 0;
  49159. }
  49160. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  49161. {
  49162. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  49163. }
  49164. int LookAndFeel::getDefaultScrollbarWidth()
  49165. {
  49166. return 18;
  49167. }
  49168. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  49169. {
  49170. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  49171. : scrollbar.getHeight());
  49172. }
  49173. const Path LookAndFeel::getTickShape (const float height)
  49174. {
  49175. static const unsigned char tickShapeData[] =
  49176. {
  49177. 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,
  49178. 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,
  49179. 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,
  49180. 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,
  49181. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  49182. };
  49183. Path p;
  49184. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  49185. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49186. return p;
  49187. }
  49188. const Path LookAndFeel::getCrossShape (const float height)
  49189. {
  49190. static const unsigned char crossShapeData[] =
  49191. {
  49192. 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,
  49193. 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,
  49194. 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,
  49195. 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,
  49196. 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,
  49197. 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,
  49198. 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
  49199. };
  49200. Path p;
  49201. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  49202. p.scaleToFit (0, 0, height * 2.0f, height, true);
  49203. return p;
  49204. }
  49205. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  49206. {
  49207. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  49208. x += (w - boxSize) >> 1;
  49209. y += (h - boxSize) >> 1;
  49210. w = boxSize;
  49211. h = boxSize;
  49212. g.setColour (Colour (0xe5ffffff));
  49213. g.fillRect (x, y, w, h);
  49214. g.setColour (Colour (0x80000000));
  49215. g.drawRect (x, y, w, h);
  49216. const float size = boxSize / 2 + 1.0f;
  49217. const float centre = (float) (boxSize / 2);
  49218. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  49219. if (isPlus)
  49220. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  49221. }
  49222. void LookAndFeel::drawBubble (Graphics& g,
  49223. float tipX, float tipY,
  49224. float boxX, float boxY,
  49225. float boxW, float boxH)
  49226. {
  49227. int side = 0;
  49228. if (tipX < boxX)
  49229. side = 1;
  49230. else if (tipX > boxX + boxW)
  49231. side = 3;
  49232. else if (tipY > boxY + boxH)
  49233. side = 2;
  49234. const float indent = 2.0f;
  49235. Path p;
  49236. p.addBubble (boxX + indent,
  49237. boxY + indent,
  49238. boxW - indent * 2.0f,
  49239. boxH - indent * 2.0f,
  49240. 5.0f,
  49241. tipX, tipY,
  49242. side,
  49243. 0.5f,
  49244. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  49245. //xxx need to take comp as param for colour
  49246. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  49247. g.fillPath (p);
  49248. //xxx as above
  49249. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  49250. g.strokePath (p, PathStrokeType (1.33f));
  49251. }
  49252. const Font LookAndFeel::getPopupMenuFont()
  49253. {
  49254. return Font (17.0f);
  49255. }
  49256. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  49257. const bool isSeparator,
  49258. int standardMenuItemHeight,
  49259. int& idealWidth,
  49260. int& idealHeight)
  49261. {
  49262. if (isSeparator)
  49263. {
  49264. idealWidth = 50;
  49265. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  49266. }
  49267. else
  49268. {
  49269. Font font (getPopupMenuFont());
  49270. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  49271. font.setHeight (standardMenuItemHeight / 1.3f);
  49272. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  49273. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  49274. }
  49275. }
  49276. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49277. {
  49278. const Colour background (findColour (PopupMenu::backgroundColourId));
  49279. g.fillAll (background);
  49280. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  49281. for (int i = 0; i < height; i += 3)
  49282. g.fillRect (0, i, width, 1);
  49283. #if ! JUCE_MAC
  49284. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  49285. g.drawRect (0, 0, width, height);
  49286. #endif
  49287. }
  49288. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  49289. int width, int height,
  49290. bool isScrollUpArrow)
  49291. {
  49292. const Colour background (findColour (PopupMenu::backgroundColourId));
  49293. GradientBrush gb (background,
  49294. 0.0f, height * 0.5f,
  49295. background.withAlpha (0.0f),
  49296. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  49297. false);
  49298. g.setBrush (&gb);
  49299. g.fillRect (1, 1, width - 2, height - 2);
  49300. const float hw = width * 0.5f;
  49301. const float arrowW = height * 0.3f;
  49302. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  49303. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  49304. Path p;
  49305. p.addTriangle (hw - arrowW, y1,
  49306. hw + arrowW, y1,
  49307. hw, y2);
  49308. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  49309. g.fillPath (p);
  49310. }
  49311. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  49312. int width, int height,
  49313. const bool isSeparator,
  49314. const bool isActive,
  49315. const bool isHighlighted,
  49316. const bool isTicked,
  49317. const bool hasSubMenu,
  49318. const String& text,
  49319. const String& shortcutKeyText,
  49320. Image* image,
  49321. const Colour* const textColourToUse)
  49322. {
  49323. const float halfH = height * 0.5f;
  49324. if (isSeparator)
  49325. {
  49326. const float separatorIndent = 5.5f;
  49327. g.setColour (Colour (0x33000000));
  49328. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  49329. g.setColour (Colour (0x66ffffff));
  49330. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  49331. }
  49332. else
  49333. {
  49334. Colour textColour (findColour (PopupMenu::textColourId));
  49335. if (textColourToUse != 0)
  49336. textColour = *textColourToUse;
  49337. if (isHighlighted)
  49338. {
  49339. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  49340. g.fillRect (1, 1, width - 2, height - 2);
  49341. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  49342. }
  49343. else
  49344. {
  49345. g.setColour (textColour);
  49346. }
  49347. if (! isActive)
  49348. g.setOpacity (0.3f);
  49349. Font font (getPopupMenuFont());
  49350. if (font.getHeight() > height / 1.3f)
  49351. font.setHeight (height / 1.3f);
  49352. g.setFont (font);
  49353. const int leftBorder = (height * 5) / 4;
  49354. const int rightBorder = 4;
  49355. if (image != 0)
  49356. {
  49357. g.drawImageWithin (image,
  49358. 2, 1, leftBorder - 4, height - 2,
  49359. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  49360. }
  49361. else if (isTicked)
  49362. {
  49363. const Path tick (getTickShape (1.0f));
  49364. const float th = font.getAscent();
  49365. const float ty = halfH - th * 0.5f;
  49366. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  49367. th, true));
  49368. }
  49369. g.drawFittedText (text,
  49370. leftBorder, 0,
  49371. width - (leftBorder + rightBorder), height,
  49372. Justification::centredLeft, 1);
  49373. if (shortcutKeyText.isNotEmpty())
  49374. {
  49375. Font f2 (g.getCurrentFont());
  49376. f2.setHeight (f2.getHeight() * 0.75f);
  49377. f2.setHorizontalScale (0.95f);
  49378. g.setFont (f2);
  49379. g.drawText (shortcutKeyText,
  49380. leftBorder,
  49381. 0,
  49382. width - (leftBorder + rightBorder + 4),
  49383. height,
  49384. Justification::centredRight,
  49385. true);
  49386. }
  49387. if (hasSubMenu)
  49388. {
  49389. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  49390. const float x = width - height * 0.6f;
  49391. Path p;
  49392. p.addTriangle (x, halfH - arrowH * 0.5f,
  49393. x, halfH + arrowH * 0.5f,
  49394. x + arrowH * 0.6f, halfH);
  49395. g.fillPath (p);
  49396. }
  49397. }
  49398. }
  49399. int LookAndFeel::getMenuWindowFlags()
  49400. {
  49401. return ComponentPeer::windowHasDropShadow;
  49402. }
  49403. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  49404. bool, MenuBarComponent& menuBar)
  49405. {
  49406. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  49407. if (menuBar.isEnabled())
  49408. {
  49409. drawShinyButtonShape (g,
  49410. -4.0f, 0.0f,
  49411. width + 8.0f, (float) height,
  49412. 0.0f,
  49413. baseColour,
  49414. 0.4f,
  49415. true, true, true, true);
  49416. }
  49417. else
  49418. {
  49419. g.fillAll (baseColour);
  49420. }
  49421. }
  49422. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  49423. {
  49424. return Font (menuBar.getHeight() * 0.7f);
  49425. }
  49426. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  49427. {
  49428. return getMenuBarFont (menuBar, itemIndex, itemText)
  49429. .getStringWidth (itemText) + menuBar.getHeight();
  49430. }
  49431. void LookAndFeel::drawMenuBarItem (Graphics& g,
  49432. int width, int height,
  49433. int itemIndex,
  49434. const String& itemText,
  49435. bool isMouseOverItem,
  49436. bool isMenuOpen,
  49437. bool /*isMouseOverBar*/,
  49438. MenuBarComponent& menuBar)
  49439. {
  49440. if (! menuBar.isEnabled())
  49441. {
  49442. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  49443. .withMultipliedAlpha (0.5f));
  49444. }
  49445. else if (isMenuOpen || isMouseOverItem)
  49446. {
  49447. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  49448. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  49449. }
  49450. else
  49451. {
  49452. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  49453. }
  49454. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  49455. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  49456. }
  49457. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  49458. TextEditor& textEditor)
  49459. {
  49460. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  49461. }
  49462. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49463. {
  49464. if (textEditor.isEnabled())
  49465. {
  49466. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  49467. {
  49468. const int border = 2;
  49469. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  49470. g.drawRect (0, 0, width, height, border);
  49471. g.setOpacity (1.0f);
  49472. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  49473. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  49474. }
  49475. else
  49476. {
  49477. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49478. g.drawRect (0, 0, width, height);
  49479. g.setOpacity (1.0f);
  49480. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  49481. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  49482. }
  49483. }
  49484. }
  49485. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49486. const bool isButtonDown,
  49487. int buttonX, int buttonY,
  49488. int buttonW, int buttonH,
  49489. ComboBox& box)
  49490. {
  49491. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49492. if (box.isEnabled() && box.hasKeyboardFocus (false))
  49493. {
  49494. g.setColour (box.findColour (TextButton::buttonColourId));
  49495. g.drawRect (0, 0, width, height, 2);
  49496. }
  49497. else
  49498. {
  49499. g.setColour (box.findColour (ComboBox::outlineColourId));
  49500. g.drawRect (0, 0, width, height);
  49501. }
  49502. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  49503. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  49504. box.hasKeyboardFocus (true),
  49505. false, isButtonDown)
  49506. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  49507. drawGlassLozenge (g,
  49508. buttonX + outlineThickness, buttonY + outlineThickness,
  49509. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  49510. baseColour, outlineThickness, -1.0f,
  49511. true, true, true, true);
  49512. if (box.isEnabled())
  49513. {
  49514. const float arrowX = 0.3f;
  49515. const float arrowH = 0.2f;
  49516. Path p;
  49517. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49518. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49519. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49520. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49521. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49522. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49523. g.setColour (box.findColour (ComboBox::arrowColourId));
  49524. g.fillPath (p);
  49525. }
  49526. }
  49527. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  49528. {
  49529. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  49530. }
  49531. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  49532. {
  49533. return new Label (String::empty, String::empty);
  49534. }
  49535. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  49536. {
  49537. label.setBounds (1, 1,
  49538. box.getWidth() + 3 - box.getHeight(),
  49539. box.getHeight() - 2);
  49540. label.setFont (getComboBoxFont (box));
  49541. }
  49542. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  49543. {
  49544. g.fillAll (label.findColour (Label::backgroundColourId));
  49545. if (! label.isBeingEdited())
  49546. {
  49547. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  49548. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  49549. g.setFont (label.getFont());
  49550. g.drawFittedText (label.getText(),
  49551. label.getHorizontalBorderSize(),
  49552. label.getVerticalBorderSize(),
  49553. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  49554. label.getHeight() - 2 * label.getVerticalBorderSize(),
  49555. label.getJustificationType(),
  49556. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  49557. label.getMinimumHorizontalScale());
  49558. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  49559. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49560. }
  49561. else if (label.isEnabled())
  49562. {
  49563. g.setColour (label.findColour (Label::outlineColourId));
  49564. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  49565. }
  49566. }
  49567. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  49568. int x, int y,
  49569. int width, int height,
  49570. float /*sliderPos*/,
  49571. float /*minSliderPos*/,
  49572. float /*maxSliderPos*/,
  49573. const Slider::SliderStyle /*style*/,
  49574. Slider& slider)
  49575. {
  49576. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49577. const Colour trackColour (slider.findColour (Slider::trackColourId));
  49578. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  49579. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  49580. Path indent;
  49581. if (slider.isHorizontal())
  49582. {
  49583. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  49584. const float ih = sliderRadius;
  49585. GradientBrush gb (gradCol1, 0.0f, iy,
  49586. gradCol2, 0.0f, iy + ih, false);
  49587. g.setBrush (&gb);
  49588. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  49589. width + sliderRadius, ih,
  49590. 5.0f);
  49591. g.fillPath (indent);
  49592. }
  49593. else
  49594. {
  49595. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  49596. const float iw = sliderRadius;
  49597. GradientBrush gb (gradCol1, ix, 0.0f,
  49598. gradCol2, ix + iw, 0.0f, false);
  49599. g.setBrush (&gb);
  49600. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  49601. iw, height + sliderRadius,
  49602. 5.0f);
  49603. g.fillPath (indent);
  49604. }
  49605. g.setColour (Colour (0x4c000000));
  49606. g.strokePath (indent, PathStrokeType (0.5f));
  49607. }
  49608. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  49609. int x, int y,
  49610. int width, int height,
  49611. float sliderPos,
  49612. float minSliderPos,
  49613. float maxSliderPos,
  49614. const Slider::SliderStyle style,
  49615. Slider& slider)
  49616. {
  49617. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  49618. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  49619. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  49620. slider.isMouseOverOrDragging() && slider.isEnabled(),
  49621. slider.isMouseButtonDown() && slider.isEnabled()));
  49622. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  49623. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  49624. {
  49625. float kx, ky;
  49626. if (style == Slider::LinearVertical)
  49627. {
  49628. kx = x + width * 0.5f;
  49629. ky = sliderPos;
  49630. }
  49631. else
  49632. {
  49633. kx = sliderPos;
  49634. ky = y + height * 0.5f;
  49635. }
  49636. drawGlassSphere (g,
  49637. kx - sliderRadius,
  49638. ky - sliderRadius,
  49639. sliderRadius * 2.0f,
  49640. knobColour, outlineThickness);
  49641. }
  49642. else
  49643. {
  49644. if (style == Slider::ThreeValueVertical)
  49645. {
  49646. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  49647. sliderPos - sliderRadius,
  49648. sliderRadius * 2.0f,
  49649. knobColour, outlineThickness);
  49650. }
  49651. else if (style == Slider::ThreeValueHorizontal)
  49652. {
  49653. drawGlassSphere (g,sliderPos - sliderRadius,
  49654. y + height * 0.5f - sliderRadius,
  49655. sliderRadius * 2.0f,
  49656. knobColour, outlineThickness);
  49657. }
  49658. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  49659. {
  49660. const float sr = jmin (sliderRadius, width * 0.4f);
  49661. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  49662. minSliderPos - sliderRadius,
  49663. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  49664. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  49665. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  49666. }
  49667. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  49668. {
  49669. const float sr = jmin (sliderRadius, height * 0.4f);
  49670. drawGlassPointer (g, minSliderPos - sr,
  49671. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  49672. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  49673. drawGlassPointer (g, maxSliderPos - sliderRadius,
  49674. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  49675. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  49676. }
  49677. }
  49678. }
  49679. void LookAndFeel::drawLinearSlider (Graphics& g,
  49680. int x, int y,
  49681. int width, int height,
  49682. float sliderPos,
  49683. float minSliderPos,
  49684. float maxSliderPos,
  49685. const Slider::SliderStyle style,
  49686. Slider& slider)
  49687. {
  49688. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49689. if (style == Slider::LinearBar)
  49690. {
  49691. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49692. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  49693. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  49694. false,
  49695. isMouseOver,
  49696. isMouseOver || slider.isMouseButtonDown()));
  49697. drawShinyButtonShape (g,
  49698. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  49699. baseColour,
  49700. slider.isEnabled() ? 0.9f : 0.3f,
  49701. true, true, true, true);
  49702. }
  49703. else
  49704. {
  49705. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49706. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  49707. }
  49708. }
  49709. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  49710. {
  49711. return jmin (7,
  49712. slider.getHeight() / 2,
  49713. slider.getWidth() / 2) + 2;
  49714. }
  49715. void LookAndFeel::drawRotarySlider (Graphics& g,
  49716. int x, int y,
  49717. int width, int height,
  49718. float sliderPos,
  49719. const float rotaryStartAngle,
  49720. const float rotaryEndAngle,
  49721. Slider& slider)
  49722. {
  49723. const float radius = jmin (width / 2, height / 2) - 2.0f;
  49724. const float centreX = x + width * 0.5f;
  49725. const float centreY = y + height * 0.5f;
  49726. const float rx = centreX - radius;
  49727. const float ry = centreY - radius;
  49728. const float rw = radius * 2.0f;
  49729. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  49730. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  49731. if (radius > 12.0f)
  49732. {
  49733. if (slider.isEnabled())
  49734. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49735. else
  49736. g.setColour (Colour (0x80808080));
  49737. const float thickness = 0.7f;
  49738. {
  49739. Path filledArc;
  49740. filledArc.addPieSegment (rx, ry, rw, rw,
  49741. rotaryStartAngle,
  49742. angle,
  49743. thickness);
  49744. g.fillPath (filledArc);
  49745. }
  49746. if (thickness > 0)
  49747. {
  49748. const float innerRadius = radius * 0.2f;
  49749. Path p;
  49750. p.addTriangle (-innerRadius, 0.0f,
  49751. 0.0f, -radius * thickness * 1.1f,
  49752. innerRadius, 0.0f);
  49753. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  49754. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49755. }
  49756. if (slider.isEnabled())
  49757. {
  49758. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  49759. Path outlineArc;
  49760. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  49761. outlineArc.closeSubPath();
  49762. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  49763. }
  49764. }
  49765. else
  49766. {
  49767. if (slider.isEnabled())
  49768. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  49769. else
  49770. g.setColour (Colour (0x80808080));
  49771. Path p;
  49772. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  49773. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  49774. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  49775. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  49776. }
  49777. }
  49778. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  49779. {
  49780. return new TextButton (isIncrement ? "+" : "-", String::empty);
  49781. }
  49782. class SliderLabelComp : public Label
  49783. {
  49784. public:
  49785. SliderLabelComp() : Label (String::empty, String::empty) {}
  49786. ~SliderLabelComp() {}
  49787. void mouseWheelMove (const MouseEvent&, float, float) {}
  49788. };
  49789. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  49790. {
  49791. Label* const l = new SliderLabelComp();
  49792. l->setJustificationType (Justification::centred);
  49793. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49794. l->setColour (Label::backgroundColourId,
  49795. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  49796. : slider.findColour (Slider::textBoxBackgroundColourId));
  49797. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49798. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  49799. l->setColour (TextEditor::backgroundColourId,
  49800. slider.findColour (Slider::textBoxBackgroundColourId)
  49801. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  49802. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  49803. return l;
  49804. }
  49805. ImageEffectFilter* LookAndFeel::getSliderEffect()
  49806. {
  49807. return 0;
  49808. }
  49809. static const TextLayout layoutTooltipText (const String& text) throw()
  49810. {
  49811. const float tooltipFontSize = 12.0f;
  49812. const int maxToolTipWidth = 400;
  49813. const Font f (tooltipFontSize, Font::bold);
  49814. TextLayout tl (text, f);
  49815. tl.layout (maxToolTipWidth, Justification::left, true);
  49816. return tl;
  49817. }
  49818. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  49819. {
  49820. const TextLayout tl (layoutTooltipText (tipText));
  49821. width = tl.getWidth() + 14;
  49822. height = tl.getHeight() + 6;
  49823. }
  49824. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  49825. {
  49826. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  49827. const Colour textCol (findColour (TooltipWindow::textColourId));
  49828. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  49829. g.setColour (findColour (TooltipWindow::outlineColourId));
  49830. g.drawRect (0, 0, width, height, 1);
  49831. #endif
  49832. const TextLayout tl (layoutTooltipText (text));
  49833. g.setColour (findColour (TooltipWindow::textColourId));
  49834. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  49835. }
  49836. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  49837. {
  49838. return new TextButton (text, TRANS("click to browse for a different file"));
  49839. }
  49840. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  49841. ComboBox* filenameBox,
  49842. Button* browseButton)
  49843. {
  49844. browseButton->setSize (80, filenameComp.getHeight());
  49845. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  49846. if (tb != 0)
  49847. tb->changeWidthToFitText();
  49848. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  49849. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  49850. }
  49851. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  49852. int imageX, int imageY, int imageW, int imageH,
  49853. const Colour& overlayColour,
  49854. float imageOpacity,
  49855. ImageButton& button)
  49856. {
  49857. if (! button.isEnabled())
  49858. imageOpacity *= 0.3f;
  49859. if (! overlayColour.isOpaque())
  49860. {
  49861. g.setOpacity (imageOpacity);
  49862. g.drawImage (image, imageX, imageY, imageW, imageH,
  49863. 0, 0, image->getWidth(), image->getHeight(), false);
  49864. }
  49865. if (! overlayColour.isTransparent())
  49866. {
  49867. g.setColour (overlayColour);
  49868. g.drawImage (image, imageX, imageY, imageW, imageH,
  49869. 0, 0, image->getWidth(), image->getHeight(), true);
  49870. }
  49871. }
  49872. void LookAndFeel::drawCornerResizer (Graphics& g,
  49873. int w, int h,
  49874. bool /*isMouseOver*/,
  49875. bool /*isMouseDragging*/)
  49876. {
  49877. const float lineThickness = jmin (w, h) * 0.075f;
  49878. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  49879. {
  49880. g.setColour (Colours::lightgrey);
  49881. g.drawLine (w * i,
  49882. h + 1.0f,
  49883. w + 1.0f,
  49884. h * i,
  49885. lineThickness);
  49886. g.setColour (Colours::darkgrey);
  49887. g.drawLine (w * i + lineThickness,
  49888. h + 1.0f,
  49889. w + 1.0f,
  49890. h * i + lineThickness,
  49891. lineThickness);
  49892. }
  49893. }
  49894. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  49895. const BorderSize& /*borders*/)
  49896. {
  49897. }
  49898. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  49899. const BorderSize& /*border*/, ResizableWindow& window)
  49900. {
  49901. g.fillAll (window.getBackgroundColour());
  49902. }
  49903. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  49904. const BorderSize& border, ResizableWindow&)
  49905. {
  49906. g.setColour (Colour (0x80000000));
  49907. g.drawRect (0, 0, w, h);
  49908. g.setColour (Colour (0x19000000));
  49909. g.drawRect (border.getLeft() - 1,
  49910. border.getTop() - 1,
  49911. w + 2 - border.getLeftAndRight(),
  49912. h + 2 - border.getTopAndBottom());
  49913. }
  49914. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  49915. Graphics& g, int w, int h,
  49916. int titleSpaceX, int titleSpaceW,
  49917. const Image* icon,
  49918. bool drawTitleTextOnLeft)
  49919. {
  49920. const bool isActive = window.isActiveWindow();
  49921. GradientBrush gb (window.getBackgroundColour(),
  49922. 0.0f, 0.0f,
  49923. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  49924. 0.0f, (float) h, false);
  49925. g.setBrush (&gb);
  49926. g.fillAll();
  49927. g.setFont (h * 0.65f, Font::bold);
  49928. int textW = g.getCurrentFont().getStringWidth (window.getName());
  49929. int iconW = 0;
  49930. int iconH = 0;
  49931. if (icon != 0)
  49932. {
  49933. iconH = (int) g.getCurrentFont().getHeight();
  49934. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  49935. }
  49936. textW = jmin (titleSpaceW, textW + iconW);
  49937. int textX = drawTitleTextOnLeft ? titleSpaceX
  49938. : jmax (titleSpaceX, (w - textW) / 2);
  49939. if (textX + textW > titleSpaceX + titleSpaceW)
  49940. textX = titleSpaceX + titleSpaceW - textW;
  49941. if (icon != 0)
  49942. {
  49943. g.setOpacity (isActive ? 1.0f : 0.6f);
  49944. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  49945. RectanglePlacement::centred, false);
  49946. textX += iconW;
  49947. textW -= iconW;
  49948. }
  49949. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  49950. g.setColour (findColour (DocumentWindow::textColourId));
  49951. else
  49952. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  49953. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  49954. }
  49955. class GlassWindowButton : public Button
  49956. {
  49957. public:
  49958. GlassWindowButton (const String& name, const Colour& col,
  49959. const Path& normalShape_,
  49960. const Path& toggledShape_) throw()
  49961. : Button (name),
  49962. colour (col),
  49963. normalShape (normalShape_),
  49964. toggledShape (toggledShape_)
  49965. {
  49966. }
  49967. ~GlassWindowButton()
  49968. {
  49969. }
  49970. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  49971. {
  49972. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  49973. if (! isEnabled())
  49974. alpha *= 0.5f;
  49975. float x = 0, y = 0, diam;
  49976. if (getWidth() < getHeight())
  49977. {
  49978. diam = (float) getWidth();
  49979. y = (getHeight() - getWidth()) * 0.5f;
  49980. }
  49981. else
  49982. {
  49983. diam = (float) getHeight();
  49984. y = (getWidth() - getHeight()) * 0.5f;
  49985. }
  49986. x += diam * 0.05f;
  49987. y += diam * 0.05f;
  49988. diam *= 0.9f;
  49989. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  49990. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  49991. g.setBrush (&gb1);
  49992. g.fillEllipse (x, y, diam, diam);
  49993. x += 2.0f;
  49994. y += 2.0f;
  49995. diam -= 4.0f;
  49996. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  49997. Path& p = getToggleState() ? toggledShape : normalShape;
  49998. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  49999. diam * 0.4f, diam * 0.4f, true));
  50000. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  50001. g.fillPath (p, t);
  50002. }
  50003. juce_UseDebuggingNewOperator
  50004. private:
  50005. Colour colour;
  50006. Path normalShape, toggledShape;
  50007. GlassWindowButton (const GlassWindowButton&);
  50008. const GlassWindowButton& operator= (const GlassWindowButton&);
  50009. };
  50010. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  50011. {
  50012. Path shape;
  50013. const float crossThickness = 0.25f;
  50014. if (buttonType == DocumentWindow::closeButton)
  50015. {
  50016. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  50017. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  50018. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  50019. }
  50020. else if (buttonType == DocumentWindow::minimiseButton)
  50021. {
  50022. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50023. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  50024. }
  50025. else if (buttonType == DocumentWindow::maximiseButton)
  50026. {
  50027. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  50028. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  50029. Path fullscreenShape;
  50030. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  50031. fullscreenShape.lineTo (0.0f, 100.0f);
  50032. fullscreenShape.lineTo (0.0f, 0.0f);
  50033. fullscreenShape.lineTo (100.0f, 0.0f);
  50034. fullscreenShape.lineTo (100.0f, 45.0f);
  50035. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  50036. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  50037. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  50038. }
  50039. jassertfalse
  50040. return 0;
  50041. }
  50042. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50043. int titleBarX,
  50044. int titleBarY,
  50045. int titleBarW,
  50046. int titleBarH,
  50047. Button* minimiseButton,
  50048. Button* maximiseButton,
  50049. Button* closeButton,
  50050. bool positionTitleBarButtonsOnLeft)
  50051. {
  50052. const int buttonW = titleBarH - titleBarH / 8;
  50053. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50054. : titleBarX + titleBarW - buttonW - buttonW / 4;
  50055. if (closeButton != 0)
  50056. {
  50057. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50058. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  50059. }
  50060. if (positionTitleBarButtonsOnLeft)
  50061. swapVariables (minimiseButton, maximiseButton);
  50062. if (maximiseButton != 0)
  50063. {
  50064. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50065. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50066. }
  50067. if (minimiseButton != 0)
  50068. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50069. }
  50070. int LookAndFeel::getDefaultMenuBarHeight()
  50071. {
  50072. return 24;
  50073. }
  50074. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  50075. {
  50076. return new DropShadower (0.4f, 1, 5, 10);
  50077. }
  50078. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  50079. int w, int h,
  50080. bool /*isVerticalBar*/,
  50081. bool isMouseOver,
  50082. bool isMouseDragging)
  50083. {
  50084. float alpha = 0.5f;
  50085. if (isMouseOver || isMouseDragging)
  50086. {
  50087. g.fillAll (Colour (0x190000ff));
  50088. alpha = 1.0f;
  50089. }
  50090. const float cx = w * 0.5f;
  50091. const float cy = h * 0.5f;
  50092. const float cr = jmin (w, h) * 0.4f;
  50093. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  50094. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  50095. true);
  50096. g.setBrush (&gb);
  50097. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  50098. }
  50099. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  50100. const String& text,
  50101. const Justification& position,
  50102. GroupComponent& group)
  50103. {
  50104. const float textH = 15.0f;
  50105. const float indent = 3.0f;
  50106. const float textEdgeGap = 4.0f;
  50107. float cs = 5.0f;
  50108. Font f (textH);
  50109. Path p;
  50110. float x = indent;
  50111. float y = f.getAscent() - 3.0f;
  50112. float w = jmax (0.0f, width - x * 2.0f);
  50113. float h = jmax (0.0f, height - y - indent);
  50114. cs = jmin (cs, w * 0.5f, h * 0.5f);
  50115. const float cs2 = 2.0f * cs;
  50116. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  50117. float textX = cs + textEdgeGap;
  50118. if (position.testFlags (Justification::horizontallyCentred))
  50119. textX = cs + (w - cs2 - textW) * 0.5f;
  50120. else if (position.testFlags (Justification::right))
  50121. textX = w - cs - textW - textEdgeGap;
  50122. p.startNewSubPath (x + textX + textW, y);
  50123. p.lineTo (x + w - cs, y);
  50124. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  50125. p.lineTo (x + w, y + h - cs);
  50126. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50127. p.lineTo (x + cs, y + h);
  50128. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50129. p.lineTo (x, y + cs);
  50130. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50131. p.lineTo (x + textX, y);
  50132. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  50133. g.setColour (group.findColour (GroupComponent::outlineColourId)
  50134. .withMultipliedAlpha (alpha));
  50135. g.strokePath (p, PathStrokeType (2.0f));
  50136. g.setColour (group.findColour (GroupComponent::textColourId)
  50137. .withMultipliedAlpha (alpha));
  50138. g.setFont (f);
  50139. g.drawText (text,
  50140. roundFloatToInt (x + textX), 0,
  50141. roundFloatToInt (textW),
  50142. roundFloatToInt (textH),
  50143. Justification::centred, true);
  50144. }
  50145. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  50146. {
  50147. return 1 + tabDepth / 3;
  50148. }
  50149. int LookAndFeel::getTabButtonSpaceAroundImage()
  50150. {
  50151. return 4;
  50152. }
  50153. void LookAndFeel::createTabButtonShape (Path& p,
  50154. int width, int height,
  50155. int /*tabIndex*/,
  50156. const String& /*text*/,
  50157. Button& /*button*/,
  50158. TabbedButtonBar::Orientation orientation,
  50159. const bool /*isMouseOver*/,
  50160. const bool /*isMouseDown*/,
  50161. const bool /*isFrontTab*/)
  50162. {
  50163. const float w = (float) width;
  50164. const float h = (float) height;
  50165. float length = w;
  50166. float depth = h;
  50167. if (orientation == TabbedButtonBar::TabsAtLeft
  50168. || orientation == TabbedButtonBar::TabsAtRight)
  50169. {
  50170. swapVariables (length, depth);
  50171. }
  50172. const float indent = (float) getTabButtonOverlap ((int) depth);
  50173. const float overhang = 4.0f;
  50174. if (orientation == TabbedButtonBar::TabsAtLeft)
  50175. {
  50176. p.startNewSubPath (w, 0.0f);
  50177. p.lineTo (0.0f, indent);
  50178. p.lineTo (0.0f, h - indent);
  50179. p.lineTo (w, h);
  50180. p.lineTo (w + overhang, h + overhang);
  50181. p.lineTo (w + overhang, -overhang);
  50182. }
  50183. else if (orientation == TabbedButtonBar::TabsAtRight)
  50184. {
  50185. p.startNewSubPath (0.0f, 0.0f);
  50186. p.lineTo (w, indent);
  50187. p.lineTo (w, h - indent);
  50188. p.lineTo (0.0f, h);
  50189. p.lineTo (-overhang, h + overhang);
  50190. p.lineTo (-overhang, -overhang);
  50191. }
  50192. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50193. {
  50194. p.startNewSubPath (0.0f, 0.0f);
  50195. p.lineTo (indent, h);
  50196. p.lineTo (w - indent, h);
  50197. p.lineTo (w, 0.0f);
  50198. p.lineTo (w + overhang, -overhang);
  50199. p.lineTo (-overhang, -overhang);
  50200. }
  50201. else
  50202. {
  50203. p.startNewSubPath (0.0f, h);
  50204. p.lineTo (indent, 0.0f);
  50205. p.lineTo (w - indent, 0.0f);
  50206. p.lineTo (w, h);
  50207. p.lineTo (w + overhang, h + overhang);
  50208. p.lineTo (-overhang, h + overhang);
  50209. }
  50210. p.closeSubPath();
  50211. p = p.createPathWithRoundedCorners (3.0f);
  50212. }
  50213. void LookAndFeel::fillTabButtonShape (Graphics& g,
  50214. const Path& path,
  50215. const Colour& preferredColour,
  50216. int /*tabIndex*/,
  50217. const String& /*text*/,
  50218. Button& button,
  50219. TabbedButtonBar::Orientation /*orientation*/,
  50220. const bool /*isMouseOver*/,
  50221. const bool /*isMouseDown*/,
  50222. const bool isFrontTab)
  50223. {
  50224. g.setColour (isFrontTab ? preferredColour
  50225. : preferredColour.withMultipliedAlpha (0.9f));
  50226. g.fillPath (path);
  50227. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  50228. : TabbedButtonBar::tabOutlineColourId, false)
  50229. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  50230. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  50231. }
  50232. void LookAndFeel::drawTabButtonText (Graphics& g,
  50233. int x, int y, int w, int h,
  50234. const Colour& preferredBackgroundColour,
  50235. int /*tabIndex*/,
  50236. const String& text,
  50237. Button& button,
  50238. TabbedButtonBar::Orientation orientation,
  50239. const bool isMouseOver,
  50240. const bool isMouseDown,
  50241. const bool isFrontTab)
  50242. {
  50243. int length = w;
  50244. int depth = h;
  50245. if (orientation == TabbedButtonBar::TabsAtLeft
  50246. || orientation == TabbedButtonBar::TabsAtRight)
  50247. {
  50248. swapVariables (length, depth);
  50249. }
  50250. Font font (depth * 0.6f);
  50251. font.setUnderline (button.hasKeyboardFocus (false));
  50252. GlyphArrangement textLayout;
  50253. textLayout.addFittedText (font, text.trim(),
  50254. 0.0f, 0.0f, (float) length, (float) depth,
  50255. Justification::centred,
  50256. jmax (1, depth / 12));
  50257. AffineTransform transform;
  50258. if (orientation == TabbedButtonBar::TabsAtLeft)
  50259. {
  50260. transform = transform.rotated (float_Pi * -0.5f)
  50261. .translated ((float) x, (float) (y + h));
  50262. }
  50263. else if (orientation == TabbedButtonBar::TabsAtRight)
  50264. {
  50265. transform = transform.rotated (float_Pi * 0.5f)
  50266. .translated ((float) (x + w), (float) y);
  50267. }
  50268. else
  50269. {
  50270. transform = transform.translated ((float) x, (float) y);
  50271. }
  50272. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  50273. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  50274. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  50275. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  50276. else
  50277. g.setColour (preferredBackgroundColour.contrasting());
  50278. if (! (isMouseOver || isMouseDown))
  50279. g.setOpacity (0.8f);
  50280. if (! button.isEnabled())
  50281. g.setOpacity (0.3f);
  50282. textLayout.draw (g, transform);
  50283. }
  50284. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  50285. const String& text,
  50286. int tabDepth,
  50287. Button&)
  50288. {
  50289. Font f (tabDepth * 0.6f);
  50290. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  50291. }
  50292. void LookAndFeel::drawTabButton (Graphics& g,
  50293. int w, int h,
  50294. const Colour& preferredColour,
  50295. int tabIndex,
  50296. const String& text,
  50297. Button& button,
  50298. TabbedButtonBar::Orientation orientation,
  50299. const bool isMouseOver,
  50300. const bool isMouseDown,
  50301. const bool isFrontTab)
  50302. {
  50303. int length = w;
  50304. int depth = h;
  50305. if (orientation == TabbedButtonBar::TabsAtLeft
  50306. || orientation == TabbedButtonBar::TabsAtRight)
  50307. {
  50308. swapVariables (length, depth);
  50309. }
  50310. Path tabShape;
  50311. createTabButtonShape (tabShape, w, h,
  50312. tabIndex, text, button, orientation,
  50313. isMouseOver, isMouseDown, isFrontTab);
  50314. fillTabButtonShape (g, tabShape, preferredColour,
  50315. tabIndex, text, button, orientation,
  50316. isMouseOver, isMouseDown, isFrontTab);
  50317. const int indent = getTabButtonOverlap (depth);
  50318. int x = 0, y = 0;
  50319. if (orientation == TabbedButtonBar::TabsAtLeft
  50320. || orientation == TabbedButtonBar::TabsAtRight)
  50321. {
  50322. y += indent;
  50323. h -= indent * 2;
  50324. }
  50325. else
  50326. {
  50327. x += indent;
  50328. w -= indent * 2;
  50329. }
  50330. drawTabButtonText (g, x, y, w, h, preferredColour,
  50331. tabIndex, text, button, orientation,
  50332. isMouseOver, isMouseDown, isFrontTab);
  50333. }
  50334. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  50335. int w, int h,
  50336. TabbedButtonBar& tabBar,
  50337. TabbedButtonBar::Orientation orientation)
  50338. {
  50339. const float shadowSize = 0.2f;
  50340. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  50341. Rectangle shadowRect;
  50342. if (orientation == TabbedButtonBar::TabsAtLeft)
  50343. {
  50344. x1 = (float) w;
  50345. x2 = w * (1.0f - shadowSize);
  50346. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  50347. }
  50348. else if (orientation == TabbedButtonBar::TabsAtRight)
  50349. {
  50350. x2 = w * shadowSize;
  50351. shadowRect.setBounds (0, 0, (int) x2, h);
  50352. }
  50353. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50354. {
  50355. y2 = h * shadowSize;
  50356. shadowRect.setBounds (0, 0, w, (int) y2);
  50357. }
  50358. else
  50359. {
  50360. y1 = (float) h;
  50361. y2 = h * (1.0f - shadowSize);
  50362. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  50363. }
  50364. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  50365. Colours::transparentBlack, x2, y2,
  50366. false);
  50367. g.setBrush (&gb);
  50368. shadowRect.expand (2, 2);
  50369. g.fillRect (shadowRect);
  50370. g.setColour (Colour (0x80000000));
  50371. if (orientation == TabbedButtonBar::TabsAtLeft)
  50372. {
  50373. g.fillRect (w - 1, 0, 1, h);
  50374. }
  50375. else if (orientation == TabbedButtonBar::TabsAtRight)
  50376. {
  50377. g.fillRect (0, 0, 1, h);
  50378. }
  50379. else if (orientation == TabbedButtonBar::TabsAtBottom)
  50380. {
  50381. g.fillRect (0, 0, w, 1);
  50382. }
  50383. else
  50384. {
  50385. g.fillRect (0, h - 1, w, 1);
  50386. }
  50387. }
  50388. Button* LookAndFeel::createTabBarExtrasButton()
  50389. {
  50390. const float thickness = 7.0f;
  50391. const float indent = 22.0f;
  50392. Path p;
  50393. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  50394. DrawablePath ellipse;
  50395. ellipse.setPath (p);
  50396. ellipse.setSolidFill (Colour (0x99ffffff));
  50397. p.clear();
  50398. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  50399. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  50400. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  50401. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  50402. p.setUsingNonZeroWinding (false);
  50403. DrawablePath dp;
  50404. dp.setPath (p);
  50405. dp.setSolidFill (Colour (0x59000000));
  50406. DrawableComposite normalImage;
  50407. normalImage.insertDrawable (ellipse);
  50408. normalImage.insertDrawable (dp);
  50409. dp.setSolidFill (Colour (0xcc000000));
  50410. DrawableComposite overImage;
  50411. overImage.insertDrawable (ellipse);
  50412. overImage.insertDrawable (dp);
  50413. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  50414. db->setImages (&normalImage, &overImage, 0);
  50415. return db;
  50416. }
  50417. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  50418. {
  50419. g.fillAll (Colours::white);
  50420. const int w = header.getWidth();
  50421. const int h = header.getHeight();
  50422. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  50423. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  50424. false);
  50425. g.setBrush (&gb);
  50426. g.fillRect (0, h / 2, w, h);
  50427. g.setColour (Colour (0x33000000));
  50428. g.fillRect (0, h - 1, w, 1);
  50429. for (int i = header.getNumColumns (true); --i >= 0;)
  50430. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  50431. }
  50432. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  50433. int width, int height,
  50434. bool isMouseOver, bool isMouseDown,
  50435. int columnFlags)
  50436. {
  50437. if (isMouseDown)
  50438. g.fillAll (Colour (0x8899aadd));
  50439. else if (isMouseOver)
  50440. g.fillAll (Colour (0x5599aadd));
  50441. int rightOfText = width - 4;
  50442. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  50443. {
  50444. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  50445. const float bottom = height - top;
  50446. const float w = height * 0.5f;
  50447. const float x = rightOfText - (w * 1.25f);
  50448. rightOfText = (int) x;
  50449. Path sortArrow;
  50450. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  50451. g.setColour (Colour (0x99000000));
  50452. g.fillPath (sortArrow);
  50453. }
  50454. g.setColour (Colours::black);
  50455. g.setFont (height * 0.5f, Font::bold);
  50456. const int textX = 4;
  50457. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  50458. }
  50459. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  50460. {
  50461. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  50462. GradientBrush gb (background, 0.0f, 0.0f,
  50463. background.darker (0.1f),
  50464. toolbar.isVertical() ? w - 1.0f : 0.0f,
  50465. toolbar.isVertical() ? 0.0f : h - 1.0f,
  50466. false);
  50467. g.setBrush (&gb);
  50468. g.fillAll();
  50469. }
  50470. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  50471. {
  50472. return createTabBarExtrasButton();
  50473. }
  50474. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  50475. bool isMouseOver, bool isMouseDown,
  50476. ToolbarItemComponent& component)
  50477. {
  50478. if (isMouseDown)
  50479. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  50480. else if (isMouseOver)
  50481. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  50482. }
  50483. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  50484. const String& text, ToolbarItemComponent& component)
  50485. {
  50486. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  50487. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  50488. const float fontHeight = jmin (14.0f, height * 0.85f);
  50489. g.setFont (fontHeight);
  50490. g.drawFittedText (text,
  50491. x, y, width, height,
  50492. Justification::centred,
  50493. jmax (1, height / (int) fontHeight));
  50494. }
  50495. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  50496. bool isOpen, int width, int height)
  50497. {
  50498. const int buttonSize = (height * 3) / 4;
  50499. const int buttonIndent = (height - buttonSize) / 2;
  50500. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  50501. const int textX = buttonIndent * 2 + buttonSize + 2;
  50502. g.setColour (Colours::black);
  50503. g.setFont (height * 0.7f, Font::bold);
  50504. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  50505. }
  50506. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  50507. PropertyComponent&)
  50508. {
  50509. g.setColour (Colour (0x66ffffff));
  50510. g.fillRect (0, 0, width, height - 1);
  50511. }
  50512. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  50513. PropertyComponent& component)
  50514. {
  50515. g.setColour (Colours::black);
  50516. if (! component.isEnabled())
  50517. g.setOpacity (g.getCurrentColour().getFloatAlpha() * 0.6f);
  50518. g.setFont (jmin (height, 24) * 0.65f);
  50519. const Rectangle r (getPropertyComponentContentPosition (component));
  50520. g.drawFittedText (component.getName(),
  50521. 3, r.getY(), r.getX() - 5, r.getHeight(),
  50522. Justification::centredLeft, 2);
  50523. }
  50524. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  50525. {
  50526. return Rectangle (component.getWidth() / 3, 1,
  50527. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  50528. }
  50529. void LookAndFeel::createFileChooserHeaderText (const String& title,
  50530. const String& instructions,
  50531. GlyphArrangement& text,
  50532. int width)
  50533. {
  50534. text.clear();
  50535. text.addJustifiedText (Font (17.0f, Font::bold), title,
  50536. 8.0f, 22.0f, width - 16.0f,
  50537. Justification::centred);
  50538. text.addJustifiedText (Font (14.0f), instructions,
  50539. 8.0f, 24.0f + 16.0f, width - 16.0f,
  50540. Justification::centred);
  50541. }
  50542. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  50543. const String& filename, Image* icon,
  50544. const String& fileSizeDescription,
  50545. const String& fileTimeDescription,
  50546. const bool isDirectory,
  50547. const bool isItemSelected,
  50548. const int /*itemIndex*/)
  50549. {
  50550. if (isItemSelected)
  50551. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  50552. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  50553. g.setFont (height * 0.7f);
  50554. Image* im = icon;
  50555. Image* toRelease = 0;
  50556. if (im == 0)
  50557. {
  50558. toRelease = im = (isDirectory ? getDefaultFolderImage()
  50559. : getDefaultDocumentFileImage());
  50560. }
  50561. const int x = 32;
  50562. if (im != 0)
  50563. {
  50564. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  50565. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  50566. false);
  50567. ImageCache::release (toRelease);
  50568. }
  50569. if (width > 450 && ! isDirectory)
  50570. {
  50571. const int sizeX = roundFloatToInt (width * 0.7f);
  50572. const int dateX = roundFloatToInt (width * 0.8f);
  50573. g.drawFittedText (filename,
  50574. x, 0, sizeX - x, height,
  50575. Justification::centredLeft, 1);
  50576. g.setFont (height * 0.5f);
  50577. g.setColour (Colours::darkgrey);
  50578. if (! isDirectory)
  50579. {
  50580. g.drawFittedText (fileSizeDescription,
  50581. sizeX, 0, dateX - sizeX - 8, height,
  50582. Justification::centredRight, 1);
  50583. g.drawFittedText (fileTimeDescription,
  50584. dateX, 0, width - 8 - dateX, height,
  50585. Justification::centredRight, 1);
  50586. }
  50587. }
  50588. else
  50589. {
  50590. g.drawFittedText (filename,
  50591. x, 0, width - x, height,
  50592. Justification::centredLeft, 1);
  50593. }
  50594. }
  50595. Button* LookAndFeel::createFileBrowserGoUpButton()
  50596. {
  50597. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  50598. Path arrowPath;
  50599. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  50600. DrawablePath arrowImage;
  50601. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  50602. arrowImage.setPath (arrowPath);
  50603. goUpButton->setImages (&arrowImage);
  50604. return goUpButton;
  50605. }
  50606. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  50607. DirectoryContentsDisplayComponent* fileListComponent,
  50608. FilePreviewComponent* previewComp,
  50609. ComboBox* currentPathBox,
  50610. TextEditor* filenameBox,
  50611. Button* goUpButton)
  50612. {
  50613. const int x = 8;
  50614. int w = browserComp.getWidth() - x - x;
  50615. if (previewComp != 0)
  50616. {
  50617. const int previewWidth = w / 3;
  50618. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  50619. w -= previewWidth + 4;
  50620. }
  50621. int y = 4;
  50622. const int controlsHeight = 22;
  50623. const int bottomSectionHeight = controlsHeight + 8;
  50624. const int upButtonWidth = 50;
  50625. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  50626. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  50627. y += controlsHeight + 4;
  50628. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  50629. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  50630. y = listAsComp->getBottom() + 4;
  50631. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  50632. }
  50633. Image* LookAndFeel::getDefaultFolderImage()
  50634. {
  50635. 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,
  50636. 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,
  50637. 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,
  50638. 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,
  50639. 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,
  50640. 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,
  50641. 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,
  50642. 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,
  50643. 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,
  50644. 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,
  50645. 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,
  50646. 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,
  50647. 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,
  50648. 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,
  50649. 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,
  50650. 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,
  50651. 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,
  50652. 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,
  50653. 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,
  50654. 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,
  50655. 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,
  50656. 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,
  50657. 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,
  50658. 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,
  50659. 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,
  50660. 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,
  50661. 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,
  50662. 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,
  50663. 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,
  50664. 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,
  50665. 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,
  50666. 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,
  50667. 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,
  50668. 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,
  50669. 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,
  50670. 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,
  50671. 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,
  50672. 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,
  50673. 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,
  50674. 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,
  50675. 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,
  50676. 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,
  50677. 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,
  50678. 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};
  50679. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  50680. }
  50681. Image* LookAndFeel::getDefaultDocumentFileImage()
  50682. {
  50683. 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,
  50684. 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,
  50685. 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,
  50686. 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,
  50687. 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,
  50688. 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,
  50689. 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,
  50690. 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,
  50691. 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,
  50692. 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,
  50693. 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,
  50694. 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,
  50695. 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,
  50696. 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,
  50697. 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,
  50698. 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,
  50699. 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,
  50700. 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,
  50701. 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,
  50702. 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,
  50703. 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,
  50704. 174,66,96,130,0,0};
  50705. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  50706. }
  50707. void LookAndFeel::playAlertSound()
  50708. {
  50709. PlatformUtilities::beep();
  50710. }
  50711. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  50712. {
  50713. g.setColour (Colours::white.withAlpha (0.7f));
  50714. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  50715. g.setColour (Colours::black.withAlpha (0.2f));
  50716. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  50717. const int totalBlocks = 7;
  50718. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  50719. const float w = (width - 6.0f) / (float) totalBlocks;
  50720. for (int i = 0; i < totalBlocks; ++i)
  50721. {
  50722. if (i >= numBlocks)
  50723. g.setColour (Colours::lightblue.withAlpha (0.6f));
  50724. else
  50725. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  50726. : Colours::red);
  50727. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  50728. }
  50729. }
  50730. static void createRoundedPath (Path& p,
  50731. const float x, const float y,
  50732. const float w, const float h,
  50733. const float cs,
  50734. const bool curveTopLeft, const bool curveTopRight,
  50735. const bool curveBottomLeft, const bool curveBottomRight) throw()
  50736. {
  50737. const float cs2 = 2.0f * cs;
  50738. if (curveTopLeft)
  50739. {
  50740. p.startNewSubPath (x, y + cs);
  50741. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  50742. }
  50743. else
  50744. {
  50745. p.startNewSubPath (x, y);
  50746. }
  50747. if (curveTopRight)
  50748. {
  50749. p.lineTo (x + w - cs, y);
  50750. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  50751. }
  50752. else
  50753. {
  50754. p.lineTo (x + w, y);
  50755. }
  50756. if (curveBottomRight)
  50757. {
  50758. p.lineTo (x + w, y + h - cs);
  50759. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  50760. }
  50761. else
  50762. {
  50763. p.lineTo (x + w, y + h);
  50764. }
  50765. if (curveBottomLeft)
  50766. {
  50767. p.lineTo (x + cs, y + h);
  50768. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  50769. }
  50770. else
  50771. {
  50772. p.lineTo (x, y + h);
  50773. }
  50774. p.closeSubPath();
  50775. }
  50776. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  50777. float x, float y, float w, float h,
  50778. float maxCornerSize,
  50779. const Colour& baseColour,
  50780. const float strokeWidth,
  50781. const bool flatOnLeft,
  50782. const bool flatOnRight,
  50783. const bool flatOnTop,
  50784. const bool flatOnBottom) throw()
  50785. {
  50786. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  50787. return;
  50788. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  50789. Path outline;
  50790. createRoundedPath (outline, x, y, w, h, cs,
  50791. ! (flatOnLeft || flatOnTop),
  50792. ! (flatOnRight || flatOnTop),
  50793. ! (flatOnLeft || flatOnBottom),
  50794. ! (flatOnRight || flatOnBottom));
  50795. ColourGradient cg (baseColour, 0.0f, y,
  50796. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  50797. false);
  50798. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  50799. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  50800. GradientBrush gb (cg);
  50801. g.setBrush (&gb);
  50802. g.fillPath (outline);
  50803. g.setColour (Colour (0x80000000));
  50804. g.strokePath (outline, PathStrokeType (strokeWidth));
  50805. }
  50806. void LookAndFeel::drawGlassSphere (Graphics& g,
  50807. const float x, const float y,
  50808. const float diameter,
  50809. const Colour& colour,
  50810. const float outlineThickness) throw()
  50811. {
  50812. if (diameter <= outlineThickness)
  50813. return;
  50814. Path p;
  50815. p.addEllipse (x, y, diameter, diameter);
  50816. {
  50817. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50818. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50819. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50820. GradientBrush gb (cg);
  50821. g.setBrush (&gb);
  50822. g.fillPath (p);
  50823. }
  50824. {
  50825. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  50826. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  50827. g.setBrush (&gb);
  50828. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  50829. }
  50830. {
  50831. ColourGradient cg (Colours::transparentBlack,
  50832. x + diameter * 0.5f, y + diameter * 0.5f,
  50833. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50834. x, y + diameter * 0.5f, true);
  50835. cg.addColour (0.7, Colours::transparentBlack);
  50836. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  50837. GradientBrush gb (cg);
  50838. g.setBrush (&gb);
  50839. g.fillPath (p);
  50840. }
  50841. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50842. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  50843. }
  50844. void LookAndFeel::drawGlassPointer (Graphics& g,
  50845. const float x, const float y,
  50846. const float diameter,
  50847. const Colour& colour, const float outlineThickness,
  50848. const int direction) throw()
  50849. {
  50850. if (diameter <= outlineThickness)
  50851. return;
  50852. Path p;
  50853. p.startNewSubPath (x + diameter * 0.5f, y);
  50854. p.lineTo (x + diameter, y + diameter * 0.6f);
  50855. p.lineTo (x + diameter, y + diameter);
  50856. p.lineTo (x, y + diameter);
  50857. p.lineTo (x, y + diameter * 0.6f);
  50858. p.closeSubPath();
  50859. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  50860. {
  50861. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  50862. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  50863. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  50864. GradientBrush gb (cg);
  50865. g.setBrush (&gb);
  50866. g.fillPath (p);
  50867. }
  50868. {
  50869. ColourGradient cg (Colours::transparentBlack,
  50870. x + diameter * 0.5f, y + diameter * 0.5f,
  50871. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  50872. x - diameter * 0.2f, y + diameter * 0.5f, true);
  50873. cg.addColour (0.5, Colours::transparentBlack);
  50874. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  50875. GradientBrush gb (cg);
  50876. g.setBrush (&gb);
  50877. g.fillPath (p);
  50878. }
  50879. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  50880. g.strokePath (p, PathStrokeType (outlineThickness));
  50881. }
  50882. void LookAndFeel::drawGlassLozenge (Graphics& g,
  50883. const float x, const float y,
  50884. const float width, const float height,
  50885. const Colour& colour,
  50886. const float outlineThickness,
  50887. const float cornerSize,
  50888. const bool flatOnLeft,
  50889. const bool flatOnRight,
  50890. const bool flatOnTop,
  50891. const bool flatOnBottom) throw()
  50892. {
  50893. if (width <= outlineThickness || height <= outlineThickness)
  50894. return;
  50895. const int intX = (int) x;
  50896. const int intY = (int) y;
  50897. const int intW = (int) width;
  50898. const int intH = (int) height;
  50899. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  50900. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  50901. const int intEdge = (int) edgeBlurRadius;
  50902. Path outline;
  50903. createRoundedPath (outline, x, y, width, height, cs,
  50904. ! (flatOnLeft || flatOnTop),
  50905. ! (flatOnRight || flatOnTop),
  50906. ! (flatOnLeft || flatOnBottom),
  50907. ! (flatOnRight || flatOnBottom));
  50908. {
  50909. ColourGradient cg (colour.darker (0.2f), 0, y,
  50910. colour.darker (0.2f), 0, y + height, false);
  50911. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  50912. cg.addColour (0.4, colour);
  50913. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  50914. GradientBrush gb (cg);
  50915. g.setBrush (&gb);
  50916. g.fillPath (outline);
  50917. }
  50918. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  50919. colour.darker (0.2f), x, y + height * 0.5f, true);
  50920. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  50921. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  50922. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  50923. {
  50924. GradientBrush gb (cg);
  50925. g.saveState();
  50926. g.setBrush (&gb);
  50927. g.reduceClipRegion (intX, intY, intEdge, intH);
  50928. g.fillPath (outline);
  50929. g.restoreState();
  50930. }
  50931. if (! (flatOnRight || flatOnTop || flatOnBottom))
  50932. {
  50933. cg.x1 = x + width - edgeBlurRadius;
  50934. cg.x2 = x + width;
  50935. GradientBrush gb (cg);
  50936. g.saveState();
  50937. g.setBrush (&gb);
  50938. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  50939. g.fillPath (outline);
  50940. g.restoreState();
  50941. }
  50942. {
  50943. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  50944. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  50945. Path highlight;
  50946. createRoundedPath (highlight,
  50947. x + leftIndent,
  50948. y + cs * 0.1f,
  50949. width - (leftIndent + rightIndent),
  50950. height * 0.4f, cs * 0.4f,
  50951. ! (flatOnLeft || flatOnTop),
  50952. ! (flatOnRight || flatOnTop),
  50953. ! (flatOnLeft || flatOnBottom),
  50954. ! (flatOnRight || flatOnBottom));
  50955. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  50956. Colours::transparentWhite, 0, y + height * 0.4f, false);
  50957. g.setBrush (&gb);
  50958. g.fillPath (highlight);
  50959. }
  50960. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  50961. g.strokePath (outline, PathStrokeType (outlineThickness));
  50962. }
  50963. END_JUCE_NAMESPACE
  50964. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  50965. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  50966. BEGIN_JUCE_NAMESPACE
  50967. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  50968. {
  50969. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  50970. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  50971. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  50972. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  50973. setColour (Slider::thumbColourId, Colours::white);
  50974. setColour (Slider::trackColourId, Colour (0x7f000000));
  50975. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  50976. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  50977. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  50978. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  50979. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  50980. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  50981. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  50982. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  50983. }
  50984. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  50985. {
  50986. }
  50987. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  50988. Button& button,
  50989. const Colour& backgroundColour,
  50990. bool isMouseOverButton,
  50991. bool isButtonDown)
  50992. {
  50993. const int width = button.getWidth();
  50994. const int height = button.getHeight();
  50995. const float indent = 2.0f;
  50996. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  50997. roundFloatToInt (height * 0.4f));
  50998. Path p;
  50999. p.addRoundedRectangle (indent, indent,
  51000. width - indent * 2.0f,
  51001. height - indent * 2.0f,
  51002. (float) cornerSize);
  51003. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  51004. if (isMouseOverButton)
  51005. {
  51006. if (isButtonDown)
  51007. bc = bc.brighter();
  51008. else if (bc.getBrightness() > 0.5f)
  51009. bc = bc.darker (0.1f);
  51010. else
  51011. bc = bc.brighter (0.1f);
  51012. }
  51013. g.setColour (bc);
  51014. g.fillPath (p);
  51015. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  51016. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  51017. }
  51018. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  51019. Component& /*component*/,
  51020. int x, int y, int w, int h,
  51021. const bool ticked,
  51022. const bool isEnabled,
  51023. const bool /*isMouseOverButton*/,
  51024. const bool isButtonDown)
  51025. {
  51026. Path box;
  51027. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  51028. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  51029. : Colours::lightgrey.withAlpha (0.1f));
  51030. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  51031. .translated ((float) x, (float) y));
  51032. g.fillPath (box, trans);
  51033. g.setColour (Colours::black.withAlpha (0.6f));
  51034. g.strokePath (box, PathStrokeType (0.9f), trans);
  51035. if (ticked)
  51036. {
  51037. Path tick;
  51038. tick.startNewSubPath (1.5f, 3.0f);
  51039. tick.lineTo (3.0f, 6.0f);
  51040. tick.lineTo (6.0f, 0.0f);
  51041. g.setColour (isEnabled ? Colours::black : Colours::grey);
  51042. g.strokePath (tick, PathStrokeType (2.5f), trans);
  51043. }
  51044. }
  51045. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  51046. ToggleButton& button,
  51047. bool isMouseOverButton,
  51048. bool isButtonDown)
  51049. {
  51050. if (button.hasKeyboardFocus (true))
  51051. {
  51052. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  51053. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  51054. }
  51055. const int tickWidth = jmin (20, button.getHeight() - 4);
  51056. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  51057. tickWidth, tickWidth,
  51058. button.getToggleState(),
  51059. button.isEnabled(),
  51060. isMouseOverButton,
  51061. isButtonDown);
  51062. g.setColour (button.findColour (ToggleButton::textColourId));
  51063. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  51064. if (! button.isEnabled())
  51065. g.setOpacity (0.5f);
  51066. const int textX = tickWidth + 5;
  51067. g.drawFittedText (button.getButtonText(),
  51068. textX, 4,
  51069. button.getWidth() - textX - 2, button.getHeight() - 8,
  51070. Justification::centredLeft, 10);
  51071. }
  51072. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  51073. int width, int height,
  51074. double progress, const String& textToShow)
  51075. {
  51076. if (progress < 0 || progress >= 1.0)
  51077. {
  51078. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  51079. }
  51080. else
  51081. {
  51082. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  51083. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  51084. g.fillAll (background);
  51085. g.setColour (foreground);
  51086. g.fillRect (1, 1,
  51087. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  51088. height - 2);
  51089. if (textToShow.isNotEmpty())
  51090. {
  51091. g.setColour (Colour::contrasting (background, foreground));
  51092. g.setFont (height * 0.6f);
  51093. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  51094. }
  51095. }
  51096. }
  51097. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  51098. ScrollBar& bar,
  51099. int width, int height,
  51100. int buttonDirection,
  51101. bool isScrollbarVertical,
  51102. bool isMouseOverButton,
  51103. bool isButtonDown)
  51104. {
  51105. if (isScrollbarVertical)
  51106. width -= 2;
  51107. else
  51108. height -= 2;
  51109. Path p;
  51110. if (buttonDirection == 0)
  51111. p.addTriangle (width * 0.5f, height * 0.2f,
  51112. width * 0.1f, height * 0.7f,
  51113. width * 0.9f, height * 0.7f);
  51114. else if (buttonDirection == 1)
  51115. p.addTriangle (width * 0.8f, height * 0.5f,
  51116. width * 0.3f, height * 0.1f,
  51117. width * 0.3f, height * 0.9f);
  51118. else if (buttonDirection == 2)
  51119. p.addTriangle (width * 0.5f, height * 0.8f,
  51120. width * 0.1f, height * 0.3f,
  51121. width * 0.9f, height * 0.3f);
  51122. else if (buttonDirection == 3)
  51123. p.addTriangle (width * 0.2f, height * 0.5f,
  51124. width * 0.7f, height * 0.1f,
  51125. width * 0.7f, height * 0.9f);
  51126. if (isButtonDown)
  51127. g.setColour (Colours::white);
  51128. else if (isMouseOverButton)
  51129. g.setColour (Colours::white.withAlpha (0.7f));
  51130. else
  51131. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  51132. g.fillPath (p);
  51133. g.setColour (Colours::black.withAlpha (0.5f));
  51134. g.strokePath (p, PathStrokeType (0.5f));
  51135. }
  51136. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  51137. ScrollBar& bar,
  51138. int x, int y,
  51139. int width, int height,
  51140. bool isScrollbarVertical,
  51141. int thumbStartPosition,
  51142. int thumbSize,
  51143. bool isMouseOver,
  51144. bool isMouseDown)
  51145. {
  51146. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  51147. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51148. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  51149. if (thumbSize > 0.0f)
  51150. {
  51151. Rectangle thumb;
  51152. if (isScrollbarVertical)
  51153. {
  51154. width -= 2;
  51155. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  51156. roundFloatToInt (width * 0.3f), height);
  51157. thumb.setBounds (x + 1, thumbStartPosition,
  51158. width - 2, thumbSize);
  51159. }
  51160. else
  51161. {
  51162. height -= 2;
  51163. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  51164. width, roundFloatToInt (height * 0.3f));
  51165. thumb.setBounds (thumbStartPosition, y + 1,
  51166. thumbSize, height - 2);
  51167. }
  51168. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  51169. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  51170. g.fillRect (thumb);
  51171. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  51172. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  51173. if (thumbSize > 16)
  51174. {
  51175. for (int i = 3; --i >= 0;)
  51176. {
  51177. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  51178. g.setColour (Colours::black.withAlpha (0.15f));
  51179. if (isScrollbarVertical)
  51180. {
  51181. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  51182. g.setColour (Colours::white.withAlpha (0.15f));
  51183. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  51184. }
  51185. else
  51186. {
  51187. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  51188. g.setColour (Colours::white.withAlpha (0.15f));
  51189. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  51190. }
  51191. }
  51192. }
  51193. }
  51194. }
  51195. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  51196. {
  51197. return &scrollbarShadow;
  51198. }
  51199. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  51200. {
  51201. g.fillAll (findColour (PopupMenu::backgroundColourId));
  51202. g.setColour (Colours::black.withAlpha (0.6f));
  51203. g.drawRect (0, 0, width, height);
  51204. }
  51205. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  51206. bool, MenuBarComponent& menuBar)
  51207. {
  51208. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  51209. }
  51210. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  51211. {
  51212. if (textEditor.isEnabled())
  51213. {
  51214. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  51215. g.drawRect (0, 0, width, height);
  51216. }
  51217. }
  51218. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  51219. const bool isButtonDown,
  51220. int buttonX, int buttonY,
  51221. int buttonW, int buttonH,
  51222. ComboBox& box)
  51223. {
  51224. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  51225. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  51226. : ComboBox::backgroundColourId));
  51227. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  51228. g.setColour (box.findColour (ComboBox::outlineColourId));
  51229. g.drawRect (0, 0, width, height);
  51230. const float arrowX = 0.2f;
  51231. const float arrowH = 0.3f;
  51232. if (box.isEnabled())
  51233. {
  51234. Path p;
  51235. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  51236. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  51237. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  51238. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  51239. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  51240. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  51241. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  51242. : ComboBox::buttonColourId));
  51243. g.fillPath (p);
  51244. }
  51245. }
  51246. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  51247. {
  51248. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  51249. f.setHorizontalScale (0.9f);
  51250. return f;
  51251. }
  51252. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  51253. {
  51254. Path p;
  51255. p.addTriangle (x1, y1, x2, y2, x3, y3);
  51256. g.setColour (fill);
  51257. g.fillPath (p);
  51258. g.setColour (outline);
  51259. g.strokePath (p, PathStrokeType (0.3f));
  51260. }
  51261. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  51262. int x, int y,
  51263. int w, int h,
  51264. float sliderPos,
  51265. float minSliderPos,
  51266. float maxSliderPos,
  51267. const Slider::SliderStyle style,
  51268. Slider& slider)
  51269. {
  51270. g.fillAll (slider.findColour (Slider::backgroundColourId));
  51271. if (style == Slider::LinearBar)
  51272. {
  51273. g.setColour (slider.findColour (Slider::thumbColourId));
  51274. g.fillRect (x, y, (int) sliderPos - x, h);
  51275. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  51276. g.drawRect (x, y, (int) sliderPos - x, h);
  51277. }
  51278. else
  51279. {
  51280. g.setColour (slider.findColour (Slider::trackColourId)
  51281. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  51282. if (slider.isHorizontal())
  51283. {
  51284. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  51285. w, roundFloatToInt (h * 0.2f));
  51286. }
  51287. else
  51288. {
  51289. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  51290. jmin (4, roundFloatToInt (w * 0.2f)), h);
  51291. }
  51292. float alpha = 0.35f;
  51293. if (slider.isEnabled())
  51294. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  51295. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  51296. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  51297. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  51298. {
  51299. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  51300. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  51301. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  51302. fill, outline);
  51303. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  51304. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  51305. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  51306. fill, outline);
  51307. }
  51308. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  51309. {
  51310. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51311. minSliderPos - 7.0f, y + h * 0.9f ,
  51312. minSliderPos, y + h * 0.9f,
  51313. fill, outline);
  51314. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  51315. maxSliderPos, y + h * 0.9f,
  51316. maxSliderPos + 7.0f, y + h * 0.9f,
  51317. fill, outline);
  51318. }
  51319. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  51320. {
  51321. drawTriangle (g, sliderPos, y + h * 0.9f,
  51322. sliderPos - 7.0f, y + h * 0.2f,
  51323. sliderPos + 7.0f, y + h * 0.2f,
  51324. fill, outline);
  51325. }
  51326. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  51327. {
  51328. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  51329. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  51330. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  51331. fill, outline);
  51332. }
  51333. }
  51334. }
  51335. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  51336. {
  51337. if (isIncrement)
  51338. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  51339. else
  51340. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  51341. }
  51342. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  51343. {
  51344. return &scrollbarShadow;
  51345. }
  51346. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  51347. {
  51348. return 8;
  51349. }
  51350. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  51351. int w, int h,
  51352. bool isMouseOver,
  51353. bool isMouseDragging)
  51354. {
  51355. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  51356. : Colours::darkgrey);
  51357. const float lineThickness = jmin (w, h) * 0.1f;
  51358. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  51359. {
  51360. g.drawLine (w * i,
  51361. h + 1.0f,
  51362. w + 1.0f,
  51363. h * i,
  51364. lineThickness);
  51365. }
  51366. }
  51367. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  51368. {
  51369. Path shape;
  51370. if (buttonType == DocumentWindow::closeButton)
  51371. {
  51372. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  51373. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  51374. ShapeButton* const b = new ShapeButton ("close",
  51375. Colour (0x7fff3333),
  51376. Colour (0xd7ff3333),
  51377. Colour (0xf7ff3333));
  51378. b->setShape (shape, true, true, true);
  51379. return b;
  51380. }
  51381. else if (buttonType == DocumentWindow::minimiseButton)
  51382. {
  51383. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51384. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  51385. DrawablePath dp;
  51386. dp.setPath (shape);
  51387. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51388. b->setImages (&dp);
  51389. return b;
  51390. }
  51391. else if (buttonType == DocumentWindow::maximiseButton)
  51392. {
  51393. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  51394. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  51395. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  51396. DrawablePath dp;
  51397. dp.setPath (shape);
  51398. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  51399. b->setImages (&dp);
  51400. return b;
  51401. }
  51402. jassertfalse
  51403. return 0;
  51404. }
  51405. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  51406. int titleBarX,
  51407. int titleBarY,
  51408. int titleBarW,
  51409. int titleBarH,
  51410. Button* minimiseButton,
  51411. Button* maximiseButton,
  51412. Button* closeButton,
  51413. bool positionTitleBarButtonsOnLeft)
  51414. {
  51415. titleBarY += titleBarH / 8;
  51416. titleBarH -= titleBarH / 4;
  51417. const int buttonW = titleBarH;
  51418. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  51419. : titleBarX + titleBarW - buttonW - 4;
  51420. if (closeButton != 0)
  51421. {
  51422. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  51423. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  51424. : -(buttonW + buttonW / 5);
  51425. }
  51426. if (positionTitleBarButtonsOnLeft)
  51427. swapVariables (minimiseButton, maximiseButton);
  51428. if (maximiseButton != 0)
  51429. {
  51430. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51431. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  51432. }
  51433. if (minimiseButton != 0)
  51434. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  51435. }
  51436. END_JUCE_NAMESPACE
  51437. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  51438. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  51439. BEGIN_JUCE_NAMESPACE
  51440. class DummyMenuComponent : public Component
  51441. {
  51442. DummyMenuComponent (const DummyMenuComponent&);
  51443. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  51444. public:
  51445. DummyMenuComponent() {}
  51446. ~DummyMenuComponent() {}
  51447. void inputAttemptWhenModal()
  51448. {
  51449. exitModalState (0);
  51450. }
  51451. };
  51452. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  51453. : model (0),
  51454. itemUnderMouse (-1),
  51455. currentPopupIndex (-1),
  51456. indexToShowAgain (-1),
  51457. lastMouseX (0),
  51458. lastMouseY (0),
  51459. inModalState (false),
  51460. currentPopup (0)
  51461. {
  51462. setRepaintsOnMouseActivity (true);
  51463. setWantsKeyboardFocus (false);
  51464. setMouseClickGrabsKeyboardFocus (false);
  51465. setModel (model_);
  51466. }
  51467. MenuBarComponent::~MenuBarComponent()
  51468. {
  51469. setModel (0);
  51470. Desktop::getInstance().removeGlobalMouseListener (this);
  51471. deleteAndZero (currentPopup);
  51472. }
  51473. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  51474. {
  51475. if (model != newModel)
  51476. {
  51477. if (model != 0)
  51478. model->removeListener (this);
  51479. model = newModel;
  51480. if (model != 0)
  51481. model->addListener (this);
  51482. repaint();
  51483. menuBarItemsChanged (0);
  51484. }
  51485. }
  51486. void MenuBarComponent::paint (Graphics& g)
  51487. {
  51488. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  51489. getLookAndFeel().drawMenuBarBackground (g,
  51490. getWidth(),
  51491. getHeight(),
  51492. isMouseOverBar,
  51493. *this);
  51494. if (model != 0)
  51495. {
  51496. for (int i = 0; i < menuNames.size(); ++i)
  51497. {
  51498. g.saveState();
  51499. g.setOrigin (xPositions [i], 0);
  51500. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  51501. getLookAndFeel().drawMenuBarItem (g,
  51502. xPositions[i + 1] - xPositions[i],
  51503. getHeight(),
  51504. i,
  51505. menuNames[i],
  51506. i == itemUnderMouse,
  51507. i == currentPopupIndex,
  51508. isMouseOverBar,
  51509. *this);
  51510. g.restoreState();
  51511. }
  51512. }
  51513. }
  51514. void MenuBarComponent::resized()
  51515. {
  51516. xPositions.clear();
  51517. int x = 2;
  51518. xPositions.add (x);
  51519. for (int i = 0; i < menuNames.size(); ++i)
  51520. {
  51521. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  51522. xPositions.add (x);
  51523. }
  51524. }
  51525. int MenuBarComponent::getItemAt (const int x, const int y)
  51526. {
  51527. for (int i = 0; i < xPositions.size(); ++i)
  51528. if (x >= xPositions[i] && x < xPositions[i + 1])
  51529. return reallyContains (x, y, true) ? i : -1;
  51530. return -1;
  51531. }
  51532. void MenuBarComponent::repaintMenuItem (int index)
  51533. {
  51534. if (((unsigned int) index) < (unsigned int) xPositions.size())
  51535. {
  51536. const int x1 = xPositions [index];
  51537. const int x2 = xPositions [index + 1];
  51538. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  51539. }
  51540. }
  51541. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  51542. {
  51543. const int newItem = getItemAt (x, y);
  51544. if (itemUnderMouse != newItem)
  51545. {
  51546. repaintMenuItem (itemUnderMouse);
  51547. itemUnderMouse = newItem;
  51548. repaintMenuItem (itemUnderMouse);
  51549. }
  51550. }
  51551. void MenuBarComponent::hideCurrentMenu()
  51552. {
  51553. deleteAndZero (currentPopup);
  51554. repaint();
  51555. }
  51556. void MenuBarComponent::showMenu (int index)
  51557. {
  51558. if (index != currentPopupIndex)
  51559. {
  51560. if (inModalState)
  51561. {
  51562. hideCurrentMenu();
  51563. indexToShowAgain = index;
  51564. return;
  51565. }
  51566. indexToShowAgain = -1;
  51567. currentPopupIndex = -1;
  51568. itemUnderMouse = index;
  51569. deleteAndZero (currentPopup);
  51570. menuBarItemsChanged (0);
  51571. Component* const prevFocused = getCurrentlyFocusedComponent();
  51572. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  51573. if (prevFocused != 0)
  51574. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  51575. ComponentDeletionWatcher deletionChecker (this);
  51576. enterModalState (false);
  51577. inModalState = true;
  51578. int result = 0;
  51579. ApplicationCommandManager* managerOfChosenCommand = 0;
  51580. Desktop::getInstance().addGlobalMouseListener (this);
  51581. for (;;)
  51582. {
  51583. const int x = getScreenX() + xPositions [itemUnderMouse];
  51584. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  51585. currentPopupIndex = itemUnderMouse;
  51586. indexToShowAgain = -1;
  51587. repaint();
  51588. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  51589. {
  51590. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  51591. menuNames [itemUnderMouse]));
  51592. currentPopup = m.createMenuComponent (x, getScreenY(),
  51593. w, getHeight(),
  51594. 0, w, 0, 0,
  51595. true, this,
  51596. &managerOfChosenCommand,
  51597. this);
  51598. }
  51599. if (currentPopup == 0)
  51600. {
  51601. currentPopup = new DummyMenuComponent();
  51602. addAndMakeVisible (currentPopup);
  51603. }
  51604. currentPopup->enterModalState (false);
  51605. currentPopup->toFront (false); // need to do this after making it modal, or it could
  51606. // be stuck behind other comps that are already modal..
  51607. result = currentPopup->runModalLoop();
  51608. if (deletionChecker.hasBeenDeleted())
  51609. {
  51610. delete prevCompDeletionChecker;
  51611. return;
  51612. }
  51613. const int lastPopupIndex = currentPopupIndex;
  51614. deleteAndZero (currentPopup);
  51615. currentPopupIndex = -1;
  51616. if (result != 0)
  51617. {
  51618. topLevelIndexClicked = lastPopupIndex;
  51619. break;
  51620. }
  51621. else if (indexToShowAgain >= 0)
  51622. {
  51623. menuBarItemsChanged (0);
  51624. repaint();
  51625. itemUnderMouse = indexToShowAgain;
  51626. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  51627. break;
  51628. }
  51629. else
  51630. {
  51631. break;
  51632. }
  51633. }
  51634. Desktop::getInstance().removeGlobalMouseListener (this);
  51635. inModalState = false;
  51636. exitModalState (0);
  51637. if (prevCompDeletionChecker != 0)
  51638. {
  51639. if (! prevCompDeletionChecker->hasBeenDeleted())
  51640. prevFocused->grabKeyboardFocus();
  51641. delete prevCompDeletionChecker;
  51642. }
  51643. int mx, my;
  51644. getMouseXYRelative (mx, my);
  51645. updateItemUnderMouse (mx, my);
  51646. repaint();
  51647. if (result != 0)
  51648. {
  51649. if (managerOfChosenCommand != 0)
  51650. {
  51651. ApplicationCommandTarget::InvocationInfo info (result);
  51652. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51653. managerOfChosenCommand->invoke (info, true);
  51654. }
  51655. postCommandMessage (result);
  51656. }
  51657. }
  51658. }
  51659. void MenuBarComponent::handleCommandMessage (int commandId)
  51660. {
  51661. if (model != 0)
  51662. model->menuItemSelected (commandId, topLevelIndexClicked);
  51663. }
  51664. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  51665. {
  51666. if (e.eventComponent == this)
  51667. updateItemUnderMouse (e.x, e.y);
  51668. }
  51669. void MenuBarComponent::mouseExit (const MouseEvent& e)
  51670. {
  51671. if (e.eventComponent == this)
  51672. updateItemUnderMouse (e.x, e.y);
  51673. }
  51674. void MenuBarComponent::mouseDown (const MouseEvent& e)
  51675. {
  51676. const MouseEvent e2 (e.getEventRelativeTo (this));
  51677. if (currentPopupIndex < 0)
  51678. {
  51679. updateItemUnderMouse (e2.x, e2.y);
  51680. currentPopupIndex = -2;
  51681. showMenu (itemUnderMouse);
  51682. }
  51683. }
  51684. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  51685. {
  51686. const MouseEvent e2 (e.getEventRelativeTo (this));
  51687. const int item = getItemAt (e2.x, e2.y);
  51688. if (item >= 0)
  51689. showMenu (item);
  51690. }
  51691. void MenuBarComponent::mouseUp (const MouseEvent& e)
  51692. {
  51693. const MouseEvent e2 (e.getEventRelativeTo (this));
  51694. updateItemUnderMouse (e2.x, e2.y);
  51695. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  51696. hideCurrentMenu();
  51697. }
  51698. void MenuBarComponent::mouseMove (const MouseEvent& e)
  51699. {
  51700. const MouseEvent e2 (e.getEventRelativeTo (this));
  51701. if (lastMouseX != e2.x || lastMouseY != e2.y)
  51702. {
  51703. if (currentPopupIndex >= 0)
  51704. {
  51705. const int item = getItemAt (e2.x, e2.y);
  51706. if (item >= 0)
  51707. showMenu (item);
  51708. }
  51709. else
  51710. {
  51711. updateItemUnderMouse (e2.x, e2.y);
  51712. }
  51713. lastMouseX = e2.x;
  51714. lastMouseY = e2.y;
  51715. }
  51716. }
  51717. bool MenuBarComponent::keyPressed (const KeyPress& key)
  51718. {
  51719. bool used = false;
  51720. const int numMenus = menuNames.size();
  51721. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  51722. if (key.isKeyCode (KeyPress::leftKey))
  51723. {
  51724. showMenu ((currentIndex + numMenus - 1) % numMenus);
  51725. used = true;
  51726. }
  51727. else if (key.isKeyCode (KeyPress::rightKey))
  51728. {
  51729. showMenu ((currentIndex + 1) % numMenus);
  51730. used = true;
  51731. }
  51732. return used;
  51733. }
  51734. void MenuBarComponent::inputAttemptWhenModal()
  51735. {
  51736. hideCurrentMenu();
  51737. }
  51738. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  51739. {
  51740. StringArray newNames;
  51741. if (model != 0)
  51742. newNames = model->getMenuBarNames();
  51743. if (newNames != menuNames)
  51744. {
  51745. menuNames = newNames;
  51746. repaint();
  51747. resized();
  51748. }
  51749. }
  51750. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  51751. const ApplicationCommandTarget::InvocationInfo& info)
  51752. {
  51753. if (model == 0
  51754. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  51755. return;
  51756. for (int i = 0; i < menuNames.size(); ++i)
  51757. {
  51758. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  51759. if (menu.containsCommandItem (info.commandID))
  51760. {
  51761. itemUnderMouse = i;
  51762. repaintMenuItem (i);
  51763. startTimer (200);
  51764. break;
  51765. }
  51766. }
  51767. }
  51768. void MenuBarComponent::timerCallback()
  51769. {
  51770. stopTimer();
  51771. int mx, my;
  51772. getMouseXYRelative (mx, my);
  51773. updateItemUnderMouse (mx, my);
  51774. }
  51775. END_JUCE_NAMESPACE
  51776. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  51777. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  51778. BEGIN_JUCE_NAMESPACE
  51779. MenuBarModel::MenuBarModel() throw()
  51780. : manager (0)
  51781. {
  51782. }
  51783. MenuBarModel::~MenuBarModel()
  51784. {
  51785. setApplicationCommandManagerToWatch (0);
  51786. }
  51787. void MenuBarModel::menuItemsChanged()
  51788. {
  51789. triggerAsyncUpdate();
  51790. }
  51791. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  51792. {
  51793. if (manager != newManager)
  51794. {
  51795. if (manager != 0)
  51796. manager->removeListener (this);
  51797. manager = newManager;
  51798. if (manager != 0)
  51799. manager->addListener (this);
  51800. }
  51801. }
  51802. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  51803. {
  51804. jassert (newListener != 0);
  51805. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  51806. if (newListener != 0)
  51807. listeners.add (newListener);
  51808. }
  51809. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  51810. {
  51811. // Trying to remove a listener that isn't on the list!
  51812. // If this assertion happens because this object is a dangling pointer, make sure you've not
  51813. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  51814. jassert (listeners.contains (listenerToRemove));
  51815. listeners.removeValue (listenerToRemove);
  51816. }
  51817. void MenuBarModel::handleAsyncUpdate()
  51818. {
  51819. for (int i = listeners.size(); --i >= 0;)
  51820. {
  51821. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  51822. i = jmin (i, listeners.size());
  51823. }
  51824. }
  51825. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  51826. {
  51827. for (int i = listeners.size(); --i >= 0;)
  51828. {
  51829. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  51830. i = jmin (i, listeners.size());
  51831. }
  51832. }
  51833. void MenuBarModel::applicationCommandListChanged()
  51834. {
  51835. menuItemsChanged();
  51836. }
  51837. END_JUCE_NAMESPACE
  51838. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  51839. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  51840. BEGIN_JUCE_NAMESPACE
  51841. static VoidArray activeMenuWindows;
  51842. class MenuItemInfo
  51843. {
  51844. public:
  51845. const int itemId;
  51846. String text;
  51847. const Colour textColour;
  51848. const bool active, isSeparator, isTicked, usesColour;
  51849. Image* image;
  51850. PopupMenuCustomComponent* const customComp;
  51851. PopupMenu* subMenu;
  51852. ApplicationCommandManager* const commandManager;
  51853. MenuItemInfo() throw()
  51854. : itemId (0),
  51855. active (true),
  51856. isSeparator (true),
  51857. isTicked (false),
  51858. usesColour (false),
  51859. image (0),
  51860. customComp (0),
  51861. subMenu (0),
  51862. commandManager (0)
  51863. {
  51864. }
  51865. MenuItemInfo (const int itemId_,
  51866. const String& text_,
  51867. const bool active_,
  51868. const bool isTicked_,
  51869. const Image* im,
  51870. const Colour& textColour_,
  51871. const bool usesColour_,
  51872. PopupMenuCustomComponent* const customComp_,
  51873. const PopupMenu* const subMenu_,
  51874. ApplicationCommandManager* const commandManager_) throw()
  51875. : itemId (itemId_),
  51876. text (text_),
  51877. textColour (textColour_),
  51878. active (active_),
  51879. isSeparator (false),
  51880. isTicked (isTicked_),
  51881. usesColour (usesColour_),
  51882. image (0),
  51883. customComp (customComp_),
  51884. commandManager (commandManager_)
  51885. {
  51886. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  51887. if (customComp != 0)
  51888. customComp->refCount_++;
  51889. if (im != 0)
  51890. image = im->createCopy();
  51891. if (commandManager_ != 0 && itemId_ != 0)
  51892. {
  51893. String shortcutKey;
  51894. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  51895. ->getKeyPressesAssignedToCommand (itemId_));
  51896. for (int i = 0; i < keyPresses.size(); ++i)
  51897. {
  51898. const String key (keyPresses.getReference(i).getTextDescription());
  51899. if (shortcutKey.isNotEmpty())
  51900. shortcutKey << ", ";
  51901. if (key.length() == 1)
  51902. shortcutKey << "shortcut: '" << key << '\'';
  51903. else
  51904. shortcutKey << key;
  51905. }
  51906. shortcutKey = shortcutKey.trim();
  51907. if (shortcutKey.isNotEmpty())
  51908. text << "<end>" << shortcutKey;
  51909. }
  51910. }
  51911. MenuItemInfo (const MenuItemInfo& other) throw()
  51912. : itemId (other.itemId),
  51913. text (other.text),
  51914. textColour (other.textColour),
  51915. active (other.active),
  51916. isSeparator (other.isSeparator),
  51917. isTicked (other.isTicked),
  51918. usesColour (other.usesColour),
  51919. customComp (other.customComp),
  51920. commandManager (other.commandManager)
  51921. {
  51922. if (other.subMenu != 0)
  51923. subMenu = new PopupMenu (*(other.subMenu));
  51924. else
  51925. subMenu = 0;
  51926. if (other.image != 0)
  51927. image = other.image->createCopy();
  51928. else
  51929. image = 0;
  51930. if (customComp != 0)
  51931. customComp->refCount_++;
  51932. }
  51933. ~MenuItemInfo() throw()
  51934. {
  51935. delete subMenu;
  51936. delete image;
  51937. if (customComp != 0 && --(customComp->refCount_) == 0)
  51938. delete customComp;
  51939. }
  51940. bool canBeTriggered() const throw()
  51941. {
  51942. return active && ! (isSeparator || (subMenu != 0));
  51943. }
  51944. bool hasActiveSubMenu() const throw()
  51945. {
  51946. return active && (subMenu != 0);
  51947. }
  51948. juce_UseDebuggingNewOperator
  51949. private:
  51950. const MenuItemInfo& operator= (const MenuItemInfo&);
  51951. };
  51952. class MenuItemComponent : public Component
  51953. {
  51954. bool isHighlighted;
  51955. public:
  51956. MenuItemInfo itemInfo;
  51957. MenuItemComponent (const MenuItemInfo& itemInfo_)
  51958. : isHighlighted (false),
  51959. itemInfo (itemInfo_)
  51960. {
  51961. if (itemInfo.customComp != 0)
  51962. addAndMakeVisible (itemInfo.customComp);
  51963. }
  51964. ~MenuItemComponent()
  51965. {
  51966. if (itemInfo.customComp != 0)
  51967. removeChildComponent (itemInfo.customComp);
  51968. }
  51969. void getIdealSize (int& idealWidth,
  51970. int& idealHeight,
  51971. const int standardItemHeight)
  51972. {
  51973. if (itemInfo.customComp != 0)
  51974. {
  51975. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  51976. }
  51977. else
  51978. {
  51979. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  51980. itemInfo.isSeparator,
  51981. standardItemHeight,
  51982. idealWidth,
  51983. idealHeight);
  51984. }
  51985. }
  51986. void paint (Graphics& g)
  51987. {
  51988. if (itemInfo.customComp == 0)
  51989. {
  51990. String mainText (itemInfo.text);
  51991. String endText;
  51992. const int endIndex = mainText.indexOf (T("<end>"));
  51993. if (endIndex >= 0)
  51994. {
  51995. endText = mainText.substring (endIndex + 5).trim();
  51996. mainText = mainText.substring (0, endIndex);
  51997. }
  51998. getLookAndFeel()
  51999. .drawPopupMenuItem (g, getWidth(), getHeight(),
  52000. itemInfo.isSeparator,
  52001. itemInfo.active,
  52002. isHighlighted,
  52003. itemInfo.isTicked,
  52004. itemInfo.subMenu != 0,
  52005. mainText, endText,
  52006. itemInfo.image,
  52007. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  52008. }
  52009. }
  52010. void resized()
  52011. {
  52012. if (getNumChildComponents() > 0)
  52013. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  52014. }
  52015. void setHighlighted (bool shouldBeHighlighted)
  52016. {
  52017. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  52018. if (isHighlighted != shouldBeHighlighted)
  52019. {
  52020. isHighlighted = shouldBeHighlighted;
  52021. if (itemInfo.customComp != 0)
  52022. {
  52023. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  52024. itemInfo.customComp->repaint();
  52025. }
  52026. repaint();
  52027. }
  52028. }
  52029. private:
  52030. MenuItemComponent (const MenuItemComponent&);
  52031. const MenuItemComponent& operator= (const MenuItemComponent&);
  52032. };
  52033. static const int scrollZone = 24;
  52034. static const int borderSize = 2;
  52035. static const int timerInterval = 50;
  52036. static const int dismissCommandId = 0x6287345f;
  52037. static bool wasHiddenBecauseOfAppChange = false;
  52038. class PopupMenuWindow : public Component,
  52039. private Timer
  52040. {
  52041. public:
  52042. PopupMenuWindow() throw()
  52043. : Component (T("menu")),
  52044. owner (0),
  52045. currentChild (0),
  52046. activeSubMenu (0),
  52047. menuBarComponent (0),
  52048. managerOfChosenCommand (0),
  52049. componentAttachedTo (0),
  52050. attachedCompWatcher (0),
  52051. lastMouseX (0),
  52052. lastMouseY (0),
  52053. minimumWidth (0),
  52054. maximumNumColumns (7),
  52055. standardItemHeight (0),
  52056. isOver (false),
  52057. hasBeenOver (false),
  52058. isDown (false),
  52059. needsToScroll (false),
  52060. hideOnExit (false),
  52061. disableMouseMoves (false),
  52062. hasAnyJuceCompHadFocus (false),
  52063. numColumns (0),
  52064. contentHeight (0),
  52065. childYOffset (0),
  52066. timeEnteredCurrentChildComp (0),
  52067. scrollAcceleration (1.0)
  52068. {
  52069. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  52070. setWantsKeyboardFocus (true);
  52071. setMouseClickGrabsKeyboardFocus (false);
  52072. setOpaque (true);
  52073. setAlwaysOnTop (true);
  52074. Desktop::getInstance().addGlobalMouseListener (this);
  52075. activeMenuWindows.add (this);
  52076. }
  52077. ~PopupMenuWindow()
  52078. {
  52079. activeMenuWindows.removeValue (this);
  52080. Desktop::getInstance().removeGlobalMouseListener (this);
  52081. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52082. delete activeSubMenu;
  52083. deleteAllChildren();
  52084. delete attachedCompWatcher;
  52085. }
  52086. static PopupMenuWindow* create (const PopupMenu& menu,
  52087. const bool dismissOnMouseUp,
  52088. PopupMenuWindow* const owner_,
  52089. const int minX, const int maxX,
  52090. const int minY, const int maxY,
  52091. const int minimumWidth,
  52092. const int maximumNumColumns,
  52093. const int standardItemHeight,
  52094. const bool alignToRectangle,
  52095. const int itemIdThatMustBeVisible,
  52096. Component* const menuBarComponent,
  52097. ApplicationCommandManager** managerOfChosenCommand,
  52098. Component* const componentAttachedTo) throw()
  52099. {
  52100. if (menu.items.size() > 0)
  52101. {
  52102. int totalItems = 0;
  52103. PopupMenuWindow* const mw = new PopupMenuWindow();
  52104. mw->setLookAndFeel (menu.lookAndFeel);
  52105. mw->setWantsKeyboardFocus (false);
  52106. mw->minimumWidth = minimumWidth;
  52107. mw->maximumNumColumns = maximumNumColumns;
  52108. mw->standardItemHeight = standardItemHeight;
  52109. mw->dismissOnMouseUp = dismissOnMouseUp;
  52110. for (int i = 0; i < menu.items.size(); ++i)
  52111. {
  52112. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  52113. mw->addItem (*item);
  52114. ++totalItems;
  52115. }
  52116. if (totalItems == 0)
  52117. {
  52118. delete mw;
  52119. }
  52120. else
  52121. {
  52122. mw->owner = owner_;
  52123. mw->menuBarComponent = menuBarComponent;
  52124. mw->managerOfChosenCommand = managerOfChosenCommand;
  52125. mw->componentAttachedTo = componentAttachedTo;
  52126. delete mw->attachedCompWatcher;
  52127. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  52128. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  52129. mw->setTopLeftPosition (mw->windowPos.getX(),
  52130. mw->windowPos.getY());
  52131. mw->updateYPositions();
  52132. if (itemIdThatMustBeVisible != 0)
  52133. {
  52134. const int y = minY - mw->windowPos.getY();
  52135. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  52136. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  52137. }
  52138. mw->resizeToBestWindowPos();
  52139. mw->addToDesktop (ComponentPeer::windowIsTemporary
  52140. | mw->getLookAndFeel().getMenuWindowFlags());
  52141. return mw;
  52142. }
  52143. }
  52144. return 0;
  52145. }
  52146. void paint (Graphics& g)
  52147. {
  52148. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  52149. }
  52150. void paintOverChildren (Graphics& g)
  52151. {
  52152. if (isScrolling())
  52153. {
  52154. LookAndFeel& lf = getLookAndFeel();
  52155. if (isScrollZoneActive (false))
  52156. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  52157. if (isScrollZoneActive (true))
  52158. {
  52159. g.setOrigin (0, getHeight() - scrollZone);
  52160. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  52161. }
  52162. }
  52163. }
  52164. bool isScrollZoneActive (bool bottomOne) const
  52165. {
  52166. return isScrolling()
  52167. && (bottomOne
  52168. ? childYOffset < contentHeight - windowPos.getHeight()
  52169. : childYOffset > 0);
  52170. }
  52171. void addItem (const MenuItemInfo& item) throw()
  52172. {
  52173. MenuItemComponent* const mic = new MenuItemComponent (item);
  52174. addAndMakeVisible (mic);
  52175. int itemW = 80;
  52176. int itemH = 16;
  52177. mic->getIdealSize (itemW, itemH, standardItemHeight);
  52178. mic->setSize (itemW, jlimit (2, 600, itemH));
  52179. mic->addMouseListener (this, false);
  52180. }
  52181. // hide this and all sub-comps
  52182. void hide (const MenuItemInfo* const item) throw()
  52183. {
  52184. if (isVisible())
  52185. {
  52186. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52187. deleteAndZero (activeSubMenu);
  52188. currentChild = 0;
  52189. exitModalState (item != 0 ? item->itemId : 0);
  52190. setVisible (false);
  52191. if (item != 0
  52192. && item->commandManager != 0
  52193. && item->itemId != 0)
  52194. {
  52195. *managerOfChosenCommand = item->commandManager;
  52196. }
  52197. }
  52198. }
  52199. void dismissMenu (const MenuItemInfo* const item) throw()
  52200. {
  52201. if (owner != 0)
  52202. {
  52203. owner->dismissMenu (item);
  52204. }
  52205. else
  52206. {
  52207. if (item != 0)
  52208. {
  52209. // need a copy of this on the stack as the one passed in will get deleted during this call
  52210. const MenuItemInfo mi (*item);
  52211. hide (&mi);
  52212. }
  52213. else
  52214. {
  52215. hide (0);
  52216. }
  52217. }
  52218. }
  52219. void mouseMove (const MouseEvent&)
  52220. {
  52221. timerCallback();
  52222. }
  52223. void mouseDown (const MouseEvent&)
  52224. {
  52225. timerCallback();
  52226. }
  52227. void mouseDrag (const MouseEvent&)
  52228. {
  52229. timerCallback();
  52230. }
  52231. void mouseUp (const MouseEvent&)
  52232. {
  52233. timerCallback();
  52234. }
  52235. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  52236. {
  52237. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  52238. lastMouseX = -1;
  52239. }
  52240. bool keyPressed (const KeyPress& key)
  52241. {
  52242. if (key.isKeyCode (KeyPress::downKey))
  52243. {
  52244. selectNextItem (1);
  52245. }
  52246. else if (key.isKeyCode (KeyPress::upKey))
  52247. {
  52248. selectNextItem (-1);
  52249. }
  52250. else if (key.isKeyCode (KeyPress::leftKey))
  52251. {
  52252. PopupMenuWindow* parentWindow = owner;
  52253. if (parentWindow != 0)
  52254. {
  52255. MenuItemComponent* currentChildOfParent
  52256. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  52257. hide (0);
  52258. if (parentWindow->isValidComponent())
  52259. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  52260. disableTimerUntilMouseMoves();
  52261. }
  52262. else if (menuBarComponent != 0)
  52263. {
  52264. menuBarComponent->keyPressed (key);
  52265. }
  52266. }
  52267. else if (key.isKeyCode (KeyPress::rightKey))
  52268. {
  52269. disableTimerUntilMouseMoves();
  52270. if (showSubMenuFor (currentChild))
  52271. {
  52272. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52273. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  52274. activeSubMenu->selectNextItem (1);
  52275. }
  52276. else if (menuBarComponent != 0)
  52277. {
  52278. menuBarComponent->keyPressed (key);
  52279. }
  52280. }
  52281. else if (key.isKeyCode (KeyPress::returnKey))
  52282. {
  52283. triggerCurrentlyHighlightedItem();
  52284. }
  52285. else if (key.isKeyCode (KeyPress::escapeKey))
  52286. {
  52287. dismissMenu (0);
  52288. }
  52289. else
  52290. {
  52291. return false;
  52292. }
  52293. return true;
  52294. }
  52295. void inputAttemptWhenModal()
  52296. {
  52297. timerCallback();
  52298. if (! isOverAnyMenu())
  52299. {
  52300. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  52301. {
  52302. // we want to dismiss the menu, but if we do it synchronously, then
  52303. // the mouse-click will be allowed to pass through. That's good, except
  52304. // when the user clicks on the button that orginally popped the menu up,
  52305. // as they'll expect the menu to go away, and in fact it'll just
  52306. // come back. So only dismiss synchronously if they're not on the original
  52307. // comp that we're attached to.
  52308. int mx, my;
  52309. componentAttachedTo->getMouseXYRelative (mx, my);
  52310. if (componentAttachedTo->reallyContains (mx, my, true))
  52311. {
  52312. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  52313. return;
  52314. }
  52315. }
  52316. dismissMenu (0);
  52317. }
  52318. }
  52319. void handleCommandMessage (int commandId)
  52320. {
  52321. Component::handleCommandMessage (commandId);
  52322. if (commandId == dismissCommandId)
  52323. dismissMenu (0);
  52324. }
  52325. void timerCallback()
  52326. {
  52327. if (! isVisible())
  52328. return;
  52329. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  52330. {
  52331. dismissMenu (0);
  52332. return;
  52333. }
  52334. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  52335. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  52336. return;
  52337. startTimer (timerInterval); // do this in case it was called from a mouse
  52338. // move rather than a real timer callback
  52339. int mx, my;
  52340. Desktop::getMousePosition (mx, my);
  52341. int x = mx, y = my;
  52342. globalPositionToRelative (x, y);
  52343. const uint32 now = Time::getMillisecondCounter();
  52344. if (now > timeEnteredCurrentChildComp + 100
  52345. && reallyContains (x, y, true)
  52346. && currentChild->isValidComponent()
  52347. && (! disableMouseMoves)
  52348. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  52349. {
  52350. showSubMenuFor (currentChild);
  52351. }
  52352. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  52353. {
  52354. highlightItemUnderMouse (mx, my, x, y);
  52355. }
  52356. bool overScrollArea = false;
  52357. if (isScrolling()
  52358. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  52359. && ((isScrollZoneActive (false) && y < scrollZone)
  52360. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  52361. {
  52362. if (now > lastScroll + 20)
  52363. {
  52364. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  52365. int amount = 0;
  52366. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  52367. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  52368. alterChildYPos (y < scrollZone ? -amount : amount);
  52369. lastScroll = now;
  52370. }
  52371. overScrollArea = true;
  52372. lastMouseX = -1; // trigger a mouse-move
  52373. }
  52374. else
  52375. {
  52376. scrollAcceleration = 1.0;
  52377. }
  52378. const bool wasDown = isDown;
  52379. bool isOverAny = isOverAnyMenu();
  52380. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  52381. {
  52382. activeSubMenu->updateMouseOverStatus (mx, my);
  52383. isOverAny = isOverAnyMenu();
  52384. }
  52385. if (hideOnExit && hasBeenOver && ! isOverAny)
  52386. {
  52387. hide (0);
  52388. }
  52389. else
  52390. {
  52391. isDown = hasBeenOver
  52392. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  52393. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  52394. bool anyFocused = Process::isForegroundProcess();
  52395. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  52396. {
  52397. // because no component at all may have focus, our test here will
  52398. // only be triggered when something has focus and then loses it.
  52399. anyFocused = ! hasAnyJuceCompHadFocus;
  52400. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  52401. {
  52402. if (ComponentPeer::getPeer (i)->isFocused())
  52403. {
  52404. anyFocused = true;
  52405. hasAnyJuceCompHadFocus = true;
  52406. break;
  52407. }
  52408. }
  52409. }
  52410. if (! anyFocused)
  52411. {
  52412. if (now > lastFocused + 10)
  52413. {
  52414. wasHiddenBecauseOfAppChange = true;
  52415. dismissMenu (0);
  52416. return; // may have been deleted by the previous call..
  52417. }
  52418. }
  52419. else if (wasDown && now > menuCreationTime + 250
  52420. && ! (isDown || overScrollArea))
  52421. {
  52422. isOver = reallyContains (x, y, true);
  52423. if (isOver)
  52424. {
  52425. triggerCurrentlyHighlightedItem();
  52426. }
  52427. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  52428. {
  52429. dismissMenu (0);
  52430. }
  52431. return; // may have been deleted by the previous calls..
  52432. }
  52433. else
  52434. {
  52435. lastFocused = now;
  52436. }
  52437. }
  52438. }
  52439. juce_UseDebuggingNewOperator
  52440. private:
  52441. PopupMenuWindow* owner;
  52442. MenuItemComponent* currentChild;
  52443. PopupMenuWindow* activeSubMenu;
  52444. Component* menuBarComponent;
  52445. ApplicationCommandManager** managerOfChosenCommand;
  52446. Component* componentAttachedTo;
  52447. ComponentDeletionWatcher* attachedCompWatcher;
  52448. Rectangle windowPos;
  52449. int lastMouseX, lastMouseY;
  52450. int minimumWidth, maximumNumColumns, standardItemHeight;
  52451. bool isOver, hasBeenOver, isDown, needsToScroll;
  52452. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  52453. int numColumns, contentHeight, childYOffset;
  52454. Array <int> columnWidths;
  52455. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  52456. double scrollAcceleration;
  52457. bool overlaps (const Rectangle& r) const throw()
  52458. {
  52459. return r.intersects (getBounds())
  52460. || (owner != 0 && owner->overlaps (r));
  52461. }
  52462. bool isOverAnyMenu() const throw()
  52463. {
  52464. return (owner != 0) ? owner->isOverAnyMenu()
  52465. : isOverChildren();
  52466. }
  52467. bool isOverChildren() const throw()
  52468. {
  52469. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52470. return isVisible()
  52471. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  52472. }
  52473. void updateMouseOverStatus (const int mx, const int my) throw()
  52474. {
  52475. int rx = mx, ry = my;
  52476. globalPositionToRelative (rx, ry);
  52477. isOver = reallyContains (rx, ry, true);
  52478. if (activeSubMenu != 0)
  52479. activeSubMenu->updateMouseOverStatus (mx, my);
  52480. }
  52481. bool treeContains (const PopupMenuWindow* const window) const throw()
  52482. {
  52483. const PopupMenuWindow* mw = this;
  52484. while (mw->owner != 0)
  52485. mw = mw->owner;
  52486. while (mw != 0)
  52487. {
  52488. if (mw == window)
  52489. return true;
  52490. mw = mw->activeSubMenu;
  52491. }
  52492. return false;
  52493. }
  52494. void calculateWindowPos (const int minX, const int maxX,
  52495. const int minY, const int maxY,
  52496. const bool alignToRectangle)
  52497. {
  52498. const Rectangle mon (Desktop::getInstance()
  52499. .getMonitorAreaContaining ((minX + maxX) / 2,
  52500. (minY + maxY) / 2,
  52501. #if JUCE_MAC
  52502. true));
  52503. #else
  52504. false)); // on windows, don't stop the menu overlapping the taskbar
  52505. #endif
  52506. int x, y, widthToUse, heightToUse;
  52507. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  52508. if (alignToRectangle)
  52509. {
  52510. x = minX;
  52511. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  52512. const int spaceOver = minY - mon.getY();
  52513. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  52514. y = maxY;
  52515. else
  52516. y = minY - heightToUse;
  52517. }
  52518. else
  52519. {
  52520. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  52521. if (owner != 0)
  52522. {
  52523. if (owner->owner != 0)
  52524. {
  52525. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  52526. > owner->owner->getX() + owner->owner->getWidth() / 2);
  52527. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  52528. tendTowardsRight = true;
  52529. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  52530. tendTowardsRight = false;
  52531. }
  52532. else if (maxX + widthToUse < mon.getRight() - 32)
  52533. {
  52534. tendTowardsRight = true;
  52535. }
  52536. }
  52537. const int biggestSpace = jmax (mon.getRight() - maxX,
  52538. minX - mon.getX()) - 32;
  52539. if (biggestSpace < widthToUse)
  52540. {
  52541. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  52542. if (numColumns > 1)
  52543. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  52544. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  52545. }
  52546. if (tendTowardsRight)
  52547. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  52548. else
  52549. x = jmax (mon.getX() + 4, minX - widthToUse);
  52550. y = minY;
  52551. if ((minY + maxY) / 2 > mon.getCentreY())
  52552. y = jmax (mon.getY(), maxY - heightToUse);
  52553. }
  52554. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  52555. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  52556. windowPos.setBounds (x, y, widthToUse, heightToUse);
  52557. // sets this flag if it's big enough to obscure any of its parent menus
  52558. hideOnExit = (owner != 0)
  52559. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  52560. }
  52561. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  52562. {
  52563. numColumns = 0;
  52564. contentHeight = 0;
  52565. const int maxMenuH = getParentHeight() - 24;
  52566. int totalW;
  52567. do
  52568. {
  52569. ++numColumns;
  52570. totalW = workOutBestSize (numColumns, maxMenuW);
  52571. if (totalW > maxMenuW)
  52572. {
  52573. numColumns = jmax (1, numColumns - 1);
  52574. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  52575. break;
  52576. }
  52577. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  52578. {
  52579. break;
  52580. }
  52581. } while (numColumns < maximumNumColumns);
  52582. const int actualH = jmin (contentHeight, maxMenuH);
  52583. needsToScroll = contentHeight > actualH;
  52584. width = updateYPositions();
  52585. height = actualH + borderSize * 2;
  52586. }
  52587. int workOutBestSize (const int numColumns, const int maxMenuW)
  52588. {
  52589. int totalW = 0;
  52590. contentHeight = 0;
  52591. int childNum = 0;
  52592. for (int col = 0; col < numColumns; ++col)
  52593. {
  52594. int i, colW = 50, colH = 0;
  52595. const int numChildren = jmin (getNumChildComponents() - childNum,
  52596. (getNumChildComponents() + numColumns - 1) / numColumns);
  52597. for (i = numChildren; --i >= 0;)
  52598. {
  52599. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  52600. colH += getChildComponent (childNum + i)->getHeight();
  52601. }
  52602. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  52603. columnWidths.set (col, colW);
  52604. totalW += colW;
  52605. contentHeight = jmax (contentHeight, colH);
  52606. childNum += numChildren;
  52607. }
  52608. if (totalW < minimumWidth)
  52609. {
  52610. totalW = minimumWidth;
  52611. for (int col = 0; col < numColumns; ++col)
  52612. columnWidths.set (0, totalW / numColumns);
  52613. }
  52614. return totalW;
  52615. }
  52616. void ensureItemIsVisible (const int itemId, int wantedY)
  52617. {
  52618. jassert (itemId != 0)
  52619. for (int i = getNumChildComponents(); --i >= 0;)
  52620. {
  52621. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  52622. if (m != 0
  52623. && m->itemInfo.itemId == itemId
  52624. && windowPos.getHeight() > scrollZone * 4)
  52625. {
  52626. const int currentY = m->getY();
  52627. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  52628. {
  52629. if (wantedY < 0)
  52630. wantedY = jlimit (scrollZone,
  52631. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  52632. currentY);
  52633. const Rectangle mon (Desktop::getInstance()
  52634. .getMonitorAreaContaining (windowPos.getX(),
  52635. windowPos.getY(),
  52636. true));
  52637. int deltaY = wantedY - currentY;
  52638. const int newY = jlimit (mon.getY(),
  52639. mon.getBottom() - windowPos.getHeight(),
  52640. windowPos.getY() + deltaY);
  52641. deltaY -= newY - windowPos.getY();
  52642. childYOffset -= deltaY;
  52643. windowPos.setPosition (windowPos.getX(), newY);
  52644. updateYPositions();
  52645. }
  52646. break;
  52647. }
  52648. }
  52649. }
  52650. void resizeToBestWindowPos()
  52651. {
  52652. Rectangle r (windowPos);
  52653. if (childYOffset < 0)
  52654. {
  52655. r.setBounds (r.getX(), r.getY() - childYOffset,
  52656. r.getWidth(), r.getHeight() + childYOffset);
  52657. }
  52658. else if (childYOffset > 0)
  52659. {
  52660. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  52661. if (spaceAtBottom > 0)
  52662. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  52663. }
  52664. setBounds (r);
  52665. updateYPositions();
  52666. }
  52667. void alterChildYPos (const int delta)
  52668. {
  52669. if (isScrolling())
  52670. {
  52671. childYOffset += delta;
  52672. if (delta < 0)
  52673. {
  52674. childYOffset = jmax (childYOffset, 0);
  52675. }
  52676. else if (delta > 0)
  52677. {
  52678. childYOffset = jmin (childYOffset,
  52679. contentHeight - windowPos.getHeight() + borderSize);
  52680. }
  52681. updateYPositions();
  52682. }
  52683. else
  52684. {
  52685. childYOffset = 0;
  52686. }
  52687. resizeToBestWindowPos();
  52688. repaint();
  52689. }
  52690. int updateYPositions()
  52691. {
  52692. int x = 0;
  52693. int childNum = 0;
  52694. for (int col = 0; col < numColumns; ++col)
  52695. {
  52696. const int numChildren = jmin (getNumChildComponents() - childNum,
  52697. (getNumChildComponents() + numColumns - 1) / numColumns);
  52698. const int colW = columnWidths [col];
  52699. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  52700. for (int i = 0; i < numChildren; ++i)
  52701. {
  52702. Component* const c = getChildComponent (childNum + i);
  52703. c->setBounds (x, y, colW, c->getHeight());
  52704. y += c->getHeight();
  52705. }
  52706. x += colW;
  52707. childNum += numChildren;
  52708. }
  52709. return x;
  52710. }
  52711. bool isScrolling() const throw()
  52712. {
  52713. return childYOffset != 0 || needsToScroll;
  52714. }
  52715. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  52716. {
  52717. if (currentChild->isValidComponent())
  52718. currentChild->setHighlighted (false);
  52719. currentChild = child;
  52720. if (currentChild != 0)
  52721. {
  52722. currentChild->setHighlighted (true);
  52723. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  52724. }
  52725. }
  52726. bool showSubMenuFor (MenuItemComponent* const childComp)
  52727. {
  52728. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  52729. deleteAndZero (activeSubMenu);
  52730. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  52731. {
  52732. int left = 0, top = 0;
  52733. childComp->relativePositionToGlobal (left, top);
  52734. int right = childComp->getWidth(), bottom = childComp->getHeight();
  52735. childComp->relativePositionToGlobal (right, bottom);
  52736. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  52737. dismissOnMouseUp,
  52738. this,
  52739. left, right, top, bottom,
  52740. 0, maximumNumColumns,
  52741. standardItemHeight,
  52742. false, 0, menuBarComponent,
  52743. managerOfChosenCommand,
  52744. componentAttachedTo);
  52745. if (activeSubMenu != 0)
  52746. {
  52747. activeSubMenu->setVisible (true);
  52748. activeSubMenu->enterModalState (false);
  52749. activeSubMenu->toFront (false);
  52750. return true;
  52751. }
  52752. }
  52753. return false;
  52754. }
  52755. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  52756. {
  52757. isOver = reallyContains (x, y, true);
  52758. if (isOver)
  52759. hasBeenOver = true;
  52760. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  52761. {
  52762. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  52763. if (disableMouseMoves && isOver)
  52764. disableMouseMoves = false;
  52765. }
  52766. if (disableMouseMoves)
  52767. return;
  52768. bool isMovingTowardsMenu = false;
  52769. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  52770. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  52771. {
  52772. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  52773. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  52774. // extends from the last mouse pos to the submenu's rectangle..
  52775. float subX = (float) activeSubMenu->getScreenX();
  52776. if (activeSubMenu->getX() > getX())
  52777. {
  52778. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  52779. }
  52780. else
  52781. {
  52782. lastMouseX += 2;
  52783. subX += activeSubMenu->getWidth();
  52784. }
  52785. Path areaTowardsSubMenu;
  52786. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  52787. (float) lastMouseY,
  52788. subX,
  52789. (float) activeSubMenu->getScreenY(),
  52790. subX,
  52791. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  52792. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  52793. }
  52794. lastMouseX = mx;
  52795. lastMouseY = my;
  52796. if (! isMovingTowardsMenu)
  52797. {
  52798. Component* c = getComponentAt (x, y);
  52799. if (c == this)
  52800. c = 0;
  52801. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  52802. if (mic == 0 && c != 0)
  52803. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  52804. if (mic != currentChild
  52805. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  52806. {
  52807. if (isOver && (c != 0) && (activeSubMenu != 0))
  52808. {
  52809. activeSubMenu->hide (0);
  52810. }
  52811. if (! isOver)
  52812. mic = 0;
  52813. setCurrentlyHighlightedChild (mic);
  52814. }
  52815. }
  52816. }
  52817. void triggerCurrentlyHighlightedItem()
  52818. {
  52819. if (currentChild->isValidComponent()
  52820. && currentChild->itemInfo.canBeTriggered()
  52821. && (currentChild->itemInfo.customComp == 0
  52822. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  52823. {
  52824. dismissMenu (&currentChild->itemInfo);
  52825. }
  52826. }
  52827. void selectNextItem (const int delta)
  52828. {
  52829. disableTimerUntilMouseMoves();
  52830. MenuItemComponent* mic = 0;
  52831. bool wasLastOne = (currentChild == 0);
  52832. const int numItems = getNumChildComponents();
  52833. for (int i = 0; i < numItems + 1; ++i)
  52834. {
  52835. int index = (delta > 0) ? i : (numItems - 1 - i);
  52836. index = (index + numItems) % numItems;
  52837. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  52838. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  52839. && wasLastOne)
  52840. break;
  52841. if (mic == currentChild)
  52842. wasLastOne = true;
  52843. }
  52844. setCurrentlyHighlightedChild (mic);
  52845. }
  52846. void disableTimerUntilMouseMoves() throw()
  52847. {
  52848. disableMouseMoves = true;
  52849. if (owner != 0)
  52850. owner->disableTimerUntilMouseMoves();
  52851. }
  52852. PopupMenuWindow (const PopupMenuWindow&);
  52853. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  52854. };
  52855. PopupMenu::PopupMenu() throw()
  52856. : items (8),
  52857. lookAndFeel (0),
  52858. separatorPending (false)
  52859. {
  52860. }
  52861. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  52862. : items (8),
  52863. lookAndFeel (other.lookAndFeel),
  52864. separatorPending (false)
  52865. {
  52866. items.ensureStorageAllocated (other.items.size());
  52867. for (int i = 0; i < other.items.size(); ++i)
  52868. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52869. }
  52870. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  52871. {
  52872. if (this != &other)
  52873. {
  52874. lookAndFeel = other.lookAndFeel;
  52875. clear();
  52876. items.ensureStorageAllocated (other.items.size());
  52877. for (int i = 0; i < other.items.size(); ++i)
  52878. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  52879. }
  52880. return *this;
  52881. }
  52882. PopupMenu::~PopupMenu() throw()
  52883. {
  52884. clear();
  52885. }
  52886. void PopupMenu::clear() throw()
  52887. {
  52888. for (int i = items.size(); --i >= 0;)
  52889. {
  52890. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  52891. delete mi;
  52892. }
  52893. items.clear();
  52894. separatorPending = false;
  52895. }
  52896. void PopupMenu::addSeparatorIfPending()
  52897. {
  52898. if (separatorPending)
  52899. {
  52900. separatorPending = false;
  52901. if (items.size() > 0)
  52902. items.add (new MenuItemInfo());
  52903. }
  52904. }
  52905. void PopupMenu::addItem (const int itemResultId,
  52906. const String& itemText,
  52907. const bool isActive,
  52908. const bool isTicked,
  52909. const Image* const iconToUse) throw()
  52910. {
  52911. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52912. // didn't pick anything, so you shouldn't use it as the id
  52913. // for an item..
  52914. addSeparatorIfPending();
  52915. items.add (new MenuItemInfo (itemResultId,
  52916. itemText,
  52917. isActive,
  52918. isTicked,
  52919. iconToUse,
  52920. Colours::black,
  52921. false,
  52922. 0, 0, 0));
  52923. }
  52924. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  52925. const int commandID,
  52926. const String& displayName) throw()
  52927. {
  52928. jassert (commandManager != 0 && commandID != 0);
  52929. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  52930. if (registeredInfo != 0)
  52931. {
  52932. ApplicationCommandInfo info (*registeredInfo);
  52933. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  52934. addSeparatorIfPending();
  52935. items.add (new MenuItemInfo (commandID,
  52936. displayName.isNotEmpty() ? displayName
  52937. : info.shortName,
  52938. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  52939. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  52940. 0,
  52941. Colours::black,
  52942. false,
  52943. 0, 0,
  52944. commandManager));
  52945. }
  52946. }
  52947. void PopupMenu::addColouredItem (const int itemResultId,
  52948. const String& itemText,
  52949. const Colour& itemTextColour,
  52950. const bool isActive,
  52951. const bool isTicked,
  52952. const Image* const iconToUse) throw()
  52953. {
  52954. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52955. // didn't pick anything, so you shouldn't use it as the id
  52956. // for an item..
  52957. addSeparatorIfPending();
  52958. items.add (new MenuItemInfo (itemResultId,
  52959. itemText,
  52960. isActive,
  52961. isTicked,
  52962. iconToUse,
  52963. itemTextColour,
  52964. true,
  52965. 0, 0, 0));
  52966. }
  52967. void PopupMenu::addCustomItem (const int itemResultId,
  52968. PopupMenuCustomComponent* const customComponent) throw()
  52969. {
  52970. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  52971. // didn't pick anything, so you shouldn't use it as the id
  52972. // for an item..
  52973. addSeparatorIfPending();
  52974. items.add (new MenuItemInfo (itemResultId,
  52975. String::empty,
  52976. true,
  52977. false,
  52978. 0,
  52979. Colours::black,
  52980. false,
  52981. customComponent,
  52982. 0, 0));
  52983. }
  52984. class NormalComponentWrapper : public PopupMenuCustomComponent
  52985. {
  52986. public:
  52987. NormalComponentWrapper (Component* const comp,
  52988. const int w, const int h,
  52989. const bool triggerMenuItemAutomaticallyWhenClicked)
  52990. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  52991. width (w),
  52992. height (h)
  52993. {
  52994. addAndMakeVisible (comp);
  52995. }
  52996. ~NormalComponentWrapper() {}
  52997. void getIdealSize (int& idealWidth, int& idealHeight)
  52998. {
  52999. idealWidth = width;
  53000. idealHeight = height;
  53001. }
  53002. void resized()
  53003. {
  53004. if (getChildComponent(0) != 0)
  53005. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  53006. }
  53007. juce_UseDebuggingNewOperator
  53008. private:
  53009. const int width, height;
  53010. NormalComponentWrapper (const NormalComponentWrapper&);
  53011. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  53012. };
  53013. void PopupMenu::addCustomItem (const int itemResultId,
  53014. Component* customComponent,
  53015. int idealWidth, int idealHeight,
  53016. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  53017. {
  53018. addCustomItem (itemResultId,
  53019. new NormalComponentWrapper (customComponent,
  53020. idealWidth, idealHeight,
  53021. triggerMenuItemAutomaticallyWhenClicked));
  53022. }
  53023. void PopupMenu::addSubMenu (const String& subMenuName,
  53024. const PopupMenu& subMenu,
  53025. const bool isActive,
  53026. Image* const iconToUse,
  53027. const bool isTicked) throw()
  53028. {
  53029. addSeparatorIfPending();
  53030. items.add (new MenuItemInfo (0,
  53031. subMenuName,
  53032. isActive && (subMenu.getNumItems() > 0),
  53033. isTicked,
  53034. iconToUse,
  53035. Colours::black,
  53036. false,
  53037. 0,
  53038. &subMenu,
  53039. 0));
  53040. }
  53041. void PopupMenu::addSeparator() throw()
  53042. {
  53043. separatorPending = true;
  53044. }
  53045. class HeaderItemComponent : public PopupMenuCustomComponent
  53046. {
  53047. public:
  53048. HeaderItemComponent (const String& name)
  53049. : PopupMenuCustomComponent (false)
  53050. {
  53051. setName (name);
  53052. }
  53053. ~HeaderItemComponent()
  53054. {
  53055. }
  53056. void paint (Graphics& g)
  53057. {
  53058. Font f (getLookAndFeel().getPopupMenuFont());
  53059. f.setBold (true);
  53060. g.setFont (f);
  53061. g.setColour (findColour (PopupMenu::headerTextColourId));
  53062. g.drawFittedText (getName(),
  53063. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  53064. Justification::bottomLeft, 1);
  53065. }
  53066. void getIdealSize (int& idealWidth,
  53067. int& idealHeight)
  53068. {
  53069. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  53070. idealHeight += idealHeight / 2;
  53071. idealWidth += idealWidth / 4;
  53072. }
  53073. juce_UseDebuggingNewOperator
  53074. };
  53075. void PopupMenu::addSectionHeader (const String& title) throw()
  53076. {
  53077. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  53078. }
  53079. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  53080. const int itemIdThatMustBeVisible,
  53081. const int minimumWidth,
  53082. const int maximumNumColumns,
  53083. const int standardItemHeight,
  53084. const bool alignToRectangle,
  53085. Component* menuBarComponent,
  53086. ApplicationCommandManager** managerOfChosenCommand,
  53087. Component* const componentAttachedTo) throw()
  53088. {
  53089. PopupMenuWindow* const pw
  53090. = PopupMenuWindow::create (*this,
  53091. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  53092. 0,
  53093. x, x + w,
  53094. y, y + h,
  53095. minimumWidth,
  53096. maximumNumColumns,
  53097. standardItemHeight,
  53098. alignToRectangle,
  53099. itemIdThatMustBeVisible,
  53100. menuBarComponent,
  53101. managerOfChosenCommand,
  53102. componentAttachedTo);
  53103. if (pw != 0)
  53104. pw->setVisible (true);
  53105. return pw;
  53106. }
  53107. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  53108. const int itemIdThatMustBeVisible,
  53109. const int minimumWidth,
  53110. const int maximumNumColumns,
  53111. const int standardItemHeight,
  53112. const bool alignToRectangle,
  53113. Component* const componentAttachedTo) throw()
  53114. {
  53115. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  53116. ComponentDeletionWatcher* deletionChecker1 = 0;
  53117. if (prevFocused != 0)
  53118. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  53119. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  53120. ComponentDeletionWatcher* deletionChecker2 = 0;
  53121. if (prevTopLevel != 0)
  53122. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  53123. wasHiddenBecauseOfAppChange = false;
  53124. int result = 0;
  53125. ApplicationCommandManager* managerOfChosenCommand = 0;
  53126. Component* const popupComp = createMenuComponent (x, y, w, h,
  53127. itemIdThatMustBeVisible,
  53128. minimumWidth,
  53129. maximumNumColumns > 0 ? maximumNumColumns : 7,
  53130. standardItemHeight,
  53131. alignToRectangle, 0,
  53132. &managerOfChosenCommand,
  53133. componentAttachedTo);
  53134. if (popupComp != 0)
  53135. {
  53136. popupComp->enterModalState (false);
  53137. popupComp->toFront (false); // need to do this after making it modal, or it could
  53138. // be stuck behind other comps that are already modal..
  53139. result = popupComp->runModalLoop();
  53140. delete popupComp;
  53141. if (! wasHiddenBecauseOfAppChange)
  53142. {
  53143. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  53144. prevTopLevel->toFront (true);
  53145. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  53146. prevFocused->grabKeyboardFocus();
  53147. }
  53148. }
  53149. delete deletionChecker1;
  53150. delete deletionChecker2;
  53151. if (managerOfChosenCommand != 0 && result != 0)
  53152. {
  53153. ApplicationCommandTarget::InvocationInfo info (result);
  53154. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  53155. managerOfChosenCommand->invoke (info, true);
  53156. }
  53157. return result;
  53158. }
  53159. int PopupMenu::show (const int itemIdThatMustBeVisible,
  53160. const int minimumWidth,
  53161. const int maximumNumColumns,
  53162. const int standardItemHeight)
  53163. {
  53164. int x, y;
  53165. Desktop::getMousePosition (x, y);
  53166. return showAt (x, y,
  53167. itemIdThatMustBeVisible,
  53168. minimumWidth,
  53169. maximumNumColumns,
  53170. standardItemHeight);
  53171. }
  53172. int PopupMenu::showAt (const int screenX,
  53173. const int screenY,
  53174. const int itemIdThatMustBeVisible,
  53175. const int minimumWidth,
  53176. const int maximumNumColumns,
  53177. const int standardItemHeight)
  53178. {
  53179. return showMenu (screenX, screenY, 1, 1,
  53180. itemIdThatMustBeVisible,
  53181. minimumWidth, maximumNumColumns,
  53182. standardItemHeight,
  53183. false, 0);
  53184. }
  53185. int PopupMenu::showAt (Component* componentToAttachTo,
  53186. const int itemIdThatMustBeVisible,
  53187. const int minimumWidth,
  53188. const int maximumNumColumns,
  53189. const int standardItemHeight)
  53190. {
  53191. if (componentToAttachTo != 0)
  53192. {
  53193. return showMenu (componentToAttachTo->getScreenX(),
  53194. componentToAttachTo->getScreenY(),
  53195. componentToAttachTo->getWidth(),
  53196. componentToAttachTo->getHeight(),
  53197. itemIdThatMustBeVisible,
  53198. minimumWidth,
  53199. maximumNumColumns,
  53200. standardItemHeight,
  53201. true, componentToAttachTo);
  53202. }
  53203. else
  53204. {
  53205. return show (itemIdThatMustBeVisible,
  53206. minimumWidth,
  53207. maximumNumColumns,
  53208. standardItemHeight);
  53209. }
  53210. }
  53211. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  53212. {
  53213. for (int i = activeMenuWindows.size(); --i >= 0;)
  53214. {
  53215. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  53216. if (pmw != 0)
  53217. pmw->dismissMenu (0);
  53218. }
  53219. }
  53220. int PopupMenu::getNumItems() const throw()
  53221. {
  53222. int num = 0;
  53223. for (int i = items.size(); --i >= 0;)
  53224. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  53225. ++num;
  53226. return num;
  53227. }
  53228. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  53229. {
  53230. for (int i = items.size(); --i >= 0;)
  53231. {
  53232. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  53233. if ((mi->itemId == commandID && mi->commandManager != 0)
  53234. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  53235. {
  53236. return true;
  53237. }
  53238. }
  53239. return false;
  53240. }
  53241. bool PopupMenu::containsAnyActiveItems() const throw()
  53242. {
  53243. for (int i = items.size(); --i >= 0;)
  53244. {
  53245. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  53246. if (mi->subMenu != 0)
  53247. {
  53248. if (mi->subMenu->containsAnyActiveItems())
  53249. return true;
  53250. }
  53251. else if (mi->active)
  53252. {
  53253. return true;
  53254. }
  53255. }
  53256. return false;
  53257. }
  53258. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  53259. {
  53260. lookAndFeel = newLookAndFeel;
  53261. }
  53262. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  53263. : refCount_ (0),
  53264. isHighlighted (false),
  53265. isTriggeredAutomatically (isTriggeredAutomatically_)
  53266. {
  53267. }
  53268. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  53269. {
  53270. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  53271. }
  53272. void PopupMenuCustomComponent::triggerMenuItem()
  53273. {
  53274. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  53275. if (mic != 0)
  53276. {
  53277. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  53278. if (pmw != 0)
  53279. {
  53280. pmw->dismissMenu (&mic->itemInfo);
  53281. }
  53282. else
  53283. {
  53284. // something must have gone wrong with the component hierarchy if this happens..
  53285. jassertfalse
  53286. }
  53287. }
  53288. else
  53289. {
  53290. // why isn't this component inside a menu? Not much point triggering the item if
  53291. // there's no menu.
  53292. jassertfalse
  53293. }
  53294. }
  53295. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  53296. : subMenu (0),
  53297. itemId (0),
  53298. isSeparator (false),
  53299. isTicked (false),
  53300. isEnabled (false),
  53301. isCustomComponent (false),
  53302. isSectionHeader (false),
  53303. customColour (0),
  53304. customImage (0),
  53305. menu (menu_),
  53306. index (0)
  53307. {
  53308. }
  53309. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  53310. {
  53311. }
  53312. bool PopupMenu::MenuItemIterator::next() throw()
  53313. {
  53314. if (index >= menu.items.size())
  53315. return false;
  53316. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  53317. ++index;
  53318. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  53319. subMenu = item->subMenu;
  53320. itemId = item->itemId;
  53321. isSeparator = item->isSeparator;
  53322. isTicked = item->isTicked;
  53323. isEnabled = item->active;
  53324. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  53325. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  53326. customColour = item->usesColour ? &(item->textColour) : 0;
  53327. customImage = item->image;
  53328. commandManager = item->commandManager;
  53329. return true;
  53330. }
  53331. END_JUCE_NAMESPACE
  53332. /********* End of inlined file: juce_PopupMenu.cpp *********/
  53333. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  53334. BEGIN_JUCE_NAMESPACE
  53335. ComponentDragger::ComponentDragger()
  53336. : constrainer (0),
  53337. originalX (0),
  53338. originalY (0)
  53339. {
  53340. }
  53341. ComponentDragger::~ComponentDragger()
  53342. {
  53343. }
  53344. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  53345. ComponentBoundsConstrainer* const constrainer_)
  53346. {
  53347. jassert (componentToDrag->isValidComponent());
  53348. if (componentToDrag->isValidComponent())
  53349. {
  53350. constrainer = constrainer_;
  53351. originalX = 0;
  53352. originalY = 0;
  53353. componentToDrag->relativePositionToGlobal (originalX, originalY);
  53354. }
  53355. }
  53356. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  53357. {
  53358. jassert (componentToDrag->isValidComponent());
  53359. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  53360. if (componentToDrag->isValidComponent())
  53361. {
  53362. int x = originalX;
  53363. int y = originalY;
  53364. int w = componentToDrag->getWidth();
  53365. int h = componentToDrag->getHeight();
  53366. const Component* const parentComp = componentToDrag->getParentComponent();
  53367. if (parentComp != 0)
  53368. parentComp->globalPositionToRelative (x, y);
  53369. x += e.getDistanceFromDragStartX();
  53370. y += e.getDistanceFromDragStartY();
  53371. if (constrainer != 0)
  53372. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  53373. false, false, false, false);
  53374. else
  53375. componentToDrag->setBounds (x, y, w, h);
  53376. }
  53377. }
  53378. END_JUCE_NAMESPACE
  53379. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  53380. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  53381. BEGIN_JUCE_NAMESPACE
  53382. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  53383. bool juce_performDragDropText (const String& text, bool& shouldStop);
  53384. class DragImageComponent : public Component,
  53385. public Timer
  53386. {
  53387. private:
  53388. Image* image;
  53389. Component* const source;
  53390. DragAndDropContainer* const owner;
  53391. ComponentDeletionWatcher* sourceWatcher;
  53392. Component* mouseDragSource;
  53393. ComponentDeletionWatcher* mouseDragSourceWatcher;
  53394. DragAndDropTarget* currentlyOver;
  53395. ComponentDeletionWatcher* currentlyOverWatcher;
  53396. String dragDesc;
  53397. int xOff, yOff;
  53398. bool hasCheckedForExternalDrag, drawImage;
  53399. DragImageComponent (const DragImageComponent&);
  53400. const DragImageComponent& operator= (const DragImageComponent&);
  53401. public:
  53402. DragImageComponent (Image* const im,
  53403. const String& desc,
  53404. Component* const s,
  53405. DragAndDropContainer* const o)
  53406. : image (im),
  53407. source (s),
  53408. owner (o),
  53409. currentlyOver (0),
  53410. currentlyOverWatcher (0),
  53411. dragDesc (desc),
  53412. hasCheckedForExternalDrag (false),
  53413. drawImage (true)
  53414. {
  53415. setSize (im->getWidth(), im->getHeight());
  53416. sourceWatcher = new ComponentDeletionWatcher (source);
  53417. mouseDragSource = Component::getComponentUnderMouse();
  53418. if (mouseDragSource == 0)
  53419. mouseDragSource = source;
  53420. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  53421. mouseDragSource->addMouseListener (this, false);
  53422. int mx, my;
  53423. Desktop::getLastMouseDownPosition (mx, my);
  53424. source->globalPositionToRelative (mx, my);
  53425. xOff = jlimit (0, im->getWidth(), mx);
  53426. yOff = jlimit (0, im->getHeight(), my);
  53427. startTimer (200);
  53428. setInterceptsMouseClicks (false, false);
  53429. setAlwaysOnTop (true);
  53430. }
  53431. ~DragImageComponent()
  53432. {
  53433. if (owner->dragImageComponent == this)
  53434. owner->dragImageComponent = 0;
  53435. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53436. {
  53437. mouseDragSource->removeMouseListener (this);
  53438. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53439. if (currentlyOver->isInterestedInDragSource (dragDesc, source))
  53440. currentlyOver->itemDragExit (dragDesc, source);
  53441. }
  53442. delete mouseDragSourceWatcher;
  53443. delete sourceWatcher;
  53444. delete image;
  53445. delete currentlyOverWatcher;
  53446. }
  53447. void paint (Graphics& g)
  53448. {
  53449. if (isOpaque())
  53450. g.fillAll (Colours::white);
  53451. if (drawImage)
  53452. {
  53453. g.setOpacity (1.0f);
  53454. g.drawImageAt (image, 0, 0);
  53455. }
  53456. }
  53457. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  53458. int& relX, int& relY) const throw()
  53459. {
  53460. Component* hit = getParentComponent();
  53461. if (hit == 0)
  53462. {
  53463. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  53464. }
  53465. else
  53466. {
  53467. int rx = screenX, ry = screenY;
  53468. hit->globalPositionToRelative (rx, ry);
  53469. hit = hit->getComponentAt (rx, ry);
  53470. }
  53471. // (note: use a local copy of the dragDesc member in case the callback runs
  53472. // a modal loop and deletes this object before the method completes)
  53473. const String dragDescLocal (dragDesc);
  53474. while (hit != 0)
  53475. {
  53476. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  53477. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  53478. {
  53479. relX = screenX;
  53480. relY = screenY;
  53481. hit->globalPositionToRelative (relX, relY);
  53482. return ddt;
  53483. }
  53484. hit = hit->getParentComponent();
  53485. }
  53486. return 0;
  53487. }
  53488. void mouseUp (const MouseEvent& e)
  53489. {
  53490. if (e.originalComponent != this)
  53491. {
  53492. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53493. mouseDragSource->removeMouseListener (this);
  53494. bool dropAccepted = false;
  53495. DragAndDropTarget* ddt = 0;
  53496. int relX = 0, relY = 0;
  53497. if (isVisible())
  53498. {
  53499. setVisible (false);
  53500. ddt = findTarget (e.getScreenX(),
  53501. e.getScreenY(),
  53502. relX, relY);
  53503. // fade this component and remove it - it'll be deleted later by the timer callback
  53504. dropAccepted = ddt != 0;
  53505. setVisible (true);
  53506. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  53507. {
  53508. fadeOutComponent (120);
  53509. }
  53510. else
  53511. {
  53512. int targetX = source->getWidth() / 2;
  53513. int targetY = source->getHeight() / 2;
  53514. source->relativePositionToGlobal (targetX, targetY);
  53515. int ourCentreX = getWidth() / 2;
  53516. int ourCentreY = getHeight() / 2;
  53517. relativePositionToGlobal (ourCentreX, ourCentreY);
  53518. fadeOutComponent (120,
  53519. targetX - ourCentreX,
  53520. targetY - ourCentreY);
  53521. }
  53522. }
  53523. if (getParentComponent() != 0)
  53524. getParentComponent()->removeChildComponent (this);
  53525. if (dropAccepted && ddt != 0)
  53526. {
  53527. // (note: use a local copy of the dragDesc member in case the callback runs
  53528. // a modal loop and deletes this object before the method completes)
  53529. const String dragDescLocal (dragDesc);
  53530. currentlyOver = 0;
  53531. deleteAndZero (currentlyOverWatcher);
  53532. ddt->itemDropped (dragDescLocal, source, relX, relY);
  53533. }
  53534. // careful - this object could now be deleted..
  53535. }
  53536. }
  53537. void updateLocation (const bool canDoExternalDrag, int x, int y)
  53538. {
  53539. // (note: use a local copy of the dragDesc member in case the callback runs
  53540. // a modal loop and deletes this object before it returns)
  53541. const String dragDescLocal (dragDesc);
  53542. int newX = x - xOff;
  53543. int newY = y - yOff;
  53544. if (getParentComponent() != 0)
  53545. getParentComponent()->globalPositionToRelative (newX, newY);
  53546. if (newX != getX() || newY != getY())
  53547. {
  53548. setTopLeftPosition (newX, newY);
  53549. int relX = 0, relY = 0;
  53550. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  53551. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  53552. if (ddt != currentlyOver)
  53553. {
  53554. if (currentlyOverWatcher != 0 && ! currentlyOverWatcher->hasBeenDeleted())
  53555. {
  53556. Component* const over = dynamic_cast <Component*> (currentlyOver);
  53557. if (over != 0
  53558. && over->isValidComponent()
  53559. && ! (sourceWatcher->hasBeenDeleted())
  53560. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53561. {
  53562. currentlyOver->itemDragExit (dragDescLocal, source);
  53563. }
  53564. }
  53565. currentlyOver = ddt;
  53566. deleteAndZero (currentlyOverWatcher);
  53567. if (ddt != 0)
  53568. {
  53569. currentlyOverWatcher = new ComponentDeletionWatcher (dynamic_cast <Component*> (ddt));
  53570. if (currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53571. currentlyOver->itemDragEnter (dragDescLocal, source, relX, relY);
  53572. }
  53573. }
  53574. else if (currentlyOverWatcher != 0 && currentlyOverWatcher->hasBeenDeleted())
  53575. {
  53576. currentlyOver = 0;
  53577. deleteAndZero (currentlyOverWatcher);
  53578. }
  53579. if (currentlyOver != 0
  53580. && currentlyOver->isInterestedInDragSource (dragDescLocal, source))
  53581. currentlyOver->itemDragMove (dragDescLocal, source, relX, relY);
  53582. if (currentlyOver == 0
  53583. && canDoExternalDrag
  53584. && ! hasCheckedForExternalDrag)
  53585. {
  53586. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  53587. {
  53588. hasCheckedForExternalDrag = true;
  53589. StringArray files;
  53590. bool canMoveFiles = false;
  53591. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  53592. && files.size() > 0)
  53593. {
  53594. ComponentDeletionWatcher cdw (this);
  53595. setVisible (false);
  53596. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  53597. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  53598. if (! cdw.hasBeenDeleted())
  53599. delete this;
  53600. return;
  53601. }
  53602. }
  53603. }
  53604. }
  53605. }
  53606. void mouseDrag (const MouseEvent& e)
  53607. {
  53608. if (e.originalComponent != this)
  53609. updateLocation (true, e.getScreenX(), e.getScreenY());
  53610. }
  53611. void timerCallback()
  53612. {
  53613. if (sourceWatcher->hasBeenDeleted())
  53614. {
  53615. delete this;
  53616. }
  53617. else if (! isMouseButtonDownAnywhere())
  53618. {
  53619. if (! mouseDragSourceWatcher->hasBeenDeleted())
  53620. mouseDragSource->removeMouseListener (this);
  53621. delete this;
  53622. }
  53623. }
  53624. };
  53625. DragAndDropContainer::DragAndDropContainer()
  53626. : dragImageComponent (0)
  53627. {
  53628. }
  53629. DragAndDropContainer::~DragAndDropContainer()
  53630. {
  53631. if (dragImageComponent != 0)
  53632. delete dragImageComponent;
  53633. }
  53634. void DragAndDropContainer::startDragging (const String& sourceDescription,
  53635. Component* sourceComponent,
  53636. Image* im,
  53637. const bool allowDraggingToExternalWindows)
  53638. {
  53639. if (dragImageComponent != 0)
  53640. {
  53641. if (im != 0)
  53642. delete im;
  53643. }
  53644. else
  53645. {
  53646. Component* const thisComp = dynamic_cast <Component*> (this);
  53647. if (thisComp != 0)
  53648. {
  53649. int mx, my;
  53650. Desktop::getLastMouseDownPosition (mx, my);
  53651. if (im == 0)
  53652. {
  53653. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  53654. if (im->getFormat() != Image::ARGB)
  53655. {
  53656. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  53657. Graphics g2 (*newIm);
  53658. g2.drawImageAt (im, 0, 0);
  53659. delete im;
  53660. im = newIm;
  53661. }
  53662. im->multiplyAllAlphas (0.6f);
  53663. const int lo = 150;
  53664. const int hi = 400;
  53665. int rx = mx, ry = my;
  53666. sourceComponent->globalPositionToRelative (rx, ry);
  53667. const int cx = jlimit (0, im->getWidth(), rx);
  53668. const int cy = jlimit (0, im->getHeight(), ry);
  53669. for (int y = im->getHeight(); --y >= 0;)
  53670. {
  53671. const double dy = (y - cy) * (y - cy);
  53672. for (int x = im->getWidth(); --x >= 0;)
  53673. {
  53674. const int dx = x - cx;
  53675. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  53676. if (distance > lo)
  53677. {
  53678. const float alpha = (distance > hi) ? 0
  53679. : (hi - distance) / (float) (hi - lo)
  53680. + Random::getSystemRandom().nextFloat() * 0.008f;
  53681. im->multiplyAlphaAt (x, y, alpha);
  53682. }
  53683. }
  53684. }
  53685. }
  53686. DragImageComponent* const dic
  53687. = new DragImageComponent (im,
  53688. sourceDescription,
  53689. sourceComponent,
  53690. this);
  53691. dragImageComponent = dic;
  53692. currentDragDesc = sourceDescription;
  53693. if (allowDraggingToExternalWindows)
  53694. {
  53695. if (! Desktop::canUseSemiTransparentWindows())
  53696. dic->setOpaque (true);
  53697. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53698. | ComponentPeer::windowIsTemporary);
  53699. }
  53700. else
  53701. thisComp->addChildComponent (dic);
  53702. dic->updateLocation (false, mx, my);
  53703. dic->setVisible (true);
  53704. }
  53705. else
  53706. {
  53707. // this class must only be implemented by an object that
  53708. // is also a Component.
  53709. jassertfalse
  53710. if (im != 0)
  53711. delete im;
  53712. }
  53713. }
  53714. }
  53715. bool DragAndDropContainer::isDragAndDropActive() const
  53716. {
  53717. return dragImageComponent != 0;
  53718. }
  53719. const String DragAndDropContainer::getCurrentDragDescription() const
  53720. {
  53721. return (dragImageComponent != 0) ? currentDragDesc
  53722. : String::empty;
  53723. }
  53724. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  53725. {
  53726. if (c == 0)
  53727. return 0;
  53728. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53729. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  53730. }
  53731. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  53732. {
  53733. return false;
  53734. }
  53735. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  53736. {
  53737. }
  53738. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  53739. {
  53740. }
  53741. void DragAndDropTarget::itemDragExit (const String&, Component*)
  53742. {
  53743. }
  53744. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  53745. {
  53746. return true;
  53747. }
  53748. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  53749. {
  53750. }
  53751. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  53752. {
  53753. }
  53754. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  53755. {
  53756. }
  53757. END_JUCE_NAMESPACE
  53758. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  53759. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  53760. BEGIN_JUCE_NAMESPACE
  53761. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  53762. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  53763. // isStandard set depending on which interface was used to create the cursor
  53764. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  53765. static CriticalSection mouseCursorLock;
  53766. static VoidArray standardCursors (2);
  53767. class RefCountedMouseCursor
  53768. {
  53769. public:
  53770. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  53771. : refCount (1),
  53772. standardType (t),
  53773. isStandard (true)
  53774. {
  53775. handle = juce_createStandardMouseCursor (standardType);
  53776. standardCursors.add (this);
  53777. }
  53778. RefCountedMouseCursor (Image& image,
  53779. const int hotSpotX,
  53780. const int hotSpotY) throw()
  53781. : refCount (1),
  53782. standardType (MouseCursor::NormalCursor),
  53783. isStandard (false)
  53784. {
  53785. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  53786. }
  53787. ~RefCountedMouseCursor() throw()
  53788. {
  53789. juce_deleteMouseCursor (handle, isStandard);
  53790. standardCursors.removeValue (this);
  53791. }
  53792. void decRef() throw()
  53793. {
  53794. if (--refCount == 0)
  53795. delete this;
  53796. }
  53797. void incRef() throw()
  53798. {
  53799. ++refCount;
  53800. }
  53801. void* getHandle() const throw()
  53802. {
  53803. return handle;
  53804. }
  53805. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  53806. {
  53807. const ScopedLock sl (mouseCursorLock);
  53808. for (int i = 0; i < standardCursors.size(); i++)
  53809. {
  53810. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  53811. if (r->standardType == type)
  53812. {
  53813. r->incRef();
  53814. return r;
  53815. }
  53816. }
  53817. return new RefCountedMouseCursor (type);
  53818. }
  53819. juce_UseDebuggingNewOperator
  53820. private:
  53821. void* handle;
  53822. int refCount;
  53823. const MouseCursor::StandardCursorType standardType;
  53824. const bool isStandard;
  53825. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  53826. };
  53827. MouseCursor::MouseCursor() throw()
  53828. {
  53829. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  53830. }
  53831. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  53832. {
  53833. cursorHandle = RefCountedMouseCursor::findInstance (type);
  53834. }
  53835. MouseCursor::MouseCursor (Image& image,
  53836. const int hotSpotX,
  53837. const int hotSpotY) throw()
  53838. {
  53839. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  53840. }
  53841. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  53842. : cursorHandle (other.cursorHandle)
  53843. {
  53844. const ScopedLock sl (mouseCursorLock);
  53845. cursorHandle->incRef();
  53846. }
  53847. MouseCursor::~MouseCursor() throw()
  53848. {
  53849. const ScopedLock sl (mouseCursorLock);
  53850. cursorHandle->decRef();
  53851. }
  53852. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  53853. {
  53854. if (this != &other)
  53855. {
  53856. const ScopedLock sl (mouseCursorLock);
  53857. cursorHandle->decRef();
  53858. cursorHandle = other.cursorHandle;
  53859. cursorHandle->incRef();
  53860. }
  53861. return *this;
  53862. }
  53863. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  53864. {
  53865. return cursorHandle == other.cursorHandle;
  53866. }
  53867. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  53868. {
  53869. return cursorHandle != other.cursorHandle;
  53870. }
  53871. void* MouseCursor::getHandle() const throw()
  53872. {
  53873. return cursorHandle->getHandle();
  53874. }
  53875. void MouseCursor::showWaitCursor() throw()
  53876. {
  53877. const MouseCursor mc (MouseCursor::WaitCursor);
  53878. mc.showInAllWindows();
  53879. }
  53880. void MouseCursor::hideWaitCursor() throw()
  53881. {
  53882. if (Component::getComponentUnderMouse()->isValidComponent())
  53883. {
  53884. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  53885. }
  53886. else
  53887. {
  53888. const MouseCursor mc (MouseCursor::NormalCursor);
  53889. mc.showInAllWindows();
  53890. }
  53891. }
  53892. END_JUCE_NAMESPACE
  53893. /********* End of inlined file: juce_MouseCursor.cpp *********/
  53894. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  53895. BEGIN_JUCE_NAMESPACE
  53896. MouseEvent::MouseEvent (const int x_,
  53897. const int y_,
  53898. const ModifierKeys& mods_,
  53899. Component* const originator,
  53900. const Time& eventTime_,
  53901. const int mouseDownX_,
  53902. const int mouseDownY_,
  53903. const Time& mouseDownTime_,
  53904. const int numberOfClicks_,
  53905. const bool mouseWasDragged) throw()
  53906. : x (x_),
  53907. y (y_),
  53908. mods (mods_),
  53909. eventComponent (originator),
  53910. originalComponent (originator),
  53911. eventTime (eventTime_),
  53912. mouseDownX (mouseDownX_),
  53913. mouseDownY (mouseDownY_),
  53914. mouseDownTime (mouseDownTime_),
  53915. numberOfClicks (numberOfClicks_),
  53916. wasMovedSinceMouseDown (mouseWasDragged)
  53917. {
  53918. }
  53919. MouseEvent::~MouseEvent() throw()
  53920. {
  53921. }
  53922. bool MouseEvent::mouseWasClicked() const throw()
  53923. {
  53924. return ! wasMovedSinceMouseDown;
  53925. }
  53926. int MouseEvent::getMouseDownX() const throw()
  53927. {
  53928. return mouseDownX;
  53929. }
  53930. int MouseEvent::getMouseDownY() const throw()
  53931. {
  53932. return mouseDownY;
  53933. }
  53934. int MouseEvent::getDistanceFromDragStartX() const throw()
  53935. {
  53936. return x - mouseDownX;
  53937. }
  53938. int MouseEvent::getDistanceFromDragStartY() const throw()
  53939. {
  53940. return y - mouseDownY;
  53941. }
  53942. int MouseEvent::getDistanceFromDragStart() const throw()
  53943. {
  53944. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  53945. getDistanceFromDragStartY()));
  53946. }
  53947. int MouseEvent::getLengthOfMousePress() const throw()
  53948. {
  53949. if (mouseDownTime.toMilliseconds() > 0)
  53950. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  53951. return 0;
  53952. }
  53953. int MouseEvent::getScreenX() const throw()
  53954. {
  53955. int sx = x, sy = y;
  53956. eventComponent->relativePositionToGlobal (sx, sy);
  53957. return sx;
  53958. }
  53959. int MouseEvent::getScreenY() const throw()
  53960. {
  53961. int sx = x, sy = y;
  53962. eventComponent->relativePositionToGlobal (sx, sy);
  53963. return sy;
  53964. }
  53965. int MouseEvent::getMouseDownScreenX() const throw()
  53966. {
  53967. int sx = mouseDownX, sy = mouseDownY;
  53968. eventComponent->relativePositionToGlobal (sx, sy);
  53969. return sx;
  53970. }
  53971. int MouseEvent::getMouseDownScreenY() const throw()
  53972. {
  53973. int sx = mouseDownX, sy = mouseDownY;
  53974. eventComponent->relativePositionToGlobal (sx, sy);
  53975. return sy;
  53976. }
  53977. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  53978. {
  53979. if (otherComponent == 0)
  53980. {
  53981. jassertfalse
  53982. return *this;
  53983. }
  53984. MouseEvent me (*this);
  53985. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  53986. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  53987. me.eventComponent = otherComponent;
  53988. return me;
  53989. }
  53990. static int doubleClickTimeOutMs = 400;
  53991. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  53992. {
  53993. doubleClickTimeOutMs = newTime;
  53994. }
  53995. int MouseEvent::getDoubleClickTimeout() throw()
  53996. {
  53997. return doubleClickTimeOutMs;
  53998. }
  53999. END_JUCE_NAMESPACE
  54000. /********* End of inlined file: juce_MouseEvent.cpp *********/
  54001. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  54002. BEGIN_JUCE_NAMESPACE
  54003. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  54004. : source (0),
  54005. hoverTimeMillisecs (hoverTimeMillisecs_),
  54006. hasJustHovered (false)
  54007. {
  54008. internalTimer.owner = this;
  54009. }
  54010. MouseHoverDetector::~MouseHoverDetector()
  54011. {
  54012. setHoverComponent (0);
  54013. }
  54014. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  54015. {
  54016. hoverTimeMillisecs = newTimeInMillisecs;
  54017. }
  54018. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  54019. {
  54020. if (source != newSourceComponent)
  54021. {
  54022. internalTimer.stopTimer();
  54023. hasJustHovered = false;
  54024. if (source != 0)
  54025. {
  54026. // ! you need to delete the hover detector before deleting its component
  54027. jassert (source->isValidComponent());
  54028. source->removeMouseListener (&internalTimer);
  54029. }
  54030. source = newSourceComponent;
  54031. if (newSourceComponent != 0)
  54032. newSourceComponent->addMouseListener (&internalTimer, false);
  54033. }
  54034. }
  54035. void MouseHoverDetector::hoverTimerCallback()
  54036. {
  54037. internalTimer.stopTimer();
  54038. if (source != 0)
  54039. {
  54040. int mx, my;
  54041. source->getMouseXYRelative (mx, my);
  54042. if (source->reallyContains (mx, my, false))
  54043. {
  54044. hasJustHovered = true;
  54045. mouseHovered (mx, my);
  54046. }
  54047. }
  54048. }
  54049. void MouseHoverDetector::checkJustHoveredCallback()
  54050. {
  54051. if (hasJustHovered)
  54052. {
  54053. hasJustHovered = false;
  54054. mouseMovedAfterHover();
  54055. }
  54056. }
  54057. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  54058. {
  54059. owner->hoverTimerCallback();
  54060. }
  54061. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  54062. {
  54063. stopTimer();
  54064. owner->checkJustHoveredCallback();
  54065. }
  54066. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  54067. {
  54068. stopTimer();
  54069. owner->checkJustHoveredCallback();
  54070. }
  54071. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  54072. {
  54073. stopTimer();
  54074. owner->checkJustHoveredCallback();
  54075. }
  54076. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  54077. {
  54078. stopTimer();
  54079. owner->checkJustHoveredCallback();
  54080. }
  54081. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  54082. {
  54083. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  54084. {
  54085. lastX = e.x;
  54086. lastY = e.y;
  54087. if (owner->source != 0)
  54088. startTimer (owner->hoverTimeMillisecs);
  54089. owner->checkJustHoveredCallback();
  54090. }
  54091. }
  54092. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  54093. {
  54094. stopTimer();
  54095. owner->checkJustHoveredCallback();
  54096. }
  54097. END_JUCE_NAMESPACE
  54098. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  54099. /********* Start of inlined file: juce_MouseListener.cpp *********/
  54100. BEGIN_JUCE_NAMESPACE
  54101. void MouseListener::mouseEnter (const MouseEvent&)
  54102. {
  54103. }
  54104. void MouseListener::mouseExit (const MouseEvent&)
  54105. {
  54106. }
  54107. void MouseListener::mouseDown (const MouseEvent&)
  54108. {
  54109. }
  54110. void MouseListener::mouseUp (const MouseEvent&)
  54111. {
  54112. }
  54113. void MouseListener::mouseDrag (const MouseEvent&)
  54114. {
  54115. }
  54116. void MouseListener::mouseMove (const MouseEvent&)
  54117. {
  54118. }
  54119. void MouseListener::mouseDoubleClick (const MouseEvent&)
  54120. {
  54121. }
  54122. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  54123. {
  54124. }
  54125. END_JUCE_NAMESPACE
  54126. /********* End of inlined file: juce_MouseListener.cpp *********/
  54127. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54128. BEGIN_JUCE_NAMESPACE
  54129. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  54130. const String& buttonTextWhenTrue,
  54131. const String& buttonTextWhenFalse)
  54132. : PropertyComponent (name),
  54133. onText (buttonTextWhenTrue),
  54134. offText (buttonTextWhenFalse)
  54135. {
  54136. addAndMakeVisible (button = new ToggleButton (String::empty));
  54137. button->setClickingTogglesState (false);
  54138. button->addButtonListener (this);
  54139. }
  54140. BooleanPropertyComponent::~BooleanPropertyComponent()
  54141. {
  54142. deleteAllChildren();
  54143. }
  54144. void BooleanPropertyComponent::paint (Graphics& g)
  54145. {
  54146. PropertyComponent::paint (g);
  54147. const Rectangle r (button->getBounds());
  54148. g.setColour (Colours::white);
  54149. g.fillRect (r);
  54150. g.setColour (findColour (ComboBox::outlineColourId));
  54151. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  54152. }
  54153. void BooleanPropertyComponent::refresh()
  54154. {
  54155. button->setToggleState (getState(), false);
  54156. button->setButtonText (button->getToggleState() ? onText : offText);
  54157. }
  54158. void BooleanPropertyComponent::buttonClicked (Button*)
  54159. {
  54160. setState (! getState());
  54161. }
  54162. END_JUCE_NAMESPACE
  54163. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  54164. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54165. BEGIN_JUCE_NAMESPACE
  54166. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  54167. const bool triggerOnMouseDown)
  54168. : PropertyComponent (name)
  54169. {
  54170. addAndMakeVisible (button = new TextButton (String::empty));
  54171. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  54172. button->addButtonListener (this);
  54173. }
  54174. ButtonPropertyComponent::~ButtonPropertyComponent()
  54175. {
  54176. deleteAllChildren();
  54177. }
  54178. void ButtonPropertyComponent::refresh()
  54179. {
  54180. button->setButtonText (getButtonText());
  54181. }
  54182. void ButtonPropertyComponent::buttonClicked (Button*)
  54183. {
  54184. buttonClicked();
  54185. }
  54186. END_JUCE_NAMESPACE
  54187. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  54188. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54189. BEGIN_JUCE_NAMESPACE
  54190. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  54191. : PropertyComponent (name),
  54192. comboBox (0)
  54193. {
  54194. }
  54195. ChoicePropertyComponent::~ChoicePropertyComponent()
  54196. {
  54197. deleteAllChildren();
  54198. }
  54199. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  54200. {
  54201. return choices;
  54202. }
  54203. void ChoicePropertyComponent::refresh()
  54204. {
  54205. if (comboBox == 0)
  54206. {
  54207. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  54208. for (int i = 0; i < choices.size(); ++i)
  54209. {
  54210. if (choices[i].isNotEmpty())
  54211. comboBox->addItem (choices[i], i + 1);
  54212. else
  54213. comboBox->addSeparator();
  54214. }
  54215. comboBox->setEditableText (false);
  54216. comboBox->addListener (this);
  54217. }
  54218. comboBox->setSelectedId (getIndex() + 1, true);
  54219. }
  54220. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  54221. {
  54222. const int newIndex = comboBox->getSelectedId() - 1;
  54223. if (newIndex != getIndex())
  54224. setIndex (newIndex);
  54225. }
  54226. END_JUCE_NAMESPACE
  54227. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  54228. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  54229. BEGIN_JUCE_NAMESPACE
  54230. PropertyComponent::PropertyComponent (const String& name,
  54231. const int preferredHeight_)
  54232. : Component (name),
  54233. preferredHeight (preferredHeight_)
  54234. {
  54235. jassert (name.isNotEmpty());
  54236. }
  54237. PropertyComponent::~PropertyComponent()
  54238. {
  54239. }
  54240. void PropertyComponent::paint (Graphics& g)
  54241. {
  54242. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  54243. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  54244. }
  54245. void PropertyComponent::resized()
  54246. {
  54247. if (getNumChildComponents() > 0)
  54248. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  54249. }
  54250. void PropertyComponent::enablementChanged()
  54251. {
  54252. repaint();
  54253. }
  54254. END_JUCE_NAMESPACE
  54255. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  54256. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  54257. BEGIN_JUCE_NAMESPACE
  54258. class PropertyHolderComponent : public Component
  54259. {
  54260. public:
  54261. PropertyHolderComponent()
  54262. {
  54263. }
  54264. ~PropertyHolderComponent()
  54265. {
  54266. deleteAllChildren();
  54267. }
  54268. void paint (Graphics&)
  54269. {
  54270. }
  54271. void updateLayout (const int width);
  54272. void refreshAll() const;
  54273. };
  54274. class PropertySectionComponent : public Component
  54275. {
  54276. public:
  54277. PropertySectionComponent (const String& sectionTitle,
  54278. const Array <PropertyComponent*>& newProperties,
  54279. const bool open)
  54280. : Component (sectionTitle),
  54281. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  54282. isOpen_ (open)
  54283. {
  54284. for (int i = newProperties.size(); --i >= 0;)
  54285. {
  54286. addAndMakeVisible (newProperties.getUnchecked(i));
  54287. newProperties.getUnchecked(i)->refresh();
  54288. }
  54289. }
  54290. ~PropertySectionComponent()
  54291. {
  54292. deleteAllChildren();
  54293. }
  54294. void paint (Graphics& g)
  54295. {
  54296. if (titleHeight > 0)
  54297. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  54298. }
  54299. void resized()
  54300. {
  54301. int y = titleHeight;
  54302. for (int i = getNumChildComponents(); --i >= 0;)
  54303. {
  54304. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54305. if (pec != 0)
  54306. {
  54307. const int prefH = pec->getPreferredHeight();
  54308. pec->setBounds (1, y, getWidth() - 2, prefH);
  54309. y += prefH;
  54310. }
  54311. }
  54312. }
  54313. int getPreferredHeight() const
  54314. {
  54315. int y = titleHeight;
  54316. if (isOpen())
  54317. {
  54318. for (int i = 0; i < getNumChildComponents(); ++i)
  54319. {
  54320. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54321. if (pec != 0)
  54322. y += pec->getPreferredHeight();
  54323. }
  54324. }
  54325. return y;
  54326. }
  54327. void setOpen (const bool open)
  54328. {
  54329. if (isOpen_ != open)
  54330. {
  54331. isOpen_ = open;
  54332. for (int i = 0; i < getNumChildComponents(); ++i)
  54333. {
  54334. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54335. if (pec != 0)
  54336. pec->setVisible (open);
  54337. }
  54338. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  54339. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  54340. if (pp != 0)
  54341. pp->resized();
  54342. }
  54343. }
  54344. bool isOpen() const throw()
  54345. {
  54346. return isOpen_;
  54347. }
  54348. void refreshAll() const
  54349. {
  54350. for (int i = 0; i < getNumChildComponents(); ++i)
  54351. {
  54352. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  54353. if (pec != 0)
  54354. pec->refresh();
  54355. }
  54356. }
  54357. void mouseDown (const MouseEvent&)
  54358. {
  54359. }
  54360. void mouseUp (const MouseEvent& e)
  54361. {
  54362. if (e.getMouseDownX() < titleHeight
  54363. && e.x < titleHeight
  54364. && e.y < titleHeight
  54365. && e.getNumberOfClicks() != 2)
  54366. {
  54367. setOpen (! isOpen());
  54368. }
  54369. }
  54370. void mouseDoubleClick (const MouseEvent& e)
  54371. {
  54372. if (e.y < titleHeight)
  54373. setOpen (! isOpen());
  54374. }
  54375. private:
  54376. int titleHeight;
  54377. bool isOpen_;
  54378. };
  54379. void PropertyHolderComponent::updateLayout (const int width)
  54380. {
  54381. int y = 0;
  54382. for (int i = getNumChildComponents(); --i >= 0;)
  54383. {
  54384. PropertySectionComponent* const section
  54385. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54386. if (section != 0)
  54387. {
  54388. const int prefH = section->getPreferredHeight();
  54389. section->setBounds (0, y, width, prefH);
  54390. y += prefH;
  54391. }
  54392. }
  54393. setSize (width, y);
  54394. repaint();
  54395. }
  54396. void PropertyHolderComponent::refreshAll() const
  54397. {
  54398. for (int i = getNumChildComponents(); --i >= 0;)
  54399. {
  54400. PropertySectionComponent* const section
  54401. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  54402. if (section != 0)
  54403. section->refreshAll();
  54404. }
  54405. }
  54406. PropertyPanel::PropertyPanel()
  54407. {
  54408. messageWhenEmpty = TRANS("(nothing selected)");
  54409. addAndMakeVisible (viewport = new Viewport());
  54410. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  54411. viewport->setFocusContainer (true);
  54412. }
  54413. PropertyPanel::~PropertyPanel()
  54414. {
  54415. clear();
  54416. deleteAllChildren();
  54417. }
  54418. void PropertyPanel::paint (Graphics& g)
  54419. {
  54420. if (propertyHolderComponent->getNumChildComponents() == 0)
  54421. {
  54422. g.setColour (Colours::black.withAlpha (0.5f));
  54423. g.setFont (14.0f);
  54424. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  54425. Justification::centred, true);
  54426. }
  54427. }
  54428. void PropertyPanel::resized()
  54429. {
  54430. viewport->setBounds (0, 0, getWidth(), getHeight());
  54431. updatePropHolderLayout();
  54432. }
  54433. void PropertyPanel::clear()
  54434. {
  54435. if (propertyHolderComponent->getNumChildComponents() > 0)
  54436. {
  54437. propertyHolderComponent->deleteAllChildren();
  54438. repaint();
  54439. }
  54440. }
  54441. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  54442. {
  54443. if (propertyHolderComponent->getNumChildComponents() == 0)
  54444. repaint();
  54445. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  54446. newProperties,
  54447. true), 0);
  54448. updatePropHolderLayout();
  54449. }
  54450. void PropertyPanel::addSection (const String& sectionTitle,
  54451. const Array <PropertyComponent*>& newProperties,
  54452. const bool shouldBeOpen)
  54453. {
  54454. jassert (sectionTitle.isNotEmpty());
  54455. if (propertyHolderComponent->getNumChildComponents() == 0)
  54456. repaint();
  54457. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  54458. newProperties,
  54459. shouldBeOpen), 0);
  54460. updatePropHolderLayout();
  54461. }
  54462. void PropertyPanel::updatePropHolderLayout() const
  54463. {
  54464. const int maxWidth = viewport->getMaximumVisibleWidth();
  54465. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  54466. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  54467. if (maxWidth != newMaxWidth)
  54468. {
  54469. // need to do this twice because of scrollbars changing the size, etc.
  54470. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  54471. }
  54472. }
  54473. void PropertyPanel::refreshAll() const
  54474. {
  54475. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  54476. }
  54477. const StringArray PropertyPanel::getSectionNames() const
  54478. {
  54479. StringArray s;
  54480. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54481. {
  54482. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54483. if (section != 0 && section->getName().isNotEmpty())
  54484. s.add (section->getName());
  54485. }
  54486. return s;
  54487. }
  54488. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  54489. {
  54490. int index = 0;
  54491. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54492. {
  54493. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54494. if (section != 0 && section->getName().isNotEmpty())
  54495. {
  54496. if (index == sectionIndex)
  54497. return section->isOpen();
  54498. ++index;
  54499. }
  54500. }
  54501. return false;
  54502. }
  54503. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  54504. {
  54505. int index = 0;
  54506. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54507. {
  54508. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54509. if (section != 0 && section->getName().isNotEmpty())
  54510. {
  54511. if (index == sectionIndex)
  54512. {
  54513. section->setOpen (shouldBeOpen);
  54514. break;
  54515. }
  54516. ++index;
  54517. }
  54518. }
  54519. }
  54520. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  54521. {
  54522. int index = 0;
  54523. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  54524. {
  54525. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  54526. if (section != 0 && section->getName().isNotEmpty())
  54527. {
  54528. if (index == sectionIndex)
  54529. {
  54530. section->setEnabled (shouldBeEnabled);
  54531. break;
  54532. }
  54533. ++index;
  54534. }
  54535. }
  54536. }
  54537. XmlElement* PropertyPanel::getOpennessState() const
  54538. {
  54539. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  54540. const StringArray sections (getSectionNames());
  54541. for (int i = 0; i < sections.size(); ++i)
  54542. {
  54543. if (sections[i].isNotEmpty())
  54544. {
  54545. XmlElement* const e = new XmlElement (T("SECTION"));
  54546. e->setAttribute (T("name"), sections[i]);
  54547. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  54548. xml->addChildElement (e);
  54549. }
  54550. }
  54551. return xml;
  54552. }
  54553. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  54554. {
  54555. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  54556. {
  54557. const StringArray sections (getSectionNames());
  54558. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  54559. {
  54560. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  54561. e->getBoolAttribute (T("open")));
  54562. }
  54563. }
  54564. }
  54565. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  54566. {
  54567. if (messageWhenEmpty != newMessage)
  54568. {
  54569. messageWhenEmpty = newMessage;
  54570. repaint();
  54571. }
  54572. }
  54573. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  54574. {
  54575. return messageWhenEmpty;
  54576. }
  54577. END_JUCE_NAMESPACE
  54578. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  54579. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  54580. BEGIN_JUCE_NAMESPACE
  54581. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  54582. const double rangeMin,
  54583. const double rangeMax,
  54584. const double interval,
  54585. const double skewFactor)
  54586. : PropertyComponent (name)
  54587. {
  54588. addAndMakeVisible (slider = new Slider (name));
  54589. slider->setRange (rangeMin, rangeMax, interval);
  54590. slider->setSkewFactor (skewFactor);
  54591. slider->setSliderStyle (Slider::LinearBar);
  54592. slider->addListener (this);
  54593. }
  54594. SliderPropertyComponent::~SliderPropertyComponent()
  54595. {
  54596. deleteAllChildren();
  54597. }
  54598. void SliderPropertyComponent::refresh()
  54599. {
  54600. slider->setValue (getValue(), false);
  54601. }
  54602. void SliderPropertyComponent::sliderValueChanged (Slider*)
  54603. {
  54604. if (getValue() != slider->getValue())
  54605. setValue (slider->getValue());
  54606. }
  54607. END_JUCE_NAMESPACE
  54608. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  54609. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  54610. BEGIN_JUCE_NAMESPACE
  54611. class TextPropLabel : public Label
  54612. {
  54613. TextPropertyComponent& owner;
  54614. int maxChars;
  54615. bool isMultiline;
  54616. public:
  54617. TextPropLabel (TextPropertyComponent& owner_,
  54618. const int maxChars_, const bool isMultiline_)
  54619. : Label (String::empty, String::empty),
  54620. owner (owner_),
  54621. maxChars (maxChars_),
  54622. isMultiline (isMultiline_)
  54623. {
  54624. setEditable (true, true, false);
  54625. setColour (backgroundColourId, Colours::white);
  54626. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  54627. }
  54628. ~TextPropLabel()
  54629. {
  54630. }
  54631. TextEditor* createEditorComponent()
  54632. {
  54633. TextEditor* const textEditor = Label::createEditorComponent();
  54634. textEditor->setInputRestrictions (maxChars);
  54635. if (isMultiline)
  54636. {
  54637. textEditor->setMultiLine (true, true);
  54638. textEditor->setReturnKeyStartsNewLine (true);
  54639. }
  54640. return textEditor;
  54641. }
  54642. void textWasEdited()
  54643. {
  54644. owner.textWasEdited();
  54645. }
  54646. };
  54647. TextPropertyComponent::TextPropertyComponent (const String& name,
  54648. const int maxNumChars,
  54649. const bool isMultiLine)
  54650. : PropertyComponent (name)
  54651. {
  54652. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  54653. if (isMultiLine)
  54654. {
  54655. textEditor->setJustificationType (Justification::topLeft);
  54656. preferredHeight = 120;
  54657. }
  54658. }
  54659. TextPropertyComponent::~TextPropertyComponent()
  54660. {
  54661. deleteAllChildren();
  54662. }
  54663. void TextPropertyComponent::refresh()
  54664. {
  54665. textEditor->setText (getText(), false);
  54666. }
  54667. void TextPropertyComponent::textWasEdited()
  54668. {
  54669. const String newText (textEditor->getText());
  54670. if (getText() != newText)
  54671. setText (newText);
  54672. }
  54673. END_JUCE_NAMESPACE
  54674. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  54675. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54676. BEGIN_JUCE_NAMESPACE
  54677. class SimpleDeviceManagerInputLevelMeter : public Component,
  54678. public Timer
  54679. {
  54680. public:
  54681. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  54682. : manager (manager_),
  54683. level (0)
  54684. {
  54685. startTimer (50);
  54686. manager->enableInputLevelMeasurement (true);
  54687. }
  54688. ~SimpleDeviceManagerInputLevelMeter()
  54689. {
  54690. manager->enableInputLevelMeasurement (false);
  54691. }
  54692. void timerCallback()
  54693. {
  54694. const float newLevel = (float) manager->getCurrentInputLevel();
  54695. if (fabsf (level - newLevel) > 0.005f)
  54696. {
  54697. level = newLevel;
  54698. repaint();
  54699. }
  54700. }
  54701. void paint (Graphics& g)
  54702. {
  54703. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  54704. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  54705. }
  54706. private:
  54707. AudioDeviceManager* const manager;
  54708. float level;
  54709. };
  54710. class MidiInputSelectorComponentListBox : public ListBox,
  54711. public ListBoxModel
  54712. {
  54713. public:
  54714. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  54715. const String& noItemsMessage_,
  54716. const int minNumber_,
  54717. const int maxNumber_)
  54718. : ListBox (String::empty, 0),
  54719. deviceManager (deviceManager_),
  54720. noItemsMessage (noItemsMessage_),
  54721. minNumber (minNumber_),
  54722. maxNumber (maxNumber_)
  54723. {
  54724. items = MidiInput::getDevices();
  54725. setModel (this);
  54726. setOutlineThickness (1);
  54727. }
  54728. ~MidiInputSelectorComponentListBox()
  54729. {
  54730. }
  54731. int getNumRows()
  54732. {
  54733. return items.size();
  54734. }
  54735. void paintListBoxItem (int row,
  54736. Graphics& g,
  54737. int width, int height,
  54738. bool rowIsSelected)
  54739. {
  54740. if (((unsigned int) row) < (unsigned int) items.size())
  54741. {
  54742. if (rowIsSelected)
  54743. g.fillAll (findColour (TextEditor::highlightColourId)
  54744. .withMultipliedAlpha (0.3f));
  54745. const String item (items [row]);
  54746. bool enabled = deviceManager.isMidiInputEnabled (item);
  54747. const int x = getTickX();
  54748. const int tickW = height - height / 4;
  54749. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  54750. enabled, true, true, false);
  54751. g.setFont (height * 0.6f);
  54752. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  54753. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  54754. }
  54755. }
  54756. void listBoxItemClicked (int row, const MouseEvent& e)
  54757. {
  54758. selectRow (row);
  54759. if (e.x < getTickX())
  54760. flipEnablement (row);
  54761. }
  54762. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  54763. {
  54764. flipEnablement (row);
  54765. }
  54766. void returnKeyPressed (int row)
  54767. {
  54768. flipEnablement (row);
  54769. }
  54770. void paint (Graphics& g)
  54771. {
  54772. ListBox::paint (g);
  54773. if (items.size() == 0)
  54774. {
  54775. g.setColour (Colours::grey);
  54776. g.setFont (13.0f);
  54777. g.drawText (noItemsMessage,
  54778. 0, 0, getWidth(), getHeight() / 2,
  54779. Justification::centred, true);
  54780. }
  54781. }
  54782. int getBestHeight (const int preferredHeight)
  54783. {
  54784. const int extra = getOutlineThickness() * 2;
  54785. return jmax (getRowHeight() * 2 + extra,
  54786. jmin (getRowHeight() * getNumRows() + extra,
  54787. preferredHeight));
  54788. }
  54789. juce_UseDebuggingNewOperator
  54790. private:
  54791. AudioDeviceManager& deviceManager;
  54792. const String noItemsMessage;
  54793. StringArray items;
  54794. int minNumber, maxNumber;
  54795. void flipEnablement (const int row)
  54796. {
  54797. if (((unsigned int) row) < (unsigned int) items.size())
  54798. {
  54799. const String item (items [row]);
  54800. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  54801. }
  54802. }
  54803. int getTickX() const throw()
  54804. {
  54805. return getRowHeight() + 5;
  54806. }
  54807. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  54808. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  54809. };
  54810. class AudioDeviceSettingsPanel : public Component,
  54811. public ComboBoxListener,
  54812. public ChangeListener,
  54813. public ButtonListener
  54814. {
  54815. public:
  54816. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  54817. AudioIODeviceType::DeviceSetupDetails& setup_,
  54818. const bool hideAdvancedOptionsWithButton)
  54819. : type (type_),
  54820. setup (setup_)
  54821. {
  54822. sampleRateDropDown = 0;
  54823. sampleRateLabel = 0;
  54824. bufferSizeDropDown = 0;
  54825. bufferSizeLabel = 0;
  54826. outputDeviceDropDown = 0;
  54827. outputDeviceLabel = 0;
  54828. inputDeviceDropDown = 0;
  54829. inputDeviceLabel = 0;
  54830. testButton = 0;
  54831. inputLevelMeter = 0;
  54832. showUIButton = 0;
  54833. inputChanList = 0;
  54834. outputChanList = 0;
  54835. inputChanLabel = 0;
  54836. outputChanLabel = 0;
  54837. showAdvancedSettingsButton = 0;
  54838. if (hideAdvancedOptionsWithButton)
  54839. {
  54840. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  54841. showAdvancedSettingsButton->addButtonListener (this);
  54842. }
  54843. type->scanForDevices();
  54844. setup.manager->addChangeListener (this);
  54845. changeListenerCallback (0);
  54846. }
  54847. ~AudioDeviceSettingsPanel()
  54848. {
  54849. setup.manager->removeChangeListener (this);
  54850. deleteAndZero (outputDeviceLabel);
  54851. deleteAndZero (inputDeviceLabel);
  54852. deleteAndZero (sampleRateLabel);
  54853. deleteAndZero (bufferSizeLabel);
  54854. deleteAndZero (showUIButton);
  54855. deleteAndZero (inputChanLabel);
  54856. deleteAndZero (outputChanLabel);
  54857. deleteAndZero (showAdvancedSettingsButton);
  54858. deleteAllChildren();
  54859. }
  54860. void resized()
  54861. {
  54862. const int lx = proportionOfWidth (0.35f);
  54863. const int w = proportionOfWidth (0.4f);
  54864. const int h = 24;
  54865. const int space = 6;
  54866. const int dh = h + space;
  54867. int y = 0;
  54868. if (outputDeviceDropDown != 0)
  54869. {
  54870. outputDeviceDropDown->setBounds (lx, y, w, h);
  54871. if (testButton != 0)
  54872. testButton->setBounds (proportionOfWidth (0.77f),
  54873. outputDeviceDropDown->getY(),
  54874. proportionOfWidth (0.18f),
  54875. h);
  54876. y += dh;
  54877. }
  54878. if (inputDeviceDropDown != 0)
  54879. {
  54880. inputDeviceDropDown->setBounds (lx, y, w, h);
  54881. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  54882. inputDeviceDropDown->getY(),
  54883. proportionOfWidth (0.18f),
  54884. h);
  54885. y += dh;
  54886. }
  54887. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  54888. if (outputChanList != 0)
  54889. {
  54890. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  54891. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54892. y += bh + space;
  54893. }
  54894. if (inputChanList != 0)
  54895. {
  54896. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  54897. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  54898. y += bh + space;
  54899. }
  54900. y += space * 2;
  54901. if (showAdvancedSettingsButton != 0)
  54902. {
  54903. showAdvancedSettingsButton->changeWidthToFitText (h);
  54904. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  54905. }
  54906. if (sampleRateDropDown != 0)
  54907. {
  54908. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  54909. || ! showAdvancedSettingsButton->isVisible());
  54910. sampleRateDropDown->setBounds (lx, y, w, h);
  54911. y += dh;
  54912. }
  54913. if (bufferSizeDropDown != 0)
  54914. {
  54915. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  54916. || ! showAdvancedSettingsButton->isVisible());
  54917. bufferSizeDropDown->setBounds (lx, y, w, h);
  54918. y += dh;
  54919. }
  54920. if (showUIButton != 0)
  54921. {
  54922. showUIButton->setVisible (showAdvancedSettingsButton == 0
  54923. || ! showAdvancedSettingsButton->isVisible());
  54924. showUIButton->changeWidthToFitText (h);
  54925. showUIButton->setTopLeftPosition (lx, y);
  54926. }
  54927. }
  54928. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  54929. {
  54930. if (comboBoxThatHasChanged == 0)
  54931. return;
  54932. AudioDeviceManager::AudioDeviceSetup config;
  54933. setup.manager->getAudioDeviceSetup (config);
  54934. String error;
  54935. if (comboBoxThatHasChanged == outputDeviceDropDown
  54936. || comboBoxThatHasChanged == inputDeviceDropDown)
  54937. {
  54938. if (outputDeviceDropDown != 0)
  54939. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54940. : outputDeviceDropDown->getText();
  54941. if (inputDeviceDropDown != 0)
  54942. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  54943. : inputDeviceDropDown->getText();
  54944. if (! type->hasSeparateInputsAndOutputs())
  54945. config.inputDeviceName = config.outputDeviceName;
  54946. if (comboBoxThatHasChanged == inputDeviceDropDown)
  54947. config.useDefaultInputChannels = true;
  54948. else
  54949. config.useDefaultOutputChannels = true;
  54950. error = setup.manager->setAudioDeviceSetup (config, true);
  54951. showCorrectDeviceName (inputDeviceDropDown, true);
  54952. showCorrectDeviceName (outputDeviceDropDown, false);
  54953. updateControlPanelButton();
  54954. resized();
  54955. }
  54956. else if (comboBoxThatHasChanged == sampleRateDropDown)
  54957. {
  54958. if (sampleRateDropDown->getSelectedId() > 0)
  54959. {
  54960. config.sampleRate = sampleRateDropDown->getSelectedId();
  54961. error = setup.manager->setAudioDeviceSetup (config, true);
  54962. }
  54963. }
  54964. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  54965. {
  54966. if (bufferSizeDropDown->getSelectedId() > 0)
  54967. {
  54968. config.bufferSize = bufferSizeDropDown->getSelectedId();
  54969. error = setup.manager->setAudioDeviceSetup (config, true);
  54970. }
  54971. }
  54972. if (error.isNotEmpty())
  54973. {
  54974. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  54975. T("Error when trying to open audio device!"),
  54976. error);
  54977. }
  54978. }
  54979. void buttonClicked (Button* button)
  54980. {
  54981. if (button == showAdvancedSettingsButton)
  54982. {
  54983. showAdvancedSettingsButton->setVisible (false);
  54984. resized();
  54985. }
  54986. else if (button == showUIButton)
  54987. {
  54988. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  54989. if (device != 0 && device->showControlPanel())
  54990. {
  54991. setup.manager->closeAudioDevice();
  54992. setup.manager->restartLastAudioDevice();
  54993. getTopLevelComponent()->toFront (true);
  54994. }
  54995. }
  54996. else if (button == testButton && testButton != 0)
  54997. {
  54998. setup.manager->playTestSound();
  54999. }
  55000. }
  55001. void updateControlPanelButton()
  55002. {
  55003. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55004. deleteAndZero (showUIButton);
  55005. if (currentDevice != 0 && currentDevice->hasControlPanel())
  55006. {
  55007. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  55008. TRANS ("opens the device's own control panel")));
  55009. showUIButton->addButtonListener (this);
  55010. }
  55011. resized();
  55012. }
  55013. void changeListenerCallback (void*)
  55014. {
  55015. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55016. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  55017. {
  55018. if (outputDeviceDropDown == 0)
  55019. {
  55020. outputDeviceDropDown = new ComboBox (String::empty);
  55021. outputDeviceDropDown->addListener (this);
  55022. addAndMakeVisible (outputDeviceDropDown);
  55023. outputDeviceLabel = new Label (String::empty,
  55024. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  55025. : TRANS ("device:"));
  55026. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  55027. if (setup.maxNumOutputChannels > 0)
  55028. {
  55029. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  55030. testButton->addButtonListener (this);
  55031. }
  55032. }
  55033. addNamesToDeviceBox (*outputDeviceDropDown, false);
  55034. }
  55035. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  55036. {
  55037. if (inputDeviceDropDown == 0)
  55038. {
  55039. inputDeviceDropDown = new ComboBox (String::empty);
  55040. inputDeviceDropDown->addListener (this);
  55041. addAndMakeVisible (inputDeviceDropDown);
  55042. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  55043. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  55044. addAndMakeVisible (inputLevelMeter
  55045. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  55046. }
  55047. addNamesToDeviceBox (*inputDeviceDropDown, true);
  55048. }
  55049. updateControlPanelButton();
  55050. showCorrectDeviceName (inputDeviceDropDown, true);
  55051. showCorrectDeviceName (outputDeviceDropDown, false);
  55052. if (currentDevice != 0)
  55053. {
  55054. if (setup.maxNumOutputChannels > 0
  55055. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  55056. {
  55057. if (outputChanList == 0)
  55058. {
  55059. addAndMakeVisible (outputChanList
  55060. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  55061. TRANS ("(no audio output channels found)")));
  55062. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  55063. outputChanLabel->attachToComponent (outputChanList, true);
  55064. }
  55065. outputChanList->refresh();
  55066. }
  55067. else
  55068. {
  55069. deleteAndZero (outputChanLabel);
  55070. deleteAndZero (outputChanList);
  55071. }
  55072. if (setup.maxNumInputChannels > 0
  55073. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  55074. {
  55075. if (inputChanList == 0)
  55076. {
  55077. addAndMakeVisible (inputChanList
  55078. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  55079. TRANS ("(no audio input channels found)")));
  55080. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  55081. inputChanLabel->attachToComponent (inputChanList, true);
  55082. }
  55083. inputChanList->refresh();
  55084. }
  55085. else
  55086. {
  55087. deleteAndZero (inputChanLabel);
  55088. deleteAndZero (inputChanList);
  55089. }
  55090. // sample rate..
  55091. {
  55092. if (sampleRateDropDown == 0)
  55093. {
  55094. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  55095. sampleRateDropDown->addListener (this);
  55096. delete sampleRateLabel;
  55097. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  55098. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  55099. }
  55100. else
  55101. {
  55102. sampleRateDropDown->clear();
  55103. sampleRateDropDown->removeListener (this);
  55104. }
  55105. const int numRates = currentDevice->getNumSampleRates();
  55106. for (int i = 0; i < numRates; ++i)
  55107. {
  55108. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  55109. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  55110. }
  55111. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  55112. sampleRateDropDown->addListener (this);
  55113. }
  55114. // buffer size
  55115. {
  55116. if (bufferSizeDropDown == 0)
  55117. {
  55118. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  55119. bufferSizeDropDown->addListener (this);
  55120. delete bufferSizeLabel;
  55121. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  55122. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  55123. }
  55124. else
  55125. {
  55126. bufferSizeDropDown->clear();
  55127. }
  55128. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  55129. double currentRate = currentDevice->getCurrentSampleRate();
  55130. if (currentRate == 0)
  55131. currentRate = 48000.0;
  55132. for (int i = 0; i < numBufferSizes; ++i)
  55133. {
  55134. const int bs = currentDevice->getBufferSizeSamples (i);
  55135. bufferSizeDropDown->addItem (String (bs)
  55136. + T(" samples (")
  55137. + String (bs * 1000.0 / currentRate, 1)
  55138. + T(" ms)"),
  55139. bs);
  55140. }
  55141. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  55142. }
  55143. }
  55144. else
  55145. {
  55146. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  55147. deleteAndZero (sampleRateLabel);
  55148. deleteAndZero (bufferSizeLabel);
  55149. deleteAndZero (sampleRateDropDown);
  55150. deleteAndZero (bufferSizeDropDown);
  55151. if (outputDeviceDropDown != 0)
  55152. outputDeviceDropDown->setSelectedId (-1, true);
  55153. if (inputDeviceDropDown != 0)
  55154. inputDeviceDropDown->setSelectedId (-1, true);
  55155. }
  55156. resized();
  55157. setSize (getWidth(), getLowestY() + 4);
  55158. }
  55159. private:
  55160. AudioIODeviceType* const type;
  55161. const AudioIODeviceType::DeviceSetupDetails setup;
  55162. ComboBox* outputDeviceDropDown;
  55163. ComboBox* inputDeviceDropDown;
  55164. ComboBox* sampleRateDropDown;
  55165. ComboBox* bufferSizeDropDown;
  55166. Label* outputDeviceLabel;
  55167. Label* inputDeviceLabel;
  55168. Label* sampleRateLabel;
  55169. Label* bufferSizeLabel;
  55170. Label* inputChanLabel;
  55171. Label* outputChanLabel;
  55172. TextButton* testButton;
  55173. Component* inputLevelMeter;
  55174. TextButton* showUIButton;
  55175. TextButton* showAdvancedSettingsButton;
  55176. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  55177. {
  55178. if (box != 0)
  55179. {
  55180. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  55181. const int index = type->getIndexOfDevice (currentDevice, isInput);
  55182. box->setSelectedId (index + 1, true);
  55183. if (testButton != 0 && ! isInput)
  55184. testButton->setEnabled (index >= 0);
  55185. }
  55186. }
  55187. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  55188. {
  55189. const StringArray devs (type->getDeviceNames (isInputs));
  55190. combo.clear (true);
  55191. for (int i = 0; i < devs.size(); ++i)
  55192. combo.addItem (devs[i], i + 1);
  55193. combo.addItem (TRANS("<< none >>"), -1);
  55194. combo.setSelectedId (-1, true);
  55195. }
  55196. int getLowestY() const
  55197. {
  55198. int y = 0;
  55199. for (int i = getNumChildComponents(); --i >= 0;)
  55200. y = jmax (y, getChildComponent (i)->getBottom());
  55201. return y;
  55202. }
  55203. class ChannelSelectorListBox : public ListBox,
  55204. public ListBoxModel
  55205. {
  55206. public:
  55207. enum BoxType
  55208. {
  55209. audioInputType,
  55210. audioOutputType
  55211. };
  55212. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  55213. const BoxType type_,
  55214. const String& noItemsMessage_)
  55215. : ListBox (String::empty, 0),
  55216. setup (setup_),
  55217. type (type_),
  55218. noItemsMessage (noItemsMessage_)
  55219. {
  55220. refresh();
  55221. setModel (this);
  55222. setOutlineThickness (1);
  55223. }
  55224. ~ChannelSelectorListBox()
  55225. {
  55226. }
  55227. void refresh()
  55228. {
  55229. items.clear();
  55230. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  55231. if (currentDevice != 0)
  55232. {
  55233. if (type == audioInputType)
  55234. items = currentDevice->getInputChannelNames();
  55235. else if (type == audioOutputType)
  55236. items = currentDevice->getOutputChannelNames();
  55237. if (setup.useStereoPairs)
  55238. {
  55239. StringArray pairs;
  55240. for (int i = 0; i < items.size(); i += 2)
  55241. {
  55242. String name (items[i]);
  55243. String name2 (items[i + 1]);
  55244. String commonBit;
  55245. for (int j = 0; j < name.length(); ++j)
  55246. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  55247. commonBit = name.substring (0, j);
  55248. pairs.add (name.trim()
  55249. + " + "
  55250. + name2.substring (commonBit.length()).trim());
  55251. }
  55252. items = pairs;
  55253. }
  55254. }
  55255. updateContent();
  55256. repaint();
  55257. }
  55258. int getNumRows()
  55259. {
  55260. return items.size();
  55261. }
  55262. void paintListBoxItem (int row,
  55263. Graphics& g,
  55264. int width, int height,
  55265. bool rowIsSelected)
  55266. {
  55267. if (((unsigned int) row) < (unsigned int) items.size())
  55268. {
  55269. if (rowIsSelected)
  55270. g.fillAll (findColour (TextEditor::highlightColourId)
  55271. .withMultipliedAlpha (0.3f));
  55272. const String item (items [row]);
  55273. bool enabled = false;
  55274. AudioDeviceManager::AudioDeviceSetup config;
  55275. setup.manager->getAudioDeviceSetup (config);
  55276. if (setup.useStereoPairs)
  55277. {
  55278. if (type == audioInputType)
  55279. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  55280. else if (type == audioOutputType)
  55281. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  55282. }
  55283. else
  55284. {
  55285. if (type == audioInputType)
  55286. enabled = config.inputChannels [row];
  55287. else if (type == audioOutputType)
  55288. enabled = config.outputChannels [row];
  55289. }
  55290. const int x = getTickX();
  55291. const int tickW = height - height / 4;
  55292. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  55293. enabled, true, true, false);
  55294. g.setFont (height * 0.6f);
  55295. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  55296. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  55297. }
  55298. }
  55299. void listBoxItemClicked (int row, const MouseEvent& e)
  55300. {
  55301. selectRow (row);
  55302. if (e.x < getTickX())
  55303. flipEnablement (row);
  55304. }
  55305. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  55306. {
  55307. flipEnablement (row);
  55308. }
  55309. void returnKeyPressed (int row)
  55310. {
  55311. flipEnablement (row);
  55312. }
  55313. void paint (Graphics& g)
  55314. {
  55315. ListBox::paint (g);
  55316. if (items.size() == 0)
  55317. {
  55318. g.setColour (Colours::grey);
  55319. g.setFont (13.0f);
  55320. g.drawText (noItemsMessage,
  55321. 0, 0, getWidth(), getHeight() / 2,
  55322. Justification::centred, true);
  55323. }
  55324. }
  55325. int getBestHeight (int maxHeight)
  55326. {
  55327. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  55328. getNumRows())
  55329. + getOutlineThickness() * 2;
  55330. }
  55331. juce_UseDebuggingNewOperator
  55332. private:
  55333. const AudioIODeviceType::DeviceSetupDetails setup;
  55334. const BoxType type;
  55335. const String noItemsMessage;
  55336. StringArray items;
  55337. void flipEnablement (const int row)
  55338. {
  55339. jassert (type == audioInputType || type == audioOutputType);
  55340. if (((unsigned int) row) < (unsigned int) items.size())
  55341. {
  55342. AudioDeviceManager::AudioDeviceSetup config;
  55343. setup.manager->getAudioDeviceSetup (config);
  55344. if (setup.useStereoPairs)
  55345. {
  55346. BitArray bits;
  55347. BitArray& original = (type == audioInputType ? config.inputChannels
  55348. : config.outputChannels);
  55349. int i;
  55350. for (i = 0; i < 256; i += 2)
  55351. bits.setBit (i / 2, original [i] || original [i + 1]);
  55352. if (type == audioInputType)
  55353. {
  55354. config.useDefaultInputChannels = false;
  55355. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  55356. }
  55357. else
  55358. {
  55359. config.useDefaultOutputChannels = false;
  55360. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  55361. }
  55362. for (i = 0; i < 256; ++i)
  55363. original.setBit (i, bits [i / 2]);
  55364. }
  55365. else
  55366. {
  55367. if (type == audioInputType)
  55368. {
  55369. config.useDefaultInputChannels = false;
  55370. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  55371. }
  55372. else
  55373. {
  55374. config.useDefaultOutputChannels = false;
  55375. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  55376. }
  55377. }
  55378. String error (setup.manager->setAudioDeviceSetup (config, true));
  55379. if (! error.isEmpty())
  55380. {
  55381. //xxx
  55382. }
  55383. }
  55384. }
  55385. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  55386. {
  55387. const int numActive = chans.countNumberOfSetBits();
  55388. if (chans [index])
  55389. {
  55390. if (numActive > minNumber)
  55391. chans.setBit (index, false);
  55392. }
  55393. else
  55394. {
  55395. if (numActive >= maxNumber)
  55396. {
  55397. const int firstActiveChan = chans.findNextSetBit();
  55398. chans.setBit (index > firstActiveChan
  55399. ? firstActiveChan : chans.getHighestBit(),
  55400. false);
  55401. }
  55402. chans.setBit (index, true);
  55403. }
  55404. }
  55405. int getTickX() const throw()
  55406. {
  55407. return getRowHeight() + 5;
  55408. }
  55409. ChannelSelectorListBox (const ChannelSelectorListBox&);
  55410. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  55411. };
  55412. ChannelSelectorListBox* inputChanList;
  55413. ChannelSelectorListBox* outputChanList;
  55414. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  55415. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  55416. };
  55417. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  55418. const int minInputChannels_,
  55419. const int maxInputChannels_,
  55420. const int minOutputChannels_,
  55421. const int maxOutputChannels_,
  55422. const bool showMidiInputOptions,
  55423. const bool showMidiOutputSelector,
  55424. const bool showChannelsAsStereoPairs_,
  55425. const bool hideAdvancedOptionsWithButton_)
  55426. : deviceManager (deviceManager_),
  55427. deviceTypeDropDown (0),
  55428. deviceTypeDropDownLabel (0),
  55429. audioDeviceSettingsComp (0),
  55430. minOutputChannels (minOutputChannels_),
  55431. maxOutputChannels (maxOutputChannels_),
  55432. minInputChannels (minInputChannels_),
  55433. maxInputChannels (maxInputChannels_),
  55434. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  55435. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  55436. {
  55437. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  55438. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  55439. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  55440. {
  55441. deviceTypeDropDown = new ComboBox (String::empty);
  55442. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  55443. {
  55444. deviceTypeDropDown
  55445. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  55446. i + 1);
  55447. }
  55448. addAndMakeVisible (deviceTypeDropDown);
  55449. deviceTypeDropDown->addListener (this);
  55450. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  55451. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  55452. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  55453. }
  55454. if (showMidiInputOptions)
  55455. {
  55456. addAndMakeVisible (midiInputsList
  55457. = new MidiInputSelectorComponentListBox (deviceManager,
  55458. TRANS("(no midi inputs available)"),
  55459. 0, 0));
  55460. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  55461. midiInputsLabel->setJustificationType (Justification::topRight);
  55462. midiInputsLabel->attachToComponent (midiInputsList, true);
  55463. }
  55464. else
  55465. {
  55466. midiInputsList = 0;
  55467. midiInputsLabel = 0;
  55468. }
  55469. if (showMidiOutputSelector)
  55470. {
  55471. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  55472. midiOutputSelector->addListener (this);
  55473. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  55474. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  55475. }
  55476. else
  55477. {
  55478. midiOutputSelector = 0;
  55479. midiOutputLabel = 0;
  55480. }
  55481. deviceManager_.addChangeListener (this);
  55482. changeListenerCallback (0);
  55483. }
  55484. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  55485. {
  55486. deviceManager.removeChangeListener (this);
  55487. deleteAllChildren();
  55488. }
  55489. void AudioDeviceSelectorComponent::resized()
  55490. {
  55491. const int lx = proportionOfWidth (0.35f);
  55492. const int w = proportionOfWidth (0.4f);
  55493. const int h = 24;
  55494. const int space = 6;
  55495. const int dh = h + space;
  55496. int y = 15;
  55497. if (deviceTypeDropDown != 0)
  55498. {
  55499. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  55500. y += dh + space * 2;
  55501. }
  55502. if (audioDeviceSettingsComp != 0)
  55503. {
  55504. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  55505. y += audioDeviceSettingsComp->getHeight() + space;
  55506. }
  55507. if (midiInputsList != 0)
  55508. {
  55509. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  55510. midiInputsList->setBounds (lx, y, w, bh);
  55511. y += bh + space;
  55512. }
  55513. if (midiOutputSelector != 0)
  55514. midiOutputSelector->setBounds (lx, y, w, h);
  55515. }
  55516. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  55517. {
  55518. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  55519. if (device != 0 && device->hasControlPanel())
  55520. {
  55521. if (device->showControlPanel())
  55522. deviceManager.restartLastAudioDevice();
  55523. getTopLevelComponent()->toFront (true);
  55524. }
  55525. }
  55526. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  55527. {
  55528. if (comboBoxThatHasChanged == deviceTypeDropDown)
  55529. {
  55530. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  55531. if (type != 0)
  55532. {
  55533. deleteAndZero (audioDeviceSettingsComp);
  55534. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  55535. changeListenerCallback (0); // needed in case the type hasn't actally changed
  55536. }
  55537. }
  55538. else if (comboBoxThatHasChanged == midiOutputSelector)
  55539. {
  55540. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  55541. }
  55542. }
  55543. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  55544. {
  55545. if (deviceTypeDropDown != 0)
  55546. {
  55547. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  55548. }
  55549. if (audioDeviceSettingsComp == 0
  55550. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  55551. {
  55552. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  55553. deleteAndZero (audioDeviceSettingsComp);
  55554. AudioIODeviceType* const type
  55555. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  55556. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  55557. if (type != 0)
  55558. {
  55559. AudioIODeviceType::DeviceSetupDetails details;
  55560. details.manager = &deviceManager;
  55561. details.minNumInputChannels = minInputChannels;
  55562. details.maxNumInputChannels = maxInputChannels;
  55563. details.minNumOutputChannels = minOutputChannels;
  55564. details.maxNumOutputChannels = maxOutputChannels;
  55565. details.useStereoPairs = showChannelsAsStereoPairs;
  55566. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  55567. if (audioDeviceSettingsComp != 0)
  55568. {
  55569. addAndMakeVisible (audioDeviceSettingsComp);
  55570. audioDeviceSettingsComp->resized();
  55571. }
  55572. }
  55573. }
  55574. if (midiInputsList != 0)
  55575. {
  55576. midiInputsList->updateContent();
  55577. midiInputsList->repaint();
  55578. }
  55579. if (midiOutputSelector != 0)
  55580. {
  55581. midiOutputSelector->clear();
  55582. const StringArray midiOuts (MidiOutput::getDevices());
  55583. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  55584. midiOutputSelector->addSeparator();
  55585. for (int i = 0; i < midiOuts.size(); ++i)
  55586. midiOutputSelector->addItem (midiOuts[i], i + 1);
  55587. int current = -1;
  55588. if (deviceManager.getDefaultMidiOutput() != 0)
  55589. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  55590. midiOutputSelector->setSelectedId (current, true);
  55591. }
  55592. resized();
  55593. }
  55594. END_JUCE_NAMESPACE
  55595. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  55596. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  55597. BEGIN_JUCE_NAMESPACE
  55598. BubbleComponent::BubbleComponent()
  55599. : side (0),
  55600. allowablePlacements (above | below | left | right),
  55601. arrowTipX (0.0f),
  55602. arrowTipY (0.0f)
  55603. {
  55604. setInterceptsMouseClicks (false, false);
  55605. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  55606. setComponentEffect (&shadow);
  55607. }
  55608. BubbleComponent::~BubbleComponent()
  55609. {
  55610. }
  55611. void BubbleComponent::paint (Graphics& g)
  55612. {
  55613. int x = content.getX();
  55614. int y = content.getY();
  55615. int w = content.getWidth();
  55616. int h = content.getHeight();
  55617. int cw, ch;
  55618. getContentSize (cw, ch);
  55619. if (side == 3)
  55620. x += w - cw;
  55621. else if (side != 1)
  55622. x += (w - cw) / 2;
  55623. w = cw;
  55624. if (side == 2)
  55625. y += h - ch;
  55626. else if (side != 0)
  55627. y += (h - ch) / 2;
  55628. h = ch;
  55629. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  55630. (float) x, (float) y,
  55631. (float) w, (float) h);
  55632. const int cx = x + (w - cw) / 2;
  55633. const int cy = y + (h - ch) / 2;
  55634. const int indent = 3;
  55635. g.setOrigin (cx + indent, cy + indent);
  55636. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  55637. paintContent (g, cw - indent * 2, ch - indent * 2);
  55638. }
  55639. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  55640. {
  55641. allowablePlacements = newPlacement;
  55642. }
  55643. void BubbleComponent::setPosition (Component* componentToPointTo)
  55644. {
  55645. jassert (componentToPointTo->isValidComponent());
  55646. int tx = 0;
  55647. int ty = 0;
  55648. if (getParentComponent() != 0)
  55649. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  55650. else
  55651. componentToPointTo->relativePositionToGlobal (tx, ty);
  55652. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  55653. }
  55654. void BubbleComponent::setPosition (const int arrowTipX,
  55655. const int arrowTipY)
  55656. {
  55657. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  55658. }
  55659. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  55660. {
  55661. Rectangle availableSpace;
  55662. if (getParentComponent() != 0)
  55663. {
  55664. availableSpace.setSize (getParentComponent()->getWidth(),
  55665. getParentComponent()->getHeight());
  55666. }
  55667. else
  55668. {
  55669. availableSpace = getParentMonitorArea();
  55670. }
  55671. int x = 0;
  55672. int y = 0;
  55673. int w = 150;
  55674. int h = 30;
  55675. getContentSize (w, h);
  55676. w += 30;
  55677. h += 30;
  55678. const float edgeIndent = 2.0f;
  55679. const int arrowLength = jmin (10, h / 3, w / 3);
  55680. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  55681. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  55682. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  55683. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  55684. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  55685. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  55686. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  55687. {
  55688. spaceLeft = spaceRight = 0;
  55689. }
  55690. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  55691. && (spaceLeft > w + 20 || spaceRight > w + 20))
  55692. {
  55693. spaceAbove = spaceBelow = 0;
  55694. }
  55695. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  55696. {
  55697. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  55698. arrowTipX = w * 0.5f;
  55699. content.setSize (w, h - arrowLength);
  55700. if (spaceAbove >= spaceBelow)
  55701. {
  55702. // above
  55703. y = rectangleToPointTo.getY() - h;
  55704. content.setPosition (0, 0);
  55705. arrowTipY = h - edgeIndent;
  55706. side = 2;
  55707. }
  55708. else
  55709. {
  55710. // below
  55711. y = rectangleToPointTo.getBottom();
  55712. content.setPosition (0, arrowLength);
  55713. arrowTipY = edgeIndent;
  55714. side = 0;
  55715. }
  55716. }
  55717. else
  55718. {
  55719. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  55720. arrowTipY = h * 0.5f;
  55721. content.setSize (w - arrowLength, h);
  55722. if (spaceLeft > spaceRight)
  55723. {
  55724. // on the left
  55725. x = rectangleToPointTo.getX() - w;
  55726. content.setPosition (0, 0);
  55727. arrowTipX = w - edgeIndent;
  55728. side = 3;
  55729. }
  55730. else
  55731. {
  55732. // on the right
  55733. x = rectangleToPointTo.getRight();
  55734. content.setPosition (arrowLength, 0);
  55735. arrowTipX = edgeIndent;
  55736. side = 1;
  55737. }
  55738. }
  55739. setBounds (x, y, w, h);
  55740. }
  55741. END_JUCE_NAMESPACE
  55742. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  55743. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  55744. BEGIN_JUCE_NAMESPACE
  55745. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  55746. : fadeOutLength (fadeOutLengthMs),
  55747. deleteAfterUse (false)
  55748. {
  55749. }
  55750. BubbleMessageComponent::~BubbleMessageComponent()
  55751. {
  55752. fadeOutComponent (fadeOutLength);
  55753. }
  55754. void BubbleMessageComponent::showAt (int x, int y,
  55755. const String& text,
  55756. const int numMillisecondsBeforeRemoving,
  55757. const bool removeWhenMouseClicked,
  55758. const bool deleteSelfAfterUse)
  55759. {
  55760. textLayout.clear();
  55761. textLayout.setText (text, Font (14.0f));
  55762. textLayout.layout (256, Justification::centredLeft, true);
  55763. setPosition (x, y);
  55764. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55765. }
  55766. void BubbleMessageComponent::showAt (Component* const component,
  55767. const String& text,
  55768. const int numMillisecondsBeforeRemoving,
  55769. const bool removeWhenMouseClicked,
  55770. const bool deleteSelfAfterUse)
  55771. {
  55772. textLayout.clear();
  55773. textLayout.setText (text, Font (14.0f));
  55774. textLayout.layout (256, Justification::centredLeft, true);
  55775. setPosition (component);
  55776. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  55777. }
  55778. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  55779. const bool removeWhenMouseClicked,
  55780. const bool deleteSelfAfterUse)
  55781. {
  55782. setVisible (true);
  55783. deleteAfterUse = deleteSelfAfterUse;
  55784. if (numMillisecondsBeforeRemoving > 0)
  55785. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  55786. else
  55787. expiryTime = 0;
  55788. startTimer (77);
  55789. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  55790. if (! (removeWhenMouseClicked && isShowing()))
  55791. mouseClickCounter += 0xfffff;
  55792. repaint();
  55793. }
  55794. void BubbleMessageComponent::getContentSize (int& w, int& h)
  55795. {
  55796. w = textLayout.getWidth() + 16;
  55797. h = textLayout.getHeight() + 16;
  55798. }
  55799. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  55800. {
  55801. g.setColour (findColour (TooltipWindow::textColourId));
  55802. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  55803. }
  55804. void BubbleMessageComponent::timerCallback()
  55805. {
  55806. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  55807. {
  55808. stopTimer();
  55809. setVisible (false);
  55810. if (deleteAfterUse)
  55811. delete this;
  55812. }
  55813. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  55814. {
  55815. stopTimer();
  55816. fadeOutComponent (fadeOutLength);
  55817. if (deleteAfterUse)
  55818. delete this;
  55819. }
  55820. }
  55821. END_JUCE_NAMESPACE
  55822. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  55823. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  55824. BEGIN_JUCE_NAMESPACE
  55825. static const int swatchesPerRow = 8;
  55826. static const int swatchHeight = 22;
  55827. class ColourComponentSlider : public Slider
  55828. {
  55829. public:
  55830. ColourComponentSlider (const String& name)
  55831. : Slider (name)
  55832. {
  55833. setRange (0.0, 255.0, 1.0);
  55834. }
  55835. ~ColourComponentSlider()
  55836. {
  55837. }
  55838. const String getTextFromValue (double currentValue)
  55839. {
  55840. return String::formatted (T("%02X"), (int)currentValue);
  55841. }
  55842. double getValueFromText (const String& text)
  55843. {
  55844. return (double) text.getHexValue32();
  55845. }
  55846. private:
  55847. ColourComponentSlider (const ColourComponentSlider&);
  55848. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  55849. };
  55850. class ColourSpaceMarker : public Component
  55851. {
  55852. public:
  55853. ColourSpaceMarker()
  55854. {
  55855. setInterceptsMouseClicks (false, false);
  55856. }
  55857. ~ColourSpaceMarker()
  55858. {
  55859. }
  55860. void paint (Graphics& g)
  55861. {
  55862. g.setColour (Colour::greyLevel (0.1f));
  55863. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  55864. g.setColour (Colour::greyLevel (0.9f));
  55865. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  55866. }
  55867. private:
  55868. ColourSpaceMarker (const ColourSpaceMarker&);
  55869. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  55870. };
  55871. class ColourSpaceView : public Component
  55872. {
  55873. ColourSelector* const owner;
  55874. float& h;
  55875. float& s;
  55876. float& v;
  55877. float lastHue;
  55878. ColourSpaceMarker* marker;
  55879. const int edge;
  55880. public:
  55881. ColourSpaceView (ColourSelector* owner_,
  55882. float& h_, float& s_, float& v_,
  55883. const int edgeSize)
  55884. : owner (owner_),
  55885. h (h_), s (s_), v (v_),
  55886. lastHue (0.0f),
  55887. edge (edgeSize)
  55888. {
  55889. addAndMakeVisible (marker = new ColourSpaceMarker());
  55890. setMouseCursor (MouseCursor::CrosshairCursor);
  55891. }
  55892. ~ColourSpaceView()
  55893. {
  55894. deleteAllChildren();
  55895. }
  55896. void paint (Graphics& g)
  55897. {
  55898. const float hue = h;
  55899. const float xScale = 1.0f / (getWidth() - edge * 2);
  55900. const float yScale = 1.0f / (getHeight() - edge * 2);
  55901. const Rectangle clip (g.getClipBounds());
  55902. const int x1 = jmax (clip.getX(), edge) & ~1;
  55903. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  55904. const int y1 = jmax (clip.getY(), edge) & ~1;
  55905. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  55906. for (int y = y1; y < y2; y += 2)
  55907. {
  55908. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  55909. for (int x = x1; x < x2; x += 2)
  55910. {
  55911. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  55912. g.setColour (Colour (hue, s, v, 1.0f));
  55913. g.fillRect (x, y, 2, 2);
  55914. }
  55915. }
  55916. }
  55917. void mouseDown (const MouseEvent& e)
  55918. {
  55919. mouseDrag (e);
  55920. }
  55921. void mouseDrag (const MouseEvent& e)
  55922. {
  55923. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  55924. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  55925. owner->setSV (s, v);
  55926. }
  55927. void updateIfNeeded()
  55928. {
  55929. if (lastHue != h)
  55930. {
  55931. lastHue = h;
  55932. repaint();
  55933. }
  55934. resized();
  55935. }
  55936. void resized()
  55937. {
  55938. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  55939. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  55940. edge * 2, edge * 2);
  55941. }
  55942. private:
  55943. ColourSpaceView (const ColourSpaceView&);
  55944. const ColourSpaceView& operator= (const ColourSpaceView&);
  55945. };
  55946. class HueSelectorMarker : public Component
  55947. {
  55948. public:
  55949. HueSelectorMarker()
  55950. {
  55951. setInterceptsMouseClicks (false, false);
  55952. }
  55953. ~HueSelectorMarker()
  55954. {
  55955. }
  55956. void paint (Graphics& g)
  55957. {
  55958. Path p;
  55959. p.addTriangle (1.0f, 1.0f,
  55960. getWidth() * 0.3f, getHeight() * 0.5f,
  55961. 1.0f, getHeight() - 1.0f);
  55962. p.addTriangle (getWidth() - 1.0f, 1.0f,
  55963. getWidth() * 0.7f, getHeight() * 0.5f,
  55964. getWidth() - 1.0f, getHeight() - 1.0f);
  55965. g.setColour (Colours::white.withAlpha (0.75f));
  55966. g.fillPath (p);
  55967. g.setColour (Colours::black.withAlpha (0.75f));
  55968. g.strokePath (p, PathStrokeType (1.2f));
  55969. }
  55970. private:
  55971. HueSelectorMarker (const HueSelectorMarker&);
  55972. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  55973. };
  55974. class HueSelectorComp : public Component
  55975. {
  55976. public:
  55977. HueSelectorComp (ColourSelector* owner_,
  55978. float& h_, float& s_, float& v_,
  55979. const int edgeSize)
  55980. : owner (owner_),
  55981. h (h_), s (s_), v (v_),
  55982. lastHue (0.0f),
  55983. edge (edgeSize)
  55984. {
  55985. addAndMakeVisible (marker = new HueSelectorMarker());
  55986. }
  55987. ~HueSelectorComp()
  55988. {
  55989. deleteAllChildren();
  55990. }
  55991. void paint (Graphics& g)
  55992. {
  55993. const float yScale = 1.0f / (getHeight() - edge * 2);
  55994. const Rectangle clip (g.getClipBounds());
  55995. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  55996. {
  55997. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  55998. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  55999. }
  56000. }
  56001. void resized()
  56002. {
  56003. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  56004. getWidth(), edge * 2);
  56005. }
  56006. void mouseDown (const MouseEvent& e)
  56007. {
  56008. mouseDrag (e);
  56009. }
  56010. void mouseDrag (const MouseEvent& e)
  56011. {
  56012. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  56013. owner->setHue (hue);
  56014. }
  56015. void updateIfNeeded()
  56016. {
  56017. resized();
  56018. }
  56019. private:
  56020. ColourSelector* const owner;
  56021. float& h;
  56022. float& s;
  56023. float& v;
  56024. float lastHue;
  56025. HueSelectorMarker* marker;
  56026. const int edge;
  56027. HueSelectorComp (const HueSelectorComp&);
  56028. const HueSelectorComp& operator= (const HueSelectorComp&);
  56029. };
  56030. class SwatchComponent : public Component
  56031. {
  56032. public:
  56033. SwatchComponent (ColourSelector* owner_, int index_)
  56034. : owner (owner_),
  56035. index (index_)
  56036. {
  56037. }
  56038. ~SwatchComponent()
  56039. {
  56040. }
  56041. void paint (Graphics& g)
  56042. {
  56043. const Colour colour (owner->getSwatchColour (index));
  56044. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  56045. 6, 6,
  56046. Colour (0xffdddddd).overlaidWith (colour),
  56047. Colour (0xffffffff).overlaidWith (colour));
  56048. }
  56049. void mouseDown (const MouseEvent&)
  56050. {
  56051. PopupMenu m;
  56052. m.addItem (1, TRANS("Use this swatch as the current colour"));
  56053. m.addSeparator();
  56054. m.addItem (2, TRANS("Set this swatch to the current colour"));
  56055. const int r = m.showAt (this);
  56056. if (r == 1)
  56057. {
  56058. owner->setCurrentColour (owner->getSwatchColour (index));
  56059. }
  56060. else if (r == 2)
  56061. {
  56062. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  56063. {
  56064. owner->setSwatchColour (index, owner->getCurrentColour());
  56065. repaint();
  56066. }
  56067. }
  56068. }
  56069. private:
  56070. ColourSelector* const owner;
  56071. const int index;
  56072. SwatchComponent (const SwatchComponent&);
  56073. const SwatchComponent& operator= (const SwatchComponent&);
  56074. };
  56075. ColourSelector::ColourSelector (const int flags_,
  56076. const int edgeGap_,
  56077. const int gapAroundColourSpaceComponent)
  56078. : colour (Colours::white),
  56079. flags (flags_),
  56080. topSpace (0),
  56081. edgeGap (edgeGap_)
  56082. {
  56083. // not much point having a selector with no components in it!
  56084. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  56085. updateHSV();
  56086. if ((flags & showSliders) != 0)
  56087. {
  56088. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  56089. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  56090. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  56091. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  56092. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  56093. for (int i = 4; --i >= 0;)
  56094. sliders[i]->addListener (this);
  56095. }
  56096. else
  56097. {
  56098. zeromem (sliders, sizeof (sliders));
  56099. }
  56100. if ((flags & showColourspace) != 0)
  56101. {
  56102. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  56103. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  56104. }
  56105. else
  56106. {
  56107. colourSpace = 0;
  56108. hueSelector = 0;
  56109. }
  56110. update();
  56111. }
  56112. ColourSelector::~ColourSelector()
  56113. {
  56114. dispatchPendingMessages();
  56115. deleteAllChildren();
  56116. }
  56117. const Colour ColourSelector::getCurrentColour() const
  56118. {
  56119. return ((flags & showAlphaChannel) != 0) ? colour
  56120. : colour.withAlpha ((uint8) 0xff);
  56121. }
  56122. void ColourSelector::setCurrentColour (const Colour& c)
  56123. {
  56124. if (c != colour)
  56125. {
  56126. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  56127. updateHSV();
  56128. update();
  56129. }
  56130. }
  56131. void ColourSelector::setHue (float newH)
  56132. {
  56133. newH = jlimit (0.0f, 1.0f, newH);
  56134. if (h != newH)
  56135. {
  56136. h = newH;
  56137. colour = Colour (h, s, v, colour.getFloatAlpha());
  56138. update();
  56139. }
  56140. }
  56141. void ColourSelector::setSV (float newS, float newV)
  56142. {
  56143. newS = jlimit (0.0f, 1.0f, newS);
  56144. newV = jlimit (0.0f, 1.0f, newV);
  56145. if (s != newS || v != newV)
  56146. {
  56147. s = newS;
  56148. v = newV;
  56149. colour = Colour (h, s, v, colour.getFloatAlpha());
  56150. update();
  56151. }
  56152. }
  56153. void ColourSelector::updateHSV()
  56154. {
  56155. colour.getHSB (h, s, v);
  56156. }
  56157. void ColourSelector::update()
  56158. {
  56159. if (sliders[0] != 0)
  56160. {
  56161. sliders[0]->setValue ((int) colour.getRed());
  56162. sliders[1]->setValue ((int) colour.getGreen());
  56163. sliders[2]->setValue ((int) colour.getBlue());
  56164. sliders[3]->setValue ((int) colour.getAlpha());
  56165. }
  56166. if (colourSpace != 0)
  56167. {
  56168. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  56169. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  56170. }
  56171. if ((flags & showColourAtTop) != 0)
  56172. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  56173. sendChangeMessage (this);
  56174. }
  56175. void ColourSelector::paint (Graphics& g)
  56176. {
  56177. g.fillAll (findColour (backgroundColourId));
  56178. if ((flags & showColourAtTop) != 0)
  56179. {
  56180. const Colour colour (getCurrentColour());
  56181. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  56182. 10, 10,
  56183. Colour (0xffdddddd).overlaidWith (colour),
  56184. Colour (0xffffffff).overlaidWith (colour));
  56185. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  56186. g.setFont (14.0f, true);
  56187. g.drawText (((flags & showAlphaChannel) != 0)
  56188. ? String::formatted (T("#%02X%02X%02X%02X"),
  56189. (int) colour.getAlpha(),
  56190. (int) colour.getRed(),
  56191. (int) colour.getGreen(),
  56192. (int) colour.getBlue())
  56193. : String::formatted (T("#%02X%02X%02X"),
  56194. (int) colour.getRed(),
  56195. (int) colour.getGreen(),
  56196. (int) colour.getBlue()),
  56197. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  56198. Justification::centred, false);
  56199. }
  56200. if ((flags & showSliders) != 0)
  56201. {
  56202. g.setColour (findColour (labelTextColourId));
  56203. g.setFont (11.0f);
  56204. for (int i = 4; --i >= 0;)
  56205. {
  56206. if (sliders[i]->isVisible())
  56207. g.drawText (sliders[i]->getName() + T(":"),
  56208. 0, sliders[i]->getY(),
  56209. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  56210. Justification::centredRight, false);
  56211. }
  56212. }
  56213. }
  56214. void ColourSelector::resized()
  56215. {
  56216. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  56217. const int numSwatches = getNumSwatches();
  56218. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  56219. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  56220. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  56221. int y = topSpace;
  56222. if ((flags & showColourspace) != 0)
  56223. {
  56224. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  56225. colourSpace->setBounds (edgeGap, y,
  56226. getWidth() - hueWidth - edgeGap - 4,
  56227. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  56228. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  56229. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  56230. colourSpace->getHeight());
  56231. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  56232. }
  56233. if ((flags & showSliders) != 0)
  56234. {
  56235. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  56236. for (int i = 0; i < numSliders; ++i)
  56237. {
  56238. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  56239. proportionOfWidth (0.72f), sliderHeight - 2);
  56240. y += sliderHeight;
  56241. }
  56242. }
  56243. if (numSwatches > 0)
  56244. {
  56245. const int startX = 8;
  56246. const int xGap = 4;
  56247. const int yGap = 4;
  56248. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  56249. y += edgeGap;
  56250. if (swatchComponents.size() != numSwatches)
  56251. {
  56252. int i;
  56253. for (i = swatchComponents.size(); --i >= 0;)
  56254. {
  56255. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56256. delete sc;
  56257. }
  56258. for (i = 0; i < numSwatches; ++i)
  56259. {
  56260. SwatchComponent* const sc = new SwatchComponent (this, i);
  56261. swatchComponents.add (sc);
  56262. addAndMakeVisible (sc);
  56263. }
  56264. }
  56265. int x = startX;
  56266. for (int i = 0; i < swatchComponents.size(); ++i)
  56267. {
  56268. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  56269. sc->setBounds (x + xGap / 2,
  56270. y + yGap / 2,
  56271. swatchWidth - xGap,
  56272. swatchHeight - yGap);
  56273. if (((i + 1) % swatchesPerRow) == 0)
  56274. {
  56275. x = startX;
  56276. y += swatchHeight;
  56277. }
  56278. else
  56279. {
  56280. x += swatchWidth;
  56281. }
  56282. }
  56283. }
  56284. }
  56285. void ColourSelector::sliderValueChanged (Slider*)
  56286. {
  56287. if (sliders[0] != 0)
  56288. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  56289. (uint8) sliders[1]->getValue(),
  56290. (uint8) sliders[2]->getValue(),
  56291. (uint8) sliders[3]->getValue()));
  56292. }
  56293. int ColourSelector::getNumSwatches() const
  56294. {
  56295. return 0;
  56296. }
  56297. const Colour ColourSelector::getSwatchColour (const int) const
  56298. {
  56299. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56300. return Colours::black;
  56301. }
  56302. void ColourSelector::setSwatchColour (const int, const Colour&) const
  56303. {
  56304. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  56305. }
  56306. END_JUCE_NAMESPACE
  56307. /********* End of inlined file: juce_ColourSelector.cpp *********/
  56308. /********* Start of inlined file: juce_DropShadower.cpp *********/
  56309. BEGIN_JUCE_NAMESPACE
  56310. class ShadowWindow : public Component
  56311. {
  56312. Component* owner;
  56313. Image** shadowImageSections;
  56314. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  56315. public:
  56316. ShadowWindow (Component* const owner_,
  56317. const int type_,
  56318. Image** const shadowImageSections_)
  56319. : owner (owner_),
  56320. shadowImageSections (shadowImageSections_),
  56321. type (type_)
  56322. {
  56323. setInterceptsMouseClicks (false, false);
  56324. if (owner_->isOnDesktop())
  56325. {
  56326. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  56327. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  56328. | ComponentPeer::windowIsTemporary);
  56329. }
  56330. else if (owner_->getParentComponent() != 0)
  56331. {
  56332. owner_->getParentComponent()->addChildComponent (this);
  56333. }
  56334. }
  56335. ~ShadowWindow()
  56336. {
  56337. }
  56338. void paint (Graphics& g)
  56339. {
  56340. Image* const topLeft = shadowImageSections [type * 3];
  56341. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  56342. Image* const filler = shadowImageSections [type * 3 + 2];
  56343. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  56344. g.setOpacity (1.0f);
  56345. if (type < 2)
  56346. {
  56347. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  56348. g.drawImage (topLeft,
  56349. 0, 0, topLeft->getWidth(), imH,
  56350. 0, 0, topLeft->getWidth(), imH);
  56351. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  56352. g.drawImage (bottomRight,
  56353. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  56354. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  56355. g.setBrush (&fillBrush);
  56356. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  56357. }
  56358. else
  56359. {
  56360. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  56361. g.drawImage (topLeft,
  56362. 0, 0, imW, topLeft->getHeight(),
  56363. 0, 0, imW, topLeft->getHeight());
  56364. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  56365. g.drawImage (bottomRight,
  56366. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  56367. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  56368. g.setBrush (&fillBrush);
  56369. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  56370. }
  56371. }
  56372. void resized()
  56373. {
  56374. repaint(); // (needed for correct repainting)
  56375. }
  56376. private:
  56377. ShadowWindow (const ShadowWindow&);
  56378. const ShadowWindow& operator= (const ShadowWindow&);
  56379. };
  56380. DropShadower::DropShadower (const float alpha_,
  56381. const int xOffset_,
  56382. const int yOffset_,
  56383. const float blurRadius_)
  56384. : owner (0),
  56385. numShadows (0),
  56386. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  56387. xOffset (xOffset_),
  56388. yOffset (yOffset_),
  56389. alpha (alpha_),
  56390. blurRadius (blurRadius_),
  56391. inDestructor (false),
  56392. reentrant (false)
  56393. {
  56394. }
  56395. DropShadower::~DropShadower()
  56396. {
  56397. if (owner != 0)
  56398. owner->removeComponentListener (this);
  56399. inDestructor = true;
  56400. deleteShadowWindows();
  56401. }
  56402. void DropShadower::deleteShadowWindows()
  56403. {
  56404. if (numShadows > 0)
  56405. {
  56406. int i;
  56407. for (i = numShadows; --i >= 0;)
  56408. delete shadowWindows[i];
  56409. for (i = 12; --i >= 0;)
  56410. delete shadowImageSections[i];
  56411. numShadows = 0;
  56412. }
  56413. }
  56414. void DropShadower::setOwner (Component* componentToFollow)
  56415. {
  56416. if (componentToFollow != owner)
  56417. {
  56418. if (owner != 0)
  56419. owner->removeComponentListener (this);
  56420. // (the component can't be null)
  56421. jassert (componentToFollow != 0);
  56422. owner = componentToFollow;
  56423. jassert (owner != 0);
  56424. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  56425. owner->addComponentListener (this);
  56426. updateShadows();
  56427. }
  56428. }
  56429. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  56430. {
  56431. updateShadows();
  56432. }
  56433. void DropShadower::componentBroughtToFront (Component&)
  56434. {
  56435. bringShadowWindowsToFront();
  56436. }
  56437. void DropShadower::componentChildrenChanged (Component&)
  56438. {
  56439. }
  56440. void DropShadower::componentParentHierarchyChanged (Component&)
  56441. {
  56442. deleteShadowWindows();
  56443. updateShadows();
  56444. }
  56445. void DropShadower::componentVisibilityChanged (Component&)
  56446. {
  56447. updateShadows();
  56448. }
  56449. void DropShadower::updateShadows()
  56450. {
  56451. if (reentrant || inDestructor || (owner == 0))
  56452. return;
  56453. reentrant = true;
  56454. ComponentPeer* const nw = owner->getPeer();
  56455. const bool isOwnerVisible = owner->isVisible()
  56456. && (nw == 0 || ! nw->isMinimised());
  56457. const bool createShadowWindows = numShadows == 0
  56458. && owner->getWidth() > 0
  56459. && owner->getHeight() > 0
  56460. && isOwnerVisible
  56461. && (Desktop::canUseSemiTransparentWindows()
  56462. || owner->getParentComponent() != 0);
  56463. if (createShadowWindows)
  56464. {
  56465. // keep a cached version of the image to save doing the gaussian too often
  56466. String imageId;
  56467. imageId << shadowEdge << T(',')
  56468. << xOffset << T(',')
  56469. << yOffset << T(',')
  56470. << alpha;
  56471. const int hash = imageId.hashCode();
  56472. Image* bigIm = ImageCache::getFromHashCode (hash);
  56473. if (bigIm == 0)
  56474. {
  56475. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  56476. Graphics bigG (*bigIm);
  56477. bigG.setColour (Colours::black.withAlpha (alpha));
  56478. bigG.fillRect (shadowEdge + xOffset,
  56479. shadowEdge + yOffset,
  56480. bigIm->getWidth() - (shadowEdge * 2),
  56481. bigIm->getHeight() - (shadowEdge * 2));
  56482. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  56483. blurKernel.createGaussianBlur (blurRadius);
  56484. blurKernel.applyToImage (*bigIm, 0,
  56485. xOffset,
  56486. yOffset,
  56487. bigIm->getWidth(),
  56488. bigIm->getHeight());
  56489. ImageCache::addImageToCache (bigIm, hash);
  56490. }
  56491. const int iw = bigIm->getWidth();
  56492. const int ih = bigIm->getHeight();
  56493. const int shadowEdge2 = shadowEdge * 2;
  56494. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  56495. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  56496. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  56497. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  56498. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  56499. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  56500. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  56501. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  56502. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  56503. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  56504. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  56505. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  56506. ImageCache::release (bigIm);
  56507. for (int i = 0; i < 4; ++i)
  56508. {
  56509. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  56510. ++numShadows;
  56511. }
  56512. }
  56513. if (numShadows > 0)
  56514. {
  56515. for (int i = numShadows; --i >= 0;)
  56516. {
  56517. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  56518. shadowWindows[i]->setVisible (isOwnerVisible);
  56519. }
  56520. const int x = owner->getX();
  56521. const int y = owner->getY() - shadowEdge;
  56522. const int w = owner->getWidth();
  56523. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  56524. shadowWindows[0]->setBounds (x - shadowEdge,
  56525. y,
  56526. shadowEdge,
  56527. h);
  56528. shadowWindows[1]->setBounds (x + w,
  56529. y,
  56530. shadowEdge,
  56531. h);
  56532. shadowWindows[2]->setBounds (x,
  56533. y,
  56534. w,
  56535. shadowEdge);
  56536. shadowWindows[3]->setBounds (x,
  56537. owner->getBottom(),
  56538. w,
  56539. shadowEdge);
  56540. }
  56541. reentrant = false;
  56542. if (createShadowWindows)
  56543. bringShadowWindowsToFront();
  56544. }
  56545. void DropShadower::setShadowImage (Image* const src,
  56546. const int num,
  56547. const int w,
  56548. const int h,
  56549. const int sx,
  56550. const int sy) throw()
  56551. {
  56552. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  56553. Graphics g (*shadowImageSections[num]);
  56554. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  56555. }
  56556. void DropShadower::bringShadowWindowsToFront()
  56557. {
  56558. if (! (inDestructor || reentrant))
  56559. {
  56560. updateShadows();
  56561. reentrant = true;
  56562. for (int i = numShadows; --i >= 0;)
  56563. shadowWindows[i]->toBehind (owner);
  56564. reentrant = false;
  56565. }
  56566. }
  56567. END_JUCE_NAMESPACE
  56568. /********* End of inlined file: juce_DropShadower.cpp *********/
  56569. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  56570. BEGIN_JUCE_NAMESPACE
  56571. class MagnifyingPeer : public ComponentPeer
  56572. {
  56573. public:
  56574. MagnifyingPeer (Component* const component_,
  56575. MagnifierComponent* const magnifierComp_)
  56576. : ComponentPeer (component_, 0),
  56577. magnifierComp (magnifierComp_)
  56578. {
  56579. }
  56580. ~MagnifyingPeer()
  56581. {
  56582. }
  56583. void* getNativeHandle() const { return 0; }
  56584. void setVisible (bool) {}
  56585. void setTitle (const String&) {}
  56586. void setPosition (int, int) {}
  56587. void setSize (int, int) {}
  56588. void setBounds (int, int, int, int, const bool) {}
  56589. void setMinimised (bool) {}
  56590. bool isMinimised() const { return false; }
  56591. void setFullScreen (bool) {}
  56592. bool isFullScreen() const { return false; }
  56593. const BorderSize getFrameSize() const { return BorderSize (0); }
  56594. bool setAlwaysOnTop (bool) { return true; }
  56595. void toFront (bool) {}
  56596. void toBehind (ComponentPeer*) {}
  56597. void setIcon (const Image&) {}
  56598. bool isFocused() const
  56599. {
  56600. return magnifierComp->hasKeyboardFocus (true);
  56601. }
  56602. void grabFocus()
  56603. {
  56604. ComponentPeer* peer = magnifierComp->getPeer();
  56605. if (peer != 0)
  56606. peer->grabFocus();
  56607. }
  56608. void textInputRequired (int x, int y)
  56609. {
  56610. ComponentPeer* peer = magnifierComp->getPeer();
  56611. if (peer != 0)
  56612. peer->textInputRequired (x, y);
  56613. }
  56614. void getBounds (int& x, int& y, int& w, int& h) const
  56615. {
  56616. x = magnifierComp->getScreenX();
  56617. y = magnifierComp->getScreenY();
  56618. w = component->getWidth();
  56619. h = component->getHeight();
  56620. }
  56621. int getScreenX() const { return magnifierComp->getScreenX(); }
  56622. int getScreenY() const { return magnifierComp->getScreenY(); }
  56623. void relativePositionToGlobal (int& x, int& y)
  56624. {
  56625. const double zoom = magnifierComp->getScaleFactor();
  56626. x = roundDoubleToInt (x * zoom);
  56627. y = roundDoubleToInt (y * zoom);
  56628. magnifierComp->relativePositionToGlobal (x, y);
  56629. }
  56630. void globalPositionToRelative (int& x, int& y)
  56631. {
  56632. magnifierComp->globalPositionToRelative (x, y);
  56633. const double zoom = magnifierComp->getScaleFactor();
  56634. x = roundDoubleToInt (x / zoom);
  56635. y = roundDoubleToInt (y / zoom);
  56636. }
  56637. bool contains (int x, int y, bool) const
  56638. {
  56639. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  56640. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  56641. }
  56642. void repaint (int x, int y, int w, int h)
  56643. {
  56644. const double zoom = magnifierComp->getScaleFactor();
  56645. magnifierComp->repaint ((int) (x * zoom),
  56646. (int) (y * zoom),
  56647. roundDoubleToInt (w * zoom) + 1,
  56648. roundDoubleToInt (h * zoom) + 1);
  56649. }
  56650. void performAnyPendingRepaintsNow()
  56651. {
  56652. }
  56653. juce_UseDebuggingNewOperator
  56654. private:
  56655. MagnifierComponent* const magnifierComp;
  56656. MagnifyingPeer (const MagnifyingPeer&);
  56657. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  56658. };
  56659. class PeerHolderComp : public Component
  56660. {
  56661. public:
  56662. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  56663. : magnifierComp (magnifierComp_)
  56664. {
  56665. setVisible (true);
  56666. }
  56667. ~PeerHolderComp()
  56668. {
  56669. }
  56670. ComponentPeer* createNewPeer (int, void*)
  56671. {
  56672. return new MagnifyingPeer (this, magnifierComp);
  56673. }
  56674. void childBoundsChanged (Component* c)
  56675. {
  56676. if (c != 0)
  56677. {
  56678. setSize (c->getWidth(), c->getHeight());
  56679. magnifierComp->childBoundsChanged (this);
  56680. }
  56681. }
  56682. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56683. {
  56684. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  56685. Component* const p = magnifierComp->getParentComponent();
  56686. if (p != 0)
  56687. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  56688. }
  56689. private:
  56690. MagnifierComponent* const magnifierComp;
  56691. PeerHolderComp (const PeerHolderComp&);
  56692. const PeerHolderComp& operator= (const PeerHolderComp&);
  56693. };
  56694. MagnifierComponent::MagnifierComponent (Component* const content_,
  56695. const bool deleteContentCompWhenNoLongerNeeded)
  56696. : content (content_),
  56697. scaleFactor (0.0),
  56698. peer (0),
  56699. deleteContent (deleteContentCompWhenNoLongerNeeded),
  56700. quality (Graphics::lowResamplingQuality)
  56701. {
  56702. holderComp = new PeerHolderComp (this);
  56703. setScaleFactor (1.0);
  56704. }
  56705. MagnifierComponent::~MagnifierComponent()
  56706. {
  56707. delete holderComp;
  56708. if (deleteContent)
  56709. delete content;
  56710. }
  56711. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  56712. {
  56713. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  56714. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  56715. if (scaleFactor != newScaleFactor)
  56716. {
  56717. scaleFactor = newScaleFactor;
  56718. if (scaleFactor == 1.0)
  56719. {
  56720. holderComp->removeFromDesktop();
  56721. peer = 0;
  56722. addChildComponent (content);
  56723. childBoundsChanged (content);
  56724. }
  56725. else
  56726. {
  56727. holderComp->addAndMakeVisible (content);
  56728. holderComp->childBoundsChanged (content);
  56729. childBoundsChanged (holderComp);
  56730. holderComp->addToDesktop (0);
  56731. peer = holderComp->getPeer();
  56732. }
  56733. repaint();
  56734. }
  56735. }
  56736. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  56737. {
  56738. quality = newQuality;
  56739. }
  56740. void MagnifierComponent::paint (Graphics& g)
  56741. {
  56742. const int w = holderComp->getWidth();
  56743. const int h = holderComp->getHeight();
  56744. if (w == 0 || h == 0)
  56745. return;
  56746. const Rectangle r (g.getClipBounds());
  56747. const int srcX = (int) (r.getX() / scaleFactor);
  56748. const int srcY = (int) (r.getY() / scaleFactor);
  56749. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  56750. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  56751. if (scaleFactor >= 1.0)
  56752. {
  56753. ++srcW;
  56754. ++srcH;
  56755. }
  56756. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  56757. temp.clear (srcX, srcY, srcW, srcH);
  56758. Graphics g2 (temp);
  56759. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  56760. holderComp->paintEntireComponent (g2);
  56761. g.setImageResamplingQuality (quality);
  56762. g.drawImage (&temp,
  56763. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  56764. 0, 0, w, h,
  56765. false);
  56766. }
  56767. void MagnifierComponent::childBoundsChanged (Component* c)
  56768. {
  56769. if (c != 0)
  56770. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  56771. roundDoubleToInt (c->getHeight() * scaleFactor));
  56772. }
  56773. void MagnifierComponent::mouseDown (const MouseEvent& e)
  56774. {
  56775. if (peer != 0)
  56776. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56777. }
  56778. void MagnifierComponent::mouseUp (const MouseEvent& e)
  56779. {
  56780. if (peer != 0)
  56781. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56782. }
  56783. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  56784. {
  56785. if (peer != 0)
  56786. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56787. }
  56788. void MagnifierComponent::mouseMove (const MouseEvent& e)
  56789. {
  56790. if (peer != 0)
  56791. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56792. }
  56793. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  56794. {
  56795. if (peer != 0)
  56796. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56797. }
  56798. void MagnifierComponent::mouseExit (const MouseEvent& e)
  56799. {
  56800. if (peer != 0)
  56801. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  56802. }
  56803. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  56804. {
  56805. if (peer != 0)
  56806. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  56807. roundFloatToInt (iy * 256.0f),
  56808. e.eventTime.toMilliseconds());
  56809. else
  56810. Component::mouseWheelMove (e, ix, iy);
  56811. }
  56812. int MagnifierComponent::scaleInt (const int n) const throw()
  56813. {
  56814. return roundDoubleToInt (n / scaleFactor);
  56815. }
  56816. END_JUCE_NAMESPACE
  56817. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  56818. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56819. BEGIN_JUCE_NAMESPACE
  56820. class MidiKeyboardUpDownButton : public Button
  56821. {
  56822. public:
  56823. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  56824. const int delta_)
  56825. : Button (String::empty),
  56826. owner (owner_),
  56827. delta (delta_)
  56828. {
  56829. setOpaque (true);
  56830. }
  56831. ~MidiKeyboardUpDownButton()
  56832. {
  56833. }
  56834. void clicked()
  56835. {
  56836. int note = owner->getLowestVisibleKey();
  56837. if (delta < 0)
  56838. note = (note - 1) / 12;
  56839. else
  56840. note = note / 12 + 1;
  56841. owner->setLowestVisibleKey (note * 12);
  56842. }
  56843. void paintButton (Graphics& g,
  56844. bool isMouseOverButton,
  56845. bool isButtonDown)
  56846. {
  56847. owner->drawUpDownButton (g, getWidth(), getHeight(),
  56848. isMouseOverButton, isButtonDown,
  56849. delta > 0);
  56850. }
  56851. private:
  56852. MidiKeyboardComponent* const owner;
  56853. const int delta;
  56854. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  56855. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  56856. };
  56857. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  56858. const Orientation orientation_)
  56859. : state (state_),
  56860. xOffset (0),
  56861. blackNoteLength (1),
  56862. keyWidth (16.0f),
  56863. orientation (orientation_),
  56864. midiChannel (1),
  56865. midiInChannelMask (0xffff),
  56866. velocity (1.0f),
  56867. noteUnderMouse (-1),
  56868. mouseDownNote (-1),
  56869. rangeStart (0),
  56870. rangeEnd (127),
  56871. firstKey (12 * 4),
  56872. canScroll (true),
  56873. mouseDragging (false),
  56874. keyPresses (4),
  56875. keyPressNotes (16),
  56876. keyMappingOctave (6),
  56877. octaveNumForMiddleC (3)
  56878. {
  56879. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  56880. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  56881. // initialise with a default set of querty key-mappings..
  56882. const char* const keymap = "awsedftgyhujkolp;";
  56883. for (int i = String (keymap).length(); --i >= 0;)
  56884. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  56885. setOpaque (true);
  56886. setWantsKeyboardFocus (true);
  56887. state.addListener (this);
  56888. }
  56889. MidiKeyboardComponent::~MidiKeyboardComponent()
  56890. {
  56891. state.removeListener (this);
  56892. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  56893. deleteAllChildren();
  56894. }
  56895. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  56896. {
  56897. keyWidth = widthInPixels;
  56898. resized();
  56899. }
  56900. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  56901. {
  56902. if (orientation != newOrientation)
  56903. {
  56904. orientation = newOrientation;
  56905. resized();
  56906. }
  56907. }
  56908. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  56909. const int highestNote)
  56910. {
  56911. jassert (lowestNote >= 0 && lowestNote <= 127);
  56912. jassert (highestNote >= 0 && highestNote <= 127);
  56913. jassert (lowestNote <= highestNote);
  56914. if (rangeStart != lowestNote || rangeEnd != highestNote)
  56915. {
  56916. rangeStart = jlimit (0, 127, lowestNote);
  56917. rangeEnd = jlimit (0, 127, highestNote);
  56918. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  56919. resized();
  56920. }
  56921. }
  56922. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  56923. {
  56924. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  56925. if (noteNumber != firstKey)
  56926. {
  56927. firstKey = noteNumber;
  56928. sendChangeMessage (this);
  56929. resized();
  56930. }
  56931. }
  56932. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  56933. {
  56934. if (canScroll != canScroll_)
  56935. {
  56936. canScroll = canScroll_;
  56937. resized();
  56938. }
  56939. }
  56940. void MidiKeyboardComponent::colourChanged()
  56941. {
  56942. repaint();
  56943. }
  56944. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  56945. {
  56946. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  56947. if (midiChannel != midiChannelNumber)
  56948. {
  56949. resetAnyKeysInUse();
  56950. midiChannel = jlimit (1, 16, midiChannelNumber);
  56951. }
  56952. }
  56953. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  56954. {
  56955. midiInChannelMask = midiChannelMask;
  56956. triggerAsyncUpdate();
  56957. }
  56958. void MidiKeyboardComponent::setVelocity (const float velocity_)
  56959. {
  56960. velocity = jlimit (0.0f, 1.0f, velocity_);
  56961. }
  56962. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  56963. {
  56964. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  56965. static const float blackNoteWidth = 0.7f;
  56966. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  56967. 1.0f, 2 - blackNoteWidth * 0.4f,
  56968. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  56969. 4.0f, 5 - blackNoteWidth * 0.5f,
  56970. 5.0f, 6 - blackNoteWidth * 0.3f,
  56971. 6.0f };
  56972. static const float widths[] = { 1.0f, blackNoteWidth,
  56973. 1.0f, blackNoteWidth,
  56974. 1.0f, 1.0f, blackNoteWidth,
  56975. 1.0f, blackNoteWidth,
  56976. 1.0f, blackNoteWidth,
  56977. 1.0f };
  56978. const int octave = midiNoteNumber / 12;
  56979. const int note = midiNoteNumber % 12;
  56980. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  56981. w = roundFloatToInt (widths [note] * keyWidth);
  56982. }
  56983. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  56984. {
  56985. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  56986. int rx, rw;
  56987. getKeyPosition (rangeStart, keyWidth, rx, rw);
  56988. x -= xOffset + rx;
  56989. }
  56990. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  56991. {
  56992. int x, y;
  56993. getKeyPos (midiNoteNumber, x, y);
  56994. return x;
  56995. }
  56996. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  56997. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  56998. int MidiKeyboardComponent::xyToNote (int x, int y)
  56999. {
  57000. if (! reallyContains (x, y, false))
  57001. return -1;
  57002. if (orientation != horizontalKeyboard)
  57003. {
  57004. swapVariables (x, y);
  57005. if (orientation == verticalKeyboardFacingLeft)
  57006. y = getWidth() - y;
  57007. else
  57008. x = getHeight() - x;
  57009. }
  57010. return remappedXYToNote (x + xOffset, y);
  57011. }
  57012. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  57013. {
  57014. if (y < blackNoteLength)
  57015. {
  57016. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57017. {
  57018. for (int i = 0; i < 5; ++i)
  57019. {
  57020. const int note = octaveStart + blackNotes [i];
  57021. if (note >= rangeStart && note <= rangeEnd)
  57022. {
  57023. int kx, kw;
  57024. getKeyPos (note, kx, kw);
  57025. kx += xOffset;
  57026. if (x >= kx && x < kx + kw)
  57027. return note;
  57028. }
  57029. }
  57030. }
  57031. }
  57032. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  57033. {
  57034. for (int i = 0; i < 7; ++i)
  57035. {
  57036. const int note = octaveStart + whiteNotes [i];
  57037. if (note >= rangeStart && note <= rangeEnd)
  57038. {
  57039. int kx, kw;
  57040. getKeyPos (note, kx, kw);
  57041. kx += xOffset;
  57042. if (x >= kx && x < kx + kw)
  57043. return note;
  57044. }
  57045. }
  57046. }
  57047. return -1;
  57048. }
  57049. void MidiKeyboardComponent::repaintNote (const int noteNum)
  57050. {
  57051. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57052. {
  57053. int x, w;
  57054. getKeyPos (noteNum, x, w);
  57055. if (orientation == horizontalKeyboard)
  57056. repaint (x, 0, w, getHeight());
  57057. else if (orientation == verticalKeyboardFacingLeft)
  57058. repaint (0, x, getWidth(), w);
  57059. else if (orientation == verticalKeyboardFacingRight)
  57060. repaint (0, getHeight() - x - w, getWidth(), w);
  57061. }
  57062. }
  57063. void MidiKeyboardComponent::paint (Graphics& g)
  57064. {
  57065. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  57066. const Colour lineColour (findColour (keySeparatorLineColourId));
  57067. const Colour textColour (findColour (textLabelColourId));
  57068. int x, w, octave;
  57069. for (octave = 0; octave < 128; octave += 12)
  57070. {
  57071. for (int white = 0; white < 7; ++white)
  57072. {
  57073. const int noteNum = octave + whiteNotes [white];
  57074. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57075. {
  57076. getKeyPos (noteNum, x, w);
  57077. if (orientation == horizontalKeyboard)
  57078. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  57079. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57080. noteUnderMouse == noteNum,
  57081. lineColour, textColour);
  57082. else if (orientation == verticalKeyboardFacingLeft)
  57083. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  57084. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57085. noteUnderMouse == noteNum,
  57086. lineColour, textColour);
  57087. else if (orientation == verticalKeyboardFacingRight)
  57088. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  57089. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57090. noteUnderMouse == noteNum,
  57091. lineColour, textColour);
  57092. }
  57093. }
  57094. }
  57095. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  57096. if (orientation == verticalKeyboardFacingLeft)
  57097. {
  57098. x1 = getWidth() - 1.0f;
  57099. x2 = getWidth() - 5.0f;
  57100. }
  57101. else if (orientation == verticalKeyboardFacingRight)
  57102. x2 = 5.0f;
  57103. else
  57104. y2 = 5.0f;
  57105. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  57106. Colours::transparentBlack, x2, y2, false);
  57107. g.setBrush (&gb);
  57108. getKeyPos (rangeEnd, x, w);
  57109. x += w;
  57110. if (orientation == verticalKeyboardFacingLeft)
  57111. g.fillRect (getWidth() - 5, 0, 5, x);
  57112. else if (orientation == verticalKeyboardFacingRight)
  57113. g.fillRect (0, 0, 5, x);
  57114. else
  57115. g.fillRect (0, 0, x, 5);
  57116. g.setColour (lineColour);
  57117. if (orientation == verticalKeyboardFacingLeft)
  57118. g.fillRect (0, 0, 1, x);
  57119. else if (orientation == verticalKeyboardFacingRight)
  57120. g.fillRect (getWidth() - 1, 0, 1, x);
  57121. else
  57122. g.fillRect (0, getHeight() - 1, x, 1);
  57123. const Colour blackNoteColour (findColour (blackNoteColourId));
  57124. for (octave = 0; octave < 128; octave += 12)
  57125. {
  57126. for (int black = 0; black < 5; ++black)
  57127. {
  57128. const int noteNum = octave + blackNotes [black];
  57129. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  57130. {
  57131. getKeyPos (noteNum, x, w);
  57132. if (orientation == horizontalKeyboard)
  57133. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  57134. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57135. noteUnderMouse == noteNum,
  57136. blackNoteColour);
  57137. else if (orientation == verticalKeyboardFacingLeft)
  57138. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  57139. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57140. noteUnderMouse == noteNum,
  57141. blackNoteColour);
  57142. else if (orientation == verticalKeyboardFacingRight)
  57143. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  57144. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  57145. noteUnderMouse == noteNum,
  57146. blackNoteColour);
  57147. }
  57148. }
  57149. }
  57150. }
  57151. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  57152. Graphics& g, int x, int y, int w, int h,
  57153. bool isDown, bool isOver,
  57154. const Colour& lineColour,
  57155. const Colour& textColour)
  57156. {
  57157. Colour c (Colours::transparentWhite);
  57158. if (isDown)
  57159. c = findColour (keyDownOverlayColourId);
  57160. if (isOver)
  57161. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57162. g.setColour (c);
  57163. g.fillRect (x, y, w, h);
  57164. const String text (getWhiteNoteText (midiNoteNumber));
  57165. if (! text.isEmpty())
  57166. {
  57167. g.setColour (textColour);
  57168. Font f (jmin (12.0f, keyWidth * 0.9f));
  57169. f.setHorizontalScale (0.8f);
  57170. g.setFont (f);
  57171. Justification justification (Justification::centredBottom);
  57172. if (orientation == verticalKeyboardFacingLeft)
  57173. justification = Justification::centredLeft;
  57174. else if (orientation == verticalKeyboardFacingRight)
  57175. justification = Justification::centredRight;
  57176. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  57177. }
  57178. g.setColour (lineColour);
  57179. if (orientation == horizontalKeyboard)
  57180. g.fillRect (x, y, 1, h);
  57181. else if (orientation == verticalKeyboardFacingLeft)
  57182. g.fillRect (x, y, w, 1);
  57183. else if (orientation == verticalKeyboardFacingRight)
  57184. g.fillRect (x, y + h - 1, w, 1);
  57185. if (midiNoteNumber == rangeEnd)
  57186. {
  57187. if (orientation == horizontalKeyboard)
  57188. g.fillRect (x + w, y, 1, h);
  57189. else if (orientation == verticalKeyboardFacingLeft)
  57190. g.fillRect (x, y + h, w, 1);
  57191. else if (orientation == verticalKeyboardFacingRight)
  57192. g.fillRect (x, y - 1, w, 1);
  57193. }
  57194. }
  57195. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  57196. Graphics& g, int x, int y, int w, int h,
  57197. bool isDown, bool isOver,
  57198. const Colour& noteFillColour)
  57199. {
  57200. Colour c (noteFillColour);
  57201. if (isDown)
  57202. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  57203. if (isOver)
  57204. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  57205. g.setColour (c);
  57206. g.fillRect (x, y, w, h);
  57207. if (isDown)
  57208. {
  57209. g.setColour (noteFillColour);
  57210. g.drawRect (x, y, w, h);
  57211. }
  57212. else
  57213. {
  57214. const int xIndent = jmax (1, jmin (w, h) / 8);
  57215. g.setColour (c.brighter());
  57216. if (orientation == horizontalKeyboard)
  57217. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  57218. else if (orientation == verticalKeyboardFacingLeft)
  57219. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  57220. else if (orientation == verticalKeyboardFacingRight)
  57221. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  57222. }
  57223. }
  57224. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  57225. {
  57226. octaveNumForMiddleC = octaveNumForMiddleC_;
  57227. repaint();
  57228. }
  57229. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  57230. {
  57231. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  57232. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  57233. return String::empty;
  57234. }
  57235. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  57236. const bool isMouseOver,
  57237. const bool isButtonDown,
  57238. const bool movesOctavesUp)
  57239. {
  57240. g.fillAll (findColour (upDownButtonBackgroundColourId));
  57241. float angle;
  57242. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  57243. angle = movesOctavesUp ? 0.0f : 0.5f;
  57244. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  57245. angle = movesOctavesUp ? 0.25f : 0.75f;
  57246. else
  57247. angle = movesOctavesUp ? 0.75f : 0.25f;
  57248. Path path;
  57249. path.lineTo (0.0f, 1.0f);
  57250. path.lineTo (1.0f, 0.5f);
  57251. path.closeSubPath();
  57252. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  57253. g.setColour (findColour (upDownButtonArrowColourId)
  57254. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  57255. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  57256. w - 2.0f,
  57257. h - 2.0f,
  57258. true));
  57259. }
  57260. void MidiKeyboardComponent::resized()
  57261. {
  57262. int w = getWidth();
  57263. int h = getHeight();
  57264. if (w > 0 && h > 0)
  57265. {
  57266. if (orientation != horizontalKeyboard)
  57267. swapVariables (w, h);
  57268. blackNoteLength = roundFloatToInt (h * 0.7f);
  57269. int kx2, kw2;
  57270. getKeyPos (rangeEnd, kx2, kw2);
  57271. kx2 += kw2;
  57272. if (firstKey != rangeStart)
  57273. {
  57274. int kx1, kw1;
  57275. getKeyPos (rangeStart, kx1, kw1);
  57276. if (kx2 - kx1 <= w)
  57277. {
  57278. firstKey = rangeStart;
  57279. sendChangeMessage (this);
  57280. repaint();
  57281. }
  57282. }
  57283. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  57284. scrollDown->setVisible (showScrollButtons);
  57285. scrollUp->setVisible (showScrollButtons);
  57286. xOffset = 0;
  57287. if (showScrollButtons)
  57288. {
  57289. const int scrollButtonW = jmin (12, w / 2);
  57290. if (orientation == horizontalKeyboard)
  57291. {
  57292. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  57293. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  57294. }
  57295. else if (orientation == verticalKeyboardFacingLeft)
  57296. {
  57297. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  57298. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57299. }
  57300. else if (orientation == verticalKeyboardFacingRight)
  57301. {
  57302. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  57303. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  57304. }
  57305. int endOfLastKey, kw;
  57306. getKeyPos (rangeEnd, endOfLastKey, kw);
  57307. endOfLastKey += kw;
  57308. const int spaceAvailable = w - scrollButtonW * 2;
  57309. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  57310. if (lastStartKey >= 0 && firstKey > lastStartKey)
  57311. {
  57312. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  57313. sendChangeMessage (this);
  57314. }
  57315. int newOffset = 0;
  57316. getKeyPos (firstKey, newOffset, kw);
  57317. xOffset = newOffset - scrollButtonW;
  57318. }
  57319. else
  57320. {
  57321. firstKey = rangeStart;
  57322. }
  57323. timerCallback();
  57324. repaint();
  57325. }
  57326. }
  57327. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  57328. {
  57329. triggerAsyncUpdate();
  57330. }
  57331. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  57332. {
  57333. triggerAsyncUpdate();
  57334. }
  57335. void MidiKeyboardComponent::handleAsyncUpdate()
  57336. {
  57337. for (int i = rangeStart; i <= rangeEnd; ++i)
  57338. {
  57339. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  57340. {
  57341. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  57342. repaintNote (i);
  57343. }
  57344. }
  57345. }
  57346. void MidiKeyboardComponent::resetAnyKeysInUse()
  57347. {
  57348. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  57349. {
  57350. state.allNotesOff (midiChannel);
  57351. keysPressed.clear();
  57352. mouseDownNote = -1;
  57353. }
  57354. }
  57355. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  57356. {
  57357. const int newNote = (mouseDragging || isMouseOver())
  57358. ? xyToNote (x, y) : -1;
  57359. if (noteUnderMouse != newNote)
  57360. {
  57361. if (mouseDownNote >= 0)
  57362. {
  57363. state.noteOff (midiChannel, mouseDownNote);
  57364. mouseDownNote = -1;
  57365. }
  57366. if (mouseDragging && newNote >= 0)
  57367. {
  57368. state.noteOn (midiChannel, newNote, velocity);
  57369. mouseDownNote = newNote;
  57370. }
  57371. repaintNote (noteUnderMouse);
  57372. noteUnderMouse = newNote;
  57373. repaintNote (noteUnderMouse);
  57374. }
  57375. else if (mouseDownNote >= 0 && ! mouseDragging)
  57376. {
  57377. state.noteOff (midiChannel, mouseDownNote);
  57378. mouseDownNote = -1;
  57379. }
  57380. }
  57381. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  57382. {
  57383. updateNoteUnderMouse (e.x, e.y);
  57384. stopTimer();
  57385. }
  57386. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  57387. {
  57388. const int newNote = xyToNote (e.x, e.y);
  57389. if (newNote >= 0)
  57390. mouseDraggedToKey (newNote, e);
  57391. updateNoteUnderMouse (e.x, e.y);
  57392. }
  57393. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  57394. {
  57395. return true;
  57396. }
  57397. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  57398. {
  57399. }
  57400. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  57401. {
  57402. const int newNote = xyToNote (e.x, e.y);
  57403. mouseDragging = false;
  57404. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  57405. {
  57406. repaintNote (noteUnderMouse);
  57407. noteUnderMouse = -1;
  57408. mouseDragging = true;
  57409. updateNoteUnderMouse (e.x, e.y);
  57410. startTimer (500);
  57411. }
  57412. }
  57413. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  57414. {
  57415. mouseDragging = false;
  57416. updateNoteUnderMouse (e.x, e.y);
  57417. stopTimer();
  57418. }
  57419. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  57420. {
  57421. updateNoteUnderMouse (e.x, e.y);
  57422. }
  57423. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  57424. {
  57425. updateNoteUnderMouse (e.x, e.y);
  57426. }
  57427. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  57428. {
  57429. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  57430. }
  57431. void MidiKeyboardComponent::timerCallback()
  57432. {
  57433. int mx, my;
  57434. getMouseXYRelative (mx, my);
  57435. updateNoteUnderMouse (mx, my);
  57436. }
  57437. void MidiKeyboardComponent::clearKeyMappings()
  57438. {
  57439. resetAnyKeysInUse();
  57440. keyPressNotes.clear();
  57441. keyPresses.clear();
  57442. }
  57443. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  57444. const int midiNoteOffsetFromC)
  57445. {
  57446. removeKeyPressForNote (midiNoteOffsetFromC);
  57447. keyPressNotes.add (midiNoteOffsetFromC);
  57448. keyPresses.add (key);
  57449. }
  57450. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  57451. {
  57452. for (int i = keyPressNotes.size(); --i >= 0;)
  57453. {
  57454. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  57455. {
  57456. keyPressNotes.remove (i);
  57457. keyPresses.remove (i);
  57458. }
  57459. }
  57460. }
  57461. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  57462. {
  57463. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  57464. keyMappingOctave = newOctaveNumber;
  57465. }
  57466. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  57467. {
  57468. bool keyPressUsed = false;
  57469. for (int i = keyPresses.size(); --i >= 0;)
  57470. {
  57471. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  57472. if (keyPresses.getReference(i).isCurrentlyDown())
  57473. {
  57474. if (! keysPressed [note])
  57475. {
  57476. keysPressed.setBit (note);
  57477. state.noteOn (midiChannel, note, velocity);
  57478. keyPressUsed = true;
  57479. }
  57480. }
  57481. else
  57482. {
  57483. if (keysPressed [note])
  57484. {
  57485. keysPressed.clearBit (note);
  57486. state.noteOff (midiChannel, note);
  57487. keyPressUsed = true;
  57488. }
  57489. }
  57490. }
  57491. return keyPressUsed;
  57492. }
  57493. void MidiKeyboardComponent::focusLost (FocusChangeType)
  57494. {
  57495. resetAnyKeysInUse();
  57496. }
  57497. END_JUCE_NAMESPACE
  57498. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  57499. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  57500. #if JUCE_OPENGL
  57501. BEGIN_JUCE_NAMESPACE
  57502. extern void juce_glViewport (const int w, const int h);
  57503. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  57504. const int alphaBits_,
  57505. const int depthBufferBits_,
  57506. const int stencilBufferBits_) throw()
  57507. : redBits (bitsPerRGBComponent),
  57508. greenBits (bitsPerRGBComponent),
  57509. blueBits (bitsPerRGBComponent),
  57510. alphaBits (alphaBits_),
  57511. depthBufferBits (depthBufferBits_),
  57512. stencilBufferBits (stencilBufferBits_),
  57513. accumulationBufferRedBits (0),
  57514. accumulationBufferGreenBits (0),
  57515. accumulationBufferBlueBits (0),
  57516. accumulationBufferAlphaBits (0),
  57517. fullSceneAntiAliasingNumSamples (0)
  57518. {
  57519. }
  57520. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  57521. {
  57522. return memcmp (this, &other, sizeof (other)) == 0;
  57523. }
  57524. static VoidArray knownContexts;
  57525. OpenGLContext::OpenGLContext() throw()
  57526. {
  57527. knownContexts.add (this);
  57528. }
  57529. OpenGLContext::~OpenGLContext()
  57530. {
  57531. knownContexts.removeValue (this);
  57532. }
  57533. OpenGLContext* OpenGLContext::getCurrentContext()
  57534. {
  57535. for (int i = knownContexts.size(); --i >= 0;)
  57536. {
  57537. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  57538. if (oglc->isActive())
  57539. return oglc;
  57540. }
  57541. return 0;
  57542. }
  57543. class OpenGLComponentWatcher : public ComponentMovementWatcher
  57544. {
  57545. public:
  57546. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  57547. : ComponentMovementWatcher (owner_),
  57548. owner (owner_),
  57549. wasShowing (false)
  57550. {
  57551. }
  57552. ~OpenGLComponentWatcher() {}
  57553. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  57554. {
  57555. owner->updateContextPosition();
  57556. }
  57557. void componentPeerChanged()
  57558. {
  57559. const ScopedLock sl (owner->getContextLock());
  57560. owner->deleteContext();
  57561. }
  57562. void componentVisibilityChanged (Component&)
  57563. {
  57564. const bool isShowingNow = owner->isShowing();
  57565. if (wasShowing != isShowingNow)
  57566. {
  57567. wasShowing = isShowingNow;
  57568. owner->updateContextPosition();
  57569. }
  57570. }
  57571. juce_UseDebuggingNewOperator
  57572. private:
  57573. OpenGLComponent* const owner;
  57574. bool wasShowing;
  57575. };
  57576. OpenGLComponent::OpenGLComponent()
  57577. : context (0),
  57578. contextToShareListsWith (0),
  57579. needToUpdateViewport (true)
  57580. {
  57581. setOpaque (true);
  57582. componentWatcher = new OpenGLComponentWatcher (this);
  57583. }
  57584. OpenGLComponent::~OpenGLComponent()
  57585. {
  57586. deleteContext();
  57587. delete componentWatcher;
  57588. }
  57589. void OpenGLComponent::deleteContext()
  57590. {
  57591. const ScopedLock sl (contextLock);
  57592. deleteAndZero (context);
  57593. }
  57594. void OpenGLComponent::updateContextPosition()
  57595. {
  57596. needToUpdateViewport = true;
  57597. if (getWidth() > 0 && getHeight() > 0)
  57598. {
  57599. Component* const topComp = getTopLevelComponent();
  57600. if (topComp->getPeer() != 0)
  57601. {
  57602. const ScopedLock sl (contextLock);
  57603. if (context != 0)
  57604. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  57605. getScreenY() - topComp->getScreenY(),
  57606. getWidth(),
  57607. getHeight(),
  57608. topComp->getHeight());
  57609. }
  57610. }
  57611. }
  57612. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  57613. {
  57614. OpenGLPixelFormat pf;
  57615. const ScopedLock sl (contextLock);
  57616. if (context != 0)
  57617. pf = context->getPixelFormat();
  57618. return pf;
  57619. }
  57620. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  57621. {
  57622. if (! (preferredPixelFormat == formatToUse))
  57623. {
  57624. const ScopedLock sl (contextLock);
  57625. deleteContext();
  57626. preferredPixelFormat = formatToUse;
  57627. }
  57628. }
  57629. void OpenGLComponent::shareWith (OpenGLContext* context)
  57630. {
  57631. if (contextToShareListsWith != context)
  57632. {
  57633. const ScopedLock sl (contextLock);
  57634. deleteContext();
  57635. contextToShareListsWith = context;
  57636. }
  57637. }
  57638. bool OpenGLComponent::makeCurrentContextActive()
  57639. {
  57640. if (context == 0)
  57641. {
  57642. const ScopedLock sl (contextLock);
  57643. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  57644. {
  57645. context = OpenGLContext::createContextForWindow (this,
  57646. preferredPixelFormat,
  57647. contextToShareListsWith);
  57648. if (context != 0)
  57649. {
  57650. updateContextPosition();
  57651. if (context->makeActive())
  57652. newOpenGLContextCreated();
  57653. }
  57654. }
  57655. }
  57656. return context != 0 && context->makeActive();
  57657. }
  57658. void OpenGLComponent::makeCurrentContextInactive()
  57659. {
  57660. if (context != 0)
  57661. context->makeInactive();
  57662. }
  57663. bool OpenGLComponent::isActiveContext() const throw()
  57664. {
  57665. return context != 0 && context->isActive();
  57666. }
  57667. void OpenGLComponent::swapBuffers()
  57668. {
  57669. if (context != 0)
  57670. context->swapBuffers();
  57671. }
  57672. void OpenGLComponent::paint (Graphics&)
  57673. {
  57674. if (renderAndSwapBuffers())
  57675. {
  57676. ComponentPeer* const peer = getPeer();
  57677. if (peer != 0)
  57678. {
  57679. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  57680. getScreenY() - peer->getScreenY(),
  57681. getWidth(), getHeight());
  57682. }
  57683. }
  57684. }
  57685. bool OpenGLComponent::renderAndSwapBuffers()
  57686. {
  57687. const ScopedLock sl (contextLock);
  57688. if (! makeCurrentContextActive())
  57689. return false;
  57690. if (needToUpdateViewport)
  57691. {
  57692. needToUpdateViewport = false;
  57693. juce_glViewport (getWidth(), getHeight());
  57694. }
  57695. renderOpenGL();
  57696. swapBuffers();
  57697. return true;
  57698. }
  57699. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  57700. {
  57701. Component::internalRepaint (x, y, w, h);
  57702. if (context != 0)
  57703. context->repaint();
  57704. }
  57705. END_JUCE_NAMESPACE
  57706. #endif
  57707. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  57708. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  57709. BEGIN_JUCE_NAMESPACE
  57710. PreferencesPanel::PreferencesPanel()
  57711. : currentPage (0),
  57712. buttonSize (70)
  57713. {
  57714. }
  57715. PreferencesPanel::~PreferencesPanel()
  57716. {
  57717. deleteAllChildren();
  57718. }
  57719. void PreferencesPanel::addSettingsPage (const String& title,
  57720. const Drawable* icon,
  57721. const Drawable* overIcon,
  57722. const Drawable* downIcon)
  57723. {
  57724. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  57725. button->setImages (icon, overIcon, downIcon);
  57726. button->setRadioGroupId (1);
  57727. button->addButtonListener (this);
  57728. button->setClickingTogglesState (true);
  57729. button->setWantsKeyboardFocus (false);
  57730. addAndMakeVisible (button);
  57731. resized();
  57732. if (currentPage == 0)
  57733. setCurrentPage (title);
  57734. }
  57735. void PreferencesPanel::addSettingsPage (const String& title,
  57736. const char* imageData,
  57737. const int imageDataSize)
  57738. {
  57739. DrawableImage icon, iconOver, iconDown;
  57740. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57741. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57742. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  57743. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  57744. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  57745. addSettingsPage (title, &icon, &iconOver, &iconDown);
  57746. }
  57747. class PrefsDialogWindow : public DialogWindow
  57748. {
  57749. public:
  57750. PrefsDialogWindow (const String& dialogtitle,
  57751. const Colour& backgroundColour)
  57752. : DialogWindow (dialogtitle, backgroundColour, true)
  57753. {
  57754. }
  57755. ~PrefsDialogWindow()
  57756. {
  57757. }
  57758. void closeButtonPressed()
  57759. {
  57760. exitModalState (0);
  57761. }
  57762. private:
  57763. PrefsDialogWindow (const PrefsDialogWindow&);
  57764. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  57765. };
  57766. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  57767. int dialogWidth,
  57768. int dialogHeight,
  57769. const Colour& backgroundColour)
  57770. {
  57771. setSize (dialogWidth, dialogHeight);
  57772. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  57773. dw.setContentComponent (this, true, true);
  57774. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  57775. dw.runModalLoop();
  57776. dw.setContentComponent (0, false, false);
  57777. }
  57778. void PreferencesPanel::resized()
  57779. {
  57780. int x = 0;
  57781. for (int i = 0; i < getNumChildComponents(); ++i)
  57782. {
  57783. Component* c = getChildComponent (i);
  57784. if (dynamic_cast <DrawableButton*> (c) == 0)
  57785. {
  57786. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  57787. }
  57788. else
  57789. {
  57790. c->setBounds (x, 0, buttonSize, buttonSize);
  57791. x += buttonSize;
  57792. }
  57793. }
  57794. }
  57795. void PreferencesPanel::paint (Graphics& g)
  57796. {
  57797. g.setColour (Colours::grey);
  57798. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  57799. }
  57800. void PreferencesPanel::setCurrentPage (const String& pageName)
  57801. {
  57802. if (currentPageName != pageName)
  57803. {
  57804. currentPageName = pageName;
  57805. deleteAndZero (currentPage);
  57806. currentPage = createComponentForPage (pageName);
  57807. if (currentPage != 0)
  57808. {
  57809. addAndMakeVisible (currentPage);
  57810. currentPage->toBack();
  57811. resized();
  57812. }
  57813. for (int i = 0; i < getNumChildComponents(); ++i)
  57814. {
  57815. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57816. if (db != 0 && db->getName() == pageName)
  57817. {
  57818. db->setToggleState (true, false);
  57819. break;
  57820. }
  57821. }
  57822. }
  57823. }
  57824. void PreferencesPanel::buttonClicked (Button*)
  57825. {
  57826. for (int i = 0; i < getNumChildComponents(); ++i)
  57827. {
  57828. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  57829. if (db != 0 && db->getToggleState())
  57830. {
  57831. setCurrentPage (db->getName());
  57832. break;
  57833. }
  57834. }
  57835. }
  57836. END_JUCE_NAMESPACE
  57837. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  57838. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57839. #if JUCE_WIN32 || JUCE_LINUX
  57840. BEGIN_JUCE_NAMESPACE
  57841. SystemTrayIconComponent::SystemTrayIconComponent()
  57842. {
  57843. addToDesktop (0);
  57844. }
  57845. SystemTrayIconComponent::~SystemTrayIconComponent()
  57846. {
  57847. }
  57848. END_JUCE_NAMESPACE
  57849. #endif
  57850. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  57851. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  57852. BEGIN_JUCE_NAMESPACE
  57853. static const int titleH = 24;
  57854. static const int iconWidth = 80;
  57855. class AlertWindowTextEditor : public TextEditor
  57856. {
  57857. public:
  57858. #if JUCE_LINUX
  57859. #define PASSWORD_CHAR 0x2022
  57860. #else
  57861. #define PASSWORD_CHAR 0x25cf
  57862. #endif
  57863. AlertWindowTextEditor (const String& name,
  57864. const bool isPasswordBox)
  57865. : TextEditor (name,
  57866. isPasswordBox ? (const tchar) PASSWORD_CHAR
  57867. : (const tchar) 0)
  57868. {
  57869. setSelectAllWhenFocused (true);
  57870. }
  57871. ~AlertWindowTextEditor()
  57872. {
  57873. }
  57874. void returnPressed()
  57875. {
  57876. // pass these up the component hierarchy to be trigger the buttons
  57877. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  57878. }
  57879. void escapePressed()
  57880. {
  57881. // pass these up the component hierarchy to be trigger the buttons
  57882. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  57883. }
  57884. private:
  57885. AlertWindowTextEditor (const AlertWindowTextEditor&);
  57886. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  57887. };
  57888. AlertWindow::AlertWindow (const String& title,
  57889. const String& message,
  57890. AlertIconType iconType,
  57891. Component* associatedComponent_)
  57892. : TopLevelWindow (title, true),
  57893. alertIconType (iconType),
  57894. associatedComponent (associatedComponent_)
  57895. {
  57896. if (message.isEmpty())
  57897. text = T(" "); // to force an update if the message is empty
  57898. setMessage (message);
  57899. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  57900. {
  57901. Component* const c = Desktop::getInstance().getComponent (i);
  57902. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  57903. {
  57904. setAlwaysOnTop (true);
  57905. break;
  57906. }
  57907. }
  57908. if (JUCEApplication::getInstance() == 0)
  57909. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  57910. lookAndFeelChanged();
  57911. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  57912. }
  57913. AlertWindow::~AlertWindow()
  57914. {
  57915. for (int i = customComps.size(); --i >= 0;)
  57916. removeChildComponent ((Component*) customComps[i]);
  57917. deleteAllChildren();
  57918. }
  57919. void AlertWindow::userTriedToCloseWindow()
  57920. {
  57921. exitModalState (0);
  57922. }
  57923. void AlertWindow::setMessage (const String& message)
  57924. {
  57925. const String newMessage (message.substring (0, 2048));
  57926. if (text != newMessage)
  57927. {
  57928. text = newMessage;
  57929. font.setHeight (15.0f);
  57930. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  57931. textLayout.setText (getName() + T("\n\n"), titleFont);
  57932. textLayout.appendText (text, font);
  57933. updateLayout (true);
  57934. repaint();
  57935. }
  57936. }
  57937. void AlertWindow::buttonClicked (Button* button)
  57938. {
  57939. for (int i = 0; i < buttons.size(); i++)
  57940. {
  57941. TextButton* const c = (TextButton*) buttons[i];
  57942. if (button->getName() == c->getName())
  57943. {
  57944. if (c->getParentComponent() != 0)
  57945. c->getParentComponent()->exitModalState (c->getCommandID());
  57946. break;
  57947. }
  57948. }
  57949. }
  57950. void AlertWindow::addButton (const String& name,
  57951. const int returnValue,
  57952. const KeyPress& shortcutKey1,
  57953. const KeyPress& shortcutKey2)
  57954. {
  57955. TextButton* const b = new TextButton (name, String::empty);
  57956. b->setWantsKeyboardFocus (true);
  57957. b->setMouseClickGrabsKeyboardFocus (false);
  57958. b->setCommandToTrigger (0, returnValue, false);
  57959. b->addShortcut (shortcutKey1);
  57960. b->addShortcut (shortcutKey2);
  57961. b->addButtonListener (this);
  57962. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  57963. addAndMakeVisible (b, 0);
  57964. buttons.add (b);
  57965. updateLayout (false);
  57966. }
  57967. int AlertWindow::getNumButtons() const
  57968. {
  57969. return buttons.size();
  57970. }
  57971. void AlertWindow::addTextEditor (const String& name,
  57972. const String& initialContents,
  57973. const String& onScreenLabel,
  57974. const bool isPasswordBox)
  57975. {
  57976. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  57977. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  57978. tc->setFont (font);
  57979. tc->setText (initialContents);
  57980. tc->setCaretPosition (initialContents.length());
  57981. addAndMakeVisible (tc);
  57982. textBoxes.add (tc);
  57983. allComps.add (tc);
  57984. textboxNames.add (onScreenLabel);
  57985. updateLayout (false);
  57986. }
  57987. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  57988. {
  57989. for (int i = textBoxes.size(); --i >= 0;)
  57990. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  57991. return ((TextEditor*)textBoxes[i])->getText();
  57992. return String::empty;
  57993. }
  57994. void AlertWindow::addComboBox (const String& name,
  57995. const StringArray& items,
  57996. const String& onScreenLabel)
  57997. {
  57998. ComboBox* const cb = new ComboBox (name);
  57999. for (int i = 0; i < items.size(); ++i)
  58000. cb->addItem (items[i], i + 1);
  58001. addAndMakeVisible (cb);
  58002. cb->setSelectedItemIndex (0);
  58003. comboBoxes.add (cb);
  58004. allComps.add (cb);
  58005. comboBoxNames.add (onScreenLabel);
  58006. updateLayout (false);
  58007. }
  58008. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  58009. {
  58010. for (int i = comboBoxes.size(); --i >= 0;)
  58011. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  58012. return (ComboBox*) comboBoxes[i];
  58013. return 0;
  58014. }
  58015. class AlertTextComp : public TextEditor
  58016. {
  58017. AlertTextComp (const AlertTextComp&);
  58018. const AlertTextComp& operator= (const AlertTextComp&);
  58019. int bestWidth;
  58020. public:
  58021. AlertTextComp (const String& message,
  58022. const Font& font)
  58023. {
  58024. setReadOnly (true);
  58025. setMultiLine (true, true);
  58026. setCaretVisible (false);
  58027. setScrollbarsShown (true);
  58028. lookAndFeelChanged();
  58029. setWantsKeyboardFocus (false);
  58030. setFont (font);
  58031. setText (message, false);
  58032. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  58033. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  58034. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  58035. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  58036. }
  58037. ~AlertTextComp()
  58038. {
  58039. }
  58040. int getPreferredWidth() const throw() { return bestWidth; }
  58041. void updateLayout (const int width)
  58042. {
  58043. TextLayout text;
  58044. text.appendText (getText(), getFont());
  58045. text.layout (width - 8, Justification::topLeft, true);
  58046. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  58047. }
  58048. };
  58049. void AlertWindow::addTextBlock (const String& text)
  58050. {
  58051. AlertTextComp* const c = new AlertTextComp (text, font);
  58052. textBlocks.add (c);
  58053. allComps.add (c);
  58054. addAndMakeVisible (c);
  58055. updateLayout (false);
  58056. }
  58057. void AlertWindow::addProgressBarComponent (double& progressValue)
  58058. {
  58059. ProgressBar* const pb = new ProgressBar (progressValue);
  58060. progressBars.add (pb);
  58061. allComps.add (pb);
  58062. addAndMakeVisible (pb);
  58063. updateLayout (false);
  58064. }
  58065. void AlertWindow::addCustomComponent (Component* const component)
  58066. {
  58067. customComps.add (component);
  58068. allComps.add (component);
  58069. addAndMakeVisible (component);
  58070. updateLayout (false);
  58071. }
  58072. int AlertWindow::getNumCustomComponents() const
  58073. {
  58074. return customComps.size();
  58075. }
  58076. Component* AlertWindow::getCustomComponent (const int index) const
  58077. {
  58078. return (Component*) customComps [index];
  58079. }
  58080. Component* AlertWindow::removeCustomComponent (const int index)
  58081. {
  58082. Component* const c = getCustomComponent (index);
  58083. if (c != 0)
  58084. {
  58085. customComps.removeValue (c);
  58086. allComps.removeValue (c);
  58087. removeChildComponent (c);
  58088. updateLayout (false);
  58089. }
  58090. return c;
  58091. }
  58092. void AlertWindow::paint (Graphics& g)
  58093. {
  58094. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  58095. g.setColour (findColour (textColourId));
  58096. g.setFont (getLookAndFeel().getAlertWindowFont());
  58097. int i;
  58098. for (i = textBoxes.size(); --i >= 0;)
  58099. {
  58100. if (textboxNames[i].isNotEmpty())
  58101. {
  58102. const TextEditor* const te = (TextEditor*) textBoxes[i];
  58103. g.drawFittedText (textboxNames[i],
  58104. te->getX(), te->getY() - 14,
  58105. te->getWidth(), 14,
  58106. Justification::centredLeft, 1);
  58107. }
  58108. }
  58109. for (i = comboBoxNames.size(); --i >= 0;)
  58110. {
  58111. if (comboBoxNames[i].isNotEmpty())
  58112. {
  58113. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  58114. g.drawFittedText (comboBoxNames[i],
  58115. cb->getX(), cb->getY() - 14,
  58116. cb->getWidth(), 14,
  58117. Justification::centredLeft, 1);
  58118. }
  58119. }
  58120. }
  58121. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  58122. {
  58123. const int wid = jmax (font.getStringWidth (text),
  58124. font.getStringWidth (getName()));
  58125. const int sw = (int) sqrt (font.getHeight() * wid);
  58126. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  58127. const int edgeGap = 10;
  58128. int iconSpace;
  58129. if (alertIconType == NoIcon)
  58130. {
  58131. textLayout.layout (w, Justification::horizontallyCentred, true);
  58132. iconSpace = 0;
  58133. }
  58134. else
  58135. {
  58136. textLayout.layout (w, Justification::left, true);
  58137. iconSpace = iconWidth;
  58138. }
  58139. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  58140. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58141. const int textLayoutH = textLayout.getHeight();
  58142. const int textBottom = 16 + titleH + textLayoutH;
  58143. int h = textBottom;
  58144. int buttonW = 40;
  58145. int i;
  58146. for (i = 0; i < buttons.size(); ++i)
  58147. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  58148. w = jmax (buttonW, w);
  58149. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  58150. if (buttons.size() > 0)
  58151. h += 20 + ((TextButton*) buttons[0])->getHeight();
  58152. for (i = customComps.size(); --i >= 0;)
  58153. {
  58154. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  58155. h += 10 + ((Component*) customComps[i])->getHeight();
  58156. }
  58157. for (i = textBlocks.size(); --i >= 0;)
  58158. {
  58159. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58160. w = jmax (w, ac->getPreferredWidth());
  58161. }
  58162. w = jmin (w, (int) (getParentWidth() * 0.7f));
  58163. for (i = textBlocks.size(); --i >= 0;)
  58164. {
  58165. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  58166. ac->updateLayout ((int) (w * 0.8f));
  58167. h += ac->getHeight() + 10;
  58168. }
  58169. h = jmin (getParentHeight() - 50, h);
  58170. if (onlyIncreaseSize)
  58171. {
  58172. w = jmax (w, getWidth());
  58173. h = jmax (h, getHeight());
  58174. }
  58175. if (! isVisible())
  58176. {
  58177. centreAroundComponent (associatedComponent, w, h);
  58178. }
  58179. else
  58180. {
  58181. const int cx = getX() + getWidth() / 2;
  58182. const int cy = getY() + getHeight() / 2;
  58183. setBounds (cx - w / 2,
  58184. cy - h / 2,
  58185. w, h);
  58186. }
  58187. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  58188. const int spacer = 16;
  58189. int totalWidth = -spacer;
  58190. for (i = buttons.size(); --i >= 0;)
  58191. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  58192. int x = (w - totalWidth) / 2;
  58193. int y = (int) (getHeight() * 0.95f);
  58194. for (i = 0; i < buttons.size(); ++i)
  58195. {
  58196. TextButton* const c = (TextButton*) buttons[i];
  58197. int ny = proportionOfHeight (0.95f) - c->getHeight();
  58198. c->setTopLeftPosition (x, ny);
  58199. if (ny < y)
  58200. y = ny;
  58201. x += c->getWidth() + spacer;
  58202. c->toFront (false);
  58203. }
  58204. y = textBottom;
  58205. for (i = 0; i < allComps.size(); ++i)
  58206. {
  58207. Component* const c = (Component*) allComps[i];
  58208. const int h = 22;
  58209. const int comboIndex = comboBoxes.indexOf (c);
  58210. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  58211. y += 18;
  58212. const int tbIndex = textBoxes.indexOf (c);
  58213. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  58214. y += 18;
  58215. if (customComps.contains (c) || textBlocks.contains (c))
  58216. {
  58217. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  58218. y += c->getHeight() + 10;
  58219. }
  58220. else
  58221. {
  58222. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  58223. y += h + 10;
  58224. }
  58225. }
  58226. setWantsKeyboardFocus (getNumChildComponents() == 0);
  58227. }
  58228. bool AlertWindow::containsAnyExtraComponents() const
  58229. {
  58230. return textBoxes.size()
  58231. + comboBoxes.size()
  58232. + progressBars.size()
  58233. + customComps.size() > 0;
  58234. }
  58235. void AlertWindow::mouseDown (const MouseEvent&)
  58236. {
  58237. dragger.startDraggingComponent (this, &constrainer);
  58238. }
  58239. void AlertWindow::mouseDrag (const MouseEvent& e)
  58240. {
  58241. dragger.dragComponent (this, e);
  58242. }
  58243. bool AlertWindow::keyPressed (const KeyPress& key)
  58244. {
  58245. for (int i = buttons.size(); --i >= 0;)
  58246. {
  58247. TextButton* const b = (TextButton*) buttons[i];
  58248. if (b->isRegisteredForShortcut (key))
  58249. {
  58250. b->triggerClick();
  58251. return true;
  58252. }
  58253. }
  58254. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  58255. {
  58256. exitModalState (0);
  58257. return true;
  58258. }
  58259. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  58260. {
  58261. ((TextButton*) buttons.getFirst())->triggerClick();
  58262. return true;
  58263. }
  58264. return false;
  58265. }
  58266. void AlertWindow::lookAndFeelChanged()
  58267. {
  58268. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  58269. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  58270. setDropShadowEnabled (isOpaque() && (flags & ComponentPeer::windowHasDropShadow) != 0);
  58271. }
  58272. int AlertWindow::getDesktopWindowStyleFlags() const
  58273. {
  58274. return getLookAndFeel().getAlertBoxWindowFlags();
  58275. }
  58276. struct AlertWindowInfo
  58277. {
  58278. String title, message, button1, button2, button3;
  58279. AlertWindow::AlertIconType iconType;
  58280. int numButtons;
  58281. Component* associatedComponent;
  58282. int run() const
  58283. {
  58284. return (int) (pointer_sized_int)
  58285. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  58286. }
  58287. private:
  58288. int show() const
  58289. {
  58290. jassert (associatedComponent == 0 || associatedComponent->isValidComponent()); // has your comp been deleted?
  58291. LookAndFeel& lf = associatedComponent->isValidComponent() ? associatedComponent->getLookAndFeel()
  58292. : LookAndFeel::getDefaultLookAndFeel();
  58293. Component* const alertBox = lf.createAlertWindow (title, message, button1, button2, button3,
  58294. iconType, numButtons, associatedComponent);
  58295. jassert (alertBox != 0); // you have to return one of these!
  58296. const int result = alertBox->runModalLoop();
  58297. delete alertBox;
  58298. return result;
  58299. }
  58300. static void* showCallback (void* userData)
  58301. {
  58302. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  58303. }
  58304. };
  58305. void AlertWindow::showMessageBox (AlertIconType iconType,
  58306. const String& title,
  58307. const String& message,
  58308. const String& buttonText,
  58309. Component* associatedComponent)
  58310. {
  58311. AlertWindowInfo info;
  58312. info.title = title;
  58313. info.message = message;
  58314. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  58315. info.iconType = iconType;
  58316. info.numButtons = 1;
  58317. info.associatedComponent = associatedComponent;
  58318. info.run();
  58319. }
  58320. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  58321. const String& title,
  58322. const String& message,
  58323. const String& button1Text,
  58324. const String& button2Text,
  58325. Component* associatedComponent)
  58326. {
  58327. AlertWindowInfo info;
  58328. info.title = title;
  58329. info.message = message;
  58330. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  58331. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  58332. info.iconType = iconType;
  58333. info.numButtons = 2;
  58334. info.associatedComponent = associatedComponent;
  58335. return info.run() != 0;
  58336. }
  58337. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  58338. const String& title,
  58339. const String& message,
  58340. const String& button1Text,
  58341. const String& button2Text,
  58342. const String& button3Text,
  58343. Component* associatedComponent)
  58344. {
  58345. AlertWindowInfo info;
  58346. info.title = title;
  58347. info.message = message;
  58348. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  58349. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  58350. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  58351. info.iconType = iconType;
  58352. info.numButtons = 3;
  58353. info.associatedComponent = associatedComponent;
  58354. return info.run();
  58355. }
  58356. END_JUCE_NAMESPACE
  58357. /********* End of inlined file: juce_AlertWindow.cpp *********/
  58358. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  58359. BEGIN_JUCE_NAMESPACE
  58360. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  58361. // these are over in juce_component.cpp
  58362. extern int64 juce_recentMouseDownTimes[4];
  58363. extern int juce_recentMouseDownX [4];
  58364. extern int juce_recentMouseDownY [4];
  58365. extern Component* juce_recentMouseDownComponent [4];
  58366. extern int juce_LastMousePosX;
  58367. extern int juce_LastMousePosY;
  58368. extern int juce_MouseClickCounter;
  58369. extern bool juce_MouseHasMovedSignificantlySincePressed;
  58370. static const int fakeMouseMoveMessage = 0x7fff00ff;
  58371. static VoidArray heavyweightPeers (4);
  58372. ComponentPeer::ComponentPeer (Component* const component_,
  58373. const int styleFlags_) throw()
  58374. : component (component_),
  58375. styleFlags (styleFlags_),
  58376. lastPaintTime (0),
  58377. constrainer (0),
  58378. lastFocusedComponent (0),
  58379. dragAndDropTargetComponent (0),
  58380. lastDragAndDropCompUnderMouse (0),
  58381. fakeMouseMessageSent (false),
  58382. isWindowMinimised (false)
  58383. {
  58384. heavyweightPeers.add (this);
  58385. }
  58386. ComponentPeer::~ComponentPeer()
  58387. {
  58388. heavyweightPeers.removeValue (this);
  58389. delete dragAndDropTargetComponent;
  58390. Desktop::getInstance().triggerFocusCallback();
  58391. }
  58392. int ComponentPeer::getNumPeers() throw()
  58393. {
  58394. return heavyweightPeers.size();
  58395. }
  58396. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  58397. {
  58398. return (ComponentPeer*) heavyweightPeers [index];
  58399. }
  58400. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  58401. {
  58402. for (int i = heavyweightPeers.size(); --i >= 0;)
  58403. {
  58404. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  58405. if (peer->getComponent() == component)
  58406. return peer;
  58407. }
  58408. return 0;
  58409. }
  58410. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  58411. {
  58412. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  58413. }
  58414. void ComponentPeer::updateCurrentModifiers() throw()
  58415. {
  58416. ModifierKeys::updateCurrentModifiers();
  58417. }
  58418. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  58419. {
  58420. jassert (component->isValidComponent());
  58421. updateCurrentModifiers();
  58422. Component* c = component->getComponentAt (x, y);
  58423. const ComponentDeletionWatcher deletionChecker (component);
  58424. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  58425. {
  58426. jassert (Component::componentUnderMouse->isValidComponent());
  58427. const int oldX = x;
  58428. const int oldY = y;
  58429. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58430. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58431. Component::componentUnderMouse = 0;
  58432. if (deletionChecker.hasBeenDeleted())
  58433. return;
  58434. c = component->getComponentAt (oldX, oldY);
  58435. }
  58436. Component::componentUnderMouse = c;
  58437. if (Component::componentUnderMouse != 0)
  58438. {
  58439. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58440. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58441. }
  58442. }
  58443. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  58444. {
  58445. jassert (component->isValidComponent());
  58446. updateCurrentModifiers();
  58447. fakeMouseMessageSent = false;
  58448. const ComponentDeletionWatcher deletionChecker (component);
  58449. Component* c = component->getComponentAt (x, y);
  58450. if (c != Component::componentUnderMouse)
  58451. {
  58452. const int oldX = x;
  58453. const int oldY = y;
  58454. if (Component::componentUnderMouse != 0)
  58455. {
  58456. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58457. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58458. x = oldX;
  58459. y = oldY;
  58460. Component::componentUnderMouse = 0;
  58461. if (deletionChecker.hasBeenDeleted())
  58462. return; // if this window has just been deleted..
  58463. c = component->getComponentAt (x, y);
  58464. }
  58465. Component::componentUnderMouse = c;
  58466. if (c != 0)
  58467. {
  58468. component->relativePositionToOtherComponent (c, x, y);
  58469. c->internalMouseEnter (x, y, time);
  58470. x = oldX;
  58471. y = oldY;
  58472. if (deletionChecker.hasBeenDeleted())
  58473. return; // if this window has just been deleted..
  58474. }
  58475. }
  58476. if (Component::componentUnderMouse != 0)
  58477. {
  58478. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58479. Component::componentUnderMouse->internalMouseMove (x, y, time);
  58480. }
  58481. }
  58482. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  58483. {
  58484. ++juce_MouseClickCounter;
  58485. updateCurrentModifiers();
  58486. int numMouseButtonsDown = 0;
  58487. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  58488. ++numMouseButtonsDown;
  58489. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  58490. ++numMouseButtonsDown;
  58491. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  58492. ++numMouseButtonsDown;
  58493. if (numMouseButtonsDown == 1)
  58494. {
  58495. Component::componentUnderMouse = component->getComponentAt (x, y);
  58496. if (Component::componentUnderMouse != 0)
  58497. {
  58498. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  58499. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  58500. {
  58501. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  58502. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  58503. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  58504. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  58505. }
  58506. juce_recentMouseDownTimes[0] = time;
  58507. juce_recentMouseDownX[0] = x;
  58508. juce_recentMouseDownY[0] = y;
  58509. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  58510. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  58511. juce_MouseHasMovedSignificantlySincePressed = false;
  58512. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58513. Component::componentUnderMouse->internalMouseDown (x, y);
  58514. }
  58515. }
  58516. }
  58517. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  58518. {
  58519. updateCurrentModifiers();
  58520. if (Component::componentUnderMouse != 0)
  58521. {
  58522. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58523. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  58524. }
  58525. }
  58526. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  58527. {
  58528. updateCurrentModifiers();
  58529. int numMouseButtonsDown = 0;
  58530. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  58531. ++numMouseButtonsDown;
  58532. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  58533. ++numMouseButtonsDown;
  58534. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  58535. ++numMouseButtonsDown;
  58536. if (numMouseButtonsDown == 1)
  58537. {
  58538. const ComponentDeletionWatcher deletionChecker (component);
  58539. Component* c = component->getComponentAt (x, y);
  58540. if (c != Component::componentUnderMouse)
  58541. {
  58542. const int oldX = x;
  58543. const int oldY = y;
  58544. if (Component::componentUnderMouse != 0)
  58545. {
  58546. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58547. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58548. x = oldX;
  58549. y = oldY;
  58550. if (Component::componentUnderMouse != 0)
  58551. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58552. if (deletionChecker.hasBeenDeleted())
  58553. return;
  58554. c = component->getComponentAt (oldX, oldY);
  58555. }
  58556. Component::componentUnderMouse = c;
  58557. if (Component::componentUnderMouse != 0)
  58558. {
  58559. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58560. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  58561. }
  58562. }
  58563. else
  58564. {
  58565. if (Component::componentUnderMouse != 0)
  58566. {
  58567. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58568. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  58569. }
  58570. }
  58571. }
  58572. }
  58573. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  58574. {
  58575. jassert (component->isValidComponent());
  58576. updateCurrentModifiers();
  58577. if (Component::componentUnderMouse != 0)
  58578. {
  58579. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  58580. Component::componentUnderMouse->internalMouseExit (x, y, time);
  58581. Component::componentUnderMouse = 0;
  58582. }
  58583. }
  58584. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  58585. {
  58586. updateCurrentModifiers();
  58587. if (Component::componentUnderMouse != 0)
  58588. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  58589. }
  58590. void ComponentPeer::sendFakeMouseMove() throw()
  58591. {
  58592. if ((! fakeMouseMessageSent)
  58593. && component->flags.hasHeavyweightPeerFlag
  58594. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58595. {
  58596. if (! isMinimised())
  58597. {
  58598. int realX, realY, realW, realH;
  58599. getBounds (realX, realY, realW, realH);
  58600. component->bounds_.setBounds (realX, realY, realW, realH);
  58601. }
  58602. int x, y;
  58603. component->getMouseXYRelative (x, y);
  58604. if (((unsigned int) x) < (unsigned int) component->getWidth()
  58605. && ((unsigned int) y) < (unsigned int) component->getHeight()
  58606. && contains (x, y, false))
  58607. {
  58608. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  58609. }
  58610. fakeMouseMessageSent = true;
  58611. }
  58612. }
  58613. void ComponentPeer::handleMessage (const Message& message)
  58614. {
  58615. if (message.intParameter1 == fakeMouseMoveMessage)
  58616. {
  58617. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  58618. handleMouseMove (message.intParameter2,
  58619. message.intParameter3,
  58620. Time::currentTimeMillis());
  58621. }
  58622. }
  58623. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  58624. {
  58625. Graphics g (&contextToPaintTo);
  58626. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58627. g.saveState();
  58628. #endif
  58629. JUCE_TRY
  58630. {
  58631. component->paintEntireComponent (g);
  58632. }
  58633. JUCE_CATCH_EXCEPTION
  58634. #if JUCE_ENABLE_REPAINT_DEBUGGING
  58635. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  58636. // clearly when things are being repainted.
  58637. {
  58638. g.restoreState();
  58639. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  58640. (uint8) Random::getSystemRandom().nextInt (255),
  58641. (uint8) Random::getSystemRandom().nextInt (255),
  58642. (uint8) 0x50));
  58643. }
  58644. #endif
  58645. }
  58646. bool ComponentPeer::handleKeyPress (const int keyCode,
  58647. const juce_wchar textCharacter)
  58648. {
  58649. updateCurrentModifiers();
  58650. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58651. ? Component::currentlyFocusedComponent
  58652. : component;
  58653. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58654. {
  58655. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58656. if (currentModalComp != 0)
  58657. target = currentModalComp;
  58658. }
  58659. const KeyPress keyInfo (keyCode,
  58660. ModifierKeys::getCurrentModifiers().getRawFlags()
  58661. & ModifierKeys::allKeyboardModifiers,
  58662. textCharacter);
  58663. bool keyWasUsed = false;
  58664. while (target != 0)
  58665. {
  58666. const ComponentDeletionWatcher deletionChecker (target);
  58667. if (target->keyListeners_ != 0)
  58668. {
  58669. for (int i = target->keyListeners_->size(); --i >= 0;)
  58670. {
  58671. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  58672. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58673. return keyWasUsed;
  58674. i = jmin (i, target->keyListeners_->size());
  58675. }
  58676. }
  58677. keyWasUsed = target->keyPressed (keyInfo);
  58678. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58679. break;
  58680. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  58681. {
  58682. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  58683. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  58684. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  58685. break;
  58686. }
  58687. target = target->parentComponent_;
  58688. }
  58689. return keyWasUsed;
  58690. }
  58691. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  58692. {
  58693. updateCurrentModifiers();
  58694. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  58695. ? Component::currentlyFocusedComponent
  58696. : component;
  58697. if (target->isCurrentlyBlockedByAnotherModalComponent())
  58698. {
  58699. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  58700. if (currentModalComp != 0)
  58701. target = currentModalComp;
  58702. }
  58703. bool keyWasUsed = false;
  58704. while (target != 0)
  58705. {
  58706. const ComponentDeletionWatcher deletionChecker (target);
  58707. keyWasUsed = target->keyStateChanged (isKeyDown);
  58708. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58709. break;
  58710. if (target->keyListeners_ != 0)
  58711. {
  58712. for (int i = target->keyListeners_->size(); --i >= 0;)
  58713. {
  58714. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (isKeyDown, target);
  58715. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  58716. return keyWasUsed;
  58717. i = jmin (i, target->keyListeners_->size());
  58718. }
  58719. }
  58720. target = target->parentComponent_;
  58721. }
  58722. return keyWasUsed;
  58723. }
  58724. void ComponentPeer::handleModifierKeysChange()
  58725. {
  58726. updateCurrentModifiers();
  58727. Component* target = Component::getComponentUnderMouse();
  58728. if (target == 0)
  58729. target = Component::getCurrentlyFocusedComponent();
  58730. if (target == 0)
  58731. target = component;
  58732. if (target->isValidComponent())
  58733. target->internalModifierKeysChanged();
  58734. }
  58735. void ComponentPeer::handleBroughtToFront()
  58736. {
  58737. updateCurrentModifiers();
  58738. if (component != 0)
  58739. component->internalBroughtToFront();
  58740. }
  58741. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  58742. {
  58743. constrainer = newConstrainer;
  58744. }
  58745. void ComponentPeer::handleMovedOrResized()
  58746. {
  58747. jassert (component->isValidComponent());
  58748. updateCurrentModifiers();
  58749. const bool nowMinimised = isMinimised();
  58750. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  58751. {
  58752. const ComponentDeletionWatcher deletionChecker (component);
  58753. int realX, realY, realW, realH;
  58754. getBounds (realX, realY, realW, realH);
  58755. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  58756. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  58757. if (wasMoved || wasResized)
  58758. {
  58759. component->bounds_.setBounds (realX, realY, realW, realH);
  58760. if (wasResized)
  58761. component->repaint();
  58762. component->sendMovedResizedMessages (wasMoved, wasResized);
  58763. if (deletionChecker.hasBeenDeleted())
  58764. return;
  58765. }
  58766. }
  58767. if (isWindowMinimised != nowMinimised)
  58768. {
  58769. isWindowMinimised = nowMinimised;
  58770. component->minimisationStateChanged (nowMinimised);
  58771. component->sendVisibilityChangeMessage();
  58772. }
  58773. if (! isFullScreen())
  58774. lastNonFullscreenBounds = component->getBounds();
  58775. }
  58776. void ComponentPeer::handleFocusGain()
  58777. {
  58778. updateCurrentModifiers();
  58779. if (component->isParentOf (lastFocusedComponent))
  58780. {
  58781. Component::currentlyFocusedComponent = lastFocusedComponent;
  58782. Desktop::getInstance().triggerFocusCallback();
  58783. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  58784. }
  58785. else
  58786. {
  58787. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  58788. component->grabKeyboardFocus();
  58789. else
  58790. Component::bringModalComponentToFront();
  58791. }
  58792. }
  58793. void ComponentPeer::handleFocusLoss()
  58794. {
  58795. updateCurrentModifiers();
  58796. if (component->hasKeyboardFocus (true))
  58797. {
  58798. lastFocusedComponent = Component::currentlyFocusedComponent;
  58799. if (lastFocusedComponent != 0)
  58800. {
  58801. Component::currentlyFocusedComponent = 0;
  58802. Desktop::getInstance().triggerFocusCallback();
  58803. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  58804. }
  58805. }
  58806. }
  58807. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  58808. {
  58809. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  58810. ? lastFocusedComponent
  58811. : component;
  58812. }
  58813. void ComponentPeer::handleScreenSizeChange()
  58814. {
  58815. updateCurrentModifiers();
  58816. component->parentSizeChanged();
  58817. handleMovedOrResized();
  58818. }
  58819. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  58820. {
  58821. lastNonFullscreenBounds = newBounds;
  58822. }
  58823. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  58824. {
  58825. return lastNonFullscreenBounds;
  58826. }
  58827. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  58828. const StringArray& files,
  58829. FileDragAndDropTarget* const lastOne)
  58830. {
  58831. while (c != 0)
  58832. {
  58833. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  58834. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  58835. return t;
  58836. c = c->getParentComponent();
  58837. }
  58838. return 0;
  58839. }
  58840. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  58841. {
  58842. updateCurrentModifiers();
  58843. FileDragAndDropTarget* lastTarget = 0;
  58844. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58845. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58846. FileDragAndDropTarget* newTarget = 0;
  58847. Component* const compUnderMouse = component->getComponentAt (x, y);
  58848. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  58849. {
  58850. lastDragAndDropCompUnderMouse = compUnderMouse;
  58851. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  58852. if (newTarget != lastTarget)
  58853. {
  58854. if (lastTarget != 0)
  58855. lastTarget->fileDragExit (files);
  58856. deleteAndZero (dragAndDropTargetComponent);
  58857. if (newTarget != 0)
  58858. {
  58859. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58860. int mx = x, my = y;
  58861. component->relativePositionToOtherComponent (targetComp, mx, my);
  58862. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  58863. newTarget->fileDragEnter (files, mx, my);
  58864. }
  58865. }
  58866. }
  58867. else
  58868. {
  58869. newTarget = lastTarget;
  58870. }
  58871. if (newTarget != 0)
  58872. {
  58873. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  58874. component->relativePositionToOtherComponent (targetComp, x, y);
  58875. newTarget->fileDragMove (files, x, y);
  58876. }
  58877. }
  58878. void ComponentPeer::handleFileDragExit (const StringArray& files)
  58879. {
  58880. handleFileDragMove (files, -1, -1);
  58881. jassert (dragAndDropTargetComponent == 0);
  58882. lastDragAndDropCompUnderMouse = 0;
  58883. }
  58884. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  58885. {
  58886. handleFileDragMove (files, x, y);
  58887. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  58888. {
  58889. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  58890. deleteAndZero (dragAndDropTargetComponent);
  58891. lastDragAndDropCompUnderMouse = 0;
  58892. if (target != 0)
  58893. {
  58894. Component* const targetComp = dynamic_cast <Component*> (target);
  58895. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58896. {
  58897. targetComp->internalModalInputAttempt();
  58898. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  58899. return;
  58900. }
  58901. component->relativePositionToOtherComponent (targetComp, x, y);
  58902. target->filesDropped (files, x, y);
  58903. }
  58904. }
  58905. }
  58906. void ComponentPeer::handleUserClosingWindow()
  58907. {
  58908. updateCurrentModifiers();
  58909. component->userTriedToCloseWindow();
  58910. }
  58911. void ComponentPeer::bringModalComponentToFront()
  58912. {
  58913. Component::bringModalComponentToFront();
  58914. }
  58915. void ComponentPeer::clearMaskedRegion() throw()
  58916. {
  58917. maskedRegion.clear();
  58918. }
  58919. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  58920. {
  58921. maskedRegion.add (x, y, w, h);
  58922. }
  58923. END_JUCE_NAMESPACE
  58924. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  58925. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  58926. BEGIN_JUCE_NAMESPACE
  58927. DialogWindow::DialogWindow (const String& name,
  58928. const Colour& backgroundColour_,
  58929. const bool escapeKeyTriggersCloseButton_,
  58930. const bool addToDesktop_)
  58931. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  58932. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  58933. {
  58934. }
  58935. DialogWindow::~DialogWindow()
  58936. {
  58937. }
  58938. void DialogWindow::resized()
  58939. {
  58940. DocumentWindow::resized();
  58941. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  58942. if (escapeKeyTriggersCloseButton
  58943. && getCloseButton() != 0
  58944. && ! getCloseButton()->isRegisteredForShortcut (esc))
  58945. {
  58946. getCloseButton()->addShortcut (esc);
  58947. }
  58948. }
  58949. class TempDialogWindow : public DialogWindow
  58950. {
  58951. public:
  58952. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  58953. : DialogWindow (title, colour, escapeCloses, true)
  58954. {
  58955. }
  58956. ~TempDialogWindow()
  58957. {
  58958. }
  58959. void closeButtonPressed()
  58960. {
  58961. setVisible (false);
  58962. }
  58963. private:
  58964. TempDialogWindow (const TempDialogWindow&);
  58965. const TempDialogWindow& operator= (const TempDialogWindow&);
  58966. };
  58967. int DialogWindow::showModalDialog (const String& dialogTitle,
  58968. Component* contentComponent,
  58969. Component* componentToCentreAround,
  58970. const Colour& colour,
  58971. const bool escapeKeyTriggersCloseButton,
  58972. const bool shouldBeResizable,
  58973. const bool useBottomRightCornerResizer)
  58974. {
  58975. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  58976. dw.setContentComponent (contentComponent, true, true);
  58977. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  58978. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  58979. const int result = dw.runModalLoop();
  58980. dw.setContentComponent (0, false);
  58981. return result;
  58982. }
  58983. END_JUCE_NAMESPACE
  58984. /********* End of inlined file: juce_DialogWindow.cpp *********/
  58985. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  58986. BEGIN_JUCE_NAMESPACE
  58987. DocumentWindow::DocumentWindow (const String& title,
  58988. const Colour& backgroundColour,
  58989. const int requiredButtons_,
  58990. const bool addToDesktop_)
  58991. : ResizableWindow (title, backgroundColour, addToDesktop_),
  58992. titleBarHeight (26),
  58993. menuBarHeight (24),
  58994. requiredButtons (requiredButtons_),
  58995. #if JUCE_MAC
  58996. positionTitleBarButtonsOnLeft (true),
  58997. #else
  58998. positionTitleBarButtonsOnLeft (false),
  58999. #endif
  59000. drawTitleTextCentred (true),
  59001. titleBarIcon (0),
  59002. menuBar (0),
  59003. menuBarModel (0)
  59004. {
  59005. zeromem (titleBarButtons, sizeof (titleBarButtons));
  59006. setResizeLimits (128, 128, 32768, 32768);
  59007. lookAndFeelChanged();
  59008. }
  59009. DocumentWindow::~DocumentWindow()
  59010. {
  59011. for (int i = 0; i < 3; ++i)
  59012. delete titleBarButtons[i];
  59013. delete titleBarIcon;
  59014. delete menuBar;
  59015. }
  59016. void DocumentWindow::repaintTitleBar()
  59017. {
  59018. const int border = getBorderSize();
  59019. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  59020. }
  59021. void DocumentWindow::setName (const String& newName)
  59022. {
  59023. if (newName != getName())
  59024. {
  59025. Component::setName (newName);
  59026. repaintTitleBar();
  59027. }
  59028. }
  59029. void DocumentWindow::setIcon (const Image* imageToUse)
  59030. {
  59031. deleteAndZero (titleBarIcon);
  59032. if (imageToUse != 0)
  59033. titleBarIcon = imageToUse->createCopy();
  59034. repaintTitleBar();
  59035. }
  59036. void DocumentWindow::setTitleBarHeight (const int newHeight)
  59037. {
  59038. titleBarHeight = newHeight;
  59039. resized();
  59040. repaintTitleBar();
  59041. }
  59042. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  59043. const bool positionTitleBarButtonsOnLeft_)
  59044. {
  59045. requiredButtons = requiredButtons_;
  59046. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  59047. lookAndFeelChanged();
  59048. }
  59049. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  59050. {
  59051. drawTitleTextCentred = textShouldBeCentred;
  59052. repaintTitleBar();
  59053. }
  59054. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  59055. const int menuBarHeight_)
  59056. {
  59057. if (menuBarModel != menuBarModel_)
  59058. {
  59059. delete menuBar;
  59060. menuBar = 0;
  59061. menuBarModel = menuBarModel_;
  59062. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  59063. : getLookAndFeel().getDefaultMenuBarHeight();
  59064. if (menuBarModel != 0)
  59065. {
  59066. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59067. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  59068. menuBar->setEnabled (isActiveWindow());
  59069. }
  59070. resized();
  59071. }
  59072. }
  59073. void DocumentWindow::closeButtonPressed()
  59074. {
  59075. /* If you've got a close button, you have to override this method to get
  59076. rid of your window!
  59077. If the window is just a pop-up, you should override this method and make
  59078. it delete the window in whatever way is appropriate for your app. E.g. you
  59079. might just want to call "delete this".
  59080. If your app is centred around this window such that the whole app should quit when
  59081. the window is closed, then you will probably want to use this method as an opportunity
  59082. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  59083. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  59084. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  59085. or closing it via the taskbar icon on Windows).
  59086. */
  59087. jassertfalse
  59088. }
  59089. void DocumentWindow::minimiseButtonPressed()
  59090. {
  59091. setMinimised (true);
  59092. }
  59093. void DocumentWindow::maximiseButtonPressed()
  59094. {
  59095. setFullScreen (! isFullScreen());
  59096. }
  59097. void DocumentWindow::paint (Graphics& g)
  59098. {
  59099. ResizableWindow::paint (g);
  59100. if (resizableBorder == 0 && getBorderSize() == 1)
  59101. {
  59102. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  59103. g.drawRect (0, 0, getWidth(), getHeight());
  59104. }
  59105. const int border = getBorderSize();
  59106. g.setOrigin (border, border);
  59107. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  59108. int titleSpaceX1 = 6;
  59109. int titleSpaceX2 = getWidth() - 6;
  59110. for (int i = 0; i < 3; ++i)
  59111. {
  59112. if (titleBarButtons[i] != 0)
  59113. {
  59114. if (positionTitleBarButtonsOnLeft)
  59115. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  59116. else
  59117. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  59118. }
  59119. }
  59120. getLookAndFeel()
  59121. .drawDocumentWindowTitleBar (*this, g,
  59122. getWidth() - border * 2,
  59123. getTitleBarHeight(),
  59124. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  59125. titleBarIcon, ! drawTitleTextCentred);
  59126. }
  59127. void DocumentWindow::resized()
  59128. {
  59129. ResizableWindow::resized();
  59130. if (titleBarButtons[1] != 0)
  59131. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  59132. const int border = getBorderSize();
  59133. getLookAndFeel()
  59134. .positionDocumentWindowButtons (*this,
  59135. border, border,
  59136. getWidth() - border * 2, getTitleBarHeight(),
  59137. titleBarButtons[0],
  59138. titleBarButtons[1],
  59139. titleBarButtons[2],
  59140. positionTitleBarButtonsOnLeft);
  59141. if (menuBar != 0)
  59142. menuBar->setBounds (border, border + getTitleBarHeight(),
  59143. getWidth() - border * 2, menuBarHeight);
  59144. }
  59145. Button* DocumentWindow::getCloseButton() const throw()
  59146. {
  59147. return titleBarButtons[2];
  59148. }
  59149. Button* DocumentWindow::getMinimiseButton() const throw()
  59150. {
  59151. return titleBarButtons[0];
  59152. }
  59153. Button* DocumentWindow::getMaximiseButton() const throw()
  59154. {
  59155. return titleBarButtons[1];
  59156. }
  59157. int DocumentWindow::getDesktopWindowStyleFlags() const
  59158. {
  59159. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  59160. if ((requiredButtons & minimiseButton) != 0)
  59161. flags |= ComponentPeer::windowHasMinimiseButton;
  59162. if ((requiredButtons & maximiseButton) != 0)
  59163. flags |= ComponentPeer::windowHasMaximiseButton;
  59164. if ((requiredButtons & closeButton) != 0)
  59165. flags |= ComponentPeer::windowHasCloseButton;
  59166. return flags;
  59167. }
  59168. void DocumentWindow::lookAndFeelChanged()
  59169. {
  59170. int i;
  59171. for (i = 0; i < 3; ++i)
  59172. deleteAndZero (titleBarButtons[i]);
  59173. if (! isUsingNativeTitleBar())
  59174. {
  59175. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  59176. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  59177. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  59178. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  59179. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  59180. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  59181. for (i = 0; i < 3; ++i)
  59182. {
  59183. if (titleBarButtons[i] != 0)
  59184. {
  59185. buttonListener.owner = this;
  59186. titleBarButtons[i]->addButtonListener (&buttonListener);
  59187. titleBarButtons[i]->setWantsKeyboardFocus (false);
  59188. // (call the Component method directly to avoid the assertion in ResizableWindow)
  59189. Component::addAndMakeVisible (titleBarButtons[i]);
  59190. }
  59191. }
  59192. if (getCloseButton() != 0)
  59193. {
  59194. #if JUCE_MAC
  59195. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  59196. #else
  59197. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  59198. #endif
  59199. }
  59200. }
  59201. activeWindowStatusChanged();
  59202. ResizableWindow::lookAndFeelChanged();
  59203. }
  59204. void DocumentWindow::parentHierarchyChanged()
  59205. {
  59206. lookAndFeelChanged();
  59207. }
  59208. void DocumentWindow::activeWindowStatusChanged()
  59209. {
  59210. ResizableWindow::activeWindowStatusChanged();
  59211. for (int i = 0; i < 3; ++i)
  59212. if (titleBarButtons[i] != 0)
  59213. titleBarButtons[i]->setEnabled (isActiveWindow());
  59214. if (menuBar != 0)
  59215. menuBar->setEnabled (isActiveWindow());
  59216. }
  59217. const BorderSize DocumentWindow::getBorderThickness()
  59218. {
  59219. return BorderSize (getBorderSize());
  59220. }
  59221. const BorderSize DocumentWindow::getContentComponentBorder()
  59222. {
  59223. const int size = getBorderSize();
  59224. return BorderSize (size
  59225. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  59226. + (menuBar != 0 ? menuBarHeight : 0),
  59227. size, size, size);
  59228. }
  59229. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  59230. {
  59231. const int border = getBorderSize();
  59232. if (e.x >= border
  59233. && e.y >= border
  59234. && e.x < getWidth() - border
  59235. && e.y < border + getTitleBarHeight()
  59236. && getMaximiseButton() != 0)
  59237. {
  59238. getMaximiseButton()->triggerClick();
  59239. }
  59240. }
  59241. void DocumentWindow::userTriedToCloseWindow()
  59242. {
  59243. closeButtonPressed();
  59244. }
  59245. int DocumentWindow::getTitleBarHeight() const
  59246. {
  59247. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  59248. }
  59249. int DocumentWindow::getBorderSize() const
  59250. {
  59251. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  59252. }
  59253. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  59254. {
  59255. }
  59256. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  59257. {
  59258. if (button == owner->getMinimiseButton())
  59259. {
  59260. owner->minimiseButtonPressed();
  59261. }
  59262. else if (button == owner->getMaximiseButton())
  59263. {
  59264. owner->maximiseButtonPressed();
  59265. }
  59266. else if (button == owner->getCloseButton())
  59267. {
  59268. owner->closeButtonPressed();
  59269. }
  59270. }
  59271. END_JUCE_NAMESPACE
  59272. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  59273. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  59274. BEGIN_JUCE_NAMESPACE
  59275. ResizableWindow::ResizableWindow (const String& name,
  59276. const bool addToDesktop_)
  59277. : TopLevelWindow (name, addToDesktop_),
  59278. resizableCorner (0),
  59279. resizableBorder (0),
  59280. contentComponent (0),
  59281. resizeToFitContent (false),
  59282. fullscreen (false),
  59283. lastNonFullScreenPos (50, 50, 256, 256),
  59284. constrainer (0)
  59285. #ifdef JUCE_DEBUG
  59286. , hasBeenResized (false)
  59287. #endif
  59288. {
  59289. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59290. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  59291. if (addToDesktop_)
  59292. Component::addToDesktop (getDesktopWindowStyleFlags());
  59293. }
  59294. ResizableWindow::ResizableWindow (const String& name,
  59295. const Colour& backgroundColour_,
  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. setBackgroundColour (backgroundColour_);
  59310. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  59311. if (addToDesktop_)
  59312. Component::addToDesktop (getDesktopWindowStyleFlags());
  59313. }
  59314. ResizableWindow::~ResizableWindow()
  59315. {
  59316. deleteAndZero (resizableCorner);
  59317. deleteAndZero (resizableBorder);
  59318. deleteAndZero (contentComponent);
  59319. // have you been adding your own components directly to this window..? tut tut tut.
  59320. // Read the instructions for using a ResizableWindow!
  59321. jassert (getNumChildComponents() == 0);
  59322. }
  59323. int ResizableWindow::getDesktopWindowStyleFlags() const
  59324. {
  59325. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  59326. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  59327. flags |= ComponentPeer::windowIsResizable;
  59328. return flags;
  59329. }
  59330. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  59331. const bool deleteOldOne,
  59332. const bool resizeToFit)
  59333. {
  59334. resizeToFitContent = resizeToFit;
  59335. if (contentComponent != newContentComponent)
  59336. {
  59337. if (deleteOldOne)
  59338. delete contentComponent;
  59339. else
  59340. removeChildComponent (contentComponent);
  59341. contentComponent = newContentComponent;
  59342. Component::addAndMakeVisible (contentComponent);
  59343. }
  59344. if (resizeToFit)
  59345. childBoundsChanged (contentComponent);
  59346. resized(); // must always be called to position the new content comp
  59347. }
  59348. void ResizableWindow::setContentComponentSize (int width, int height)
  59349. {
  59350. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  59351. const BorderSize border (getContentComponentBorder());
  59352. setSize (width + border.getLeftAndRight(),
  59353. height + border.getTopAndBottom());
  59354. }
  59355. const BorderSize ResizableWindow::getBorderThickness()
  59356. {
  59357. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  59358. }
  59359. const BorderSize ResizableWindow::getContentComponentBorder()
  59360. {
  59361. return getBorderThickness();
  59362. }
  59363. void ResizableWindow::moved()
  59364. {
  59365. updateLastPos();
  59366. }
  59367. void ResizableWindow::visibilityChanged()
  59368. {
  59369. TopLevelWindow::visibilityChanged();
  59370. updateLastPos();
  59371. }
  59372. void ResizableWindow::resized()
  59373. {
  59374. if (resizableBorder != 0)
  59375. {
  59376. resizableBorder->setVisible (! isFullScreen());
  59377. resizableBorder->setBorderThickness (getBorderThickness());
  59378. resizableBorder->setSize (getWidth(), getHeight());
  59379. resizableBorder->toBack();
  59380. }
  59381. if (resizableCorner != 0)
  59382. {
  59383. resizableCorner->setVisible (! isFullScreen());
  59384. const int resizerSize = 18;
  59385. resizableCorner->setBounds (getWidth() - resizerSize,
  59386. getHeight() - resizerSize,
  59387. resizerSize, resizerSize);
  59388. }
  59389. if (contentComponent != 0)
  59390. contentComponent->setBoundsInset (getContentComponentBorder());
  59391. updateLastPos();
  59392. #ifdef JUCE_DEBUG
  59393. hasBeenResized = true;
  59394. #endif
  59395. }
  59396. void ResizableWindow::childBoundsChanged (Component* child)
  59397. {
  59398. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  59399. {
  59400. // not going to look very good if this component has a zero size..
  59401. jassert (child->getWidth() > 0);
  59402. jassert (child->getHeight() > 0);
  59403. const BorderSize borders (getContentComponentBorder());
  59404. setSize (child->getWidth() + borders.getLeftAndRight(),
  59405. child->getHeight() + borders.getTopAndBottom());
  59406. }
  59407. }
  59408. void ResizableWindow::activeWindowStatusChanged()
  59409. {
  59410. const BorderSize borders (getContentComponentBorder());
  59411. repaint (0, 0, getWidth(), borders.getTop());
  59412. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  59413. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  59414. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  59415. }
  59416. void ResizableWindow::setResizable (const bool shouldBeResizable,
  59417. const bool useBottomRightCornerResizer)
  59418. {
  59419. if (shouldBeResizable)
  59420. {
  59421. if (useBottomRightCornerResizer)
  59422. {
  59423. deleteAndZero (resizableBorder);
  59424. if (resizableCorner == 0)
  59425. {
  59426. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  59427. resizableCorner->setAlwaysOnTop (true);
  59428. }
  59429. }
  59430. else
  59431. {
  59432. deleteAndZero (resizableCorner);
  59433. if (resizableBorder == 0)
  59434. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  59435. }
  59436. }
  59437. else
  59438. {
  59439. deleteAndZero (resizableCorner);
  59440. deleteAndZero (resizableBorder);
  59441. }
  59442. if (isUsingNativeTitleBar())
  59443. recreateDesktopWindow();
  59444. childBoundsChanged (contentComponent);
  59445. resized();
  59446. }
  59447. bool ResizableWindow::isResizable() const throw()
  59448. {
  59449. return resizableCorner != 0
  59450. || resizableBorder != 0;
  59451. }
  59452. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  59453. const int newMinimumHeight,
  59454. const int newMaximumWidth,
  59455. const int newMaximumHeight) throw()
  59456. {
  59457. // if you've set up a custom constrainer then these settings won't have any effect..
  59458. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  59459. if (constrainer == 0)
  59460. setConstrainer (&defaultConstrainer);
  59461. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  59462. newMaximumWidth, newMaximumHeight);
  59463. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  59464. }
  59465. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  59466. {
  59467. if (constrainer != newConstrainer)
  59468. {
  59469. constrainer = newConstrainer;
  59470. const bool useBottomRightCornerResizer = resizableCorner != 0;
  59471. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  59472. deleteAndZero (resizableCorner);
  59473. deleteAndZero (resizableBorder);
  59474. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  59475. ComponentPeer* const peer = getPeer();
  59476. if (peer != 0)
  59477. peer->setConstrainer (newConstrainer);
  59478. }
  59479. }
  59480. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  59481. {
  59482. if (constrainer != 0)
  59483. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  59484. else
  59485. setBounds (x, y, w, h);
  59486. }
  59487. void ResizableWindow::paint (Graphics& g)
  59488. {
  59489. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  59490. getBorderThickness(), *this);
  59491. if (! isFullScreen())
  59492. {
  59493. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  59494. getBorderThickness(), *this);
  59495. }
  59496. #ifdef JUCE_DEBUG
  59497. /* If this fails, then you've probably written a subclass with a resized()
  59498. callback but forgotten to make it call its parent class's resized() method.
  59499. It's important when you override methods like resized(), moved(),
  59500. etc., that you make sure the base class methods also get called.
  59501. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  59502. because your content should all be inside the content component - and it's the
  59503. content component's resized() method that you should be using to do your
  59504. layout.
  59505. */
  59506. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  59507. #endif
  59508. }
  59509. void ResizableWindow::lookAndFeelChanged()
  59510. {
  59511. resized();
  59512. if (isOnDesktop())
  59513. {
  59514. Component::addToDesktop (getDesktopWindowStyleFlags());
  59515. ComponentPeer* const peer = getPeer();
  59516. if (peer != 0)
  59517. peer->setConstrainer (constrainer);
  59518. }
  59519. }
  59520. const Colour ResizableWindow::getBackgroundColour() const throw()
  59521. {
  59522. return findColour (backgroundColourId, false);
  59523. }
  59524. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  59525. {
  59526. Colour backgroundColour (newColour);
  59527. if (! Desktop::canUseSemiTransparentWindows())
  59528. backgroundColour = newColour.withAlpha (1.0f);
  59529. setColour (backgroundColourId, backgroundColour);
  59530. setOpaque (backgroundColour.isOpaque());
  59531. repaint();
  59532. }
  59533. bool ResizableWindow::isFullScreen() const
  59534. {
  59535. if (isOnDesktop())
  59536. {
  59537. ComponentPeer* const peer = getPeer();
  59538. return peer != 0 && peer->isFullScreen();
  59539. }
  59540. return fullscreen;
  59541. }
  59542. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  59543. {
  59544. if (shouldBeFullScreen != isFullScreen())
  59545. {
  59546. updateLastPos();
  59547. fullscreen = shouldBeFullScreen;
  59548. if (isOnDesktop())
  59549. {
  59550. ComponentPeer* const peer = getPeer();
  59551. if (peer != 0)
  59552. {
  59553. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  59554. const Rectangle lastPos (lastNonFullScreenPos);
  59555. peer->setFullScreen (shouldBeFullScreen);
  59556. if (! shouldBeFullScreen)
  59557. setBounds (lastPos);
  59558. }
  59559. else
  59560. {
  59561. jassertfalse
  59562. }
  59563. }
  59564. else
  59565. {
  59566. if (shouldBeFullScreen)
  59567. setBounds (0, 0, getParentWidth(), getParentHeight());
  59568. else
  59569. setBounds (lastNonFullScreenPos);
  59570. }
  59571. resized();
  59572. }
  59573. }
  59574. bool ResizableWindow::isMinimised() const
  59575. {
  59576. ComponentPeer* const peer = getPeer();
  59577. return (peer != 0) && peer->isMinimised();
  59578. }
  59579. void ResizableWindow::setMinimised (const bool shouldMinimise)
  59580. {
  59581. if (shouldMinimise != isMinimised())
  59582. {
  59583. ComponentPeer* const peer = getPeer();
  59584. if (peer != 0)
  59585. {
  59586. updateLastPos();
  59587. peer->setMinimised (shouldMinimise);
  59588. }
  59589. else
  59590. {
  59591. jassertfalse
  59592. }
  59593. }
  59594. }
  59595. void ResizableWindow::updateLastPos()
  59596. {
  59597. if (isShowing() && ! (isFullScreen() || isMinimised()))
  59598. {
  59599. lastNonFullScreenPos = getBounds();
  59600. }
  59601. }
  59602. void ResizableWindow::parentSizeChanged()
  59603. {
  59604. if (isFullScreen() && getParentComponent() != 0)
  59605. {
  59606. setBounds (0, 0, getParentWidth(), getParentHeight());
  59607. }
  59608. }
  59609. const String ResizableWindow::getWindowStateAsString()
  59610. {
  59611. updateLastPos();
  59612. String s;
  59613. if (isFullScreen())
  59614. s << "fs ";
  59615. s << lastNonFullScreenPos.getX() << T(' ')
  59616. << lastNonFullScreenPos.getY() << T(' ')
  59617. << lastNonFullScreenPos.getWidth() << T(' ')
  59618. << lastNonFullScreenPos.getHeight();
  59619. return s;
  59620. }
  59621. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  59622. {
  59623. StringArray tokens;
  59624. tokens.addTokens (s, false);
  59625. tokens.removeEmptyStrings();
  59626. tokens.trim();
  59627. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  59628. const int n = fs ? 1 : 0;
  59629. if (tokens.size() != 4 + n)
  59630. return false;
  59631. Rectangle r (tokens[n].getIntValue(),
  59632. tokens[n + 1].getIntValue(),
  59633. tokens[n + 2].getIntValue(),
  59634. tokens[n + 3].getIntValue());
  59635. if (r.isEmpty())
  59636. return false;
  59637. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  59638. if (! screen.contains (r))
  59639. {
  59640. r.setSize (jmin (r.getWidth(), screen.getWidth()),
  59641. jmin (r.getHeight(), screen.getHeight()));
  59642. r.setPosition (jlimit (screen.getX(), screen.getRight() - r.getWidth(), r.getX()),
  59643. jlimit (screen.getY(), screen.getBottom() - r.getHeight(), r.getY()));
  59644. }
  59645. lastNonFullScreenPos = r;
  59646. if (isOnDesktop())
  59647. {
  59648. ComponentPeer* const peer = getPeer();
  59649. if (peer != 0)
  59650. peer->setNonFullScreenBounds (r);
  59651. }
  59652. setFullScreen (fs);
  59653. if (! fs)
  59654. setBoundsConstrained (r.getX(),
  59655. r.getY(),
  59656. r.getWidth(),
  59657. r.getHeight());
  59658. return true;
  59659. }
  59660. void ResizableWindow::mouseDown (const MouseEvent&)
  59661. {
  59662. if (! isFullScreen())
  59663. dragger.startDraggingComponent (this, constrainer);
  59664. }
  59665. void ResizableWindow::mouseDrag (const MouseEvent& e)
  59666. {
  59667. if (! isFullScreen())
  59668. dragger.dragComponent (this, e);
  59669. }
  59670. #ifdef JUCE_DEBUG
  59671. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  59672. {
  59673. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59674. manages its child components automatically, and if you add your own it'll cause
  59675. trouble. Instead, use setContentComponent() to give it a component which
  59676. will be automatically resized and kept in the right place - then you can add
  59677. subcomponents to the content comp. See the notes for the ResizableWindow class
  59678. for more info.
  59679. If you really know what you're doing and want to avoid this assertion, just call
  59680. Component::addChildComponent directly.
  59681. */
  59682. jassertfalse
  59683. Component::addChildComponent (child, zOrder);
  59684. }
  59685. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  59686. {
  59687. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  59688. manages its child components automatically, and if you add your own it'll cause
  59689. trouble. Instead, use setContentComponent() to give it a component which
  59690. will be automatically resized and kept in the right place - then you can add
  59691. subcomponents to the content comp. See the notes for the ResizableWindow class
  59692. for more info.
  59693. If you really know what you're doing and want to avoid this assertion, just call
  59694. Component::addAndMakeVisible directly.
  59695. */
  59696. jassertfalse
  59697. Component::addAndMakeVisible (child, zOrder);
  59698. }
  59699. #endif
  59700. END_JUCE_NAMESPACE
  59701. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  59702. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  59703. BEGIN_JUCE_NAMESPACE
  59704. SplashScreen::SplashScreen()
  59705. : backgroundImage (0),
  59706. isImageInCache (false)
  59707. {
  59708. setOpaque (true);
  59709. }
  59710. SplashScreen::~SplashScreen()
  59711. {
  59712. if (isImageInCache)
  59713. ImageCache::release (backgroundImage);
  59714. else
  59715. delete backgroundImage;
  59716. }
  59717. void SplashScreen::show (const String& title,
  59718. Image* const backgroundImage_,
  59719. const int minimumTimeToDisplayFor,
  59720. const bool useDropShadow,
  59721. const bool removeOnMouseClick)
  59722. {
  59723. backgroundImage = backgroundImage_;
  59724. jassert (backgroundImage_ != 0);
  59725. if (backgroundImage_ != 0)
  59726. {
  59727. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  59728. setOpaque (! backgroundImage_->hasAlphaChannel());
  59729. show (title,
  59730. backgroundImage_->getWidth(),
  59731. backgroundImage_->getHeight(),
  59732. minimumTimeToDisplayFor,
  59733. useDropShadow,
  59734. removeOnMouseClick);
  59735. }
  59736. }
  59737. void SplashScreen::show (const String& title,
  59738. const int width,
  59739. const int height,
  59740. const int minimumTimeToDisplayFor,
  59741. const bool useDropShadow,
  59742. const bool removeOnMouseClick)
  59743. {
  59744. setName (title);
  59745. setAlwaysOnTop (true);
  59746. setVisible (true);
  59747. centreWithSize (width, height);
  59748. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  59749. toFront (false);
  59750. MessageManager::getInstance()->runDispatchLoopUntil (300);
  59751. repaint();
  59752. originalClickCounter = removeOnMouseClick
  59753. ? Desktop::getMouseButtonClickCounter()
  59754. : INT_MAX;
  59755. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  59756. startTimer (50);
  59757. }
  59758. void SplashScreen::paint (Graphics& g)
  59759. {
  59760. if (backgroundImage != 0)
  59761. {
  59762. g.setOpacity (1.0f);
  59763. g.drawImage (backgroundImage,
  59764. 0, 0, getWidth(), getHeight(),
  59765. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  59766. }
  59767. }
  59768. void SplashScreen::timerCallback()
  59769. {
  59770. if (Time::getCurrentTime() > earliestTimeToDelete
  59771. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  59772. {
  59773. delete this;
  59774. }
  59775. }
  59776. END_JUCE_NAMESPACE
  59777. /********* End of inlined file: juce_SplashScreen.cpp *********/
  59778. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59779. BEGIN_JUCE_NAMESPACE
  59780. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  59781. const bool hasProgressBar,
  59782. const bool hasCancelButton,
  59783. const int timeOutMsWhenCancelling_,
  59784. const String& cancelButtonText)
  59785. : Thread ("Juce Progress Window"),
  59786. progress (0.0),
  59787. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  59788. {
  59789. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  59790. .createAlertWindow (title, String::empty, cancelButtonText,
  59791. String::empty, String::empty,
  59792. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  59793. if (hasProgressBar)
  59794. alertWindow->addProgressBarComponent (progress);
  59795. }
  59796. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  59797. {
  59798. stopThread (timeOutMsWhenCancelling);
  59799. delete alertWindow;
  59800. }
  59801. bool ThreadWithProgressWindow::runThread (const int priority)
  59802. {
  59803. startThread (priority);
  59804. startTimer (100);
  59805. {
  59806. const ScopedLock sl (messageLock);
  59807. alertWindow->setMessage (message);
  59808. }
  59809. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  59810. stopThread (timeOutMsWhenCancelling);
  59811. alertWindow->setVisible (false);
  59812. return finishedNaturally;
  59813. }
  59814. void ThreadWithProgressWindow::setProgress (const double newProgress)
  59815. {
  59816. progress = newProgress;
  59817. }
  59818. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  59819. {
  59820. const ScopedLock sl (messageLock);
  59821. message = newStatusMessage;
  59822. }
  59823. void ThreadWithProgressWindow::timerCallback()
  59824. {
  59825. if (! isThreadRunning())
  59826. {
  59827. // thread has finished normally..
  59828. alertWindow->exitModalState (1);
  59829. alertWindow->setVisible (false);
  59830. }
  59831. else
  59832. {
  59833. const ScopedLock sl (messageLock);
  59834. alertWindow->setMessage (message);
  59835. }
  59836. }
  59837. END_JUCE_NAMESPACE
  59838. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  59839. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  59840. BEGIN_JUCE_NAMESPACE
  59841. TooltipWindow::TooltipWindow (Component* const parentComponent,
  59842. const int millisecondsBeforeTipAppears_)
  59843. : Component ("tooltip"),
  59844. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  59845. mouseX (0),
  59846. mouseY (0),
  59847. lastHideTime (0),
  59848. lastComponentUnderMouse (0),
  59849. changedCompsSinceShown (true)
  59850. {
  59851. startTimer (123);
  59852. setAlwaysOnTop (true);
  59853. setOpaque (true);
  59854. if (parentComponent != 0)
  59855. parentComponent->addChildComponent (this);
  59856. }
  59857. TooltipWindow::~TooltipWindow()
  59858. {
  59859. hide();
  59860. }
  59861. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  59862. {
  59863. millisecondsBeforeTipAppears = newTimeMs;
  59864. }
  59865. void TooltipWindow::paint (Graphics& g)
  59866. {
  59867. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  59868. }
  59869. void TooltipWindow::mouseEnter (const MouseEvent&)
  59870. {
  59871. hide();
  59872. }
  59873. void TooltipWindow::showFor (Component* const c, const String& tip)
  59874. {
  59875. jassert (tip.isNotEmpty());
  59876. tipShowing = tip;
  59877. int mx, my;
  59878. Desktop::getMousePosition (mx, my);
  59879. if (getParentComponent() != 0)
  59880. getParentComponent()->globalPositionToRelative (mx, my);
  59881. int x, y, w, h;
  59882. getLookAndFeel().getTooltipSize (tip, w, h);
  59883. if (mx > getParentWidth() / 2)
  59884. x = mx - (w + 12);
  59885. else
  59886. x = mx + 24;
  59887. if (my > getParentHeight() / 2)
  59888. y = my - (h + 6);
  59889. else
  59890. y = my + 6;
  59891. setBounds (x, y, w, h);
  59892. setVisible (true);
  59893. if (getParentComponent() == 0)
  59894. {
  59895. addToDesktop (ComponentPeer::windowHasDropShadow
  59896. | ComponentPeer::windowIsTemporary);
  59897. }
  59898. toFront (false);
  59899. }
  59900. const String TooltipWindow::getTipFor (Component* const c)
  59901. {
  59902. if (c->isValidComponent()
  59903. && Process::isForegroundProcess()
  59904. && ! Component::isMouseButtonDownAnywhere())
  59905. {
  59906. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  59907. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  59908. return ttc->getTooltip();
  59909. }
  59910. return String::empty;
  59911. }
  59912. void TooltipWindow::hide()
  59913. {
  59914. tipShowing = String::empty;
  59915. removeFromDesktop();
  59916. setVisible (false);
  59917. }
  59918. void TooltipWindow::timerCallback()
  59919. {
  59920. const unsigned int now = Time::getApproximateMillisecondCounter();
  59921. Component* const newComp = Component::getComponentUnderMouse();
  59922. const String newTip (getTipFor (newComp));
  59923. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  59924. lastComponentUnderMouse = newComp;
  59925. lastTipUnderMouse = newTip;
  59926. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  59927. const bool mouseWasClicked = clickCount > mouseClicks;
  59928. mouseClicks = clickCount;
  59929. int mx, my;
  59930. Desktop::getMousePosition (mx, my);
  59931. const bool mouseMovedQuickly = (abs (mx - mouseX) + abs (my - mouseY) > 12);
  59932. mouseX = mx;
  59933. mouseY = my;
  59934. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  59935. lastCompChangeTime = now;
  59936. if (isVisible() || now < lastHideTime + 500)
  59937. {
  59938. // if a tip is currently visible (or has just disappeared), update to a new one
  59939. // immediately if needed..
  59940. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  59941. {
  59942. if (isVisible())
  59943. {
  59944. lastHideTime = now;
  59945. hide();
  59946. }
  59947. }
  59948. else if (tipChanged)
  59949. {
  59950. showFor (newComp, newTip);
  59951. }
  59952. }
  59953. else
  59954. {
  59955. // if there isn't currently a tip, but one is needed, only let it
  59956. // appear after a timeout..
  59957. if (newTip.isNotEmpty()
  59958. && newTip != tipShowing
  59959. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  59960. {
  59961. showFor (newComp, newTip);
  59962. }
  59963. }
  59964. }
  59965. END_JUCE_NAMESPACE
  59966. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  59967. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  59968. BEGIN_JUCE_NAMESPACE
  59969. /** Keeps track of the active top level window.
  59970. */
  59971. class TopLevelWindowManager : public Timer,
  59972. public DeletedAtShutdown
  59973. {
  59974. public:
  59975. TopLevelWindowManager()
  59976. : windows (8),
  59977. currentActive (0)
  59978. {
  59979. }
  59980. ~TopLevelWindowManager()
  59981. {
  59982. clearSingletonInstance();
  59983. }
  59984. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  59985. void timerCallback()
  59986. {
  59987. startTimer (jmin (1731, getTimerInterval() * 2));
  59988. TopLevelWindow* active = 0;
  59989. if (Process::isForegroundProcess())
  59990. {
  59991. active = currentActive;
  59992. Component* const c = Component::getCurrentlyFocusedComponent();
  59993. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  59994. if (tlw == 0 && c != 0)
  59995. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  59996. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  59997. if (tlw != 0)
  59998. active = tlw;
  59999. }
  60000. if (active != currentActive)
  60001. {
  60002. currentActive = active;
  60003. for (int i = windows.size(); --i >= 0;)
  60004. {
  60005. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  60006. tlw->setWindowActive (isWindowActive (tlw));
  60007. i = jmin (i, windows.size() - 1);
  60008. }
  60009. Desktop::getInstance().triggerFocusCallback();
  60010. }
  60011. }
  60012. bool addWindow (TopLevelWindow* const w) throw()
  60013. {
  60014. windows.add (w);
  60015. startTimer (10);
  60016. return isWindowActive (w);
  60017. }
  60018. void removeWindow (TopLevelWindow* const w) throw()
  60019. {
  60020. startTimer (10);
  60021. if (currentActive == w)
  60022. currentActive = 0;
  60023. windows.removeValue (w);
  60024. if (windows.size() == 0)
  60025. deleteInstance();
  60026. }
  60027. VoidArray windows;
  60028. private:
  60029. TopLevelWindow* currentActive;
  60030. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  60031. {
  60032. return (tlw == currentActive
  60033. || tlw->isParentOf (currentActive)
  60034. || tlw->hasKeyboardFocus (true))
  60035. && tlw->isShowing();
  60036. }
  60037. TopLevelWindowManager (const TopLevelWindowManager&);
  60038. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  60039. };
  60040. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  60041. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  60042. {
  60043. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  60044. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  60045. }
  60046. TopLevelWindow::TopLevelWindow (const String& name,
  60047. const bool addToDesktop_)
  60048. : Component (name),
  60049. useDropShadow (true),
  60050. useNativeTitleBar (false),
  60051. windowIsActive_ (false),
  60052. shadower (0)
  60053. {
  60054. setOpaque (true);
  60055. if (addToDesktop_)
  60056. Component::addToDesktop (getDesktopWindowStyleFlags());
  60057. else
  60058. setDropShadowEnabled (true);
  60059. setWantsKeyboardFocus (true);
  60060. setBroughtToFrontOnMouseClick (true);
  60061. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  60062. }
  60063. TopLevelWindow::~TopLevelWindow()
  60064. {
  60065. deleteAndZero (shadower);
  60066. TopLevelWindowManager::getInstance()->removeWindow (this);
  60067. }
  60068. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  60069. {
  60070. if (hasKeyboardFocus (true))
  60071. TopLevelWindowManager::getInstance()->timerCallback();
  60072. else
  60073. TopLevelWindowManager::getInstance()->startTimer (10);
  60074. }
  60075. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  60076. {
  60077. if (windowIsActive_ != isNowActive)
  60078. {
  60079. windowIsActive_ = isNowActive;
  60080. activeWindowStatusChanged();
  60081. }
  60082. }
  60083. void TopLevelWindow::activeWindowStatusChanged()
  60084. {
  60085. }
  60086. void TopLevelWindow::parentHierarchyChanged()
  60087. {
  60088. setDropShadowEnabled (useDropShadow);
  60089. }
  60090. void TopLevelWindow::visibilityChanged()
  60091. {
  60092. if (isShowing())
  60093. toFront (true);
  60094. }
  60095. int TopLevelWindow::getDesktopWindowStyleFlags() const
  60096. {
  60097. int flags = ComponentPeer::windowAppearsOnTaskbar;
  60098. if (useDropShadow)
  60099. flags |= ComponentPeer::windowHasDropShadow;
  60100. if (useNativeTitleBar)
  60101. flags |= ComponentPeer::windowHasTitleBar;
  60102. return flags;
  60103. }
  60104. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  60105. {
  60106. useDropShadow = useShadow;
  60107. if (isOnDesktop())
  60108. {
  60109. deleteAndZero (shadower);
  60110. Component::addToDesktop (getDesktopWindowStyleFlags());
  60111. }
  60112. else
  60113. {
  60114. if (useShadow && isOpaque())
  60115. {
  60116. if (shadower == 0)
  60117. {
  60118. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  60119. if (shadower != 0)
  60120. shadower->setOwner (this);
  60121. }
  60122. }
  60123. else
  60124. {
  60125. deleteAndZero (shadower);
  60126. }
  60127. }
  60128. }
  60129. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  60130. {
  60131. if (useNativeTitleBar != useNativeTitleBar_)
  60132. {
  60133. useNativeTitleBar = useNativeTitleBar_;
  60134. recreateDesktopWindow();
  60135. sendLookAndFeelChange();
  60136. }
  60137. }
  60138. void TopLevelWindow::recreateDesktopWindow()
  60139. {
  60140. if (isOnDesktop())
  60141. {
  60142. Component::addToDesktop (getDesktopWindowStyleFlags());
  60143. toFront (true);
  60144. }
  60145. }
  60146. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  60147. {
  60148. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  60149. because this class needs to make sure its layout corresponds with settings like whether
  60150. it's got a native title bar or not.
  60151. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  60152. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  60153. method, then add or remove whatever flags are necessary from this value before returning it.
  60154. */
  60155. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  60156. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  60157. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  60158. if (windowStyleFlags != getDesktopWindowStyleFlags())
  60159. sendLookAndFeelChange();
  60160. }
  60161. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  60162. {
  60163. if (c == 0)
  60164. c = TopLevelWindow::getActiveTopLevelWindow();
  60165. if (c == 0)
  60166. {
  60167. centreWithSize (width, height);
  60168. }
  60169. else
  60170. {
  60171. int x = (c->getWidth() - width) / 2;
  60172. int y = (c->getHeight() - height) / 2;
  60173. c->relativePositionToGlobal (x, y);
  60174. Rectangle parentArea (c->getParentMonitorArea());
  60175. if (getParentComponent() != 0)
  60176. {
  60177. getParentComponent()->globalPositionToRelative (x, y);
  60178. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  60179. }
  60180. parentArea.reduce (12, 12);
  60181. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  60182. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  60183. width, height);
  60184. }
  60185. }
  60186. int TopLevelWindow::getNumTopLevelWindows() throw()
  60187. {
  60188. return TopLevelWindowManager::getInstance()->windows.size();
  60189. }
  60190. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  60191. {
  60192. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  60193. }
  60194. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  60195. {
  60196. TopLevelWindow* best = 0;
  60197. int bestNumTWLParents = -1;
  60198. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  60199. {
  60200. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  60201. if (tlw->isActiveWindow())
  60202. {
  60203. int numTWLParents = 0;
  60204. const Component* c = tlw->getParentComponent();
  60205. while (c != 0)
  60206. {
  60207. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  60208. ++numTWLParents;
  60209. c = c->getParentComponent();
  60210. }
  60211. if (bestNumTWLParents < numTWLParents)
  60212. {
  60213. best = tlw;
  60214. bestNumTWLParents = numTWLParents;
  60215. }
  60216. }
  60217. }
  60218. return best;
  60219. }
  60220. END_JUCE_NAMESPACE
  60221. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  60222. /********* Start of inlined file: juce_Brush.cpp *********/
  60223. BEGIN_JUCE_NAMESPACE
  60224. Brush::Brush() throw()
  60225. {
  60226. }
  60227. Brush::~Brush() throw()
  60228. {
  60229. }
  60230. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  60231. int x, float y1, float y2) throw()
  60232. {
  60233. Path p;
  60234. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  60235. paintPath (context, p, AffineTransform::identity);
  60236. }
  60237. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60238. int y, float x1, float x2) throw()
  60239. {
  60240. Path p;
  60241. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  60242. paintPath (context, p, AffineTransform::identity);
  60243. }
  60244. void Brush::paintLine (LowLevelGraphicsContext& context,
  60245. float x1, float y1, float x2, float y2) throw()
  60246. {
  60247. Path p;
  60248. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  60249. paintPath (context, p, AffineTransform::identity);
  60250. }
  60251. END_JUCE_NAMESPACE
  60252. /********* End of inlined file: juce_Brush.cpp *********/
  60253. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  60254. BEGIN_JUCE_NAMESPACE
  60255. GradientBrush::GradientBrush (const Colour& colour1,
  60256. const float x1,
  60257. const float y1,
  60258. const Colour& colour2,
  60259. const float x2,
  60260. const float y2,
  60261. const bool isRadial) throw()
  60262. : gradient (colour1, x1, y1,
  60263. colour2, x2, y2,
  60264. isRadial)
  60265. {
  60266. }
  60267. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  60268. : gradient (gradient_)
  60269. {
  60270. }
  60271. GradientBrush::~GradientBrush() throw()
  60272. {
  60273. }
  60274. Brush* GradientBrush::createCopy() const throw()
  60275. {
  60276. return new GradientBrush (gradient);
  60277. }
  60278. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  60279. {
  60280. gradient.transform = gradient.transform.followedBy (transform);
  60281. }
  60282. void GradientBrush::multiplyOpacity (const float multiple) throw()
  60283. {
  60284. gradient.multiplyOpacity (multiple);
  60285. }
  60286. bool GradientBrush::isInvisible() const throw()
  60287. {
  60288. return gradient.isInvisible();
  60289. }
  60290. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  60291. const Path& path, const AffineTransform& transform) throw()
  60292. {
  60293. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  60294. }
  60295. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  60296. int x, int y, int w, int h) throw()
  60297. {
  60298. context.fillRectWithGradient (x, y, w, h, gradient);
  60299. }
  60300. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60301. const Image& alphaChannelImage, int imageX, int imageY,
  60302. int x, int y, int w, int h) throw()
  60303. {
  60304. context.saveState();
  60305. if (context.reduceClipRegion (x, y, w, h))
  60306. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  60307. context.restoreState();
  60308. }
  60309. END_JUCE_NAMESPACE
  60310. /********* End of inlined file: juce_GradientBrush.cpp *********/
  60311. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  60312. BEGIN_JUCE_NAMESPACE
  60313. ImageBrush::ImageBrush (Image* const image_,
  60314. const int anchorX_,
  60315. const int anchorY_,
  60316. const float opacity_) throw()
  60317. : image (image_),
  60318. anchorX (anchorX_),
  60319. anchorY (anchorY_),
  60320. opacity (opacity_)
  60321. {
  60322. jassert (image != 0); // not much point creating a brush without an image, is there?
  60323. if (image != 0)
  60324. {
  60325. if (image->getWidth() == 0 || image->getHeight() == 0)
  60326. {
  60327. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  60328. image = 0;
  60329. }
  60330. }
  60331. }
  60332. ImageBrush::~ImageBrush() throw()
  60333. {
  60334. }
  60335. Brush* ImageBrush::createCopy() const throw()
  60336. {
  60337. return new ImageBrush (image, anchorX, anchorY, opacity);
  60338. }
  60339. void ImageBrush::multiplyOpacity (const float multiple) throw()
  60340. {
  60341. opacity *= multiple;
  60342. }
  60343. bool ImageBrush::isInvisible() const throw()
  60344. {
  60345. return opacity == 0.0f;
  60346. }
  60347. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60348. {
  60349. //xxx should probably be smarter and warp the image
  60350. }
  60351. void ImageBrush::getStartXY (int& x, int& y) const throw()
  60352. {
  60353. x -= anchorX;
  60354. y -= anchorY;
  60355. const int iw = image->getWidth();
  60356. const int ih = image->getHeight();
  60357. if (x < 0)
  60358. x = ((x / iw) - 1) * iw;
  60359. else
  60360. x = (x / iw) * iw;
  60361. if (y < 0)
  60362. y = ((y / ih) - 1) * ih;
  60363. else
  60364. y = (y / ih) * ih;
  60365. x += anchorX;
  60366. y += anchorY;
  60367. }
  60368. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  60369. int x, int y, int w, int h) throw()
  60370. {
  60371. context.saveState();
  60372. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60373. {
  60374. const int right = x + w;
  60375. const int bottom = y + h;
  60376. const int iw = image->getWidth();
  60377. const int ih = image->getHeight();
  60378. int startX = x;
  60379. getStartXY (startX, y);
  60380. while (y < bottom)
  60381. {
  60382. x = startX;
  60383. while (x < right)
  60384. {
  60385. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  60386. x += iw;
  60387. }
  60388. y += ih;
  60389. }
  60390. }
  60391. context.restoreState();
  60392. }
  60393. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  60394. const Path& path, const AffineTransform& transform) throw()
  60395. {
  60396. if (image != 0)
  60397. {
  60398. Rectangle clip (context.getClipBounds());
  60399. {
  60400. float x, y, w, h;
  60401. path.getBoundsTransformed (transform, x, y, w, h);
  60402. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  60403. (int) floorf (y),
  60404. 2 + (int) floorf (w),
  60405. 2 + (int) floorf (h)));
  60406. }
  60407. int x = clip.getX();
  60408. int y = clip.getY();
  60409. const int right = clip.getRight();
  60410. const int bottom = clip.getBottom();
  60411. const int iw = image->getWidth();
  60412. const int ih = image->getHeight();
  60413. int startX = x;
  60414. getStartXY (startX, y);
  60415. while (y < bottom)
  60416. {
  60417. x = startX;
  60418. while (x < right)
  60419. {
  60420. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  60421. x += iw;
  60422. }
  60423. y += ih;
  60424. }
  60425. }
  60426. }
  60427. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60428. const Image& alphaChannelImage, int imageX, int imageY,
  60429. int x, int y, int w, int h) throw()
  60430. {
  60431. context.saveState();
  60432. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  60433. {
  60434. const Rectangle clip (context.getClipBounds());
  60435. x = clip.getX();
  60436. y = clip.getY();
  60437. const int right = clip.getRight();
  60438. const int bottom = clip.getBottom();
  60439. const int iw = image->getWidth();
  60440. const int ih = image->getHeight();
  60441. int startX = x;
  60442. getStartXY (startX, y);
  60443. while (y < bottom)
  60444. {
  60445. x = startX;
  60446. while (x < right)
  60447. {
  60448. context.fillAlphaChannelWithImage (alphaChannelImage,
  60449. imageX, imageY, *image,
  60450. x, y, opacity);
  60451. x += iw;
  60452. }
  60453. y += ih;
  60454. }
  60455. }
  60456. context.restoreState();
  60457. }
  60458. END_JUCE_NAMESPACE
  60459. /********* End of inlined file: juce_ImageBrush.cpp *********/
  60460. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  60461. BEGIN_JUCE_NAMESPACE
  60462. SolidColourBrush::SolidColourBrush() throw()
  60463. : colour (0xff000000)
  60464. {
  60465. }
  60466. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  60467. : colour (colour_)
  60468. {
  60469. }
  60470. SolidColourBrush::~SolidColourBrush() throw()
  60471. {
  60472. }
  60473. Brush* SolidColourBrush::createCopy() const throw()
  60474. {
  60475. return new SolidColourBrush (colour);
  60476. }
  60477. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  60478. {
  60479. }
  60480. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  60481. {
  60482. colour = colour.withMultipliedAlpha (multiple);
  60483. }
  60484. bool SolidColourBrush::isInvisible() const throw()
  60485. {
  60486. return colour.isTransparent();
  60487. }
  60488. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  60489. const Path& path, const AffineTransform& transform) throw()
  60490. {
  60491. if (! colour.isTransparent())
  60492. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  60493. }
  60494. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  60495. int x, int y, int w, int h) throw()
  60496. {
  60497. if (! colour.isTransparent())
  60498. context.fillRectWithColour (x, y, w, h, colour, false);
  60499. }
  60500. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  60501. const Image& alphaChannelImage, int imageX, int imageY,
  60502. int x, int y, int w, int h) throw()
  60503. {
  60504. if (! colour.isTransparent())
  60505. {
  60506. context.saveState();
  60507. if (context.reduceClipRegion (x, y, w, h))
  60508. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  60509. context.restoreState();
  60510. }
  60511. }
  60512. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  60513. int x, float y1, float y2) throw()
  60514. {
  60515. context.drawVerticalLine (x, y1, y2, colour);
  60516. }
  60517. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  60518. int y, float x1, float x2) throw()
  60519. {
  60520. context.drawHorizontalLine (y, x1, x2, colour);
  60521. }
  60522. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  60523. float x1, float y1, float x2, float y2) throw()
  60524. {
  60525. context.drawLine (x1, y1, x2, y2, colour);
  60526. }
  60527. END_JUCE_NAMESPACE
  60528. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  60529. /********* Start of inlined file: juce_Colour.cpp *********/
  60530. BEGIN_JUCE_NAMESPACE
  60531. static forcedinline uint8 floatAlphaToInt (const float alpha)
  60532. {
  60533. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  60534. }
  60535. static const float oneOver255 = 1.0f / 255.0f;
  60536. Colour::Colour() throw()
  60537. : argb (0)
  60538. {
  60539. }
  60540. Colour::Colour (const Colour& other) throw()
  60541. : argb (other.argb)
  60542. {
  60543. }
  60544. const Colour& Colour::operator= (const Colour& other) throw()
  60545. {
  60546. argb = other.argb;
  60547. return *this;
  60548. }
  60549. bool Colour::operator== (const Colour& other) const throw()
  60550. {
  60551. return argb.getARGB() == other.argb.getARGB();
  60552. }
  60553. bool Colour::operator!= (const Colour& other) const throw()
  60554. {
  60555. return argb.getARGB() != other.argb.getARGB();
  60556. }
  60557. Colour::Colour (const uint32 argb_) throw()
  60558. : argb (argb_)
  60559. {
  60560. }
  60561. Colour::Colour (const uint8 red,
  60562. const uint8 green,
  60563. const uint8 blue) throw()
  60564. {
  60565. argb.setARGB (0xff, red, green, blue);
  60566. }
  60567. const Colour Colour::fromRGB (const uint8 red,
  60568. const uint8 green,
  60569. const uint8 blue) throw()
  60570. {
  60571. return Colour (red, green, blue);
  60572. }
  60573. Colour::Colour (const uint8 red,
  60574. const uint8 green,
  60575. const uint8 blue,
  60576. const uint8 alpha) throw()
  60577. {
  60578. argb.setARGB (alpha, red, green, blue);
  60579. }
  60580. const Colour Colour::fromRGBA (const uint8 red,
  60581. const uint8 green,
  60582. const uint8 blue,
  60583. const uint8 alpha) throw()
  60584. {
  60585. return Colour (red, green, blue, alpha);
  60586. }
  60587. Colour::Colour (const uint8 red,
  60588. const uint8 green,
  60589. const uint8 blue,
  60590. const float alpha) throw()
  60591. {
  60592. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  60593. }
  60594. const Colour Colour::fromRGBAFloat (const uint8 red,
  60595. const uint8 green,
  60596. const uint8 blue,
  60597. const float alpha) throw()
  60598. {
  60599. return Colour (red, green, blue, alpha);
  60600. }
  60601. static void convertHSBtoRGB (float h, const float s, float v,
  60602. uint8& r, uint8& g, uint8& b) throw()
  60603. {
  60604. v *= 255.0f;
  60605. const uint8 intV = (uint8) roundFloatToInt (v);
  60606. if (s == 0)
  60607. {
  60608. r = intV;
  60609. g = intV;
  60610. b = intV;
  60611. }
  60612. else
  60613. {
  60614. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  60615. const float f = h - floorf (h);
  60616. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  60617. const float y = v * (1.0f - s * f);
  60618. const float z = v * (1.0f - (s * (1.0f - f)));
  60619. if (h < 1.0f)
  60620. {
  60621. r = intV;
  60622. g = (uint8) roundFloatToInt (z);
  60623. b = x;
  60624. }
  60625. else if (h < 2.0f)
  60626. {
  60627. r = (uint8) roundFloatToInt (y);
  60628. g = intV;
  60629. b = x;
  60630. }
  60631. else if (h < 3.0f)
  60632. {
  60633. r = x;
  60634. g = intV;
  60635. b = (uint8) roundFloatToInt (z);
  60636. }
  60637. else if (h < 4.0f)
  60638. {
  60639. r = x;
  60640. g = (uint8) roundFloatToInt (y);
  60641. b = intV;
  60642. }
  60643. else if (h < 5.0f)
  60644. {
  60645. r = (uint8) roundFloatToInt (z);
  60646. g = x;
  60647. b = intV;
  60648. }
  60649. else if (h < 6.0f)
  60650. {
  60651. r = intV;
  60652. g = x;
  60653. b = (uint8) roundFloatToInt (y);
  60654. }
  60655. else
  60656. {
  60657. r = 0;
  60658. g = 0;
  60659. b = 0;
  60660. }
  60661. }
  60662. }
  60663. Colour::Colour (const float hue,
  60664. const float saturation,
  60665. const float brightness,
  60666. const float alpha) throw()
  60667. {
  60668. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60669. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60670. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  60671. }
  60672. const Colour Colour::fromHSV (const float hue,
  60673. const float saturation,
  60674. const float brightness,
  60675. const float alpha) throw()
  60676. {
  60677. return Colour (hue, saturation, brightness, alpha);
  60678. }
  60679. Colour::Colour (const float hue,
  60680. const float saturation,
  60681. const float brightness,
  60682. const uint8 alpha) throw()
  60683. {
  60684. uint8 r = getRed(), g = getGreen(), b = getBlue();
  60685. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  60686. argb.setARGB (alpha, r, g, b);
  60687. }
  60688. Colour::~Colour() throw()
  60689. {
  60690. }
  60691. const PixelARGB Colour::getPixelARGB() const throw()
  60692. {
  60693. PixelARGB p (argb);
  60694. p.premultiply();
  60695. return p;
  60696. }
  60697. uint32 Colour::getARGB() const throw()
  60698. {
  60699. return argb.getARGB();
  60700. }
  60701. bool Colour::isTransparent() const throw()
  60702. {
  60703. return getAlpha() == 0;
  60704. }
  60705. bool Colour::isOpaque() const throw()
  60706. {
  60707. return getAlpha() == 0xff;
  60708. }
  60709. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  60710. {
  60711. PixelARGB newCol (argb);
  60712. newCol.setAlpha (newAlpha);
  60713. return Colour (newCol.getARGB());
  60714. }
  60715. const Colour Colour::withAlpha (const float newAlpha) const throw()
  60716. {
  60717. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  60718. PixelARGB newCol (argb);
  60719. newCol.setAlpha (floatAlphaToInt (newAlpha));
  60720. return Colour (newCol.getARGB());
  60721. }
  60722. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  60723. {
  60724. jassert (alphaMultiplier >= 0);
  60725. PixelARGB newCol (argb);
  60726. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  60727. return Colour (newCol.getARGB());
  60728. }
  60729. const Colour Colour::overlaidWith (const Colour& src) const throw()
  60730. {
  60731. const int destAlpha = getAlpha();
  60732. if (destAlpha > 0)
  60733. {
  60734. const int invA = 0xff - (int) src.getAlpha();
  60735. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  60736. if (resA > 0)
  60737. {
  60738. const int da = (invA * destAlpha) / resA;
  60739. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  60740. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  60741. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  60742. (uint8) resA);
  60743. }
  60744. return *this;
  60745. }
  60746. else
  60747. {
  60748. return src;
  60749. }
  60750. }
  60751. float Colour::getFloatRed() const throw()
  60752. {
  60753. return getRed() * oneOver255;
  60754. }
  60755. float Colour::getFloatGreen() const throw()
  60756. {
  60757. return getGreen() * oneOver255;
  60758. }
  60759. float Colour::getFloatBlue() const throw()
  60760. {
  60761. return getBlue() * oneOver255;
  60762. }
  60763. float Colour::getFloatAlpha() const throw()
  60764. {
  60765. return getAlpha() * oneOver255;
  60766. }
  60767. void Colour::getHSB (float& h, float& s, float& v) const throw()
  60768. {
  60769. const int r = getRed();
  60770. const int g = getGreen();
  60771. const int b = getBlue();
  60772. const int hi = jmax (r, g, b);
  60773. const int lo = jmin (r, g, b);
  60774. if (hi != 0)
  60775. {
  60776. s = (hi - lo) / (float) hi;
  60777. if (s != 0)
  60778. {
  60779. const float invDiff = 1.0f / (hi - lo);
  60780. const float red = (hi - r) * invDiff;
  60781. const float green = (hi - g) * invDiff;
  60782. const float blue = (hi - b) * invDiff;
  60783. if (r == hi)
  60784. h = blue - green;
  60785. else if (g == hi)
  60786. h = 2.0f + red - blue;
  60787. else
  60788. h = 4.0f + green - red;
  60789. h *= 1.0f / 6.0f;
  60790. if (h < 0)
  60791. ++h;
  60792. }
  60793. else
  60794. {
  60795. h = 0;
  60796. }
  60797. }
  60798. else
  60799. {
  60800. s = 0;
  60801. h = 0;
  60802. }
  60803. v = hi * oneOver255;
  60804. }
  60805. float Colour::getHue() const throw()
  60806. {
  60807. float h, s, b;
  60808. getHSB (h, s, b);
  60809. return h;
  60810. }
  60811. const Colour Colour::withHue (const float hue) const throw()
  60812. {
  60813. float h, s, b;
  60814. getHSB (h, s, b);
  60815. return Colour (hue, s, b, getAlpha());
  60816. }
  60817. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  60818. {
  60819. float h, s, b;
  60820. getHSB (h, s, b);
  60821. h += amountToRotate;
  60822. h -= floorf (h);
  60823. return Colour (h, s, b, getAlpha());
  60824. }
  60825. float Colour::getSaturation() const throw()
  60826. {
  60827. float h, s, b;
  60828. getHSB (h, s, b);
  60829. return s;
  60830. }
  60831. const Colour Colour::withSaturation (const float saturation) const throw()
  60832. {
  60833. float h, s, b;
  60834. getHSB (h, s, b);
  60835. return Colour (h, saturation, b, getAlpha());
  60836. }
  60837. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  60838. {
  60839. float h, s, b;
  60840. getHSB (h, s, b);
  60841. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  60842. }
  60843. float Colour::getBrightness() const throw()
  60844. {
  60845. float h, s, b;
  60846. getHSB (h, s, b);
  60847. return b;
  60848. }
  60849. const Colour Colour::withBrightness (const float brightness) const throw()
  60850. {
  60851. float h, s, b;
  60852. getHSB (h, s, b);
  60853. return Colour (h, s, brightness, getAlpha());
  60854. }
  60855. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  60856. {
  60857. float h, s, b;
  60858. getHSB (h, s, b);
  60859. b *= amount;
  60860. if (b > 1.0f)
  60861. b = 1.0f;
  60862. return Colour (h, s, b, getAlpha());
  60863. }
  60864. const Colour Colour::brighter (float amount) const throw()
  60865. {
  60866. amount = 1.0f / (1.0f + amount);
  60867. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  60868. (uint8) (255 - (amount * (255 - getGreen()))),
  60869. (uint8) (255 - (amount * (255 - getBlue()))),
  60870. getAlpha());
  60871. }
  60872. const Colour Colour::darker (float amount) const throw()
  60873. {
  60874. amount = 1.0f / (1.0f + amount);
  60875. return Colour ((uint8) (amount * getRed()),
  60876. (uint8) (amount * getGreen()),
  60877. (uint8) (amount * getBlue()),
  60878. getAlpha());
  60879. }
  60880. const Colour Colour::greyLevel (const float brightness) throw()
  60881. {
  60882. const uint8 level
  60883. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  60884. return Colour (level, level, level);
  60885. }
  60886. const Colour Colour::contrasting (const float amount) const throw()
  60887. {
  60888. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  60889. ? Colours::black
  60890. : Colours::white).withAlpha (amount));
  60891. }
  60892. const Colour Colour::contrasting (const Colour& colour1,
  60893. const Colour& colour2) throw()
  60894. {
  60895. const float b1 = colour1.getBrightness();
  60896. const float b2 = colour2.getBrightness();
  60897. float best = 0.0f;
  60898. float bestDist = 0.0f;
  60899. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  60900. {
  60901. const float d1 = fabsf (i - b1);
  60902. const float d2 = fabsf (i - b2);
  60903. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  60904. if (dist > bestDist)
  60905. {
  60906. best = i;
  60907. bestDist = dist;
  60908. }
  60909. }
  60910. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  60911. .withBrightness (best);
  60912. }
  60913. const String Colour::toString() const throw()
  60914. {
  60915. return String::toHexString ((int) argb.getARGB());
  60916. }
  60917. const Colour Colour::fromString (const String& encodedColourString)
  60918. {
  60919. return Colour ((uint32) encodedColourString.getHexValue32());
  60920. }
  60921. END_JUCE_NAMESPACE
  60922. /********* End of inlined file: juce_Colour.cpp *********/
  60923. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  60924. BEGIN_JUCE_NAMESPACE
  60925. ColourGradient::ColourGradient() throw()
  60926. : colours (4)
  60927. {
  60928. #ifdef JUCE_DEBUG
  60929. x1 = 987654.0f;
  60930. #endif
  60931. }
  60932. ColourGradient::ColourGradient (const Colour& colour1,
  60933. const float x1_,
  60934. const float y1_,
  60935. const Colour& colour2,
  60936. const float x2_,
  60937. const float y2_,
  60938. const bool isRadial_) throw()
  60939. : x1 (x1_),
  60940. y1 (y1_),
  60941. x2 (x2_),
  60942. y2 (y2_),
  60943. isRadial (isRadial_),
  60944. colours (4)
  60945. {
  60946. colours.add (0);
  60947. colours.add (colour1.getARGB());
  60948. colours.add (1 << 16);
  60949. colours.add (colour2.getARGB());
  60950. }
  60951. ColourGradient::~ColourGradient() throw()
  60952. {
  60953. }
  60954. void ColourGradient::clearColours() throw()
  60955. {
  60956. colours.clear();
  60957. }
  60958. void ColourGradient::addColour (const double proportionAlongGradient,
  60959. const Colour& colour) throw()
  60960. {
  60961. // must be within the two end-points
  60962. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  60963. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  60964. int i;
  60965. for (i = 0; i < colours.size(); i += 2)
  60966. if (colours.getUnchecked(i) > pos)
  60967. break;
  60968. colours.insert (i, pos);
  60969. colours.insert (i + 1, colour.getARGB());
  60970. }
  60971. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  60972. {
  60973. for (int i = 1; i < colours.size(); i += 2)
  60974. {
  60975. const Colour c (colours.getUnchecked(i));
  60976. colours.set (i, c.withMultipliedAlpha (multiplier).getARGB());
  60977. }
  60978. }
  60979. int ColourGradient::getNumColours() const throw()
  60980. {
  60981. return colours.size() >> 1;
  60982. }
  60983. double ColourGradient::getColourPosition (const int index) const throw()
  60984. {
  60985. return jlimit (0.0, 1.0, colours [index << 1] / 65535.0);
  60986. }
  60987. const Colour ColourGradient::getColour (const int index) const throw()
  60988. {
  60989. return Colour (colours [(index << 1) + 1]);
  60990. }
  60991. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  60992. {
  60993. #ifdef JUCE_DEBUG
  60994. // trying to use the object without setting its co-ordinates? Have a careful read of
  60995. // the comments for the constructors.
  60996. jassert (x1 != 987654.0f);
  60997. #endif
  60998. const int numColours = colours.size() >> 1;
  60999. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  61000. transform.transformPoint (tx1, ty1);
  61001. transform.transformPoint (tx2, ty2);
  61002. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  61003. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  61004. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  61005. if (numColours >= 2)
  61006. {
  61007. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  61008. PixelARGB pix1 (colours.getUnchecked (1));
  61009. pix1.premultiply();
  61010. int index = 0;
  61011. for (int j = 2; j < colours.size(); j += 2)
  61012. {
  61013. const int numToDo = ((colours.getUnchecked (j) * (numEntries - 1)) >> 16) - index;
  61014. PixelARGB pix2 (colours.getUnchecked (j + 1));
  61015. pix2.premultiply();
  61016. for (int i = 0; i < numToDo; ++i)
  61017. {
  61018. jassert (index >= 0 && index < numEntries);
  61019. lookupTable[index] = pix1;
  61020. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  61021. ++index;
  61022. }
  61023. pix1 = pix2;
  61024. }
  61025. while (index < numEntries)
  61026. lookupTable [index++] = pix1;
  61027. }
  61028. else
  61029. {
  61030. jassertfalse // no colours specified!
  61031. }
  61032. return lookupTable;
  61033. }
  61034. bool ColourGradient::isOpaque() const throw()
  61035. {
  61036. for (int i = 1; i < colours.size(); i += 2)
  61037. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  61038. return false;
  61039. return true;
  61040. }
  61041. bool ColourGradient::isInvisible() const throw()
  61042. {
  61043. for (int i = 1; i < colours.size(); i += 2)
  61044. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  61045. return false;
  61046. return true;
  61047. }
  61048. END_JUCE_NAMESPACE
  61049. /********* End of inlined file: juce_ColourGradient.cpp *********/
  61050. /********* Start of inlined file: juce_Colours.cpp *********/
  61051. BEGIN_JUCE_NAMESPACE
  61052. const Colour Colours::transparentBlack (0);
  61053. const Colour Colours::transparentWhite (0x00ffffff);
  61054. const Colour Colours::aliceblue (0xfff0f8ff);
  61055. const Colour Colours::antiquewhite (0xfffaebd7);
  61056. const Colour Colours::aqua (0xff00ffff);
  61057. const Colour Colours::aquamarine (0xff7fffd4);
  61058. const Colour Colours::azure (0xfff0ffff);
  61059. const Colour Colours::beige (0xfff5f5dc);
  61060. const Colour Colours::bisque (0xffffe4c4);
  61061. const Colour Colours::black (0xff000000);
  61062. const Colour Colours::blanchedalmond (0xffffebcd);
  61063. const Colour Colours::blue (0xff0000ff);
  61064. const Colour Colours::blueviolet (0xff8a2be2);
  61065. const Colour Colours::brown (0xffa52a2a);
  61066. const Colour Colours::burlywood (0xffdeb887);
  61067. const Colour Colours::cadetblue (0xff5f9ea0);
  61068. const Colour Colours::chartreuse (0xff7fff00);
  61069. const Colour Colours::chocolate (0xffd2691e);
  61070. const Colour Colours::coral (0xffff7f50);
  61071. const Colour Colours::cornflowerblue (0xff6495ed);
  61072. const Colour Colours::cornsilk (0xfffff8dc);
  61073. const Colour Colours::crimson (0xffdc143c);
  61074. const Colour Colours::cyan (0xff00ffff);
  61075. const Colour Colours::darkblue (0xff00008b);
  61076. const Colour Colours::darkcyan (0xff008b8b);
  61077. const Colour Colours::darkgoldenrod (0xffb8860b);
  61078. const Colour Colours::darkgrey (0xff555555);
  61079. const Colour Colours::darkgreen (0xff006400);
  61080. const Colour Colours::darkkhaki (0xffbdb76b);
  61081. const Colour Colours::darkmagenta (0xff8b008b);
  61082. const Colour Colours::darkolivegreen (0xff556b2f);
  61083. const Colour Colours::darkorange (0xffff8c00);
  61084. const Colour Colours::darkorchid (0xff9932cc);
  61085. const Colour Colours::darkred (0xff8b0000);
  61086. const Colour Colours::darksalmon (0xffe9967a);
  61087. const Colour Colours::darkseagreen (0xff8fbc8f);
  61088. const Colour Colours::darkslateblue (0xff483d8b);
  61089. const Colour Colours::darkslategrey (0xff2f4f4f);
  61090. const Colour Colours::darkturquoise (0xff00ced1);
  61091. const Colour Colours::darkviolet (0xff9400d3);
  61092. const Colour Colours::deeppink (0xffff1493);
  61093. const Colour Colours::deepskyblue (0xff00bfff);
  61094. const Colour Colours::dimgrey (0xff696969);
  61095. const Colour Colours::dodgerblue (0xff1e90ff);
  61096. const Colour Colours::firebrick (0xffb22222);
  61097. const Colour Colours::floralwhite (0xfffffaf0);
  61098. const Colour Colours::forestgreen (0xff228b22);
  61099. const Colour Colours::fuchsia (0xffff00ff);
  61100. const Colour Colours::gainsboro (0xffdcdcdc);
  61101. const Colour Colours::gold (0xffffd700);
  61102. const Colour Colours::goldenrod (0xffdaa520);
  61103. const Colour Colours::grey (0xff808080);
  61104. const Colour Colours::green (0xff008000);
  61105. const Colour Colours::greenyellow (0xffadff2f);
  61106. const Colour Colours::honeydew (0xfff0fff0);
  61107. const Colour Colours::hotpink (0xffff69b4);
  61108. const Colour Colours::indianred (0xffcd5c5c);
  61109. const Colour Colours::indigo (0xff4b0082);
  61110. const Colour Colours::ivory (0xfffffff0);
  61111. const Colour Colours::khaki (0xfff0e68c);
  61112. const Colour Colours::lavender (0xffe6e6fa);
  61113. const Colour Colours::lavenderblush (0xfffff0f5);
  61114. const Colour Colours::lemonchiffon (0xfffffacd);
  61115. const Colour Colours::lightblue (0xffadd8e6);
  61116. const Colour Colours::lightcoral (0xfff08080);
  61117. const Colour Colours::lightcyan (0xffe0ffff);
  61118. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  61119. const Colour Colours::lightgreen (0xff90ee90);
  61120. const Colour Colours::lightgrey (0xffd3d3d3);
  61121. const Colour Colours::lightpink (0xffffb6c1);
  61122. const Colour Colours::lightsalmon (0xffffa07a);
  61123. const Colour Colours::lightseagreen (0xff20b2aa);
  61124. const Colour Colours::lightskyblue (0xff87cefa);
  61125. const Colour Colours::lightslategrey (0xff778899);
  61126. const Colour Colours::lightsteelblue (0xffb0c4de);
  61127. const Colour Colours::lightyellow (0xffffffe0);
  61128. const Colour Colours::lime (0xff00ff00);
  61129. const Colour Colours::limegreen (0xff32cd32);
  61130. const Colour Colours::linen (0xfffaf0e6);
  61131. const Colour Colours::magenta (0xffff00ff);
  61132. const Colour Colours::maroon (0xff800000);
  61133. const Colour Colours::mediumaquamarine (0xff66cdaa);
  61134. const Colour Colours::mediumblue (0xff0000cd);
  61135. const Colour Colours::mediumorchid (0xffba55d3);
  61136. const Colour Colours::mediumpurple (0xff9370db);
  61137. const Colour Colours::mediumseagreen (0xff3cb371);
  61138. const Colour Colours::mediumslateblue (0xff7b68ee);
  61139. const Colour Colours::mediumspringgreen (0xff00fa9a);
  61140. const Colour Colours::mediumturquoise (0xff48d1cc);
  61141. const Colour Colours::mediumvioletred (0xffc71585);
  61142. const Colour Colours::midnightblue (0xff191970);
  61143. const Colour Colours::mintcream (0xfff5fffa);
  61144. const Colour Colours::mistyrose (0xffffe4e1);
  61145. const Colour Colours::navajowhite (0xffffdead);
  61146. const Colour Colours::navy (0xff000080);
  61147. const Colour Colours::oldlace (0xfffdf5e6);
  61148. const Colour Colours::olive (0xff808000);
  61149. const Colour Colours::olivedrab (0xff6b8e23);
  61150. const Colour Colours::orange (0xffffa500);
  61151. const Colour Colours::orangered (0xffff4500);
  61152. const Colour Colours::orchid (0xffda70d6);
  61153. const Colour Colours::palegoldenrod (0xffeee8aa);
  61154. const Colour Colours::palegreen (0xff98fb98);
  61155. const Colour Colours::paleturquoise (0xffafeeee);
  61156. const Colour Colours::palevioletred (0xffdb7093);
  61157. const Colour Colours::papayawhip (0xffffefd5);
  61158. const Colour Colours::peachpuff (0xffffdab9);
  61159. const Colour Colours::peru (0xffcd853f);
  61160. const Colour Colours::pink (0xffffc0cb);
  61161. const Colour Colours::plum (0xffdda0dd);
  61162. const Colour Colours::powderblue (0xffb0e0e6);
  61163. const Colour Colours::purple (0xff800080);
  61164. const Colour Colours::red (0xffff0000);
  61165. const Colour Colours::rosybrown (0xffbc8f8f);
  61166. const Colour Colours::royalblue (0xff4169e1);
  61167. const Colour Colours::saddlebrown (0xff8b4513);
  61168. const Colour Colours::salmon (0xfffa8072);
  61169. const Colour Colours::sandybrown (0xfff4a460);
  61170. const Colour Colours::seagreen (0xff2e8b57);
  61171. const Colour Colours::seashell (0xfffff5ee);
  61172. const Colour Colours::sienna (0xffa0522d);
  61173. const Colour Colours::silver (0xffc0c0c0);
  61174. const Colour Colours::skyblue (0xff87ceeb);
  61175. const Colour Colours::slateblue (0xff6a5acd);
  61176. const Colour Colours::slategrey (0xff708090);
  61177. const Colour Colours::snow (0xfffffafa);
  61178. const Colour Colours::springgreen (0xff00ff7f);
  61179. const Colour Colours::steelblue (0xff4682b4);
  61180. const Colour Colours::tan (0xffd2b48c);
  61181. const Colour Colours::teal (0xff008080);
  61182. const Colour Colours::thistle (0xffd8bfd8);
  61183. const Colour Colours::tomato (0xffff6347);
  61184. const Colour Colours::turquoise (0xff40e0d0);
  61185. const Colour Colours::violet (0xffee82ee);
  61186. const Colour Colours::wheat (0xfff5deb3);
  61187. const Colour Colours::white (0xffffffff);
  61188. const Colour Colours::whitesmoke (0xfff5f5f5);
  61189. const Colour Colours::yellow (0xffffff00);
  61190. const Colour Colours::yellowgreen (0xff9acd32);
  61191. const Colour Colours::findColourForName (const String& colourName,
  61192. const Colour& defaultColour)
  61193. {
  61194. static const int presets[] =
  61195. {
  61196. // (first value is the string's hashcode, second is ARGB)
  61197. 0x05978fff, 0xff000000, /* black */
  61198. 0x06bdcc29, 0xffffffff, /* white */
  61199. 0x002e305a, 0xff0000ff, /* blue */
  61200. 0x00308adf, 0xff808080, /* grey */
  61201. 0x05e0cf03, 0xff008000, /* green */
  61202. 0x0001b891, 0xffff0000, /* red */
  61203. 0xd43c6474, 0xffffff00, /* yellow */
  61204. 0x620886da, 0xfff0f8ff, /* aliceblue */
  61205. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  61206. 0x002dcebc, 0xff00ffff, /* aqua */
  61207. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  61208. 0x0590228f, 0xfff0ffff, /* azure */
  61209. 0x05947fe4, 0xfff5f5dc, /* beige */
  61210. 0xad388e35, 0xffffe4c4, /* bisque */
  61211. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  61212. 0x39129959, 0xff8a2be2, /* blueviolet */
  61213. 0x059a8136, 0xffa52a2a, /* brown */
  61214. 0x89cea8f9, 0xffdeb887, /* burlywood */
  61215. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  61216. 0x6b748956, 0xff7fff00, /* chartreuse */
  61217. 0x2903623c, 0xffd2691e, /* chocolate */
  61218. 0x05a74431, 0xffff7f50, /* coral */
  61219. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  61220. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  61221. 0x3d8c4edf, 0xffdc143c, /* crimson */
  61222. 0x002ed323, 0xff00ffff, /* cyan */
  61223. 0x67cc74d0, 0xff00008b, /* darkblue */
  61224. 0x67cd1799, 0xff008b8b, /* darkcyan */
  61225. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  61226. 0x67cecf55, 0xff555555, /* darkgrey */
  61227. 0x920b194d, 0xff006400, /* darkgreen */
  61228. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  61229. 0x5c293873, 0xff8b008b, /* darkmagenta */
  61230. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  61231. 0xbcfd2524, 0xffff8c00, /* darkorange */
  61232. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  61233. 0x55ee0d5b, 0xff8b0000, /* darkred */
  61234. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  61235. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  61236. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  61237. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  61238. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  61239. 0xc8769375, 0xff9400d3, /* darkviolet */
  61240. 0x25832862, 0xffff1493, /* deeppink */
  61241. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  61242. 0x634c8b67, 0xff696969, /* dimgrey */
  61243. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  61244. 0xef19e3cb, 0xffb22222, /* firebrick */
  61245. 0xb852b195, 0xfffffaf0, /* floralwhite */
  61246. 0xd086fd06, 0xff228b22, /* forestgreen */
  61247. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  61248. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  61249. 0x00308060, 0xffffd700, /* gold */
  61250. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  61251. 0xbab8a537, 0xffadff2f, /* greenyellow */
  61252. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  61253. 0x41892743, 0xffff69b4, /* hotpink */
  61254. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  61255. 0xb969fed2, 0xff4b0082, /* indigo */
  61256. 0x05fef6a9, 0xfffffff0, /* ivory */
  61257. 0x06149302, 0xfff0e68c, /* khaki */
  61258. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  61259. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  61260. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  61261. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  61262. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  61263. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  61264. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  61265. 0xf40157ad, 0xff90ee90, /* lightgreen */
  61266. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  61267. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  61268. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  61269. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  61270. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  61271. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  61272. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  61273. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  61274. 0x0032afd5, 0xff00ff00, /* lime */
  61275. 0x607bbc4e, 0xff32cd32, /* limegreen */
  61276. 0x06234efa, 0xfffaf0e6, /* linen */
  61277. 0x316858a9, 0xffff00ff, /* magenta */
  61278. 0xbf8ca470, 0xff800000, /* maroon */
  61279. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  61280. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  61281. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  61282. 0x07556b71, 0xff9370db, /* mediumpurple */
  61283. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  61284. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  61285. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  61286. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  61287. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  61288. 0x168eb32a, 0xff191970, /* midnightblue */
  61289. 0x4306b960, 0xfff5fffa, /* mintcream */
  61290. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  61291. 0xe97218a6, 0xffffdead, /* navajowhite */
  61292. 0x00337bb6, 0xff000080, /* navy */
  61293. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  61294. 0x064ee1db, 0xff808000, /* olive */
  61295. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  61296. 0xc3de262e, 0xffffa500, /* orange */
  61297. 0x58bebba3, 0xffff4500, /* orangered */
  61298. 0xc3def8a3, 0xffda70d6, /* orchid */
  61299. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  61300. 0x3d9dd619, 0xff98fb98, /* palegreen */
  61301. 0x74022737, 0xffafeeee, /* paleturquoise */
  61302. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  61303. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  61304. 0x93e1b776, 0xffffdab9, /* peachpuff */
  61305. 0x003472f8, 0xffcd853f, /* peru */
  61306. 0x00348176, 0xffffc0cb, /* pink */
  61307. 0x00348d94, 0xffdda0dd, /* plum */
  61308. 0xd036be93, 0xffb0e0e6, /* powderblue */
  61309. 0xc5c507bc, 0xff800080, /* purple */
  61310. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  61311. 0xbd9413e1, 0xff4169e1, /* royalblue */
  61312. 0xf456044f, 0xff8b4513, /* saddlebrown */
  61313. 0xc9c6f66e, 0xfffa8072, /* salmon */
  61314. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  61315. 0x34636c14, 0xff2e8b57, /* seagreen */
  61316. 0x3507fb41, 0xfffff5ee, /* seashell */
  61317. 0xca348772, 0xffa0522d, /* sienna */
  61318. 0xca37d30d, 0xffc0c0c0, /* silver */
  61319. 0x80da74fb, 0xff87ceeb, /* skyblue */
  61320. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  61321. 0x44ab37f8, 0xff708090, /* slategrey */
  61322. 0x0035f183, 0xfffffafa, /* snow */
  61323. 0xd5440d16, 0xff00ff7f, /* springgreen */
  61324. 0x3e1524a5, 0xff4682b4, /* steelblue */
  61325. 0x0001bfa1, 0xffd2b48c, /* tan */
  61326. 0x0036425c, 0xff008080, /* teal */
  61327. 0xafc8858f, 0xffd8bfd8, /* thistle */
  61328. 0xcc41600a, 0xffff6347, /* tomato */
  61329. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  61330. 0xcf57947f, 0xffee82ee, /* violet */
  61331. 0x06bdbae7, 0xfff5deb3, /* wheat */
  61332. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  61333. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  61334. };
  61335. const int hash = colourName.trim().toLowerCase().hashCode();
  61336. for (int i = 0; i < numElementsInArray (presets); i += 2)
  61337. if (presets [i] == hash)
  61338. return Colour (presets [i + 1]);
  61339. return defaultColour;
  61340. }
  61341. END_JUCE_NAMESPACE
  61342. /********* End of inlined file: juce_Colours.cpp *********/
  61343. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  61344. BEGIN_JUCE_NAMESPACE
  61345. EdgeTable::EdgeTable (const int top_,
  61346. const int height_,
  61347. const OversamplingLevel oversampling_,
  61348. const int expectedEdgesPerLine) throw()
  61349. : top (top_),
  61350. height (height_),
  61351. maxEdgesPerLine (expectedEdgesPerLine),
  61352. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  61353. oversampling (oversampling_)
  61354. {
  61355. table = (int*) juce_calloc ((height << (int)oversampling_)
  61356. * lineStrideElements * sizeof (int));
  61357. }
  61358. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  61359. : table (0)
  61360. {
  61361. operator= (other);
  61362. }
  61363. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  61364. {
  61365. juce_free (table);
  61366. top = other.top;
  61367. height = other.height;
  61368. maxEdgesPerLine = other.maxEdgesPerLine;
  61369. lineStrideElements = other.lineStrideElements;
  61370. oversampling = other.oversampling;
  61371. const int tableSize = (height << (int)oversampling)
  61372. * lineStrideElements * sizeof (int);
  61373. table = (int*) juce_malloc (tableSize);
  61374. memcpy (table, other.table, tableSize);
  61375. return *this;
  61376. }
  61377. EdgeTable::~EdgeTable() throw()
  61378. {
  61379. juce_free (table);
  61380. }
  61381. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  61382. {
  61383. if (newNumEdgesPerLine != maxEdgesPerLine)
  61384. {
  61385. maxEdgesPerLine = newNumEdgesPerLine;
  61386. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  61387. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  61388. * newLineStrideElements * sizeof (int));
  61389. for (int i = 0; i < (height << (int) oversampling); ++i)
  61390. {
  61391. const int* srcLine = table + lineStrideElements * i;
  61392. int* dstLine = newTable + newLineStrideElements * i;
  61393. int num = *srcLine++;
  61394. *dstLine++ = num;
  61395. num <<= 1;
  61396. while (--num >= 0)
  61397. *dstLine++ = *srcLine++;
  61398. }
  61399. juce_free (table);
  61400. table = newTable;
  61401. lineStrideElements = newLineStrideElements;
  61402. }
  61403. }
  61404. void EdgeTable::optimiseTable() throw()
  61405. {
  61406. int maxLineElements = 0;
  61407. for (int i = height; --i >= 0;)
  61408. maxLineElements = jmax (maxLineElements,
  61409. table [i * lineStrideElements]);
  61410. remapTableForNumEdges (maxLineElements);
  61411. }
  61412. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  61413. {
  61414. jassert (y >= 0 && y < (height << oversampling))
  61415. int* lineStart = table + lineStrideElements * y;
  61416. int n = lineStart[0];
  61417. if (n >= maxEdgesPerLine)
  61418. {
  61419. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  61420. jassert (n < maxEdgesPerLine);
  61421. lineStart = table + lineStrideElements * y;
  61422. }
  61423. n <<= 1;
  61424. int* const line = lineStart + 1;
  61425. while (n > 0)
  61426. {
  61427. const int cx = line [n - 2];
  61428. if (cx <= x)
  61429. break;
  61430. line [n] = cx;
  61431. line [n + 1] = line [n - 1];
  61432. n -= 2;
  61433. }
  61434. line [n] = x;
  61435. line [n + 1] = winding;
  61436. lineStart[0]++;
  61437. }
  61438. void EdgeTable::addPath (const Path& path,
  61439. const AffineTransform& transform) throw()
  61440. {
  61441. const int windingAmount = 256 / (1 << (int) oversampling);
  61442. const float timesOversampling = (float) (1 << (int) oversampling);
  61443. const int bottomLimit = (height << (int) oversampling);
  61444. PathFlatteningIterator iter (path, transform);
  61445. while (iter.next())
  61446. {
  61447. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  61448. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  61449. if (y1 != y2)
  61450. {
  61451. const double x1 = 256.0 * iter.x1;
  61452. const double x2 = 256.0 * iter.x2;
  61453. const double multiplier = (x2 - x1) / (y2 - y1);
  61454. const int oldY1 = y1;
  61455. int winding;
  61456. if (y1 > y2)
  61457. {
  61458. swapVariables (y1, y2);
  61459. winding = windingAmount;
  61460. }
  61461. else
  61462. {
  61463. winding = -windingAmount;
  61464. }
  61465. jassert (y1 < y2);
  61466. if (y1 < 0)
  61467. y1 = 0;
  61468. if (y2 > bottomLimit)
  61469. y2 = bottomLimit;
  61470. while (y1 < y2)
  61471. {
  61472. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  61473. y1,
  61474. winding);
  61475. ++y1;
  61476. }
  61477. }
  61478. }
  61479. if (! path.isUsingNonZeroWinding())
  61480. {
  61481. // if it's an alternate-winding path, we need to go through and
  61482. // make sure all the windings are alternating.
  61483. int* lineStart = table;
  61484. for (int i = height << (int) oversampling; --i >= 0;)
  61485. {
  61486. int* line = lineStart;
  61487. lineStart += lineStrideElements;
  61488. int num = *line;
  61489. while (--num >= 0)
  61490. {
  61491. line += 2;
  61492. *line = abs (*line);
  61493. if (--num >= 0)
  61494. {
  61495. line += 2;
  61496. *line = -abs (*line);
  61497. }
  61498. }
  61499. }
  61500. }
  61501. }
  61502. END_JUCE_NAMESPACE
  61503. /********* End of inlined file: juce_EdgeTable.cpp *********/
  61504. /********* Start of inlined file: juce_Graphics.cpp *********/
  61505. BEGIN_JUCE_NAMESPACE
  61506. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  61507. #define MINIMUM_COORD -0x3fffffff
  61508. #define MAXIMUM_COORD 0x3fffffff
  61509. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61510. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61511. jassert ((int) x >= MINIMUM_COORD \
  61512. && (int) x <= MAXIMUM_COORD \
  61513. && (int) y >= MINIMUM_COORD \
  61514. && (int) y <= MAXIMUM_COORD \
  61515. && (int) w >= MINIMUM_COORD \
  61516. && (int) w <= MAXIMUM_COORD \
  61517. && (int) h >= MINIMUM_COORD \
  61518. && (int) h <= MAXIMUM_COORD);
  61519. LowLevelGraphicsContext::LowLevelGraphicsContext()
  61520. {
  61521. }
  61522. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  61523. {
  61524. }
  61525. Graphics::Graphics (Image& imageToDrawOnto) throw()
  61526. : context (imageToDrawOnto.createLowLevelContext()),
  61527. ownsContext (true),
  61528. state (new GraphicsState()),
  61529. saveStatePending (false)
  61530. {
  61531. }
  61532. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  61533. : context (internalContext),
  61534. ownsContext (false),
  61535. state (new GraphicsState()),
  61536. saveStatePending (false)
  61537. {
  61538. }
  61539. Graphics::~Graphics() throw()
  61540. {
  61541. delete state;
  61542. if (ownsContext)
  61543. delete context;
  61544. }
  61545. void Graphics::resetToDefaultState() throw()
  61546. {
  61547. setColour (Colours::black);
  61548. state->font.resetToDefaultState();
  61549. state->quality = defaultQuality;
  61550. }
  61551. bool Graphics::isVectorDevice() const throw()
  61552. {
  61553. return context->isVectorDevice();
  61554. }
  61555. bool Graphics::reduceClipRegion (const int x, const int y,
  61556. const int w, const int h) throw()
  61557. {
  61558. saveStateIfPending();
  61559. return context->reduceClipRegion (x, y, w, h);
  61560. }
  61561. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  61562. {
  61563. saveStateIfPending();
  61564. return context->reduceClipRegion (clipRegion);
  61565. }
  61566. void Graphics::excludeClipRegion (const int x, const int y,
  61567. const int w, const int h) throw()
  61568. {
  61569. saveStateIfPending();
  61570. context->excludeClipRegion (x, y, w, h);
  61571. }
  61572. bool Graphics::isClipEmpty() const throw()
  61573. {
  61574. return context->isClipEmpty();
  61575. }
  61576. const Rectangle Graphics::getClipBounds() const throw()
  61577. {
  61578. return context->getClipBounds();
  61579. }
  61580. void Graphics::saveState() throw()
  61581. {
  61582. saveStateIfPending();
  61583. saveStatePending = true;
  61584. }
  61585. void Graphics::restoreState() throw()
  61586. {
  61587. if (saveStatePending)
  61588. {
  61589. saveStatePending = false;
  61590. }
  61591. else
  61592. {
  61593. const int stackSize = stateStack.size();
  61594. if (stackSize > 0)
  61595. {
  61596. context->restoreState();
  61597. delete state;
  61598. state = stateStack.getUnchecked (stackSize - 1);
  61599. stateStack.removeLast (1, false);
  61600. }
  61601. else
  61602. {
  61603. // Trying to call restoreState() more times than you've called saveState() !
  61604. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  61605. jassertfalse
  61606. }
  61607. }
  61608. }
  61609. void Graphics::saveStateIfPending() throw()
  61610. {
  61611. if (saveStatePending)
  61612. {
  61613. saveStatePending = false;
  61614. context->saveState();
  61615. stateStack.add (new GraphicsState (*state));
  61616. }
  61617. }
  61618. void Graphics::setOrigin (const int newOriginX,
  61619. const int newOriginY) throw()
  61620. {
  61621. saveStateIfPending();
  61622. context->setOrigin (newOriginX, newOriginY);
  61623. }
  61624. bool Graphics::clipRegionIntersects (const int x, const int y,
  61625. const int w, const int h) const throw()
  61626. {
  61627. return context->clipRegionIntersects (x, y, w, h);
  61628. }
  61629. void Graphics::setColour (const Colour& newColour) throw()
  61630. {
  61631. saveStateIfPending();
  61632. state->colour = newColour;
  61633. deleteAndZero (state->brush);
  61634. }
  61635. const Colour& Graphics::getCurrentColour() const throw()
  61636. {
  61637. return state->colour;
  61638. }
  61639. void Graphics::setOpacity (const float newOpacity) throw()
  61640. {
  61641. saveStateIfPending();
  61642. state->colour = state->colour.withAlpha (newOpacity);
  61643. }
  61644. void Graphics::setBrush (const Brush* const newBrush) throw()
  61645. {
  61646. saveStateIfPending();
  61647. delete state->brush;
  61648. if (newBrush != 0)
  61649. state->brush = newBrush->createCopy();
  61650. else
  61651. state->brush = 0;
  61652. }
  61653. Graphics::GraphicsState::GraphicsState() throw()
  61654. : colour (Colours::black),
  61655. brush (0),
  61656. quality (defaultQuality)
  61657. {
  61658. }
  61659. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  61660. : colour (other.colour),
  61661. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  61662. font (other.font),
  61663. quality (other.quality)
  61664. {
  61665. }
  61666. Graphics::GraphicsState::~GraphicsState() throw()
  61667. {
  61668. delete brush;
  61669. }
  61670. void Graphics::setFont (const Font& newFont) throw()
  61671. {
  61672. saveStateIfPending();
  61673. state->font = newFont;
  61674. }
  61675. void Graphics::setFont (const float newFontHeight,
  61676. const int newFontStyleFlags) throw()
  61677. {
  61678. saveStateIfPending();
  61679. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  61680. }
  61681. const Font& Graphics::getCurrentFont() const throw()
  61682. {
  61683. return state->font;
  61684. }
  61685. void Graphics::drawSingleLineText (const String& text,
  61686. const int startX,
  61687. const int baselineY) const throw()
  61688. {
  61689. if (text.isNotEmpty()
  61690. && startX < context->getClipBounds().getRight())
  61691. {
  61692. GlyphArrangement arr;
  61693. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  61694. arr.draw (*this);
  61695. }
  61696. }
  61697. void Graphics::drawTextAsPath (const String& text,
  61698. const AffineTransform& transform) const throw()
  61699. {
  61700. if (text.isNotEmpty())
  61701. {
  61702. GlyphArrangement arr;
  61703. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  61704. arr.draw (*this, transform);
  61705. }
  61706. }
  61707. void Graphics::drawMultiLineText (const String& text,
  61708. const int startX,
  61709. const int baselineY,
  61710. const int maximumLineWidth) const throw()
  61711. {
  61712. if (text.isNotEmpty()
  61713. && startX < context->getClipBounds().getRight())
  61714. {
  61715. GlyphArrangement arr;
  61716. arr.addJustifiedText (state->font, text,
  61717. (float) startX, (float) baselineY, (float) maximumLineWidth,
  61718. Justification::left);
  61719. arr.draw (*this);
  61720. }
  61721. }
  61722. void Graphics::drawText (const String& text,
  61723. const int x,
  61724. const int y,
  61725. const int width,
  61726. const int height,
  61727. const Justification& justificationType,
  61728. const bool useEllipsesIfTooBig) const throw()
  61729. {
  61730. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  61731. {
  61732. GlyphArrangement arr;
  61733. arr.addCurtailedLineOfText (state->font, text,
  61734. 0.0f, 0.0f, (float)width,
  61735. useEllipsesIfTooBig);
  61736. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  61737. (float) x, (float) y,
  61738. (float) width, (float) height,
  61739. justificationType);
  61740. arr.draw (*this);
  61741. }
  61742. }
  61743. void Graphics::drawFittedText (const String& text,
  61744. const int x,
  61745. const int y,
  61746. const int width,
  61747. const int height,
  61748. const Justification& justification,
  61749. const int maximumNumberOfLines,
  61750. const float minimumHorizontalScale) const throw()
  61751. {
  61752. if (text.isNotEmpty()
  61753. && width > 0 && height > 0
  61754. && context->clipRegionIntersects (x, y, width, height))
  61755. {
  61756. GlyphArrangement arr;
  61757. arr.addFittedText (state->font, text,
  61758. (float) x, (float) y,
  61759. (float) width, (float) height,
  61760. justification,
  61761. maximumNumberOfLines,
  61762. minimumHorizontalScale);
  61763. arr.draw (*this);
  61764. }
  61765. }
  61766. void Graphics::fillRect (int x,
  61767. int y,
  61768. int width,
  61769. int height) const throw()
  61770. {
  61771. // passing in a silly number can cause maths problems in rendering!
  61772. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61773. SolidColourBrush colourBrush (state->colour);
  61774. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  61775. }
  61776. void Graphics::fillRect (const Rectangle& r) const throw()
  61777. {
  61778. fillRect (r.getX(),
  61779. r.getY(),
  61780. r.getWidth(),
  61781. r.getHeight());
  61782. }
  61783. void Graphics::fillRect (const float x,
  61784. const float y,
  61785. const float width,
  61786. const float height) const throw()
  61787. {
  61788. // passing in a silly number can cause maths problems in rendering!
  61789. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61790. Path p;
  61791. p.addRectangle (x, y, width, height);
  61792. fillPath (p);
  61793. }
  61794. void Graphics::setPixel (int x, int y) const throw()
  61795. {
  61796. if (context->clipRegionIntersects (x, y, 1, 1))
  61797. {
  61798. SolidColourBrush colourBrush (state->colour);
  61799. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  61800. }
  61801. }
  61802. void Graphics::fillAll() const throw()
  61803. {
  61804. fillRect (context->getClipBounds());
  61805. }
  61806. void Graphics::fillAll (const Colour& colourToUse) const throw()
  61807. {
  61808. if (! colourToUse.isTransparent())
  61809. {
  61810. const Rectangle clip (context->getClipBounds());
  61811. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  61812. colourToUse, false);
  61813. }
  61814. }
  61815. void Graphics::fillPath (const Path& path,
  61816. const AffineTransform& transform) const throw()
  61817. {
  61818. if ((! context->isClipEmpty()) && ! path.isEmpty())
  61819. {
  61820. SolidColourBrush colourBrush (state->colour);
  61821. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  61822. }
  61823. }
  61824. void Graphics::strokePath (const Path& path,
  61825. const PathStrokeType& strokeType,
  61826. const AffineTransform& transform) const throw()
  61827. {
  61828. if ((! state->colour.isTransparent()) || state->brush != 0)
  61829. {
  61830. Path stroke;
  61831. strokeType.createStrokedPath (stroke, path, transform);
  61832. fillPath (stroke);
  61833. }
  61834. }
  61835. void Graphics::drawRect (const int x,
  61836. const int y,
  61837. const int width,
  61838. const int height,
  61839. const int lineThickness) const throw()
  61840. {
  61841. // passing in a silly number can cause maths problems in rendering!
  61842. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61843. SolidColourBrush colourBrush (state->colour);
  61844. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  61845. b.paintRectangle (*context, x, y, width, lineThickness);
  61846. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  61847. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  61848. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  61849. }
  61850. void Graphics::drawRect (const float x,
  61851. const float y,
  61852. const float width,
  61853. const float height,
  61854. const float lineThickness) const throw()
  61855. {
  61856. // passing in a silly number can cause maths problems in rendering!
  61857. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61858. Path p;
  61859. p.addRectangle (x, y, width, lineThickness);
  61860. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61861. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  61862. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  61863. fillPath (p);
  61864. }
  61865. void Graphics::drawRect (const Rectangle& r,
  61866. const int lineThickness) const throw()
  61867. {
  61868. drawRect (r.getX(), r.getY(),
  61869. r.getWidth(), r.getHeight(),
  61870. lineThickness);
  61871. }
  61872. void Graphics::drawBevel (const int x,
  61873. const int y,
  61874. const int width,
  61875. const int height,
  61876. const int bevelThickness,
  61877. const Colour& topLeftColour,
  61878. const Colour& bottomRightColour,
  61879. const bool useGradient,
  61880. const bool sharpEdgeOnOutside) const throw()
  61881. {
  61882. // passing in a silly number can cause maths problems in rendering!
  61883. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61884. if (clipRegionIntersects (x, y, width, height))
  61885. {
  61886. const float oldOpacity = state->colour.getFloatAlpha();
  61887. const float ramp = oldOpacity / bevelThickness;
  61888. for (int i = bevelThickness; --i >= 0;)
  61889. {
  61890. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  61891. : oldOpacity;
  61892. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  61893. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  61894. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  61895. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  61896. }
  61897. }
  61898. }
  61899. void Graphics::fillEllipse (const float x,
  61900. const float y,
  61901. const float width,
  61902. const float height) const throw()
  61903. {
  61904. // passing in a silly number can cause maths problems in rendering!
  61905. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61906. Path p;
  61907. p.addEllipse (x, y, width, height);
  61908. fillPath (p);
  61909. }
  61910. void Graphics::drawEllipse (const float x,
  61911. const float y,
  61912. const float width,
  61913. const float height,
  61914. const float lineThickness) const throw()
  61915. {
  61916. // passing in a silly number can cause maths problems in rendering!
  61917. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61918. Path p;
  61919. p.addEllipse (x, y, width, height);
  61920. strokePath (p, PathStrokeType (lineThickness));
  61921. }
  61922. void Graphics::fillRoundedRectangle (const float x,
  61923. const float y,
  61924. const float width,
  61925. const float height,
  61926. const float cornerSize) 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.addRoundedRectangle (x, y, width, height, cornerSize);
  61932. fillPath (p);
  61933. }
  61934. void Graphics::fillRoundedRectangle (const Rectangle& r,
  61935. const float cornerSize) const throw()
  61936. {
  61937. fillRoundedRectangle ((float) r.getX(),
  61938. (float) r.getY(),
  61939. (float) r.getWidth(),
  61940. (float) r.getHeight(),
  61941. cornerSize);
  61942. }
  61943. void Graphics::drawRoundedRectangle (const float x,
  61944. const float y,
  61945. const float width,
  61946. const float height,
  61947. const float cornerSize,
  61948. const float lineThickness) const throw()
  61949. {
  61950. // passing in a silly number can cause maths problems in rendering!
  61951. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  61952. Path p;
  61953. p.addRoundedRectangle (x, y, width, height, cornerSize);
  61954. strokePath (p, PathStrokeType (lineThickness));
  61955. }
  61956. void Graphics::drawRoundedRectangle (const Rectangle& r,
  61957. const float cornerSize,
  61958. const float lineThickness) const throw()
  61959. {
  61960. drawRoundedRectangle ((float) r.getX(),
  61961. (float) r.getY(),
  61962. (float) r.getWidth(),
  61963. (float) r.getHeight(),
  61964. cornerSize, lineThickness);
  61965. }
  61966. void Graphics::drawArrow (const float startX,
  61967. const float startY,
  61968. const float endX,
  61969. const float endY,
  61970. const float lineThickness,
  61971. const float arrowheadWidth,
  61972. const float arrowheadLength) const throw()
  61973. {
  61974. Path p;
  61975. p.addArrow (startX, startY, endX, endY,
  61976. lineThickness, arrowheadWidth, arrowheadLength);
  61977. fillPath (p);
  61978. }
  61979. void Graphics::fillCheckerBoard (int x, int y,
  61980. int width, int height,
  61981. const int checkWidth,
  61982. const int checkHeight,
  61983. const Colour& colour1,
  61984. const Colour& colour2) const throw()
  61985. {
  61986. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  61987. if (checkWidth > 0 && checkHeight > 0)
  61988. {
  61989. if (colour1 == colour2)
  61990. {
  61991. context->fillRectWithColour (x, y, width, height, colour1, false);
  61992. }
  61993. else
  61994. {
  61995. const Rectangle clip (context->getClipBounds());
  61996. const int right = jmin (x + width, clip.getRight());
  61997. const int bottom = jmin (y + height, clip.getBottom());
  61998. int cy = 0;
  61999. while (y < bottom)
  62000. {
  62001. int cx = cy;
  62002. for (int xx = x; xx < right; xx += checkWidth)
  62003. context->fillRectWithColour (xx, y,
  62004. jmin (checkWidth, right - xx),
  62005. jmin (checkHeight, bottom - y),
  62006. ((cx++ & 1) == 0) ? colour1 : colour2,
  62007. false);
  62008. ++cy;
  62009. y += checkHeight;
  62010. }
  62011. }
  62012. }
  62013. }
  62014. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  62015. {
  62016. SolidColourBrush colourBrush (state->colour);
  62017. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  62018. }
  62019. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  62020. {
  62021. SolidColourBrush colourBrush (state->colour);
  62022. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  62023. }
  62024. void Graphics::drawLine (float x1, float y1,
  62025. float x2, float y2) const throw()
  62026. {
  62027. if (! context->isClipEmpty())
  62028. {
  62029. SolidColourBrush colourBrush (state->colour);
  62030. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  62031. }
  62032. }
  62033. void Graphics::drawLine (const float startX,
  62034. const float startY,
  62035. const float endX,
  62036. const float endY,
  62037. const float lineThickness) const throw()
  62038. {
  62039. Path p;
  62040. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  62041. fillPath (p);
  62042. }
  62043. void Graphics::drawLine (const Line& line) const throw()
  62044. {
  62045. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  62046. }
  62047. void Graphics::drawLine (const Line& line,
  62048. const float lineThickness) const throw()
  62049. {
  62050. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  62051. }
  62052. void Graphics::drawDashedLine (const float startX,
  62053. const float startY,
  62054. const float endX,
  62055. const float endY,
  62056. const float* const dashLengths,
  62057. const int numDashLengths,
  62058. const float lineThickness) const throw()
  62059. {
  62060. const double dx = endX - startX;
  62061. const double dy = endY - startY;
  62062. const double totalLen = juce_hypot (dx, dy);
  62063. if (totalLen >= 0.5)
  62064. {
  62065. const double onePixAlpha = 1.0 / totalLen;
  62066. double alpha = 0.0;
  62067. float x = startX;
  62068. float y = startY;
  62069. int n = 0;
  62070. while (alpha < 1.0f)
  62071. {
  62072. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  62073. n = n % numDashLengths;
  62074. const float oldX = x;
  62075. const float oldY = y;
  62076. x = (float) (startX + dx * alpha);
  62077. y = (float) (startY + dy * alpha);
  62078. if ((n & 1) != 0)
  62079. {
  62080. if (lineThickness != 1.0f)
  62081. drawLine (oldX, oldY, x, y, lineThickness);
  62082. else
  62083. drawLine (oldX, oldY, x, y);
  62084. }
  62085. }
  62086. }
  62087. }
  62088. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  62089. {
  62090. saveStateIfPending();
  62091. state->quality = newQuality;
  62092. }
  62093. void Graphics::drawImageAt (const Image* const imageToDraw,
  62094. const int topLeftX,
  62095. const int topLeftY,
  62096. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62097. {
  62098. if (imageToDraw != 0)
  62099. {
  62100. const int imageW = imageToDraw->getWidth();
  62101. const int imageH = imageToDraw->getHeight();
  62102. drawImage (imageToDraw,
  62103. topLeftX, topLeftY, imageW, imageH,
  62104. 0, 0, imageW, imageH,
  62105. fillAlphaChannelWithCurrentBrush);
  62106. }
  62107. }
  62108. void Graphics::drawImageWithin (const Image* const imageToDraw,
  62109. const int destX,
  62110. const int destY,
  62111. const int destW,
  62112. const int destH,
  62113. const RectanglePlacement& placementWithinTarget,
  62114. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62115. {
  62116. // passing in a silly number can cause maths problems in rendering!
  62117. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  62118. if (imageToDraw != 0)
  62119. {
  62120. const int imageW = imageToDraw->getWidth();
  62121. const int imageH = imageToDraw->getHeight();
  62122. if (imageW > 0 && imageH > 0)
  62123. {
  62124. double newX = 0.0, newY = 0.0;
  62125. double newW = imageW;
  62126. double newH = imageH;
  62127. placementWithinTarget.applyTo (newX, newY, newW, newH,
  62128. destX, destY, destW, destH);
  62129. if (newW > 0 && newH > 0)
  62130. {
  62131. drawImage (imageToDraw,
  62132. roundDoubleToInt (newX), roundDoubleToInt (newY),
  62133. roundDoubleToInt (newW), roundDoubleToInt (newH),
  62134. 0, 0, imageW, imageH,
  62135. fillAlphaChannelWithCurrentBrush);
  62136. }
  62137. }
  62138. }
  62139. }
  62140. void Graphics::drawImage (const Image* const imageToDraw,
  62141. int dx, int dy, int dw, int dh,
  62142. int sx, int sy, int sw, int sh,
  62143. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62144. {
  62145. // passing in a silly number can cause maths problems in rendering!
  62146. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  62147. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  62148. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  62149. return;
  62150. if (sw == dw && sh == dh)
  62151. {
  62152. if (sx < 0)
  62153. {
  62154. dx -= sx;
  62155. dw += sx;
  62156. sw += sx;
  62157. sx = 0;
  62158. }
  62159. if (sx + sw > imageToDraw->getWidth())
  62160. {
  62161. const int amount = sx + sw - imageToDraw->getWidth();
  62162. dw -= amount;
  62163. sw -= amount;
  62164. }
  62165. if (sy < 0)
  62166. {
  62167. dy -= sy;
  62168. dh += sy;
  62169. sh += sy;
  62170. sy = 0;
  62171. }
  62172. if (sy + sh > imageToDraw->getHeight())
  62173. {
  62174. const int amount = sy + sh - imageToDraw->getHeight();
  62175. dh -= amount;
  62176. sh -= amount;
  62177. }
  62178. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62179. return;
  62180. if (fillAlphaChannelWithCurrentBrush)
  62181. {
  62182. SolidColourBrush colourBrush (state->colour);
  62183. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62184. .paintAlphaChannel (*context, *imageToDraw,
  62185. dx - sx, dy - sy,
  62186. dx, dy,
  62187. dw, dh);
  62188. }
  62189. else
  62190. {
  62191. context->blendImage (*imageToDraw,
  62192. dx, dy, dw, dh, sx, sy,
  62193. state->colour.getFloatAlpha());
  62194. }
  62195. }
  62196. else
  62197. {
  62198. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  62199. return;
  62200. if (fillAlphaChannelWithCurrentBrush)
  62201. {
  62202. if (imageToDraw->isRGB())
  62203. {
  62204. fillRect (dx, dy, dw, dh);
  62205. }
  62206. else
  62207. {
  62208. int tx = dx;
  62209. int ty = dy;
  62210. int tw = dw;
  62211. int th = dh;
  62212. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62213. {
  62214. Image temp (imageToDraw->getFormat(), tw, th, true);
  62215. Graphics g (temp);
  62216. g.setImageResamplingQuality (state->quality);
  62217. g.setOrigin (dx - tx, dy - ty);
  62218. g.drawImage (imageToDraw,
  62219. 0, 0, dw, dh,
  62220. sx, sy, sw, sh,
  62221. false);
  62222. SolidColourBrush colourBrush (state->colour);
  62223. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  62224. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62225. }
  62226. }
  62227. }
  62228. else
  62229. {
  62230. context->blendImageRescaling (*imageToDraw,
  62231. dx, dy, dw, dh,
  62232. sx, sy, sw, sh,
  62233. state->colour.getFloatAlpha(),
  62234. state->quality);
  62235. }
  62236. }
  62237. }
  62238. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  62239. int sourceClipX,
  62240. int sourceClipY,
  62241. int sourceClipWidth,
  62242. int sourceClipHeight,
  62243. const AffineTransform& transform,
  62244. const bool fillAlphaChannelWithCurrentBrush) const throw()
  62245. {
  62246. if (imageToDraw != 0
  62247. && (! context->isClipEmpty())
  62248. && ! transform.isSingularity())
  62249. {
  62250. if (transform.isIdentity())
  62251. {
  62252. drawImage (imageToDraw,
  62253. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62254. sourceClipX, sourceClipY, sourceClipWidth, sourceClipHeight,
  62255. fillAlphaChannelWithCurrentBrush);
  62256. }
  62257. else if (fillAlphaChannelWithCurrentBrush)
  62258. {
  62259. Path p;
  62260. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  62261. (float) sourceClipWidth, (float) sourceClipHeight);
  62262. p.applyTransform (transform);
  62263. float dx, dy, dw, dh;
  62264. p.getBounds (dx, dy, dw, dh);
  62265. int tx = (int) dx;
  62266. int ty = (int) dy;
  62267. int tw = roundFloatToInt (dw) + 2;
  62268. int th = roundFloatToInt (dh) + 2;
  62269. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  62270. {
  62271. Image temp (imageToDraw->getFormat(), tw, th, true);
  62272. Graphics g (temp);
  62273. g.setImageResamplingQuality (state->quality);
  62274. g.drawImageTransformed (imageToDraw,
  62275. sourceClipX,
  62276. sourceClipY,
  62277. sourceClipWidth,
  62278. sourceClipHeight,
  62279. transform.translated ((float) -tx, (float) -ty),
  62280. false);
  62281. SolidColourBrush colourBrush (state->colour);
  62282. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  62283. }
  62284. }
  62285. else
  62286. {
  62287. context->blendImageWarping (*imageToDraw,
  62288. sourceClipX,
  62289. sourceClipY,
  62290. sourceClipWidth,
  62291. sourceClipHeight,
  62292. transform,
  62293. state->colour.getFloatAlpha(),
  62294. state->quality);
  62295. }
  62296. }
  62297. }
  62298. END_JUCE_NAMESPACE
  62299. /********* End of inlined file: juce_Graphics.cpp *********/
  62300. /********* Start of inlined file: juce_Justification.cpp *********/
  62301. BEGIN_JUCE_NAMESPACE
  62302. Justification::Justification (const Justification& other) throw()
  62303. : flags (other.flags)
  62304. {
  62305. }
  62306. const Justification& Justification::operator= (const Justification& other) throw()
  62307. {
  62308. flags = other.flags;
  62309. return *this;
  62310. }
  62311. int Justification::getOnlyVerticalFlags() const throw()
  62312. {
  62313. return flags & (top | bottom | verticallyCentred);
  62314. }
  62315. int Justification::getOnlyHorizontalFlags() const throw()
  62316. {
  62317. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  62318. }
  62319. void Justification::applyToRectangle (int& x, int& y,
  62320. const int w, const int h,
  62321. const int spaceX, const int spaceY,
  62322. const int spaceW, const int spaceH) const throw()
  62323. {
  62324. if ((flags & horizontallyCentred) != 0)
  62325. {
  62326. x = spaceX + ((spaceW - w) >> 1);
  62327. }
  62328. else if ((flags & right) != 0)
  62329. {
  62330. x = spaceX + spaceW - w;
  62331. }
  62332. else
  62333. {
  62334. x = spaceX;
  62335. }
  62336. if ((flags & verticallyCentred) != 0)
  62337. {
  62338. y = spaceY + ((spaceH - h) >> 1);
  62339. }
  62340. else if ((flags & bottom) != 0)
  62341. {
  62342. y = spaceY + spaceH - h;
  62343. }
  62344. else
  62345. {
  62346. y = spaceY;
  62347. }
  62348. }
  62349. END_JUCE_NAMESPACE
  62350. /********* End of inlined file: juce_Justification.cpp *********/
  62351. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62352. BEGIN_JUCE_NAMESPACE
  62353. #if JUCE_MSVC
  62354. #pragma warning (disable: 4996) // deprecated sprintf warning
  62355. #endif
  62356. // this will throw an assertion if you try to draw something that's not
  62357. // possible in postscript
  62358. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  62359. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  62360. #define notPossibleInPostscriptAssert jassertfalse
  62361. #else
  62362. #define notPossibleInPostscriptAssert
  62363. #endif
  62364. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  62365. const String& documentTitle,
  62366. const int totalWidth_,
  62367. const int totalHeight_)
  62368. : out (resultingPostScript),
  62369. totalWidth (totalWidth_),
  62370. totalHeight (totalHeight_),
  62371. xOffset (0),
  62372. yOffset (0),
  62373. needToClip (true)
  62374. {
  62375. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  62376. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  62377. out << "%!PS-Adobe-3.0 EPSF-3.0"
  62378. "\n%%BoundingBox: 0 0 600 824"
  62379. "\n%%Pages: 0"
  62380. "\n%%Creator: Raw Material Software JUCE"
  62381. "\n%%Title: " << documentTitle <<
  62382. "\n%%CreationDate: none"
  62383. "\n%%LanguageLevel: 2"
  62384. "\n%%EndComments"
  62385. "\n%%BeginProlog"
  62386. "\n%%BeginResource: JRes"
  62387. "\n/bd {bind def} bind def"
  62388. "\n/c {setrgbcolor} bd"
  62389. "\n/m {moveto} bd"
  62390. "\n/l {lineto} bd"
  62391. "\n/rl {rlineto} bd"
  62392. "\n/ct {curveto} bd"
  62393. "\n/cp {closepath} bd"
  62394. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  62395. "\n/doclip {initclip newpath} bd"
  62396. "\n/endclip {clip newpath} bd"
  62397. "\n%%EndResource"
  62398. "\n%%EndProlog"
  62399. "\n%%BeginSetup"
  62400. "\n%%EndSetup"
  62401. "\n%%Page: 1 1"
  62402. "\n%%BeginPageSetup"
  62403. "\n%%EndPageSetup\n\n"
  62404. << "40 800 translate\n"
  62405. << scale << ' ' << scale << " scale\n\n";
  62406. }
  62407. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  62408. {
  62409. delete clip;
  62410. }
  62411. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  62412. {
  62413. return true;
  62414. }
  62415. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  62416. {
  62417. if (x != 0 || y != 0)
  62418. {
  62419. xOffset += x;
  62420. yOffset += y;
  62421. needToClip = true;
  62422. }
  62423. }
  62424. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  62425. {
  62426. needToClip = true;
  62427. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62428. }
  62429. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62430. {
  62431. needToClip = true;
  62432. return clip->clipTo (clipRegion);
  62433. }
  62434. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  62435. {
  62436. needToClip = true;
  62437. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62438. }
  62439. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62440. {
  62441. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62442. }
  62443. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  62444. {
  62445. return clip->getBounds().translated (-xOffset, -yOffset);
  62446. }
  62447. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  62448. {
  62449. return clip->isEmpty();
  62450. }
  62451. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  62452. const int xOffset_, const int yOffset_)
  62453. : clip (clip_),
  62454. xOffset (xOffset_),
  62455. yOffset (yOffset_)
  62456. {
  62457. }
  62458. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  62459. {
  62460. delete clip;
  62461. }
  62462. void LowLevelGraphicsPostScriptRenderer::saveState()
  62463. {
  62464. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62465. }
  62466. void LowLevelGraphicsPostScriptRenderer::restoreState()
  62467. {
  62468. SavedState* const top = stateStack.getLast();
  62469. if (top != 0)
  62470. {
  62471. clip->swapWith (*top->clip);
  62472. xOffset = top->xOffset;
  62473. yOffset = top->yOffset;
  62474. stateStack.removeLast();
  62475. needToClip = true;
  62476. }
  62477. else
  62478. {
  62479. jassertfalse // trying to pop with an empty stack!
  62480. }
  62481. }
  62482. void LowLevelGraphicsPostScriptRenderer::writeClip()
  62483. {
  62484. if (needToClip)
  62485. {
  62486. needToClip = false;
  62487. out << "doclip ";
  62488. int itemsOnLine = 0;
  62489. for (RectangleList::Iterator i (*clip); i.next();)
  62490. {
  62491. if (++itemsOnLine == 6)
  62492. {
  62493. itemsOnLine = 0;
  62494. out << '\n';
  62495. }
  62496. const Rectangle& r = *i.getRectangle();
  62497. out << r.getX() << ' ' << -r.getY() << ' '
  62498. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  62499. }
  62500. out << "endclip\n";
  62501. }
  62502. }
  62503. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  62504. {
  62505. Colour c (Colours::white.overlaidWith (colour));
  62506. if (lastColour != c)
  62507. {
  62508. lastColour = c;
  62509. out << String (c.getFloatRed(), 3) << ' '
  62510. << String (c.getFloatGreen(), 3) << ' '
  62511. << String (c.getFloatBlue(), 3) << " c\n";
  62512. }
  62513. }
  62514. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  62515. {
  62516. out << String (x, 2) << ' '
  62517. << String (-y, 2) << ' ';
  62518. }
  62519. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  62520. {
  62521. out << "newpath ";
  62522. float lastX = 0.0f;
  62523. float lastY = 0.0f;
  62524. int itemsOnLine = 0;
  62525. Path::Iterator i (path);
  62526. while (i.next())
  62527. {
  62528. if (++itemsOnLine == 4)
  62529. {
  62530. itemsOnLine = 0;
  62531. out << '\n';
  62532. }
  62533. switch (i.elementType)
  62534. {
  62535. case Path::Iterator::startNewSubPath:
  62536. writeXY (i.x1, i.y1);
  62537. lastX = i.x1;
  62538. lastY = i.y1;
  62539. out << "m ";
  62540. break;
  62541. case Path::Iterator::lineTo:
  62542. writeXY (i.x1, i.y1);
  62543. lastX = i.x1;
  62544. lastY = i.y1;
  62545. out << "l ";
  62546. break;
  62547. case Path::Iterator::quadraticTo:
  62548. {
  62549. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  62550. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  62551. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  62552. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  62553. writeXY (cp1x, cp1y);
  62554. writeXY (cp2x, cp2y);
  62555. writeXY (i.x2, i.y2);
  62556. out << "ct ";
  62557. lastX = i.x2;
  62558. lastY = i.y2;
  62559. }
  62560. break;
  62561. case Path::Iterator::cubicTo:
  62562. writeXY (i.x1, i.y1);
  62563. writeXY (i.x2, i.y2);
  62564. writeXY (i.x3, i.y3);
  62565. out << "ct ";
  62566. lastX = i.x3;
  62567. lastY = i.y3;
  62568. break;
  62569. case Path::Iterator::closePath:
  62570. out << "cp ";
  62571. break;
  62572. default:
  62573. jassertfalse
  62574. break;
  62575. }
  62576. }
  62577. out << '\n';
  62578. }
  62579. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  62580. {
  62581. out << "[ "
  62582. << trans.mat00 << ' '
  62583. << trans.mat10 << ' '
  62584. << trans.mat01 << ' '
  62585. << trans.mat11 << ' '
  62586. << trans.mat02 << ' '
  62587. << trans.mat12 << " ] concat ";
  62588. }
  62589. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  62590. {
  62591. writeClip();
  62592. writeColour (colour);
  62593. x += xOffset;
  62594. y += yOffset;
  62595. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  62596. }
  62597. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62598. {
  62599. Path p;
  62600. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62601. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  62602. }
  62603. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62604. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  62605. {
  62606. writeClip();
  62607. Path p (path);
  62608. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62609. writePath (p);
  62610. writeColour (colour);
  62611. out << "fill\n";
  62612. }
  62613. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  62614. {
  62615. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  62616. // postscript can't do semi-transparent ones.
  62617. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62618. writeClip();
  62619. out << "gsave ";
  62620. {
  62621. Path p (path);
  62622. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  62623. writePath (p);
  62624. out << "clip\n";
  62625. }
  62626. int numColours = 256;
  62627. PixelARGB* const colours = gradient.createLookupTable (numColours);
  62628. for (int i = numColours; --i >= 0;)
  62629. colours[i].unpremultiply();
  62630. const Rectangle bounds (clip->getBounds());
  62631. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  62632. // time-being, this just fills it with the average colour..
  62633. writeColour (Colour (colours [numColours / 2].getARGB()));
  62634. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  62635. juce_free (colours);
  62636. out << "grestore\n";
  62637. }
  62638. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62639. const Image& sourceImage,
  62640. int imageX, int imageY,
  62641. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  62642. {
  62643. writeClip();
  62644. out << "gsave ";
  62645. Path p (path);
  62646. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  62647. writePath (p);
  62648. out << "clip\n";
  62649. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  62650. out << "grestore\n";
  62651. }
  62652. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  62653. {
  62654. x += xOffset;
  62655. y += yOffset;
  62656. writeClip();
  62657. writeColour (colour);
  62658. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62659. }
  62660. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  62661. {
  62662. imageX += xOffset;
  62663. imageY += yOffset;
  62664. writeClip();
  62665. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62666. }
  62667. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  62668. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  62669. {
  62670. alphaImageX += xOffset;
  62671. alphaImageY += yOffset;
  62672. fillerImageX += xOffset;
  62673. fillerImageY += yOffset;
  62674. writeClip();
  62675. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  62676. }
  62677. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  62678. int dx, int dy, int dw, int dh,
  62679. int sx, int sy, int sw, int sh,
  62680. float alpha,
  62681. const Graphics::ResamplingQuality quality)
  62682. {
  62683. if (sw > 0 && sh > 0)
  62684. {
  62685. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  62686. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  62687. if (sw == dw && sh == dh)
  62688. {
  62689. blendImage (sourceImage,
  62690. dx, dy, dw, dh,
  62691. sx, sy, alpha);
  62692. }
  62693. else
  62694. {
  62695. blendImageWarping (sourceImage,
  62696. sx, sy, sw, sh,
  62697. AffineTransform::scale (dw / (float) sw,
  62698. dh / (float) sh)
  62699. .translated ((float) (dx - sx),
  62700. (float) (dy - sy)),
  62701. alpha,
  62702. quality);
  62703. }
  62704. }
  62705. }
  62706. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62707. {
  62708. blendImageWarping (sourceImage,
  62709. sx, sy, dw, dh,
  62710. AffineTransform::translation ((float) dx, (float) dy),
  62711. opacity, Graphics::highResamplingQuality);
  62712. }
  62713. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  62714. const int sx, const int sy,
  62715. const int maxW, const int maxH) const
  62716. {
  62717. out << "{<\n";
  62718. const int w = jmin (maxW, im.getWidth());
  62719. const int h = jmin (maxH, im.getHeight());
  62720. int charsOnLine = 0;
  62721. int lineStride, pixelStride;
  62722. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  62723. Colour pixel;
  62724. for (int y = h; --y >= 0;)
  62725. {
  62726. for (int x = 0; x < w; ++x)
  62727. {
  62728. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  62729. if (x >= sx && y >= sy)
  62730. {
  62731. if (im.isARGB())
  62732. {
  62733. PixelARGB p (*(const PixelARGB*) pixelData);
  62734. p.unpremultiply();
  62735. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  62736. }
  62737. else if (im.isRGB())
  62738. {
  62739. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  62740. }
  62741. else
  62742. {
  62743. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  62744. }
  62745. }
  62746. else
  62747. {
  62748. pixel = Colours::transparentWhite;
  62749. }
  62750. char colourString [16];
  62751. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  62752. out << (const char*) colourString;
  62753. charsOnLine += 3;
  62754. if (charsOnLine > 100)
  62755. {
  62756. out << '\n';
  62757. charsOnLine = 0;
  62758. }
  62759. }
  62760. }
  62761. im.releasePixelDataReadOnly (data);
  62762. out << "\n>}\n";
  62763. }
  62764. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  62765. int srcClipX, int srcClipY,
  62766. int srcClipW, int srcClipH,
  62767. const AffineTransform& t,
  62768. float /*opacity*/,
  62769. const Graphics::ResamplingQuality /*quality*/)
  62770. {
  62771. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  62772. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  62773. writeClip();
  62774. out << "gsave ";
  62775. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  62776. .scaled (1.0f, -1.0f));
  62777. RectangleList imageClip;
  62778. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  62779. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  62780. out << "newpath ";
  62781. int itemsOnLine = 0;
  62782. for (RectangleList::Iterator i (imageClip); i.next();)
  62783. {
  62784. if (++itemsOnLine == 6)
  62785. {
  62786. out << '\n';
  62787. itemsOnLine = 0;
  62788. }
  62789. const Rectangle& r = *i.getRectangle();
  62790. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  62791. }
  62792. out << " clip newpath\n";
  62793. out << w << ' ' << h << " scale\n";
  62794. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  62795. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  62796. out << "false 3 colorimage grestore\n";
  62797. needToClip = true;
  62798. }
  62799. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62800. {
  62801. Path p;
  62802. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  62803. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  62804. }
  62805. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62806. {
  62807. drawLine (x, top, x, bottom, col);
  62808. }
  62809. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62810. {
  62811. drawLine (left, y, right, y, col);
  62812. }
  62813. END_JUCE_NAMESPACE
  62814. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  62815. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62816. BEGIN_JUCE_NAMESPACE
  62817. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  62818. #define JUCE_USE_SSE_INSTRUCTIONS 1
  62819. #endif
  62820. #if defined (JUCE_DEBUG) && JUCE_MSVC
  62821. #pragma warning (disable: 4714)
  62822. #endif
  62823. #define MINIMUM_COORD -0x3fffffff
  62824. #define MAXIMUM_COORD 0x3fffffff
  62825. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  62826. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  62827. jassert ((int) x >= MINIMUM_COORD \
  62828. && (int) x <= MAXIMUM_COORD \
  62829. && (int) y >= MINIMUM_COORD \
  62830. && (int) y <= MAXIMUM_COORD \
  62831. && (int) w >= 0 \
  62832. && (int) w < MAXIMUM_COORD \
  62833. && (int) h >= 0 \
  62834. && (int) h < MAXIMUM_COORD);
  62835. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62836. {
  62837. const PixelARGB blendColour (colour.getPixelARGB());
  62838. if (w < 32)
  62839. {
  62840. while (--h >= 0)
  62841. {
  62842. PixelRGB* dest = (PixelRGB*) pixels;
  62843. for (int i = w; --i >= 0;)
  62844. (dest++)->set (blendColour);
  62845. pixels += stride;
  62846. }
  62847. }
  62848. else
  62849. {
  62850. // for wider fills, it's worth using some optimisations..
  62851. const uint8 r = blendColour.getRed();
  62852. const uint8 g = blendColour.getGreen();
  62853. const uint8 b = blendColour.getBlue();
  62854. if (r == g && r == b) // if all the component values are the same, we can cheat..
  62855. {
  62856. while (--h >= 0)
  62857. {
  62858. memset (pixels, r, w * 3);
  62859. pixels += stride;
  62860. }
  62861. }
  62862. else
  62863. {
  62864. PixelRGB filler [4];
  62865. filler[0].set (blendColour);
  62866. filler[1].set (blendColour);
  62867. filler[2].set (blendColour);
  62868. filler[3].set (blendColour);
  62869. const int* const intFiller = (const int*) filler;
  62870. while (--h >= 0)
  62871. {
  62872. uint8* dest = (uint8*) pixels;
  62873. int i = w;
  62874. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  62875. {
  62876. ((PixelRGB*) dest)->set (blendColour);
  62877. dest += 3;
  62878. --i;
  62879. }
  62880. while (i >= 4)
  62881. {
  62882. ((int*) dest) [0] = intFiller[0];
  62883. ((int*) dest) [1] = intFiller[1];
  62884. ((int*) dest) [2] = intFiller[2];
  62885. dest += 12;
  62886. i -= 4;
  62887. }
  62888. while (--i >= 0)
  62889. {
  62890. ((PixelRGB*) dest)->set (blendColour);
  62891. dest += 3;
  62892. }
  62893. pixels += stride;
  62894. }
  62895. }
  62896. }
  62897. }
  62898. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62899. {
  62900. const PixelARGB blendColour (colour.getPixelARGB());
  62901. while (--h >= 0)
  62902. {
  62903. PixelARGB* const dest = (PixelARGB*) pixels;
  62904. for (int i = 0; i < w; ++i)
  62905. dest[i] = blendColour;
  62906. pixels += stride;
  62907. }
  62908. }
  62909. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  62910. {
  62911. if (colour.isOpaque())
  62912. {
  62913. replaceRectRGB (pixels, w, h, stride, colour);
  62914. }
  62915. else
  62916. {
  62917. const PixelARGB blendColour (colour.getPixelARGB());
  62918. const int alpha = blendColour.getAlpha();
  62919. if (alpha <= 0)
  62920. return;
  62921. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  62922. if (SystemStats::hasSSE())
  62923. {
  62924. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  62925. | (int64) ((blendColour.getGreen() << 16)
  62926. | blendColour.getBlue());
  62927. const int invAlpha = 0xff - alpha;
  62928. int64 aaaa = (invAlpha << 16) | invAlpha;
  62929. aaaa = (aaaa << 16) | aaaa;
  62930. #ifndef JUCE_GCC
  62931. __asm
  62932. {
  62933. movq mm1, aaaa
  62934. movq mm2, rgb0
  62935. pxor mm7, mm7
  62936. }
  62937. while (--h >= 0)
  62938. {
  62939. __asm
  62940. {
  62941. mov edx, pixels
  62942. mov ebx, w
  62943. pixloop:
  62944. prefetchnta [edx]
  62945. mov ax, [edx + 1]
  62946. shl eax, 8
  62947. mov al, [edx]
  62948. movd mm0, eax
  62949. punpcklbw mm0, mm7
  62950. pmullw mm0, mm1
  62951. psrlw mm0, 8
  62952. paddw mm0, mm2
  62953. packuswb mm0, mm7
  62954. movd eax, mm0
  62955. mov [edx], al
  62956. inc edx
  62957. shr eax, 8
  62958. mov [edx], ax
  62959. add edx, 2
  62960. dec ebx
  62961. jg pixloop
  62962. }
  62963. pixels += stride;
  62964. }
  62965. __asm emms
  62966. #else
  62967. __asm__ __volatile__ (
  62968. "\tpush %%ebx \n"
  62969. "\tmovq %[aaaa], %%mm1 \n"
  62970. "\tmovq %[rgb0], %%mm2 \n"
  62971. "\tpxor %%mm7, %%mm7 \n"
  62972. ".lineLoop2: \n"
  62973. "\tmovl %%esi,%%edx \n"
  62974. "\tmovl %[w], %%ebx \n"
  62975. ".pixLoop2: \n"
  62976. "\tprefetchnta (%%edx) \n"
  62977. "\tmov (%%edx), %%ax \n"
  62978. "\tshl $8, %%eax \n"
  62979. "\tmov 2(%%edx), %%al \n"
  62980. "\tmovd %%eax, %%mm0 \n"
  62981. "\tpunpcklbw %%mm7, %%mm0 \n"
  62982. "\tpmullw %%mm1, %%mm0 \n"
  62983. "\tpsrlw $8, %%mm0 \n"
  62984. "\tpaddw %%mm2, %%mm0 \n"
  62985. "\tpackuswb %%mm7, %%mm0 \n"
  62986. "\tmovd %%mm0, %%eax \n"
  62987. "\tmovb %%al, (%%edx) \n"
  62988. "\tinc %%edx \n"
  62989. "\tshr $8, %%eax \n"
  62990. "\tmovw %%ax, (%%edx) \n"
  62991. "\tadd $2, %%edx \n"
  62992. "\tdec %%ebx \n"
  62993. "\tjg .pixLoop2 \n"
  62994. "\tadd %%edi, %%esi \n"
  62995. "\tdec %%ecx \n"
  62996. "\tjg .lineLoop2 \n"
  62997. "\tpop %%ebx \n"
  62998. "\temms \n"
  62999. : /* No output registers */
  63000. : [aaaa] "m" (aaaa), /* Input registers */
  63001. [rgb0] "m" (rgb0),
  63002. [w] "m" (w),
  63003. "c" (h),
  63004. [stride] "D" (stride),
  63005. [pixels] "S" (pixels)
  63006. : "cc", "eax", "edx", "memory" /* Clobber list */
  63007. );
  63008. #endif
  63009. }
  63010. else
  63011. #endif
  63012. {
  63013. while (--h >= 0)
  63014. {
  63015. PixelRGB* dest = (PixelRGB*) pixels;
  63016. for (int i = w; --i >= 0;)
  63017. (dest++)->blend (blendColour);
  63018. pixels += stride;
  63019. }
  63020. }
  63021. }
  63022. }
  63023. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  63024. {
  63025. if (colour.isOpaque())
  63026. {
  63027. replaceRectARGB (pixels, w, h, stride, colour);
  63028. }
  63029. else
  63030. {
  63031. const PixelARGB blendColour (colour.getPixelARGB());
  63032. const int alpha = blendColour.getAlpha();
  63033. if (alpha <= 0)
  63034. return;
  63035. while (--h >= 0)
  63036. {
  63037. PixelARGB* dest = (PixelARGB*) pixels;
  63038. for (int i = w; --i >= 0;)
  63039. (dest++)->blend (blendColour);
  63040. pixels += stride;
  63041. }
  63042. }
  63043. }
  63044. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  63045. const uint8* alphaValues, const int w, int h,
  63046. const int pixelStride, const int lineStride,
  63047. const Colour& colour) throw()
  63048. {
  63049. const PixelARGB srcPix (colour.getPixelARGB());
  63050. while (--h >= 0)
  63051. {
  63052. PixelARGB* dest = (PixelARGB*) destPixel;
  63053. const uint8* src = alphaValues;
  63054. int i = w;
  63055. while (--i >= 0)
  63056. {
  63057. unsigned int srcAlpha = *src;
  63058. src += pixelStride;
  63059. if (srcAlpha > 0)
  63060. dest->blend (srcPix, srcAlpha);
  63061. ++dest;
  63062. }
  63063. alphaValues += lineStride;
  63064. destPixel += imageStride;
  63065. }
  63066. }
  63067. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  63068. const uint8* alphaValues, int const width, int height,
  63069. const int pixelStride, const int lineStride,
  63070. const Colour& colour) throw()
  63071. {
  63072. const PixelARGB srcPix (colour.getPixelARGB());
  63073. while (--height >= 0)
  63074. {
  63075. PixelRGB* dest = (PixelRGB*) destPixel;
  63076. const uint8* src = alphaValues;
  63077. int i = width;
  63078. while (--i >= 0)
  63079. {
  63080. unsigned int srcAlpha = *src;
  63081. src += pixelStride;
  63082. if (srcAlpha > 0)
  63083. dest->blend (srcPix, srcAlpha);
  63084. ++dest;
  63085. }
  63086. alphaValues += lineStride;
  63087. destPixel += imageStride;
  63088. }
  63089. }
  63090. template <class PixelType>
  63091. class SolidColourEdgeTableRenderer
  63092. {
  63093. uint8* const data;
  63094. const int stride;
  63095. PixelType* linePixels;
  63096. PixelARGB sourceColour;
  63097. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  63098. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  63099. public:
  63100. SolidColourEdgeTableRenderer (uint8* const data_,
  63101. const int stride_,
  63102. const Colour& colour) throw()
  63103. : data (data_),
  63104. stride (stride_),
  63105. sourceColour (colour.getPixelARGB())
  63106. {
  63107. }
  63108. forcedinline void setEdgeTableYPos (const int y) throw()
  63109. {
  63110. linePixels = (PixelType*) (data + stride * y);
  63111. }
  63112. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63113. {
  63114. linePixels[x].blend (sourceColour, alphaLevel);
  63115. }
  63116. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63117. {
  63118. PixelARGB p (sourceColour);
  63119. p.multiplyAlpha (alphaLevel);
  63120. PixelType* dest = linePixels + x;
  63121. if (p.getAlpha() < 0xff)
  63122. {
  63123. do
  63124. {
  63125. dest->blend (p);
  63126. ++dest;
  63127. } while (--width > 0);
  63128. }
  63129. else
  63130. {
  63131. do
  63132. {
  63133. dest->set (p);
  63134. ++dest;
  63135. } while (--width > 0);
  63136. }
  63137. }
  63138. };
  63139. class AlphaBitmapRenderer
  63140. {
  63141. uint8* data;
  63142. int stride;
  63143. uint8* lineStart;
  63144. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  63145. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  63146. public:
  63147. AlphaBitmapRenderer (uint8* const data_,
  63148. const int stride_) throw()
  63149. : data (data_),
  63150. stride (stride_)
  63151. {
  63152. }
  63153. forcedinline void setEdgeTableYPos (const int y) throw()
  63154. {
  63155. lineStart = data + (stride * y);
  63156. }
  63157. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63158. {
  63159. lineStart [x] = (uint8) alphaLevel;
  63160. }
  63161. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  63162. {
  63163. uint8* d = lineStart + x;
  63164. while (--width >= 0)
  63165. *d++ = (uint8) alphaLevel;
  63166. }
  63167. };
  63168. static const int numScaleBits = 12;
  63169. class LinearGradientPixelGenerator
  63170. {
  63171. const PixelARGB* const lookupTable;
  63172. const int numEntries;
  63173. PixelARGB linePix;
  63174. int start, scale;
  63175. double grad, yTerm;
  63176. bool vertical, horizontal;
  63177. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  63178. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  63179. public:
  63180. LinearGradientPixelGenerator (const ColourGradient& gradient,
  63181. const PixelARGB* const lookupTable_, const int numEntries_)
  63182. : lookupTable (lookupTable_),
  63183. numEntries (numEntries_)
  63184. {
  63185. jassert (numEntries_ >= 0);
  63186. float x1 = gradient.x1;
  63187. float y1 = gradient.y1;
  63188. float x2 = gradient.x2;
  63189. float y2 = gradient.y2;
  63190. if (! gradient.transform.isIdentity())
  63191. {
  63192. Line l (x2, y2, x1, y1);
  63193. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  63194. float x3 = p3.getX();
  63195. float y3 = p3.getY();
  63196. gradient.transform.transformPoint (x1, y1);
  63197. gradient.transform.transformPoint (x2, y2);
  63198. gradient.transform.transformPoint (x3, y3);
  63199. Line l2 (x2, y2, x3, y3);
  63200. float prop = l2.findNearestPointTo (x1, y1);
  63201. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  63202. x2 = newP2.getX();
  63203. y2 = newP2.getY();
  63204. }
  63205. vertical = fabs (x1 - x2) < 0.001f;
  63206. horizontal = fabs (y1 - y2) < 0.001f;
  63207. if (vertical)
  63208. {
  63209. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  63210. start = roundDoubleToInt (y1 * scale);
  63211. }
  63212. else if (horizontal)
  63213. {
  63214. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  63215. start = roundDoubleToInt (x1 * scale);
  63216. }
  63217. else
  63218. {
  63219. grad = (y2 - y1) / (double) (x1 - x2);
  63220. yTerm = y1 - x1 / grad;
  63221. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  63222. grad *= scale;
  63223. }
  63224. }
  63225. forcedinline void setY (const int y) throw()
  63226. {
  63227. if (vertical)
  63228. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  63229. else if (! horizontal)
  63230. start = roundDoubleToInt ((y - yTerm) * grad);
  63231. }
  63232. forcedinline const PixelARGB getPixel (const int x) const throw()
  63233. {
  63234. if (vertical)
  63235. return linePix;
  63236. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  63237. }
  63238. };
  63239. class RadialGradientPixelGenerator
  63240. {
  63241. protected:
  63242. const PixelARGB* const lookupTable;
  63243. const int numEntries;
  63244. const double gx1, gy1;
  63245. double maxDist, invScale;
  63246. double dy;
  63247. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  63248. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  63249. public:
  63250. RadialGradientPixelGenerator (const ColourGradient& gradient,
  63251. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63252. : lookupTable (lookupTable_),
  63253. numEntries (numEntries_),
  63254. gx1 (gradient.x1),
  63255. gy1 (gradient.y1)
  63256. {
  63257. jassert (numEntries_ >= 0);
  63258. const float dx = gradient.x1 - gradient.x2;
  63259. const float dy = gradient.y1 - gradient.y2;
  63260. maxDist = dx * dx + dy * dy;
  63261. invScale = (numEntries + 1) / sqrt (maxDist);
  63262. }
  63263. forcedinline void setY (const int y) throw()
  63264. {
  63265. dy = y - gy1;
  63266. dy *= dy;
  63267. }
  63268. forcedinline const PixelARGB getPixel (const int px) const throw()
  63269. {
  63270. double x = px - gx1;
  63271. x *= x;
  63272. x += dy;
  63273. if (x >= maxDist)
  63274. return lookupTable [numEntries];
  63275. else
  63276. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63277. }
  63278. };
  63279. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  63280. {
  63281. double tM10, tM00, lineYM01, lineYM11;
  63282. AffineTransform inverseTransform;
  63283. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  63284. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  63285. public:
  63286. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  63287. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  63288. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  63289. inverseTransform (gradient.transform.inverted())
  63290. {
  63291. tM10 = inverseTransform.mat10;
  63292. tM00 = inverseTransform.mat00;
  63293. }
  63294. forcedinline void setY (const int y) throw()
  63295. {
  63296. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  63297. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  63298. }
  63299. forcedinline const PixelARGB getPixel (const int px) const throw()
  63300. {
  63301. double x = px;
  63302. const double y = tM10 * x + lineYM11;
  63303. x = tM00 * x + lineYM01;
  63304. x *= x;
  63305. x += y * y;
  63306. if (x >= maxDist)
  63307. return lookupTable [numEntries];
  63308. else
  63309. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  63310. }
  63311. };
  63312. template <class PixelType, class GradientType>
  63313. class GradientEdgeTableRenderer : public GradientType
  63314. {
  63315. uint8* const data;
  63316. const int stride;
  63317. PixelType* linePixels;
  63318. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  63319. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  63320. public:
  63321. GradientEdgeTableRenderer (uint8* const data_,
  63322. const int stride_,
  63323. const ColourGradient& gradient,
  63324. const PixelARGB* const lookupTable, const int numEntries) throw()
  63325. : GradientType (gradient, lookupTable, numEntries - 1),
  63326. data (data_),
  63327. stride (stride_)
  63328. {
  63329. }
  63330. forcedinline void setEdgeTableYPos (const int y) throw()
  63331. {
  63332. linePixels = (PixelType*) (data + stride * y);
  63333. GradientType::setY (y);
  63334. }
  63335. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  63336. {
  63337. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  63338. }
  63339. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  63340. {
  63341. PixelType* dest = linePixels + x;
  63342. if (alphaLevel < 0xff)
  63343. {
  63344. do
  63345. {
  63346. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  63347. } while (--width > 0);
  63348. }
  63349. else
  63350. {
  63351. do
  63352. {
  63353. (dest++)->blend (GradientType::getPixel (x++));
  63354. } while (--width > 0);
  63355. }
  63356. }
  63357. };
  63358. template <class DestPixelType, class SrcPixelType>
  63359. class ImageFillEdgeTableRenderer
  63360. {
  63361. uint8* const destImageData;
  63362. const uint8* srcImageData;
  63363. int stride, srcStride, extraAlpha;
  63364. DestPixelType* linePixels;
  63365. SrcPixelType* sourceLineStart;
  63366. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  63367. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  63368. public:
  63369. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  63370. const int stride_,
  63371. const uint8* srcImageData_,
  63372. const int srcStride_,
  63373. int extraAlpha_,
  63374. SrcPixelType*) throw() // dummy param to avoid compiler error
  63375. : destImageData (destImageData_),
  63376. srcImageData (srcImageData_),
  63377. stride (stride_),
  63378. srcStride (srcStride_),
  63379. extraAlpha (extraAlpha_)
  63380. {
  63381. }
  63382. forcedinline void setEdgeTableYPos (int y) throw()
  63383. {
  63384. linePixels = (DestPixelType*) (destImageData + stride * y);
  63385. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  63386. }
  63387. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  63388. {
  63389. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63390. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  63391. }
  63392. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  63393. {
  63394. DestPixelType* dest = linePixels + x;
  63395. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  63396. if (alphaLevel < 0xfe)
  63397. {
  63398. do
  63399. {
  63400. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  63401. } while (--width > 0);
  63402. }
  63403. else
  63404. {
  63405. do
  63406. {
  63407. dest++ ->blend (sourceLineStart [x++]);
  63408. } while (--width > 0);
  63409. }
  63410. }
  63411. };
  63412. static void blendRowOfPixels (PixelARGB* dst,
  63413. const PixelRGB* src,
  63414. int width) throw()
  63415. {
  63416. while (--width >= 0)
  63417. (dst++)->set (*src++);
  63418. }
  63419. static void blendRowOfPixels (PixelRGB* dst,
  63420. const PixelRGB* src,
  63421. int width) throw()
  63422. {
  63423. memcpy (dst, src, 3 * width);
  63424. }
  63425. static void blendRowOfPixels (PixelRGB* dst,
  63426. const PixelARGB* src,
  63427. int width) throw()
  63428. {
  63429. while (--width >= 0)
  63430. (dst++)->blend (*src++);
  63431. }
  63432. static void blendRowOfPixels (PixelARGB* dst,
  63433. const PixelARGB* src,
  63434. int width) throw()
  63435. {
  63436. while (--width >= 0)
  63437. (dst++)->blend (*src++);
  63438. }
  63439. static void blendRowOfPixels (PixelARGB* dst,
  63440. const PixelRGB* src,
  63441. int width,
  63442. const uint8 alpha) throw()
  63443. {
  63444. while (--width >= 0)
  63445. (dst++)->blend (*src++, alpha);
  63446. }
  63447. static void blendRowOfPixels (PixelRGB* dst,
  63448. const PixelRGB* src,
  63449. int width,
  63450. const uint8 alpha) throw()
  63451. {
  63452. uint8* d = (uint8*) dst;
  63453. const uint8* s = (const uint8*) src;
  63454. const int inverseAlpha = 0xff - alpha;
  63455. while (--width >= 0)
  63456. {
  63457. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  63458. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  63459. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  63460. d += 3;
  63461. s += 3;
  63462. }
  63463. }
  63464. static void blendRowOfPixels (PixelRGB* dst,
  63465. const PixelARGB* src,
  63466. int width,
  63467. const uint8 alpha) throw()
  63468. {
  63469. while (--width >= 0)
  63470. (dst++)->blend (*src++, alpha);
  63471. }
  63472. static void blendRowOfPixels (PixelARGB* dst,
  63473. const PixelARGB* src,
  63474. int width,
  63475. const uint8 alpha) throw()
  63476. {
  63477. while (--width >= 0)
  63478. (dst++)->blend (*src++, alpha);
  63479. }
  63480. template <class DestPixelType, class SrcPixelType>
  63481. static void overlayImage (DestPixelType* dest,
  63482. const int destStride,
  63483. const SrcPixelType* src,
  63484. const int srcStride,
  63485. const int width,
  63486. int height,
  63487. const uint8 alpha) throw()
  63488. {
  63489. if (alpha < 0xff)
  63490. {
  63491. while (--height >= 0)
  63492. {
  63493. blendRowOfPixels (dest, src, width, alpha);
  63494. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63495. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63496. }
  63497. }
  63498. else
  63499. {
  63500. while (--height >= 0)
  63501. {
  63502. blendRowOfPixels (dest, src, width);
  63503. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  63504. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63505. }
  63506. }
  63507. }
  63508. template <class DestPixelType, class SrcPixelType>
  63509. static void transformedImageRender (Image& destImage,
  63510. const Image& sourceImage,
  63511. const int destClipX, const int destClipY,
  63512. const int destClipW, const int destClipH,
  63513. const int srcClipX, const int srcClipY,
  63514. const int srcClipWidth, const int srcClipHeight,
  63515. double srcX, double srcY,
  63516. const double lineDX, const double lineDY,
  63517. const double pixelDX, const double pixelDY,
  63518. const uint8 alpha,
  63519. const Graphics::ResamplingQuality quality,
  63520. DestPixelType*,
  63521. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  63522. // parameters of the templated classes to
  63523. // make it use the correct instance of this function..
  63524. {
  63525. int destStride, destPixelStride;
  63526. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  63527. int srcStride, srcPixelStride;
  63528. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  63529. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  63530. {
  63531. if (alpha == 255)
  63532. {
  63533. for (int y = 0; y < destClipH; ++y)
  63534. {
  63535. double sx = srcX;
  63536. double sy = srcY;
  63537. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63538. for (int x = destClipW; --x >= 0;)
  63539. {
  63540. const int ix = ((int) sx) - srcClipX;
  63541. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63542. {
  63543. const int iy = ((int) sy) - srcClipY;
  63544. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63545. {
  63546. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63547. dest->set (*src);
  63548. }
  63549. }
  63550. ++dest;
  63551. sx += pixelDX;
  63552. sy += pixelDY;
  63553. }
  63554. srcX += lineDX;
  63555. srcY += lineDY;
  63556. }
  63557. }
  63558. else
  63559. {
  63560. for (int y = 0; y < destClipH; ++y)
  63561. {
  63562. double sx = srcX;
  63563. double sy = srcY;
  63564. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63565. for (int x = destClipW; --x >= 0;)
  63566. {
  63567. const int ix = ((int) sx) - srcClipX;
  63568. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  63569. {
  63570. const int iy = ((int) sy) - srcClipY;
  63571. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  63572. {
  63573. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63574. dest->blend (*src, alpha);
  63575. }
  63576. }
  63577. ++dest;
  63578. sx += pixelDX;
  63579. sy += pixelDY;
  63580. }
  63581. srcX += lineDX;
  63582. srcY += lineDY;
  63583. }
  63584. }
  63585. }
  63586. else
  63587. {
  63588. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  63589. for (int y = 0; y < destClipH; ++y)
  63590. {
  63591. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  63592. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  63593. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  63594. for (int x = 0; x < destClipW; ++x)
  63595. {
  63596. const double fx = floor (sx);
  63597. const double fy = floor (sy);
  63598. const int ix = roundDoubleToInt (fx) - srcClipX;
  63599. const int iy = roundDoubleToInt (fy) - srcClipY;
  63600. if (ix < srcClipWidth && iy < srcClipHeight)
  63601. {
  63602. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  63603. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  63604. if (iy >= 0)
  63605. {
  63606. if (ix >= 0)
  63607. p1.set (src[0]);
  63608. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63609. p2.set (src[1]);
  63610. }
  63611. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  63612. {
  63613. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  63614. if (ix >= 0)
  63615. p3.set (src[0]);
  63616. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  63617. p4.set (src[1]);
  63618. }
  63619. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  63620. p1.tween (p2, dx);
  63621. p3.tween (p4, dx);
  63622. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  63623. if (p1.getAlpha() > 0)
  63624. dest->blend (p1, alpha);
  63625. }
  63626. ++dest;
  63627. sx += pixelDX;
  63628. sy += pixelDY;
  63629. }
  63630. srcX += lineDX;
  63631. srcY += lineDY;
  63632. }
  63633. }
  63634. destImage.releasePixelDataReadWrite (destPixels);
  63635. sourceImage.releasePixelDataReadOnly (srcPixels);
  63636. }
  63637. template <class SrcPixelType, class DestPixelType>
  63638. static void renderAlphaMap (DestPixelType* destPixels,
  63639. int destStride,
  63640. SrcPixelType* srcPixels,
  63641. int srcStride,
  63642. const uint8* alphaValues,
  63643. const int lineStride, const int pixelStride,
  63644. int width, int height,
  63645. const int extraAlpha) throw()
  63646. {
  63647. while (--height >= 0)
  63648. {
  63649. SrcPixelType* srcPix = srcPixels;
  63650. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  63651. DestPixelType* destPix = destPixels;
  63652. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  63653. const uint8* alpha = alphaValues;
  63654. alphaValues += lineStride;
  63655. if (extraAlpha < 0x100)
  63656. {
  63657. for (int i = width; --i >= 0;)
  63658. {
  63659. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  63660. alpha += pixelStride;
  63661. }
  63662. }
  63663. else
  63664. {
  63665. for (int i = width; --i >= 0;)
  63666. {
  63667. destPix++ ->blend (*srcPix++, *alpha);
  63668. alpha += pixelStride;
  63669. }
  63670. }
  63671. }
  63672. }
  63673. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  63674. : image (image_),
  63675. xOffset (0),
  63676. yOffset (0),
  63677. stateStack (20)
  63678. {
  63679. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  63680. }
  63681. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  63682. {
  63683. delete clip;
  63684. }
  63685. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  63686. {
  63687. return false;
  63688. }
  63689. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  63690. {
  63691. xOffset += x;
  63692. yOffset += y;
  63693. }
  63694. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  63695. {
  63696. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  63697. }
  63698. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  63699. {
  63700. RectangleList temp (clipRegion);
  63701. temp.offsetAll (xOffset, yOffset);
  63702. return clip->clipTo (temp);
  63703. }
  63704. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  63705. {
  63706. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  63707. }
  63708. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  63709. {
  63710. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  63711. }
  63712. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  63713. {
  63714. return clip->getBounds().translated (-xOffset, -yOffset);
  63715. }
  63716. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  63717. {
  63718. return clip->isEmpty();
  63719. }
  63720. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  63721. const int xOffset_, const int yOffset_)
  63722. : clip (clip_),
  63723. xOffset (xOffset_),
  63724. yOffset (yOffset_)
  63725. {
  63726. }
  63727. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  63728. {
  63729. delete clip;
  63730. }
  63731. void LowLevelGraphicsSoftwareRenderer::saveState()
  63732. {
  63733. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  63734. }
  63735. void LowLevelGraphicsSoftwareRenderer::restoreState()
  63736. {
  63737. SavedState* const top = stateStack.getLast();
  63738. if (top != 0)
  63739. {
  63740. clip->swapWith (*top->clip);
  63741. xOffset = top->xOffset;
  63742. yOffset = top->yOffset;
  63743. stateStack.removeLast();
  63744. }
  63745. else
  63746. {
  63747. jassertfalse // trying to pop with an empty stack!
  63748. }
  63749. }
  63750. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63751. {
  63752. x += xOffset;
  63753. y += yOffset;
  63754. for (RectangleList::Iterator i (*clip); i.next();)
  63755. {
  63756. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  63757. }
  63758. }
  63759. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  63760. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  63761. {
  63762. if (clipRect.intersectRectangle (x, y, w, h))
  63763. {
  63764. int stride, pixelStride;
  63765. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63766. if (image.getFormat() == Image::RGB)
  63767. {
  63768. if (replaceExistingContents)
  63769. replaceRectRGB (pixels, w, h, stride, colour);
  63770. else
  63771. blendRectRGB (pixels, w, h, stride, colour);
  63772. }
  63773. else if (image.getFormat() == Image::ARGB)
  63774. {
  63775. if (replaceExistingContents)
  63776. replaceRectARGB (pixels, w, h, stride, colour);
  63777. else
  63778. blendRectARGB (pixels, w, h, stride, colour);
  63779. }
  63780. else
  63781. {
  63782. jassertfalse // not done!
  63783. }
  63784. image.releasePixelDataReadWrite (pixels);
  63785. }
  63786. }
  63787. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  63788. {
  63789. Path p;
  63790. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  63791. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  63792. }
  63793. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  63794. const Path& path, const AffineTransform& transform,
  63795. int& x, int& y, int& w, int& h) const
  63796. {
  63797. float tx, ty, tw, th;
  63798. path.getBoundsTransformed (transform, tx, ty, tw, th);
  63799. x = roundDoubleToInt (tx) - 1;
  63800. y = roundDoubleToInt (ty) - 1;
  63801. w = roundDoubleToInt (tw) + 2;
  63802. h = roundDoubleToInt (th) + 2;
  63803. // seems like this operation is using some crazy out-of-range numbers..
  63804. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  63805. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  63806. }
  63807. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  63808. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63809. {
  63810. for (RectangleList::Iterator i (*clip); i.next();)
  63811. {
  63812. const Rectangle& r = *i.getRectangle();
  63813. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  63814. }
  63815. }
  63816. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63817. const Colour& colour, EdgeTable::OversamplingLevel quality)
  63818. {
  63819. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63820. int cx, cy, cw, ch;
  63821. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63822. {
  63823. EdgeTable edgeTable (0, ch, quality);
  63824. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63825. int stride, pixelStride;
  63826. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63827. if (image.getFormat() == Image::RGB)
  63828. {
  63829. jassert (pixelStride == 3);
  63830. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  63831. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63832. }
  63833. else if (image.getFormat() == Image::ARGB)
  63834. {
  63835. jassert (pixelStride == 4);
  63836. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  63837. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63838. }
  63839. else if (image.getFormat() == Image::SingleChannel)
  63840. {
  63841. jassert (pixelStride == 1);
  63842. AlphaBitmapRenderer renderer (pixels, stride);
  63843. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63844. }
  63845. image.releasePixelDataReadWrite (pixels);
  63846. }
  63847. }
  63848. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63849. {
  63850. for (RectangleList::Iterator i (*clip); i.next();)
  63851. {
  63852. const Rectangle& r = *i.getRectangle();
  63853. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63854. path, t, gradient, quality);
  63855. }
  63856. }
  63857. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  63858. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  63859. {
  63860. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  63861. int cx, cy, cw, ch;
  63862. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  63863. {
  63864. int stride, pixelStride;
  63865. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  63866. ColourGradient g2 (gradient);
  63867. const bool isIdentity = g2.transform.isIdentity();
  63868. if (isIdentity)
  63869. {
  63870. g2.x1 += xOffset - cx;
  63871. g2.x2 += xOffset - cx;
  63872. g2.y1 += yOffset - cy;
  63873. g2.y2 += yOffset - cy;
  63874. }
  63875. else
  63876. {
  63877. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  63878. (float) (yOffset - cy));
  63879. }
  63880. int numLookupEntries;
  63881. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  63882. jassert (numLookupEntries > 0);
  63883. EdgeTable edgeTable (0, ch, quality);
  63884. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  63885. if (image.getFormat() == Image::RGB)
  63886. {
  63887. jassert (pixelStride == 3);
  63888. if (g2.isRadial)
  63889. {
  63890. if (isIdentity)
  63891. {
  63892. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63893. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63894. }
  63895. else
  63896. {
  63897. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63898. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63899. }
  63900. }
  63901. else
  63902. {
  63903. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63904. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63905. }
  63906. }
  63907. else if (image.getFormat() == Image::ARGB)
  63908. {
  63909. jassert (pixelStride == 4);
  63910. if (g2.isRadial)
  63911. {
  63912. if (isIdentity)
  63913. {
  63914. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63915. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63916. }
  63917. else
  63918. {
  63919. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63920. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63921. }
  63922. }
  63923. else
  63924. {
  63925. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  63926. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  63927. }
  63928. }
  63929. else if (image.getFormat() == Image::SingleChannel)
  63930. {
  63931. jassertfalse // not done!
  63932. }
  63933. juce_free (lookupTable);
  63934. image.releasePixelDataReadWrite (pixels);
  63935. }
  63936. }
  63937. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  63938. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63939. {
  63940. imageX += xOffset;
  63941. imageY += yOffset;
  63942. for (RectangleList::Iterator i (*clip); i.next();)
  63943. {
  63944. const Rectangle& r = *i.getRectangle();
  63945. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63946. path, transform, sourceImage, imageX, imageY, opacity, quality);
  63947. }
  63948. }
  63949. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  63950. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  63951. {
  63952. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  63953. {
  63954. EdgeTable edgeTable (0, h, quality);
  63955. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  63956. int stride, pixelStride;
  63957. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  63958. int srcStride, srcPixelStride;
  63959. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  63960. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  63961. if (image.getFormat() == Image::RGB)
  63962. {
  63963. if (sourceImage.getFormat() == Image::RGB)
  63964. {
  63965. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  63966. srcPix, srcStride,
  63967. alpha, (PixelRGB*) 0);
  63968. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63969. }
  63970. else if (sourceImage.getFormat() == Image::ARGB)
  63971. {
  63972. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  63973. srcPix, srcStride,
  63974. alpha, (PixelARGB*) 0);
  63975. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63976. }
  63977. else
  63978. {
  63979. jassertfalse // not done!
  63980. }
  63981. }
  63982. else if (image.getFormat() == Image::ARGB)
  63983. {
  63984. if (sourceImage.getFormat() == Image::RGB)
  63985. {
  63986. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  63987. srcPix, srcStride,
  63988. alpha, (PixelRGB*) 0);
  63989. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63990. }
  63991. else if (sourceImage.getFormat() == Image::ARGB)
  63992. {
  63993. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  63994. srcPix, srcStride,
  63995. alpha, (PixelARGB*) 0);
  63996. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  63997. }
  63998. else
  63999. {
  64000. jassertfalse // not done!
  64001. }
  64002. }
  64003. else
  64004. {
  64005. jassertfalse // not done!
  64006. }
  64007. sourceImage.releasePixelDataReadOnly (srcPix);
  64008. image.releasePixelDataReadWrite (pixels);
  64009. }
  64010. }
  64011. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  64012. {
  64013. x += xOffset;
  64014. y += yOffset;
  64015. for (RectangleList::Iterator i (*clip); i.next();)
  64016. {
  64017. const Rectangle& r = *i.getRectangle();
  64018. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64019. clipImage, x, y, colour);
  64020. }
  64021. }
  64022. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  64023. {
  64024. int w = clipImage.getWidth();
  64025. int h = clipImage.getHeight();
  64026. int sx = 0;
  64027. int sy = 0;
  64028. if (x < clipX)
  64029. {
  64030. sx = clipX - x;
  64031. w -= clipX - x;
  64032. x = clipX;
  64033. }
  64034. if (y < clipY)
  64035. {
  64036. sy = clipY - y;
  64037. h -= clipY - y;
  64038. y = clipY;
  64039. }
  64040. if (x + w > clipX + clipW)
  64041. w = clipX + clipW - x;
  64042. if (y + h > clipY + clipH)
  64043. h = clipY + clipH - y;
  64044. if (w > 0 && h > 0)
  64045. {
  64046. int stride, alphaStride, pixelStride;
  64047. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  64048. const uint8* const alphaValues
  64049. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  64050. #if JUCE_BIG_ENDIAN
  64051. const uint8* const alphas = alphaValues;
  64052. #else
  64053. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  64054. #endif
  64055. if (image.getFormat() == Image::RGB)
  64056. {
  64057. blendAlphaMapRGB (pixels, stride,
  64058. alphas, w, h,
  64059. pixelStride, alphaStride,
  64060. colour);
  64061. }
  64062. else if (image.getFormat() == Image::ARGB)
  64063. {
  64064. blendAlphaMapARGB (pixels, stride,
  64065. alphas, w, h,
  64066. pixelStride, alphaStride,
  64067. colour);
  64068. }
  64069. else
  64070. {
  64071. jassertfalse // not done!
  64072. }
  64073. clipImage.releasePixelDataReadOnly (alphaValues);
  64074. image.releasePixelDataReadWrite (pixels);
  64075. }
  64076. }
  64077. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  64078. {
  64079. imageX += xOffset;
  64080. imageY += yOffset;
  64081. for (RectangleList::Iterator i (*clip); i.next();)
  64082. {
  64083. const Rectangle& r = *i.getRectangle();
  64084. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64085. alphaChannelImage, imageX, imageY, gradient);
  64086. }
  64087. }
  64088. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  64089. const Image& alphaChannelImage,
  64090. int imageX, int imageY, const ColourGradient& gradient)
  64091. {
  64092. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  64093. {
  64094. ColourGradient g2 (gradient);
  64095. g2.x1 += xOffset - x;
  64096. g2.x2 += xOffset - x;
  64097. g2.y1 += yOffset - y;
  64098. g2.y2 += yOffset - y;
  64099. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  64100. LowLevelGraphicsSoftwareRenderer tempG (temp);
  64101. tempG.fillRectWithGradient (0, 0, w, h, g2);
  64102. clippedFillAlphaChannelWithImage (x, y, w, h,
  64103. alphaChannelImage, imageX, imageY,
  64104. temp, x, y, 1.0f);
  64105. }
  64106. }
  64107. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  64108. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64109. {
  64110. alphaImageX += xOffset;
  64111. alphaImageY += yOffset;
  64112. fillerImageX += xOffset;
  64113. fillerImageY += yOffset;
  64114. for (RectangleList::Iterator i (*clip); i.next();)
  64115. {
  64116. const Rectangle& r = *i.getRectangle();
  64117. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64118. alphaImage, alphaImageX, alphaImageY,
  64119. fillerImage, fillerImageX, fillerImageY, opacity);
  64120. }
  64121. }
  64122. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  64123. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  64124. {
  64125. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  64126. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  64127. {
  64128. int dstStride, dstPixStride;
  64129. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  64130. int srcStride, srcPixStride;
  64131. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  64132. int maskStride, maskPixStride;
  64133. const uint8* const alpha
  64134. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  64135. #if JUCE_BIG_ENDIAN
  64136. const uint8* const alphaValues = alpha;
  64137. #else
  64138. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  64139. #endif
  64140. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  64141. if (image.getFormat() == Image::RGB)
  64142. {
  64143. if (fillerImage.getFormat() == Image::RGB)
  64144. {
  64145. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64146. }
  64147. else if (fillerImage.getFormat() == Image::ARGB)
  64148. {
  64149. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64150. }
  64151. else
  64152. {
  64153. jassertfalse // not done!
  64154. }
  64155. }
  64156. else if (image.getFormat() == Image::ARGB)
  64157. {
  64158. if (fillerImage.getFormat() == Image::RGB)
  64159. {
  64160. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64161. }
  64162. else if (fillerImage.getFormat() == Image::ARGB)
  64163. {
  64164. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  64165. }
  64166. else
  64167. {
  64168. jassertfalse // not done!
  64169. }
  64170. }
  64171. else
  64172. {
  64173. jassertfalse // not done!
  64174. }
  64175. alphaImage.releasePixelDataReadOnly (alphaValues);
  64176. fillerImage.releasePixelDataReadOnly (srcPix);
  64177. image.releasePixelDataReadWrite (dstPix);
  64178. }
  64179. }
  64180. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64181. {
  64182. dx += xOffset;
  64183. dy += yOffset;
  64184. for (RectangleList::Iterator i (*clip); i.next();)
  64185. {
  64186. const Rectangle& r = *i.getRectangle();
  64187. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64188. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  64189. }
  64190. }
  64191. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  64192. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  64193. {
  64194. if (dx < clipX)
  64195. {
  64196. sx += clipX - dx;
  64197. dw -= clipX - dx;
  64198. dx = clipX;
  64199. }
  64200. if (dy < clipY)
  64201. {
  64202. sy += clipY - dy;
  64203. dh -= clipY - dy;
  64204. dy = clipY;
  64205. }
  64206. if (dx + dw > clipX + clipW)
  64207. dw = clipX + clipW - dx;
  64208. if (dy + dh > clipY + clipH)
  64209. dh = clipY + clipH - dy;
  64210. if (dw <= 0 || dh <= 0)
  64211. return;
  64212. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64213. if (alpha == 0)
  64214. return;
  64215. int dstStride, dstPixelStride;
  64216. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  64217. int srcStride, srcPixelStride;
  64218. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  64219. if (image.getFormat() == Image::ARGB)
  64220. {
  64221. if (sourceImage.getFormat() == Image::ARGB)
  64222. {
  64223. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64224. (PixelARGB*) srcPixels, srcStride,
  64225. dw, dh, alpha);
  64226. }
  64227. else if (sourceImage.getFormat() == Image::RGB)
  64228. {
  64229. overlayImage ((PixelARGB*) dstPixels, dstStride,
  64230. (PixelRGB*) srcPixels, srcStride,
  64231. dw, dh, alpha);
  64232. }
  64233. else
  64234. {
  64235. jassertfalse
  64236. }
  64237. }
  64238. else if (image.getFormat() == Image::RGB)
  64239. {
  64240. if (sourceImage.getFormat() == Image::ARGB)
  64241. {
  64242. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64243. (PixelARGB*) srcPixels, srcStride,
  64244. dw, dh, alpha);
  64245. }
  64246. else if (sourceImage.getFormat() == Image::RGB)
  64247. {
  64248. overlayImage ((PixelRGB*) dstPixels, dstStride,
  64249. (PixelRGB*) srcPixels, srcStride,
  64250. dw, dh, alpha);
  64251. }
  64252. else
  64253. {
  64254. jassertfalse
  64255. }
  64256. }
  64257. else
  64258. {
  64259. jassertfalse
  64260. }
  64261. image.releasePixelDataReadWrite (dstPixels);
  64262. sourceImage.releasePixelDataReadOnly (srcPixels);
  64263. }
  64264. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  64265. int dx, int dy, int dw, int dh,
  64266. int sx, int sy, int sw, int sh,
  64267. float alpha,
  64268. const Graphics::ResamplingQuality quality)
  64269. {
  64270. if (sw > 0 && sh > 0)
  64271. {
  64272. if (sw == dw && sh == dh)
  64273. {
  64274. blendImage (sourceImage,
  64275. dx, dy, dw, dh,
  64276. sx, sy, alpha);
  64277. }
  64278. else
  64279. {
  64280. blendImageWarping (sourceImage,
  64281. sx, sy, sw, sh,
  64282. AffineTransform::translation ((float) -sx,
  64283. (float) -sy)
  64284. .scaled (dw / (float) sw,
  64285. dh / (float) sh)
  64286. .translated ((float) dx,
  64287. (float) dy),
  64288. alpha,
  64289. quality);
  64290. }
  64291. }
  64292. }
  64293. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  64294. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64295. const AffineTransform& t,
  64296. float opacity,
  64297. const Graphics::ResamplingQuality quality)
  64298. {
  64299. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  64300. for (RectangleList::Iterator i (*clip); i.next();)
  64301. {
  64302. const Rectangle& r = *i.getRectangle();
  64303. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64304. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  64305. transform, opacity, quality);
  64306. }
  64307. }
  64308. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  64309. const Image& sourceImage,
  64310. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  64311. const AffineTransform& transform,
  64312. float opacity,
  64313. const Graphics::ResamplingQuality quality)
  64314. {
  64315. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  64316. {
  64317. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  64318. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  64319. if (srcClipW <= 0 || srcClipH <= 0)
  64320. return;
  64321. jassert (srcClipX >= 0 && srcClipY >= 0);
  64322. Path imageBounds;
  64323. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  64324. imageBounds.applyTransform (transform);
  64325. float imX, imY, imW, imH;
  64326. imageBounds.getBounds (imX, imY, imW, imH);
  64327. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  64328. (int) floorf (imX),
  64329. (int) floorf (imY),
  64330. 1 + roundDoubleToInt (imW),
  64331. 1 + roundDoubleToInt (imH)))
  64332. {
  64333. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  64334. float srcX1 = (float) destClipX;
  64335. float srcY1 = (float) destClipY;
  64336. float srcX2 = (float) (destClipX + destClipW);
  64337. float srcY2 = srcY1;
  64338. float srcX3 = srcX1;
  64339. float srcY3 = (float) (destClipY + destClipH);
  64340. AffineTransform inverse (transform.inverted());
  64341. inverse.transformPoint (srcX1, srcY1);
  64342. inverse.transformPoint (srcX2, srcY2);
  64343. inverse.transformPoint (srcX3, srcY3);
  64344. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  64345. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  64346. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  64347. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  64348. if (image.getFormat() == Image::ARGB)
  64349. {
  64350. if (sourceImage.getFormat() == Image::ARGB)
  64351. {
  64352. transformedImageRender (image, sourceImage,
  64353. destClipX, destClipY, destClipW, destClipH,
  64354. srcClipX, srcClipY, srcClipW, srcClipH,
  64355. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64356. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  64357. }
  64358. else if (sourceImage.getFormat() == Image::RGB)
  64359. {
  64360. transformedImageRender (image, sourceImage,
  64361. destClipX, destClipY, destClipW, destClipH,
  64362. srcClipX, srcClipY, srcClipW, srcClipH,
  64363. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64364. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  64365. }
  64366. else
  64367. {
  64368. jassertfalse
  64369. }
  64370. }
  64371. else if (image.getFormat() == Image::RGB)
  64372. {
  64373. if (sourceImage.getFormat() == Image::ARGB)
  64374. {
  64375. transformedImageRender (image, sourceImage,
  64376. destClipX, destClipY, destClipW, destClipH,
  64377. srcClipX, srcClipY, srcClipW, srcClipH,
  64378. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64379. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  64380. }
  64381. else if (sourceImage.getFormat() == Image::RGB)
  64382. {
  64383. transformedImageRender (image, sourceImage,
  64384. destClipX, destClipY, destClipW, destClipH,
  64385. srcClipX, srcClipY, srcClipW, srcClipH,
  64386. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  64387. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  64388. }
  64389. else
  64390. {
  64391. jassertfalse
  64392. }
  64393. }
  64394. else
  64395. {
  64396. jassertfalse
  64397. }
  64398. }
  64399. }
  64400. }
  64401. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  64402. {
  64403. x1 += xOffset;
  64404. y1 += yOffset;
  64405. x2 += xOffset;
  64406. y2 += yOffset;
  64407. for (RectangleList::Iterator i (*clip); i.next();)
  64408. {
  64409. const Rectangle& r = *i.getRectangle();
  64410. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64411. x1, y1, x2, y2, colour);
  64412. }
  64413. }
  64414. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  64415. {
  64416. if (clipW > 0 && clipH > 0)
  64417. {
  64418. if (x1 == x2)
  64419. {
  64420. if (y2 < y1)
  64421. swapVariables (y1, y2);
  64422. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  64423. }
  64424. else if (y1 == y2)
  64425. {
  64426. if (x2 < x1)
  64427. swapVariables (x1, x2);
  64428. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  64429. }
  64430. else
  64431. {
  64432. double gradient = (y2 - y1) / (x2 - x1);
  64433. if (fabs (gradient) > 1.0)
  64434. {
  64435. gradient = 1.0 / gradient;
  64436. int y = roundDoubleToInt (y1);
  64437. const int startY = y;
  64438. int endY = roundDoubleToInt (y2);
  64439. if (y > endY)
  64440. swapVariables (y, endY);
  64441. while (y < endY)
  64442. {
  64443. const double x = x1 + gradient * (y - startY);
  64444. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  64445. ++y;
  64446. }
  64447. }
  64448. else
  64449. {
  64450. int x = roundDoubleToInt (x1);
  64451. const int startX = x;
  64452. int endX = roundDoubleToInt (x2);
  64453. if (x > endX)
  64454. swapVariables (x, endX);
  64455. while (x < endX)
  64456. {
  64457. const double y = y1 + gradient * (x - startX);
  64458. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  64459. ++x;
  64460. }
  64461. }
  64462. }
  64463. }
  64464. }
  64465. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  64466. {
  64467. for (RectangleList::Iterator i (*clip); i.next();)
  64468. {
  64469. const Rectangle& r = *i.getRectangle();
  64470. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64471. x + xOffset, top + yOffset, bottom + yOffset, col);
  64472. }
  64473. }
  64474. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  64475. const int x, double top, double bottom, const Colour& col)
  64476. {
  64477. jassert (top <= bottom);
  64478. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  64479. && top < clipY + clipH
  64480. && bottom > clipY
  64481. && clipW > 0)
  64482. {
  64483. if (top < clipY)
  64484. top = clipY;
  64485. if (bottom > clipY + clipH)
  64486. bottom = clipY + clipH;
  64487. if (bottom > top)
  64488. drawVertical (x, top, bottom, col);
  64489. }
  64490. }
  64491. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  64492. {
  64493. for (RectangleList::Iterator i (*clip); i.next();)
  64494. {
  64495. const Rectangle& r = *i.getRectangle();
  64496. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  64497. y + yOffset, left + xOffset, right + xOffset, col);
  64498. }
  64499. }
  64500. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  64501. const int y, double left, double right, const Colour& col)
  64502. {
  64503. jassert (left <= right);
  64504. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  64505. && left < clipX + clipW
  64506. && right > clipX
  64507. && clipW > 0)
  64508. {
  64509. if (left < clipX)
  64510. left = clipX;
  64511. if (right > clipX + clipW)
  64512. right = clipX + clipW;
  64513. if (right > left)
  64514. drawHorizontal (y, left, right, col);
  64515. }
  64516. }
  64517. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  64518. const double top,
  64519. const double bottom,
  64520. const Colour& col)
  64521. {
  64522. int wholeStart = (int) top;
  64523. const int wholeEnd = (int) bottom;
  64524. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64525. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64526. if (totalPixels <= 0)
  64527. return;
  64528. int lineStride, dstPixelStride;
  64529. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  64530. uint8* dest = dstPixels;
  64531. PixelARGB colour (col.getPixelARGB());
  64532. if (wholeEnd == wholeStart)
  64533. {
  64534. if (image.getFormat() == Image::ARGB)
  64535. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64536. else if (image.getFormat() == Image::RGB)
  64537. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64538. else
  64539. {
  64540. jassertfalse
  64541. }
  64542. }
  64543. else
  64544. {
  64545. if (image.getFormat() == Image::ARGB)
  64546. {
  64547. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64548. ++wholeStart;
  64549. dest += lineStride;
  64550. if (colour.getAlpha() == 0xff)
  64551. {
  64552. while (wholeEnd > wholeStart)
  64553. {
  64554. ((PixelARGB*) dest)->set (colour);
  64555. ++wholeStart;
  64556. dest += lineStride;
  64557. }
  64558. }
  64559. else
  64560. {
  64561. while (wholeEnd > wholeStart)
  64562. {
  64563. ((PixelARGB*) dest)->blend (colour);
  64564. ++wholeStart;
  64565. dest += lineStride;
  64566. }
  64567. }
  64568. if (lastAlpha > 0)
  64569. {
  64570. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64571. }
  64572. }
  64573. else if (image.getFormat() == Image::RGB)
  64574. {
  64575. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64576. ++wholeStart;
  64577. dest += lineStride;
  64578. if (colour.getAlpha() == 0xff)
  64579. {
  64580. while (wholeEnd > wholeStart)
  64581. {
  64582. ((PixelRGB*) dest)->set (colour);
  64583. ++wholeStart;
  64584. dest += lineStride;
  64585. }
  64586. }
  64587. else
  64588. {
  64589. while (wholeEnd > wholeStart)
  64590. {
  64591. ((PixelRGB*) dest)->blend (colour);
  64592. ++wholeStart;
  64593. dest += lineStride;
  64594. }
  64595. }
  64596. if (lastAlpha > 0)
  64597. {
  64598. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64599. }
  64600. }
  64601. else
  64602. {
  64603. jassertfalse
  64604. }
  64605. }
  64606. image.releasePixelDataReadWrite (dstPixels);
  64607. }
  64608. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  64609. const double top,
  64610. const double bottom,
  64611. const Colour& col)
  64612. {
  64613. int wholeStart = (int) top;
  64614. const int wholeEnd = (int) bottom;
  64615. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  64616. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  64617. if (totalPixels <= 0)
  64618. return;
  64619. int lineStride, dstPixelStride;
  64620. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  64621. uint8* dest = dstPixels;
  64622. PixelARGB colour (col.getPixelARGB());
  64623. if (wholeEnd == wholeStart)
  64624. {
  64625. if (image.getFormat() == Image::ARGB)
  64626. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64627. else if (image.getFormat() == Image::RGB)
  64628. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  64629. else
  64630. {
  64631. jassertfalse
  64632. }
  64633. }
  64634. else
  64635. {
  64636. if (image.getFormat() == Image::ARGB)
  64637. {
  64638. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64639. dest += dstPixelStride;
  64640. ++wholeStart;
  64641. if (colour.getAlpha() == 0xff)
  64642. {
  64643. while (wholeEnd > wholeStart)
  64644. {
  64645. ((PixelARGB*) dest)->set (colour);
  64646. dest += dstPixelStride;
  64647. ++wholeStart;
  64648. }
  64649. }
  64650. else
  64651. {
  64652. while (wholeEnd > wholeStart)
  64653. {
  64654. ((PixelARGB*) dest)->blend (colour);
  64655. dest += dstPixelStride;
  64656. ++wholeStart;
  64657. }
  64658. }
  64659. if (lastAlpha > 0)
  64660. {
  64661. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  64662. }
  64663. }
  64664. else if (image.getFormat() == Image::RGB)
  64665. {
  64666. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  64667. dest += dstPixelStride;
  64668. ++wholeStart;
  64669. if (colour.getAlpha() == 0xff)
  64670. {
  64671. while (wholeEnd > wholeStart)
  64672. {
  64673. ((PixelRGB*) dest)->set (colour);
  64674. dest += dstPixelStride;
  64675. ++wholeStart;
  64676. }
  64677. }
  64678. else
  64679. {
  64680. while (wholeEnd > wholeStart)
  64681. {
  64682. ((PixelRGB*) dest)->blend (colour);
  64683. dest += dstPixelStride;
  64684. ++wholeStart;
  64685. }
  64686. }
  64687. if (lastAlpha > 0)
  64688. {
  64689. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  64690. }
  64691. }
  64692. else
  64693. {
  64694. jassertfalse
  64695. }
  64696. }
  64697. image.releasePixelDataReadWrite (dstPixels);
  64698. }
  64699. END_JUCE_NAMESPACE
  64700. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  64701. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  64702. BEGIN_JUCE_NAMESPACE
  64703. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  64704. : flags (other.flags)
  64705. {
  64706. }
  64707. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  64708. {
  64709. flags = other.flags;
  64710. return *this;
  64711. }
  64712. void RectanglePlacement::applyTo (double& x, double& y,
  64713. double& w, double& h,
  64714. const double dx, const double dy,
  64715. const double dw, const double dh) const throw()
  64716. {
  64717. if (w == 0 || h == 0)
  64718. return;
  64719. if ((flags & stretchToFit) != 0)
  64720. {
  64721. x = dx;
  64722. y = dy;
  64723. w = dw;
  64724. h = dh;
  64725. }
  64726. else
  64727. {
  64728. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  64729. : jmin (dw / w, dh / h);
  64730. if ((flags & onlyReduceInSize) != 0)
  64731. scale = jmin (scale, 1.0);
  64732. if ((flags & onlyIncreaseInSize) != 0)
  64733. scale = jmax (scale, 1.0);
  64734. w *= scale;
  64735. h *= scale;
  64736. if ((flags & xLeft) != 0)
  64737. x = dx;
  64738. else if ((flags & xRight) != 0)
  64739. x = dx + dw - w;
  64740. else
  64741. x = dx + (dw - w) * 0.5;
  64742. if ((flags & yTop) != 0)
  64743. y = dy;
  64744. else if ((flags & yBottom) != 0)
  64745. y = dy + dh - h;
  64746. else
  64747. y = dy + (dh - h) * 0.5;
  64748. }
  64749. }
  64750. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  64751. float w, float h,
  64752. const float dx, const float dy,
  64753. const float dw, const float dh) const throw()
  64754. {
  64755. if (w == 0 || h == 0)
  64756. return AffineTransform::identity;
  64757. const float scaleX = dw / w;
  64758. const float scaleY = dh / h;
  64759. if ((flags & stretchToFit) != 0)
  64760. return AffineTransform::translation (-x, -y)
  64761. .scaled (scaleX, scaleY)
  64762. .translated (dx, dy);
  64763. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  64764. : jmin (scaleX, scaleY);
  64765. if ((flags & onlyReduceInSize) != 0)
  64766. scale = jmin (scale, 1.0f);
  64767. if ((flags & onlyIncreaseInSize) != 0)
  64768. scale = jmax (scale, 1.0f);
  64769. w *= scale;
  64770. h *= scale;
  64771. float newX = dx;
  64772. if ((flags & xRight) != 0)
  64773. newX += dw - w; // right
  64774. else if ((flags & xLeft) == 0)
  64775. newX += (dw - w) / 2.0f; // centre
  64776. float newY = dy;
  64777. if ((flags & yBottom) != 0)
  64778. newY += dh - h; // bottom
  64779. else if ((flags & yTop) == 0)
  64780. newY += (dh - h) / 2.0f; // centre
  64781. return AffineTransform::translation (-x, -y)
  64782. .scaled (scale, scale)
  64783. .translated (newX, newY);
  64784. }
  64785. END_JUCE_NAMESPACE
  64786. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  64787. /********* Start of inlined file: juce_Drawable.cpp *********/
  64788. BEGIN_JUCE_NAMESPACE
  64789. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  64790. const AffineTransform& transform_,
  64791. const float opacity_) throw()
  64792. : g (g_),
  64793. transform (transform_),
  64794. opacity (opacity_)
  64795. {
  64796. }
  64797. Drawable::Drawable()
  64798. {
  64799. }
  64800. Drawable::~Drawable()
  64801. {
  64802. }
  64803. void Drawable::draw (Graphics& g,
  64804. const AffineTransform& transform) const
  64805. {
  64806. const RenderingContext context (g, transform, g.getCurrentColour().getFloatAlpha());
  64807. render (context);
  64808. }
  64809. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  64810. {
  64811. draw (g, AffineTransform::translation (x, y));
  64812. }
  64813. void Drawable::drawWithin (Graphics& g,
  64814. const int destX,
  64815. const int destY,
  64816. const int destW,
  64817. const int destH,
  64818. const RectanglePlacement& placement) const
  64819. {
  64820. if (destW > 0 && destH > 0)
  64821. {
  64822. float x, y, w, h;
  64823. getBounds (x, y, w, h);
  64824. draw (g, placement.getTransformToFit (x, y, w, h,
  64825. (float) destX, (float) destY,
  64826. (float) destW, (float) destH));
  64827. }
  64828. }
  64829. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  64830. {
  64831. Drawable* result = 0;
  64832. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  64833. if (image != 0)
  64834. {
  64835. DrawableImage* const di = new DrawableImage();
  64836. di->setImage (image, true);
  64837. result = di;
  64838. }
  64839. else
  64840. {
  64841. const String asString (String::createStringFromData (data, numBytes));
  64842. XmlDocument doc (asString);
  64843. XmlElement* const outer = doc.getDocumentElement (true);
  64844. if (outer != 0 && outer->hasTagName (T("svg")))
  64845. {
  64846. XmlElement* const svg = doc.getDocumentElement();
  64847. if (svg != 0)
  64848. {
  64849. result = Drawable::createFromSVG (*svg);
  64850. delete svg;
  64851. }
  64852. }
  64853. delete outer;
  64854. }
  64855. return result;
  64856. }
  64857. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  64858. {
  64859. MemoryBlock mb;
  64860. dataSource.readIntoMemoryBlock (mb);
  64861. return createFromImageData (mb.getData(), mb.getSize());
  64862. }
  64863. Drawable* Drawable::createFromImageFile (const File& file)
  64864. {
  64865. FileInputStream* fin = file.createInputStream();
  64866. if (fin == 0)
  64867. return 0;
  64868. Drawable* d = createFromImageDataStream (*fin);
  64869. delete fin;
  64870. return d;
  64871. }
  64872. Drawable* Drawable::readFromBinaryStream (InputStream& input)
  64873. {
  64874. char header[8];
  64875. if (input.read (header, sizeof (header)) != sizeof (header))
  64876. return 0;
  64877. DrawableComposite* result = 0;
  64878. if (memcmp (header, "JuceDrw1", sizeof (header)) == 0)
  64879. {
  64880. result = new DrawableComposite();
  64881. if (! result->readBinary (input))
  64882. deleteAndZero (result);
  64883. }
  64884. return result;
  64885. }
  64886. bool Drawable::writeToBinaryStream (OutputStream& output) const
  64887. {
  64888. output.write ("JuceDrw1", 8);
  64889. return writeBinary (output);
  64890. }
  64891. Drawable* Drawable::readFromXml (const XmlElement& xml)
  64892. {
  64893. DrawableComposite* result = 0;
  64894. if (xml.hasTagName (T("JuceDrawable")))
  64895. {
  64896. result = new DrawableComposite();
  64897. if (! result->readXml (xml))
  64898. deleteAndZero (result);
  64899. }
  64900. return result;
  64901. }
  64902. XmlElement* Drawable::createXml() const
  64903. {
  64904. if (dynamic_cast <const DrawableComposite*> (this) == 0)
  64905. {
  64906. DrawableComposite tempDC;
  64907. tempDC.insertDrawable (const_cast <Drawable*> (this));
  64908. XmlElement* result = tempDC.createXml();
  64909. tempDC.removeDrawable (0, false);
  64910. return result;
  64911. }
  64912. else
  64913. {
  64914. XmlElement* e = new XmlElement (T("JuceDrawable"));
  64915. writeXml (*e);
  64916. return e;
  64917. }
  64918. }
  64919. END_JUCE_NAMESPACE
  64920. /********* End of inlined file: juce_Drawable.cpp *********/
  64921. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  64922. BEGIN_JUCE_NAMESPACE
  64923. DrawableComposite::DrawableComposite()
  64924. {
  64925. }
  64926. DrawableComposite::~DrawableComposite()
  64927. {
  64928. }
  64929. void DrawableComposite::insertDrawable (Drawable* drawable,
  64930. const AffineTransform& transform,
  64931. const int index)
  64932. {
  64933. if (drawable != 0)
  64934. {
  64935. if (! drawables.contains (drawable))
  64936. {
  64937. drawables.insert (index, drawable);
  64938. if (transform.isIdentity())
  64939. transforms.insert (index, 0);
  64940. else
  64941. transforms.insert (index, new AffineTransform (transform));
  64942. }
  64943. else
  64944. {
  64945. jassertfalse // trying to add a drawable that's already in here!
  64946. }
  64947. }
  64948. }
  64949. void DrawableComposite::insertDrawable (const Drawable& drawable,
  64950. const AffineTransform& transform,
  64951. const int index)
  64952. {
  64953. insertDrawable (drawable.createCopy(), transform, index);
  64954. }
  64955. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  64956. {
  64957. drawables.remove (index, deleteDrawable);
  64958. transforms.remove (index);
  64959. }
  64960. void DrawableComposite::bringToFront (const int index)
  64961. {
  64962. if (index >= 0 && index < drawables.size() - 1)
  64963. {
  64964. drawables.move (index, -1);
  64965. transforms.move (index, -1);
  64966. }
  64967. }
  64968. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  64969. {
  64970. if (drawables.size() > 0 && context.opacity > 0)
  64971. {
  64972. if (context.opacity >= 1.0f || drawables.size() == 1)
  64973. {
  64974. Drawable::RenderingContext contextCopy (context);
  64975. for (int i = 0; i < drawables.size(); ++i)
  64976. {
  64977. const AffineTransform* const t = transforms.getUnchecked(i);
  64978. contextCopy.transform = (t == 0) ? context.transform
  64979. : t->followedBy (context.transform);
  64980. drawables.getUnchecked(i)->render (contextCopy);
  64981. }
  64982. }
  64983. else
  64984. {
  64985. // To correctly render a whole composite layer with an overall transparency,
  64986. // we need to render everything opaquely into a temp buffer, then blend that
  64987. // with the target opacity...
  64988. const Rectangle clipBounds (context.g.getClipBounds());
  64989. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  64990. {
  64991. Graphics tempG (tempImage);
  64992. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  64993. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  64994. render (tempContext);
  64995. }
  64996. context.g.setOpacity (context.opacity);
  64997. context.g.drawImageAt (&tempImage, clipBounds.getX(), clipBounds.getY());
  64998. }
  64999. }
  65000. }
  65001. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  65002. {
  65003. Path totalPath;
  65004. for (int i = 0; i < drawables.size(); ++i)
  65005. {
  65006. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  65007. if (width > 0.0f && height > 0.0f)
  65008. {
  65009. Path outline;
  65010. outline.addRectangle (x, y, width, height);
  65011. const AffineTransform* const t = transforms.getUnchecked(i);
  65012. if (t == 0)
  65013. totalPath.addPath (outline);
  65014. else
  65015. totalPath.addPath (outline, *t);
  65016. }
  65017. }
  65018. totalPath.getBounds (x, y, width, height);
  65019. }
  65020. bool DrawableComposite::hitTest (float x, float y) const
  65021. {
  65022. for (int i = 0; i < drawables.size(); ++i)
  65023. {
  65024. float tx = x;
  65025. float ty = y;
  65026. const AffineTransform* const t = transforms.getUnchecked(i);
  65027. if (t != 0)
  65028. t->inverted().transformPoint (tx, ty);
  65029. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  65030. return true;
  65031. }
  65032. return false;
  65033. }
  65034. Drawable* DrawableComposite::createCopy() const
  65035. {
  65036. DrawableComposite* const dc = new DrawableComposite();
  65037. for (int i = 0; i < drawables.size(); ++i)
  65038. {
  65039. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  65040. const AffineTransform* const t = transforms.getUnchecked(i);
  65041. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  65042. }
  65043. return dc;
  65044. }
  65045. const char juce_drawableCompositeTransformFlag = 't';
  65046. const char juce_drawableCompositeBinaryType = 'C';
  65047. const char juce_drawablePathBinaryType = 'P';
  65048. const char juce_drawableImageBinaryType = 'I';
  65049. const char juce_drawableTextBinaryType = 'T';
  65050. bool DrawableComposite::readBinary (InputStream& input)
  65051. {
  65052. AffineTransform transform;
  65053. while (! input.isExhausted())
  65054. {
  65055. const int n = input.readByte();
  65056. if (n == 0)
  65057. break;
  65058. if (n == juce_drawableCompositeTransformFlag)
  65059. {
  65060. float f[6];
  65061. for (int i = 0; i < 6; ++i)
  65062. f[i] = input.readFloat();
  65063. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65064. }
  65065. else
  65066. {
  65067. Drawable* d = 0;
  65068. switch (n)
  65069. {
  65070. case juce_drawableCompositeBinaryType: d = new DrawableComposite(); break;
  65071. case juce_drawablePathBinaryType: d = new DrawablePath(); break;
  65072. case juce_drawableImageBinaryType: d = new DrawableImage(); break;
  65073. case juce_drawableTextBinaryType: d = new DrawableText(); break;
  65074. default: jassertfalse; return false;
  65075. }
  65076. d->setName (input.readString());
  65077. if (! d->readBinary (input))
  65078. {
  65079. delete d;
  65080. return false;
  65081. }
  65082. insertDrawable (d, transform);
  65083. transform = AffineTransform::identity;
  65084. }
  65085. }
  65086. return true;
  65087. }
  65088. bool DrawableComposite::writeBinary (OutputStream& output) const
  65089. {
  65090. for (int i = 0; i < drawables.size(); ++i)
  65091. {
  65092. AffineTransform* transform = transforms.getUnchecked(i);
  65093. if (transform != 0)
  65094. {
  65095. output.writeByte (juce_drawableCompositeTransformFlag);
  65096. output.writeFloat (transform->mat00);
  65097. output.writeFloat (transform->mat01);
  65098. output.writeFloat (transform->mat02);
  65099. output.writeFloat (transform->mat10);
  65100. output.writeFloat (transform->mat11);
  65101. output.writeFloat (transform->mat12);
  65102. }
  65103. Drawable* const d = drawables.getUnchecked(i);
  65104. char typeFlag;
  65105. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65106. typeFlag = juce_drawableCompositeBinaryType;
  65107. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65108. typeFlag = juce_drawablePathBinaryType;
  65109. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65110. typeFlag = juce_drawableImageBinaryType;
  65111. else if (dynamic_cast <DrawableText*> (d) != 0)
  65112. typeFlag = juce_drawableTextBinaryType;
  65113. else
  65114. {
  65115. jassertfalse;
  65116. continue;
  65117. }
  65118. output.writeByte (typeFlag);
  65119. output.writeString (d->getName());
  65120. d->writeBinary (output);
  65121. }
  65122. output.writeByte (0);
  65123. return true;
  65124. }
  65125. const tchar* juce_drawableCompositeXmlTag = T("Group");
  65126. const tchar* juce_drawablePathXmlTag = T("Path");
  65127. const tchar* juce_drawableImageXmlTag = T("Image");
  65128. const tchar* juce_drawableTextXmlTag = T("Text");
  65129. bool DrawableComposite::readXml (const XmlElement& xml)
  65130. {
  65131. forEachXmlChildElement (xml, e)
  65132. {
  65133. Drawable* d = 0;
  65134. if (e->hasTagName (juce_drawableCompositeXmlTag))
  65135. d = new DrawableComposite();
  65136. else if (e->hasTagName (juce_drawablePathXmlTag))
  65137. d = new DrawablePath();
  65138. else if (e->hasTagName (juce_drawableImageXmlTag))
  65139. d = new DrawableImage();
  65140. else if (e->hasTagName (juce_drawableTextXmlTag))
  65141. d = new DrawableText();
  65142. else
  65143. {
  65144. jassertfalse;
  65145. return false;
  65146. }
  65147. d->setName (e->getStringAttribute (T("id")));
  65148. if (! d->readXml (*e))
  65149. {
  65150. jassertfalse;
  65151. delete d;
  65152. return false;
  65153. }
  65154. AffineTransform transform;
  65155. const String transformAtt (e->getStringAttribute (T("transform")));
  65156. if (transformAtt.isNotEmpty())
  65157. {
  65158. StringArray tokens;
  65159. tokens.addTokens (transformAtt.trim(), false);
  65160. tokens.removeEmptyStrings (true);
  65161. if (tokens.size() == 6)
  65162. {
  65163. float f[6];
  65164. for (int i = 0; i < 6; ++i)
  65165. f[i] = (float) tokens[i].getDoubleValue();
  65166. transform = AffineTransform (f[0], f[1], f[2], f[3], f[4], f[5]);
  65167. }
  65168. }
  65169. insertDrawable (d, transform);
  65170. }
  65171. return true;
  65172. }
  65173. void DrawableComposite::writeXml (XmlElement& xml) const
  65174. {
  65175. for (int i = 0; i < drawables.size(); ++i)
  65176. {
  65177. XmlElement* e = 0;
  65178. Drawable* const d = drawables.getUnchecked(i);
  65179. if (dynamic_cast <DrawableComposite*> (d) != 0)
  65180. e = new XmlElement (juce_drawableCompositeXmlTag);
  65181. else if (dynamic_cast <DrawablePath*> (d) != 0)
  65182. e = new XmlElement (juce_drawablePathXmlTag);
  65183. else if (dynamic_cast <DrawableImage*> (d) != 0)
  65184. e = new XmlElement (juce_drawableImageXmlTag);
  65185. else if (dynamic_cast <DrawableText*> (d) != 0)
  65186. e = new XmlElement (juce_drawableTextXmlTag);
  65187. else
  65188. {
  65189. jassertfalse;
  65190. continue;
  65191. }
  65192. AffineTransform* transform = transforms.getUnchecked(i);
  65193. if (transform != 0)
  65194. {
  65195. String t;
  65196. t << transform->mat00 << " " << transform->mat01 << " " << transform->mat02 << " "
  65197. << transform->mat10 << " " << transform->mat11 << " " << transform->mat12;
  65198. e->setAttribute (T("transform"), t);
  65199. }
  65200. if (d->getName().isNotEmpty())
  65201. e->setAttribute (T("id"), d->getName());
  65202. d->writeXml (*e);
  65203. xml.addChildElement (e);
  65204. }
  65205. }
  65206. END_JUCE_NAMESPACE
  65207. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  65208. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  65209. BEGIN_JUCE_NAMESPACE
  65210. DrawableImage::DrawableImage()
  65211. : image (0),
  65212. canDeleteImage (false),
  65213. opacity (1.0f),
  65214. overlayColour (0x00000000)
  65215. {
  65216. }
  65217. DrawableImage::~DrawableImage()
  65218. {
  65219. clearImage();
  65220. }
  65221. void DrawableImage::clearImage()
  65222. {
  65223. if (canDeleteImage && image != 0)
  65224. {
  65225. if (ImageCache::isImageInCache (image))
  65226. ImageCache::release (image);
  65227. else
  65228. delete image;
  65229. }
  65230. image = 0;
  65231. }
  65232. void DrawableImage::setImage (const Image& imageToCopy)
  65233. {
  65234. clearImage();
  65235. image = new Image (imageToCopy);
  65236. canDeleteImage = true;
  65237. }
  65238. void DrawableImage::setImage (Image* imageToUse,
  65239. const bool releaseWhenNotNeeded)
  65240. {
  65241. clearImage();
  65242. image = imageToUse;
  65243. canDeleteImage = releaseWhenNotNeeded;
  65244. }
  65245. void DrawableImage::setOpacity (const float newOpacity)
  65246. {
  65247. opacity = newOpacity;
  65248. }
  65249. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  65250. {
  65251. overlayColour = newOverlayColour;
  65252. }
  65253. void DrawableImage::render (const Drawable::RenderingContext& context) const
  65254. {
  65255. if (image != 0)
  65256. {
  65257. if (opacity > 0.0f && ! overlayColour.isOpaque())
  65258. {
  65259. context.g.setOpacity (context.opacity * opacity);
  65260. context.g.drawImageTransformed (image,
  65261. 0, 0, image->getWidth(), image->getHeight(),
  65262. context.transform, false);
  65263. }
  65264. if (! overlayColour.isTransparent())
  65265. {
  65266. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  65267. context.g.drawImageTransformed (image,
  65268. 0, 0, image->getWidth(), image->getHeight(),
  65269. context.transform, true);
  65270. }
  65271. }
  65272. }
  65273. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  65274. {
  65275. x = 0.0f;
  65276. y = 0.0f;
  65277. width = 0.0f;
  65278. height = 0.0f;
  65279. if (image != 0)
  65280. {
  65281. width = (float) image->getWidth();
  65282. height = (float) image->getHeight();
  65283. }
  65284. }
  65285. bool DrawableImage::hitTest (float x, float y) const
  65286. {
  65287. return image != 0
  65288. && x >= 0.0f
  65289. && y >= 0.0f
  65290. && x < image->getWidth()
  65291. && y < image->getHeight()
  65292. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  65293. }
  65294. Drawable* DrawableImage::createCopy() const
  65295. {
  65296. DrawableImage* const di = new DrawableImage();
  65297. di->opacity = opacity;
  65298. di->overlayColour = overlayColour;
  65299. if (image != 0)
  65300. {
  65301. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  65302. {
  65303. di->setImage (*image);
  65304. }
  65305. else
  65306. {
  65307. ImageCache::incReferenceCount (image);
  65308. di->setImage (image, true);
  65309. }
  65310. }
  65311. return di;
  65312. }
  65313. bool DrawableImage::readBinary (InputStream& input)
  65314. {
  65315. opacity = input.readFloat();
  65316. overlayColour = Colour (input.readInt());
  65317. const int dataLen = input.readInt();
  65318. if (dataLen > 0)
  65319. {
  65320. MemoryBlock imageData;
  65321. input.readIntoMemoryBlock (imageData, dataLen);
  65322. Image* im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65323. if (im == 0)
  65324. return false;
  65325. setImage (im, true);
  65326. }
  65327. return true;
  65328. }
  65329. bool DrawableImage::writeBinary (OutputStream& output) const
  65330. {
  65331. MemoryOutputStream imageData;
  65332. if (image != 0)
  65333. {
  65334. PNGImageFormat pngFormat;
  65335. if (! pngFormat.writeImageToStream (*image, imageData))
  65336. return false;
  65337. }
  65338. output.writeFloat (opacity);
  65339. output.writeInt (overlayColour.getARGB());
  65340. output.writeInt (imageData.getDataSize());
  65341. output.write (imageData.getData(), imageData.getDataSize());
  65342. return true;
  65343. }
  65344. bool DrawableImage::readXml (const XmlElement& xml)
  65345. {
  65346. opacity = (float) xml.getDoubleAttribute (T("opacity"), 1.0);
  65347. overlayColour = Colour (xml.getStringAttribute (T("overlay"), T("0")).getHexValue32());
  65348. MemoryBlock imageData;
  65349. if (imageData.fromBase64Encoding (xml.getAllSubText()))
  65350. {
  65351. Image* const im = ImageFileFormat::loadFrom (imageData.getData(), imageData.getSize());
  65352. if (im == 0)
  65353. return false;
  65354. setImage (im, true);
  65355. }
  65356. return true;
  65357. }
  65358. void DrawableImage::writeXml (XmlElement& xml) const
  65359. {
  65360. if (opacity < 1.0f)
  65361. xml.setAttribute (T("opacity"), (double) opacity);
  65362. if (! overlayColour.isTransparent())
  65363. xml.setAttribute (T("overlay"), String::toHexString ((int) overlayColour.getARGB()));
  65364. if (image != 0)
  65365. {
  65366. MemoryOutputStream imageData;
  65367. PNGImageFormat pngFormat;
  65368. if (pngFormat.writeImageToStream (*image, imageData))
  65369. {
  65370. String base64 (MemoryBlock (imageData.getData(), imageData.getDataSize()).toBase64Encoding());
  65371. for (int i = (base64.length() & ~127); i >= 0; i -= 128)
  65372. base64 = base64.substring (0, i) + "\n" + base64.substring (i);
  65373. xml.addTextElement (base64);
  65374. }
  65375. }
  65376. }
  65377. END_JUCE_NAMESPACE
  65378. /********* End of inlined file: juce_DrawableImage.cpp *********/
  65379. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  65380. BEGIN_JUCE_NAMESPACE
  65381. DrawablePath::DrawablePath()
  65382. : fillBrush (new SolidColourBrush (Colours::black)),
  65383. strokeBrush (0),
  65384. strokeType (0.0f)
  65385. {
  65386. }
  65387. DrawablePath::~DrawablePath()
  65388. {
  65389. delete fillBrush;
  65390. delete strokeBrush;
  65391. }
  65392. void DrawablePath::setPath (const Path& newPath)
  65393. {
  65394. path = newPath;
  65395. updateOutline();
  65396. }
  65397. void DrawablePath::setSolidFill (const Colour& newColour)
  65398. {
  65399. delete fillBrush;
  65400. fillBrush = new SolidColourBrush (newColour);
  65401. }
  65402. void DrawablePath::setFillBrush (const Brush& newBrush)
  65403. {
  65404. delete fillBrush;
  65405. fillBrush = newBrush.createCopy();
  65406. }
  65407. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  65408. {
  65409. strokeType = PathStrokeType (thickness);
  65410. delete strokeBrush;
  65411. strokeBrush = new SolidColourBrush (colour);
  65412. updateOutline();
  65413. }
  65414. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  65415. {
  65416. strokeType = strokeType_;
  65417. delete strokeBrush;
  65418. strokeBrush = newStrokeBrush.createCopy();
  65419. updateOutline();
  65420. }
  65421. void DrawablePath::render (const Drawable::RenderingContext& context) const
  65422. {
  65423. {
  65424. Brush* const tempBrush = fillBrush->createCopy();
  65425. tempBrush->applyTransform (context.transform);
  65426. tempBrush->multiplyOpacity (context.opacity);
  65427. context.g.setBrush (tempBrush);
  65428. context.g.fillPath (path, context.transform);
  65429. delete tempBrush;
  65430. }
  65431. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  65432. {
  65433. Brush* const tempBrush = strokeBrush->createCopy();
  65434. tempBrush->applyTransform (context.transform);
  65435. tempBrush->multiplyOpacity (context.opacity);
  65436. context.g.setBrush (tempBrush);
  65437. context.g.fillPath (outline, context.transform);
  65438. delete tempBrush;
  65439. }
  65440. }
  65441. void DrawablePath::updateOutline()
  65442. {
  65443. outline.clear();
  65444. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  65445. }
  65446. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  65447. {
  65448. if (strokeType.getStrokeThickness() > 0.0f)
  65449. outline.getBounds (x, y, width, height);
  65450. else
  65451. path.getBounds (x, y, width, height);
  65452. }
  65453. bool DrawablePath::hitTest (float x, float y) const
  65454. {
  65455. return path.contains (x, y)
  65456. || outline.contains (x, y);
  65457. }
  65458. Drawable* DrawablePath::createCopy() const
  65459. {
  65460. DrawablePath* const dp = new DrawablePath();
  65461. dp->path = path;
  65462. dp->setFillBrush (*fillBrush);
  65463. if (strokeBrush != 0)
  65464. dp->setOutline (strokeType, *strokeBrush);
  65465. return dp;
  65466. }
  65467. static Brush* readBrushFromBinary (InputStream& input)
  65468. {
  65469. switch (input.readByte())
  65470. {
  65471. case 1:
  65472. return new SolidColourBrush (Colour ((uint32) input.readInt()));
  65473. case 2:
  65474. {
  65475. ColourGradient gradient;
  65476. gradient.x1 = input.readFloat();
  65477. gradient.y1 = input.readFloat();
  65478. gradient.x2 = input.readFloat();
  65479. gradient.y2 = input.readFloat();
  65480. gradient.isRadial = input.readByte() != 0;
  65481. const int numColours = input.readCompressedInt();
  65482. for (int i = 0; i < numColours; ++i)
  65483. {
  65484. double proportion = (double) input.readFloat();
  65485. const Colour colour ((uint32) input.readInt());
  65486. gradient.addColour (proportion, colour);
  65487. }
  65488. return new GradientBrush (gradient);
  65489. }
  65490. case 3:
  65491. {
  65492. jassertfalse; //xxx TODO
  65493. return new ImageBrush (0, 0, 0, 0);
  65494. }
  65495. default:
  65496. break;
  65497. }
  65498. return 0;
  65499. }
  65500. static void writeBrushToBinary (OutputStream& output, const Brush* const brush)
  65501. {
  65502. if (brush == 0)
  65503. {
  65504. output.writeByte (0);
  65505. return;
  65506. }
  65507. const SolidColourBrush* cb;
  65508. const GradientBrush* gb;
  65509. const ImageBrush* ib;
  65510. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65511. {
  65512. output.writeByte (1);
  65513. output.writeInt ((int) cb->getColour().getARGB());
  65514. }
  65515. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65516. {
  65517. output.writeByte (2);
  65518. const ColourGradient& g = gb->getGradient();
  65519. output.writeFloat (g.x1);
  65520. output.writeFloat (g.y1);
  65521. output.writeFloat (g.x2);
  65522. output.writeFloat (g.y2);
  65523. output.writeByte (g.isRadial ? 1 : 0);
  65524. output.writeCompressedInt (g.getNumColours());
  65525. for (int i = 0; i < g.getNumColours(); ++i)
  65526. {
  65527. output.writeFloat ((float) g.getColourPosition (i));
  65528. output.writeInt ((int) g.getColour (i).getARGB());
  65529. }
  65530. }
  65531. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65532. {
  65533. output.writeByte (3);
  65534. jassertfalse; //xxx TODO
  65535. }
  65536. }
  65537. static Brush* readBrushFromXml (const XmlElement* xml)
  65538. {
  65539. if (xml == 0)
  65540. return 0;
  65541. const String type (xml->getStringAttribute (T("type")));
  65542. if (type.equalsIgnoreCase (T("solid")))
  65543. return new SolidColourBrush (Colour ((uint32) xml->getStringAttribute (T("colour"), T("ff000000")).getHexValue32()));
  65544. if (type.equalsIgnoreCase (T("gradient")))
  65545. {
  65546. ColourGradient gradient;
  65547. gradient.x1 = (float) xml->getDoubleAttribute (T("x1"));
  65548. gradient.y1 = (float) xml->getDoubleAttribute (T("y1"));
  65549. gradient.x2 = (float) xml->getDoubleAttribute (T("x2"));
  65550. gradient.y2 = (float) xml->getDoubleAttribute (T("y2"));
  65551. gradient.isRadial = xml->getBoolAttribute (T("radial"), false);
  65552. StringArray colours;
  65553. colours.addTokens (xml->getStringAttribute (T("colours")), false);
  65554. for (int i = 0; i < colours.size() / 2; ++i)
  65555. gradient.addColour (colours[i * 2].getDoubleValue(),
  65556. Colour ((uint32) colours[i * 2 + 1].getHexValue32()));
  65557. return new GradientBrush (gradient);
  65558. }
  65559. if (type.equalsIgnoreCase (T("image")))
  65560. {
  65561. jassertfalse; //xxx TODO
  65562. return new ImageBrush (0, 0, 0, 0);
  65563. }
  65564. return 0;
  65565. }
  65566. static XmlElement* writeBrushToXml (const String& tagName, const Brush* brush)
  65567. {
  65568. if (brush == 0)
  65569. return 0;
  65570. XmlElement* const xml = new XmlElement (tagName);
  65571. const SolidColourBrush* cb;
  65572. const GradientBrush* gb;
  65573. const ImageBrush* ib;
  65574. if ((cb = dynamic_cast <const SolidColourBrush*> (brush)) != 0)
  65575. {
  65576. xml->setAttribute (T("type"), T("solid"));
  65577. xml->setAttribute (T("colour"), String::toHexString ((int) cb->getColour().getARGB()));
  65578. }
  65579. else if ((gb = dynamic_cast <const GradientBrush*> (brush)) != 0)
  65580. {
  65581. xml->setAttribute (T("type"), T("gradient"));
  65582. const ColourGradient& g = gb->getGradient();
  65583. xml->setAttribute (T("x1"), g.x1);
  65584. xml->setAttribute (T("y1"), g.y1);
  65585. xml->setAttribute (T("x2"), g.x2);
  65586. xml->setAttribute (T("y2"), g.y2);
  65587. xml->setAttribute (T("radial"), g.isRadial);
  65588. String s;
  65589. for (int i = 0; i < g.getNumColours(); ++i)
  65590. s << " " << g.getColourPosition (i) << " " << String::toHexString ((int) g.getColour(i).getARGB());
  65591. xml->setAttribute (T("colours"), s.trimStart());
  65592. }
  65593. else if ((ib = dynamic_cast <const ImageBrush*> (brush)) != 0)
  65594. {
  65595. xml->setAttribute (T("type"), T("image"));
  65596. jassertfalse; //xxx TODO
  65597. }
  65598. return xml;
  65599. }
  65600. bool DrawablePath::readBinary (InputStream& input)
  65601. {
  65602. delete fillBrush;
  65603. fillBrush = readBrushFromBinary (input);
  65604. delete strokeBrush;
  65605. strokeBrush = readBrushFromBinary (input);
  65606. const float strokeThickness = input.readFloat();
  65607. const int jointStyle = input.readByte();
  65608. const int endStyle = input.readByte();
  65609. strokeType = PathStrokeType (strokeThickness,
  65610. jointStyle == 1 ? PathStrokeType::curved
  65611. : (jointStyle == 2 ? PathStrokeType::beveled
  65612. : PathStrokeType::mitered),
  65613. endStyle == 1 ? PathStrokeType::square
  65614. : (endStyle == 2 ? PathStrokeType::rounded
  65615. : PathStrokeType::butt));
  65616. const int pathSize = input.readInt();
  65617. MemoryBlock pathData;
  65618. input.readIntoMemoryBlock (pathData, pathSize);
  65619. if (pathData.getSize() != pathSize)
  65620. return false;
  65621. path.clear();
  65622. path.loadPathFromData ((const uint8*) pathData.getData(), pathSize);
  65623. updateOutline();
  65624. return true;
  65625. }
  65626. bool DrawablePath::writeBinary (OutputStream& output) const
  65627. {
  65628. writeBrushToBinary (output, fillBrush);
  65629. writeBrushToBinary (output, strokeBrush);
  65630. output.writeFloat (strokeType.getStrokeThickness());
  65631. output.writeByte (strokeType.getJointStyle() == PathStrokeType::mitered ? 0
  65632. : (strokeType.getJointStyle() == PathStrokeType::curved ? 1 : 2));
  65633. output.writeByte (strokeType.getEndStyle() == PathStrokeType::butt ? 0
  65634. : (strokeType.getEndStyle() == PathStrokeType::square ? 1 : 2));
  65635. MemoryOutputStream out;
  65636. path.writePathToStream (out);
  65637. output.writeInt (out.getDataSize());
  65638. output.write (out.getData(), out.getDataSize());
  65639. return true;
  65640. }
  65641. bool DrawablePath::readXml (const XmlElement& xml)
  65642. {
  65643. delete fillBrush;
  65644. fillBrush = readBrushFromXml (xml.getChildByName (T("fill")));
  65645. delete strokeBrush;
  65646. strokeBrush = readBrushFromXml (xml.getChildByName (T("stroke")));
  65647. const String jointStyle (xml.getStringAttribute (T("jointStyle"), String::empty));
  65648. const String endStyle (xml.getStringAttribute (T("capStyle"), String::empty));
  65649. strokeType = PathStrokeType ((float) xml.getDoubleAttribute (T("strokeWidth"), 0.0),
  65650. jointStyle.equalsIgnoreCase (T("curved")) ? PathStrokeType::curved
  65651. : (jointStyle.equalsIgnoreCase (T("bevel")) ? PathStrokeType::beveled
  65652. : PathStrokeType::mitered),
  65653. endStyle.equalsIgnoreCase (T("square")) ? PathStrokeType::square
  65654. : (endStyle.equalsIgnoreCase (T("round")) ? PathStrokeType::rounded
  65655. : PathStrokeType::butt));
  65656. path.clear();
  65657. path.restoreFromString (xml.getAllSubText());
  65658. updateOutline();
  65659. return true;
  65660. }
  65661. void DrawablePath::writeXml (XmlElement& xml) const
  65662. {
  65663. xml.addChildElement (writeBrushToXml (T("fill"), fillBrush));
  65664. xml.addChildElement (writeBrushToXml (T("stroke"), strokeBrush));
  65665. xml.setAttribute (T("strokeWidth"), (double) strokeType.getStrokeThickness());
  65666. xml.setAttribute (T("jointStyle"),
  65667. strokeType.getJointStyle() == PathStrokeType::mitered ? T("miter")
  65668. : (strokeType.getJointStyle() == PathStrokeType::curved ? T("curved") : T("bevel")));
  65669. xml.setAttribute (T("capStyle"),
  65670. strokeType.getEndStyle() == PathStrokeType::butt ? T("butt")
  65671. : (strokeType.getEndStyle() == PathStrokeType::square ? T("square") : T("round")));
  65672. xml.addTextElement (path.toString());
  65673. }
  65674. END_JUCE_NAMESPACE
  65675. /********* End of inlined file: juce_DrawablePath.cpp *********/
  65676. /********* Start of inlined file: juce_DrawableText.cpp *********/
  65677. BEGIN_JUCE_NAMESPACE
  65678. DrawableText::DrawableText()
  65679. : colour (Colours::white)
  65680. {
  65681. }
  65682. DrawableText::~DrawableText()
  65683. {
  65684. }
  65685. void DrawableText::setText (const GlyphArrangement& newText)
  65686. {
  65687. text = newText;
  65688. }
  65689. void DrawableText::setText (const String& newText, const Font& fontToUse)
  65690. {
  65691. text.clear();
  65692. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  65693. }
  65694. void DrawableText::setColour (const Colour& newColour)
  65695. {
  65696. colour = newColour;
  65697. }
  65698. void DrawableText::render (const Drawable::RenderingContext& context) const
  65699. {
  65700. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  65701. text.draw (context.g, context.transform);
  65702. }
  65703. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  65704. {
  65705. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  65706. width -= x;
  65707. height -= y;
  65708. }
  65709. bool DrawableText::hitTest (float x, float y) const
  65710. {
  65711. return text.findGlyphIndexAt (x, y) >= 0;
  65712. }
  65713. Drawable* DrawableText::createCopy() const
  65714. {
  65715. DrawableText* const dt = new DrawableText();
  65716. dt->text = text;
  65717. dt->colour = colour;
  65718. return dt;
  65719. }
  65720. bool DrawableText::readBinary (InputStream& input)
  65721. {
  65722. jassertfalse; //xxx TODO
  65723. return false;
  65724. }
  65725. bool DrawableText::writeBinary (OutputStream& output) const
  65726. {
  65727. jassertfalse; //xxx TODO
  65728. return false;
  65729. }
  65730. bool DrawableText::readXml (const XmlElement& xml)
  65731. {
  65732. jassertfalse; //xxx TODO
  65733. return false;
  65734. }
  65735. void DrawableText::writeXml (XmlElement& xml) const
  65736. {
  65737. jassertfalse; //xxx TODO
  65738. }
  65739. END_JUCE_NAMESPACE
  65740. /********* End of inlined file: juce_DrawableText.cpp *********/
  65741. /********* Start of inlined file: juce_SVGParser.cpp *********/
  65742. BEGIN_JUCE_NAMESPACE
  65743. class SVGState
  65744. {
  65745. public:
  65746. SVGState (const XmlElement* const topLevel)
  65747. : topLevelXml (topLevel),
  65748. x (0), y (0),
  65749. width (512), height (512),
  65750. viewBoxW (0), viewBoxH (0)
  65751. {
  65752. }
  65753. ~SVGState()
  65754. {
  65755. }
  65756. Drawable* parseSVGElement (const XmlElement& xml)
  65757. {
  65758. if (! xml.hasTagName (T("svg")))
  65759. return 0;
  65760. DrawableComposite* const drawable = new DrawableComposite();
  65761. drawable->setName (xml.getStringAttribute (T("id")));
  65762. SVGState newState (*this);
  65763. if (xml.hasAttribute (T("transform")))
  65764. newState.addTransform (xml);
  65765. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  65766. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  65767. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  65768. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  65769. if (xml.hasAttribute (T("viewBox")))
  65770. {
  65771. const String viewParams (xml.getStringAttribute (T("viewBox")));
  65772. int i = 0;
  65773. float vx, vy, vw, vh;
  65774. if (parseCoords (viewParams, vx, vy, i, true)
  65775. && parseCoords (viewParams, vw, vh, i, true)
  65776. && vw > 0
  65777. && vh > 0)
  65778. {
  65779. newState.viewBoxW = vw;
  65780. newState.viewBoxH = vh;
  65781. int placementFlags = 0;
  65782. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  65783. if (aspect.containsIgnoreCase (T("none")))
  65784. {
  65785. placementFlags = RectanglePlacement::stretchToFit;
  65786. }
  65787. else
  65788. {
  65789. if (aspect.containsIgnoreCase (T("slice")))
  65790. placementFlags |= RectanglePlacement::fillDestination;
  65791. if (aspect.containsIgnoreCase (T("xMin")))
  65792. placementFlags |= RectanglePlacement::xLeft;
  65793. else if (aspect.containsIgnoreCase (T("xMax")))
  65794. placementFlags |= RectanglePlacement::xRight;
  65795. else
  65796. placementFlags |= RectanglePlacement::xMid;
  65797. if (aspect.containsIgnoreCase (T("yMin")))
  65798. placementFlags |= RectanglePlacement::yTop;
  65799. else if (aspect.containsIgnoreCase (T("yMax")))
  65800. placementFlags |= RectanglePlacement::yBottom;
  65801. else
  65802. placementFlags |= RectanglePlacement::yMid;
  65803. }
  65804. const RectanglePlacement placement (placementFlags);
  65805. newState.transform
  65806. = placement.getTransformToFit (vx, vy, vw, vh,
  65807. 0.0f, 0.0f, newState.width, newState.height)
  65808. .followedBy (newState.transform);
  65809. }
  65810. }
  65811. else
  65812. {
  65813. if (viewBoxW == 0)
  65814. newState.viewBoxW = newState.width;
  65815. if (viewBoxH == 0)
  65816. newState.viewBoxH = newState.height;
  65817. }
  65818. newState.parseSubElements (xml, drawable);
  65819. return drawable;
  65820. }
  65821. private:
  65822. const XmlElement* const topLevelXml;
  65823. float x, y, width, height, viewBoxW, viewBoxH;
  65824. AffineTransform transform;
  65825. String cssStyleText;
  65826. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  65827. {
  65828. forEachXmlChildElement (xml, e)
  65829. {
  65830. Drawable* d = 0;
  65831. if (e->hasTagName (T("g")))
  65832. d = parseGroupElement (*e);
  65833. else if (e->hasTagName (T("svg")))
  65834. d = parseSVGElement (*e);
  65835. else if (e->hasTagName (T("path")))
  65836. d = parsePath (*e);
  65837. else if (e->hasTagName (T("rect")))
  65838. d = parseRect (*e);
  65839. else if (e->hasTagName (T("circle")))
  65840. d = parseCircle (*e);
  65841. else if (e->hasTagName (T("ellipse")))
  65842. d = parseEllipse (*e);
  65843. else if (e->hasTagName (T("line")))
  65844. d = parseLine (*e);
  65845. else if (e->hasTagName (T("polyline")))
  65846. d = parsePolygon (*e, true);
  65847. else if (e->hasTagName (T("polygon")))
  65848. d = parsePolygon (*e, false);
  65849. else if (e->hasTagName (T("text")))
  65850. d = parseText (*e);
  65851. else if (e->hasTagName (T("switch")))
  65852. d = parseSwitch (*e);
  65853. else if (e->hasTagName (T("style")))
  65854. parseCSSStyle (*e);
  65855. parentDrawable->insertDrawable (d);
  65856. }
  65857. }
  65858. DrawableComposite* parseSwitch (const XmlElement& xml)
  65859. {
  65860. const XmlElement* const group = xml.getChildByName (T("g"));
  65861. if (group != 0)
  65862. return parseGroupElement (*group);
  65863. return 0;
  65864. }
  65865. DrawableComposite* parseGroupElement (const XmlElement& xml)
  65866. {
  65867. DrawableComposite* const drawable = new DrawableComposite();
  65868. drawable->setName (xml.getStringAttribute (T("id")));
  65869. if (xml.hasAttribute (T("transform")))
  65870. {
  65871. SVGState newState (*this);
  65872. newState.addTransform (xml);
  65873. newState.parseSubElements (xml, drawable);
  65874. }
  65875. else
  65876. {
  65877. parseSubElements (xml, drawable);
  65878. }
  65879. return drawable;
  65880. }
  65881. Drawable* parsePath (const XmlElement& xml) const
  65882. {
  65883. const String d (xml.getStringAttribute (T("d")).trimStart());
  65884. Path path;
  65885. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  65886. path.setUsingNonZeroWinding (false);
  65887. int index = 0;
  65888. float lastX = 0, lastY = 0;
  65889. float lastX2 = 0, lastY2 = 0;
  65890. tchar lastCommandChar = 0;
  65891. bool carryOn = true;
  65892. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  65893. for (;;)
  65894. {
  65895. float x, y, x2, y2, x3, y3;
  65896. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  65897. if (validCommandChars.containsChar (d[index]))
  65898. lastCommandChar = d [index++];
  65899. switch (lastCommandChar)
  65900. {
  65901. case T('M'):
  65902. case T('m'):
  65903. case T('L'):
  65904. case T('l'):
  65905. if (parseCoords (d, x, y, index, false))
  65906. {
  65907. if (isRelative)
  65908. {
  65909. x += lastX;
  65910. y += lastY;
  65911. }
  65912. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  65913. path.startNewSubPath (x, y);
  65914. else
  65915. path.lineTo (x, y);
  65916. lastX2 = lastX;
  65917. lastY2 = lastY;
  65918. lastX = x;
  65919. lastY = y;
  65920. }
  65921. else
  65922. {
  65923. ++index;
  65924. }
  65925. break;
  65926. case T('H'):
  65927. case T('h'):
  65928. if (parseCoord (d, x, index, false, true))
  65929. {
  65930. if (isRelative)
  65931. x += lastX;
  65932. path.lineTo (x, lastY);
  65933. lastX2 = lastX;
  65934. lastX = x;
  65935. }
  65936. else
  65937. {
  65938. ++index;
  65939. }
  65940. break;
  65941. case T('V'):
  65942. case T('v'):
  65943. if (parseCoord (d, y, index, false, false))
  65944. {
  65945. if (isRelative)
  65946. y += lastY;
  65947. path.lineTo (lastX, y);
  65948. lastY2 = lastY;
  65949. lastY = y;
  65950. }
  65951. else
  65952. {
  65953. ++index;
  65954. }
  65955. break;
  65956. case T('C'):
  65957. case T('c'):
  65958. if (parseCoords (d, x, y, index, false)
  65959. && parseCoords (d, x2, y2, index, false)
  65960. && parseCoords (d, x3, y3, index, false))
  65961. {
  65962. if (isRelative)
  65963. {
  65964. x += lastX;
  65965. y += lastY;
  65966. x2 += lastX;
  65967. y2 += lastY;
  65968. x3 += lastX;
  65969. y3 += lastY;
  65970. }
  65971. path.cubicTo (x, y, x2, y2, x3, y3);
  65972. lastX2 = x2;
  65973. lastY2 = y2;
  65974. lastX = x3;
  65975. lastY = y3;
  65976. }
  65977. else
  65978. {
  65979. ++index;
  65980. }
  65981. break;
  65982. case T('S'):
  65983. case T('s'):
  65984. if (parseCoords (d, x, y, index, false)
  65985. && parseCoords (d, x3, y3, index, false))
  65986. {
  65987. if (isRelative)
  65988. {
  65989. x += lastX;
  65990. y += lastY;
  65991. x3 += lastX;
  65992. y3 += lastY;
  65993. }
  65994. x2 = lastX + (lastX - lastX2);
  65995. y2 = lastY + (lastY - lastY2);
  65996. path.cubicTo (x2, y2, x, y, x3, y3);
  65997. lastX2 = x;
  65998. lastY2 = y;
  65999. lastX = x3;
  66000. lastY = y3;
  66001. }
  66002. else
  66003. {
  66004. ++index;
  66005. }
  66006. break;
  66007. case T('Q'):
  66008. case T('q'):
  66009. if (parseCoords (d, x, y, index, false)
  66010. && parseCoords (d, x2, y2, index, false))
  66011. {
  66012. if (isRelative)
  66013. {
  66014. x += lastX;
  66015. y += lastY;
  66016. x2 += lastX;
  66017. y2 += lastY;
  66018. }
  66019. path.quadraticTo (x, y, x2, y2);
  66020. lastX2 = x;
  66021. lastY2 = y;
  66022. lastX = x2;
  66023. lastY = y2;
  66024. }
  66025. else
  66026. {
  66027. ++index;
  66028. }
  66029. break;
  66030. case T('T'):
  66031. case T('t'):
  66032. if (parseCoords (d, x, y, index, false))
  66033. {
  66034. if (isRelative)
  66035. {
  66036. x += lastX;
  66037. y += lastY;
  66038. }
  66039. x2 = lastX + (lastX - lastX2);
  66040. y2 = lastY + (lastY - lastY2);
  66041. path.quadraticTo (x2, y2, x, y);
  66042. lastX2 = x2;
  66043. lastY2 = y2;
  66044. lastX = x;
  66045. lastY = y;
  66046. }
  66047. else
  66048. {
  66049. ++index;
  66050. }
  66051. break;
  66052. case T('A'):
  66053. case T('a'):
  66054. if (parseCoords (d, x, y, index, false))
  66055. {
  66056. String num;
  66057. if (parseNextNumber (d, num, index, false))
  66058. {
  66059. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  66060. if (parseNextNumber (d, num, index, false))
  66061. {
  66062. const bool largeArc = num.getIntValue() != 0;
  66063. if (parseNextNumber (d, num, index, false))
  66064. {
  66065. const bool sweep = num.getIntValue() != 0;
  66066. if (parseCoords (d, x2, y2, index, false))
  66067. {
  66068. if (isRelative)
  66069. {
  66070. x2 += lastX;
  66071. y2 += lastY;
  66072. }
  66073. if (lastX != x2 || lastY != y2)
  66074. {
  66075. double centreX, centreY, startAngle, deltaAngle;
  66076. double rx = x, ry = y;
  66077. endpointToCentreParameters (lastX, lastY, x2, y2,
  66078. angle, largeArc, sweep,
  66079. rx, ry, centreX, centreY,
  66080. startAngle, deltaAngle);
  66081. path.addCentredArc ((float) centreX, (float) centreY,
  66082. (float) rx, (float) ry,
  66083. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  66084. false);
  66085. path.lineTo (x2, y2);
  66086. }
  66087. lastX2 = lastX;
  66088. lastY2 = lastY;
  66089. lastX = x2;
  66090. lastY = y2;
  66091. }
  66092. }
  66093. }
  66094. }
  66095. }
  66096. else
  66097. {
  66098. ++index;
  66099. }
  66100. break;
  66101. case T('Z'):
  66102. case T('z'):
  66103. path.closeSubPath();
  66104. while (CharacterFunctions::isWhitespace (d [index]))
  66105. ++index;
  66106. break;
  66107. default:
  66108. carryOn = false;
  66109. break;
  66110. }
  66111. if (! carryOn)
  66112. break;
  66113. }
  66114. return parseShape (xml, path);
  66115. }
  66116. Drawable* parseRect (const XmlElement& xml) const
  66117. {
  66118. Path rect;
  66119. const bool hasRX = xml.hasAttribute (T("rx"));
  66120. const bool hasRY = xml.hasAttribute (T("ry"));
  66121. if (hasRX || hasRY)
  66122. {
  66123. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66124. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66125. if (! hasRX)
  66126. rx = ry;
  66127. else if (! hasRY)
  66128. ry = rx;
  66129. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66130. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66131. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66132. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  66133. rx, ry);
  66134. }
  66135. else
  66136. {
  66137. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  66138. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  66139. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  66140. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  66141. }
  66142. return parseShape (xml, rect);
  66143. }
  66144. Drawable* parseCircle (const XmlElement& xml) const
  66145. {
  66146. Path circle;
  66147. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66148. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66149. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  66150. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  66151. return parseShape (xml, circle);
  66152. }
  66153. Drawable* parseEllipse (const XmlElement& xml) const
  66154. {
  66155. Path ellipse;
  66156. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  66157. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  66158. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  66159. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  66160. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  66161. return parseShape (xml, ellipse);
  66162. }
  66163. Drawable* parseLine (const XmlElement& xml) const
  66164. {
  66165. Path line;
  66166. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  66167. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  66168. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  66169. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  66170. line.startNewSubPath (x1, y1);
  66171. line.lineTo (x2, y2);
  66172. return parseShape (xml, line);
  66173. }
  66174. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  66175. {
  66176. const String points (xml.getStringAttribute (T("points")));
  66177. Path path;
  66178. int index = 0;
  66179. float x, y;
  66180. if (parseCoords (points, x, y, index, true))
  66181. {
  66182. float firstX = x;
  66183. float firstY = y;
  66184. float lastX = 0, lastY = 0;
  66185. path.startNewSubPath (x, y);
  66186. while (parseCoords (points, x, y, index, true))
  66187. {
  66188. lastX = x;
  66189. lastY = y;
  66190. path.lineTo (x, y);
  66191. }
  66192. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  66193. path.closeSubPath();
  66194. }
  66195. return parseShape (xml, path);
  66196. }
  66197. Drawable* parseShape (const XmlElement& xml, Path& path,
  66198. const bool parseTransform = true) const
  66199. {
  66200. if (parseTransform && xml.hasAttribute (T("transform")))
  66201. {
  66202. SVGState newState (*this);
  66203. newState.addTransform (xml);
  66204. return newState.parseShape (xml, path, false);
  66205. }
  66206. DrawablePath* dp = new DrawablePath();
  66207. dp->setName (xml.getStringAttribute (T("id")));
  66208. dp->setSolidFill (Colours::transparentBlack);
  66209. path.applyTransform (transform);
  66210. dp->setPath (path);
  66211. Path::Iterator iter (path);
  66212. bool containsClosedSubPath = false;
  66213. while (iter.next())
  66214. {
  66215. if (iter.elementType == Path::Iterator::closePath)
  66216. {
  66217. containsClosedSubPath = true;
  66218. break;
  66219. }
  66220. }
  66221. Brush* const fillBrush
  66222. = getBrushForFill (path,
  66223. getStyleAttribute (&xml, T("fill")),
  66224. getStyleAttribute (&xml, T("fill-opacity")),
  66225. getStyleAttribute (&xml, T("opacity")),
  66226. containsClosedSubPath ? Colours::black
  66227. : Colours::transparentBlack);
  66228. if (fillBrush != 0)
  66229. {
  66230. if (! fillBrush->isInvisible())
  66231. {
  66232. fillBrush->applyTransform (transform);
  66233. dp->setFillBrush (*fillBrush);
  66234. }
  66235. delete fillBrush;
  66236. }
  66237. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  66238. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  66239. {
  66240. Brush* const strokeBrush
  66241. = getBrushForFill (path, strokeType,
  66242. getStyleAttribute (&xml, T("stroke-opacity")),
  66243. getStyleAttribute (&xml, T("opacity")),
  66244. Colours::transparentBlack);
  66245. if (strokeBrush != 0)
  66246. {
  66247. const PathStrokeType stroke (getStrokeFor (&xml));
  66248. if (! strokeBrush->isInvisible())
  66249. {
  66250. strokeBrush->applyTransform (transform);
  66251. dp->setOutline (stroke, *strokeBrush);
  66252. }
  66253. delete strokeBrush;
  66254. }
  66255. }
  66256. return dp;
  66257. }
  66258. const XmlElement* findLinkedElement (const XmlElement* e) const
  66259. {
  66260. const String id (e->getStringAttribute (T("xlink:href")));
  66261. if (! id.startsWithChar (T('#')))
  66262. return 0;
  66263. return findElementForId (topLevelXml, id.substring (1));
  66264. }
  66265. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  66266. {
  66267. if (fillXml == 0)
  66268. return;
  66269. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  66270. {
  66271. int index = 0;
  66272. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  66273. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  66274. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  66275. double offset = e->getDoubleAttribute (T("offset"));
  66276. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  66277. offset *= 0.01;
  66278. cg.addColour (jlimit (0.0, 1.0, offset), col);
  66279. }
  66280. }
  66281. Brush* getBrushForFill (const Path& path,
  66282. const String& fill,
  66283. const String& fillOpacity,
  66284. const String& overallOpacity,
  66285. const Colour& defaultColour) const
  66286. {
  66287. float opacity = 1.0f;
  66288. if (overallOpacity.isNotEmpty())
  66289. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  66290. if (fillOpacity.isNotEmpty())
  66291. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  66292. if (fill.startsWithIgnoreCase (T("url")))
  66293. {
  66294. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  66295. .upToLastOccurrenceOf (T(")"), false, false).trim());
  66296. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  66297. if (fillXml != 0
  66298. && (fillXml->hasTagName (T("linearGradient"))
  66299. || fillXml->hasTagName (T("radialGradient"))))
  66300. {
  66301. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  66302. ColourGradient cg;
  66303. addGradientStopsIn (cg, inheritedFrom);
  66304. addGradientStopsIn (cg, fillXml);
  66305. if (cg.getNumColours() > 0)
  66306. {
  66307. cg.addColour (0.0, cg.getColour (0));
  66308. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  66309. }
  66310. else
  66311. {
  66312. cg.addColour (0.0, Colours::black);
  66313. cg.addColour (1.0, Colours::black);
  66314. }
  66315. if (overallOpacity.isNotEmpty())
  66316. cg.multiplyOpacity (overallOpacity.getFloatValue());
  66317. jassert (cg.getNumColours() > 0);
  66318. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  66319. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  66320. float width = viewBoxW;
  66321. float height = viewBoxH;
  66322. float dx = 0.0;
  66323. float dy = 0.0;
  66324. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  66325. if (! userSpace)
  66326. path.getBounds (dx, dy, width, height);
  66327. if (cg.isRadial)
  66328. {
  66329. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  66330. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  66331. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  66332. cg.x2 = cg.x1 + radius;
  66333. cg.y2 = cg.y1;
  66334. //xxx (the fx, fy focal point isn't handled properly here..)
  66335. }
  66336. else
  66337. {
  66338. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  66339. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  66340. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  66341. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  66342. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  66343. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  66344. }
  66345. return new GradientBrush (cg);
  66346. }
  66347. }
  66348. if (fill.equalsIgnoreCase (T("none")))
  66349. return new SolidColourBrush (Colours::transparentBlack);
  66350. int i = 0;
  66351. Colour colour (parseColour (fill, i, defaultColour));
  66352. colour = colour.withMultipliedAlpha (opacity);
  66353. return new SolidColourBrush (colour);
  66354. }
  66355. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  66356. {
  66357. const String width (getStyleAttribute (xml, T("stroke-width")));
  66358. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  66359. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  66360. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  66361. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  66362. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  66363. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  66364. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  66365. if (join.equalsIgnoreCase (T("round")))
  66366. joinStyle = PathStrokeType::curved;
  66367. else if (join.equalsIgnoreCase (T("bevel")))
  66368. joinStyle = PathStrokeType::beveled;
  66369. if (cap.equalsIgnoreCase (T("round")))
  66370. capStyle = PathStrokeType::rounded;
  66371. else if (cap.equalsIgnoreCase (T("square")))
  66372. capStyle = PathStrokeType::square;
  66373. float ox = 0.0f, oy = 0.0f;
  66374. transform.transformPoint (ox, oy);
  66375. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  66376. transform.transformPoint (x, y);
  66377. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  66378. joinStyle, capStyle);
  66379. }
  66380. Drawable* parseText (const XmlElement& xml)
  66381. {
  66382. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  66383. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  66384. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  66385. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  66386. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  66387. //xxx not done text yet!
  66388. forEachXmlChildElement (xml, e)
  66389. {
  66390. if (e->isTextElement())
  66391. {
  66392. const String text (e->getText());
  66393. Path path;
  66394. Drawable* s = parseShape (*e, path);
  66395. delete s;
  66396. }
  66397. else if (e->hasTagName (T("tspan")))
  66398. {
  66399. Drawable* s = parseText (*e);
  66400. delete s;
  66401. }
  66402. }
  66403. return 0;
  66404. }
  66405. void addTransform (const XmlElement& xml)
  66406. {
  66407. transform = parseTransform (xml.getStringAttribute (T("transform")))
  66408. .followedBy (transform);
  66409. }
  66410. bool parseCoord (const String& s, float& value, int& index,
  66411. const bool allowUnits, const bool isX) const
  66412. {
  66413. String number;
  66414. if (! parseNextNumber (s, number, index, allowUnits))
  66415. {
  66416. value = 0;
  66417. return false;
  66418. }
  66419. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  66420. return true;
  66421. }
  66422. bool parseCoords (const String& s, float& x, float& y,
  66423. int& index, const bool allowUnits) const
  66424. {
  66425. return parseCoord (s, x, index, allowUnits, true)
  66426. && parseCoord (s, y, index, allowUnits, false);
  66427. }
  66428. float getCoordLength (const String& s, const float sizeForProportions) const
  66429. {
  66430. float n = s.getFloatValue();
  66431. const int len = s.length();
  66432. if (len > 2)
  66433. {
  66434. const float dpi = 96.0f;
  66435. const tchar n1 = s [len - 2];
  66436. const tchar n2 = s [len - 1];
  66437. if (n1 == T('i') && n2 == T('n'))
  66438. n *= dpi;
  66439. else if (n1 == T('m') && n2 == T('m'))
  66440. n *= dpi / 25.4f;
  66441. else if (n1 == T('c') && n2 == T('m'))
  66442. n *= dpi / 2.54f;
  66443. else if (n1 == T('p') && n2 == T('c'))
  66444. n *= 15.0f;
  66445. else if (n2 == T('%'))
  66446. n *= 0.01f * sizeForProportions;
  66447. }
  66448. return n;
  66449. }
  66450. void getCoordList (Array <float>& coords, const String& list,
  66451. const bool allowUnits, const bool isX) const
  66452. {
  66453. int index = 0;
  66454. float value;
  66455. while (parseCoord (list, value, index, allowUnits, isX))
  66456. coords.add (value);
  66457. }
  66458. void parseCSSStyle (const XmlElement& xml)
  66459. {
  66460. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  66461. }
  66462. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  66463. const String& defaultValue = String::empty) const
  66464. {
  66465. if (xml->hasAttribute (attributeName))
  66466. return xml->getStringAttribute (attributeName, defaultValue);
  66467. const String styleAtt (xml->getStringAttribute (T("style")));
  66468. if (styleAtt.isNotEmpty())
  66469. {
  66470. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  66471. if (value.isNotEmpty())
  66472. return value;
  66473. }
  66474. else if (xml->hasAttribute (T("class")))
  66475. {
  66476. const String className (T(".") + xml->getStringAttribute (T("class")));
  66477. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  66478. if (index < 0)
  66479. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  66480. if (index >= 0)
  66481. {
  66482. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  66483. if (openBracket > index)
  66484. {
  66485. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  66486. if (closeBracket > openBracket)
  66487. {
  66488. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  66489. if (value.isNotEmpty())
  66490. return value;
  66491. }
  66492. }
  66493. }
  66494. }
  66495. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66496. if (xml != 0)
  66497. return getStyleAttribute (xml, attributeName, defaultValue);
  66498. return defaultValue;
  66499. }
  66500. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  66501. {
  66502. if (xml->hasAttribute (attributeName))
  66503. return xml->getStringAttribute (attributeName);
  66504. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  66505. if (xml != 0)
  66506. return getInheritedAttribute (xml, attributeName);
  66507. return String::empty;
  66508. }
  66509. static bool isIdentifierChar (const tchar c)
  66510. {
  66511. return CharacterFunctions::isLetter (c) || c == T('-');
  66512. }
  66513. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  66514. {
  66515. int i = 0;
  66516. for (;;)
  66517. {
  66518. i = list.indexOf (i, attributeName);
  66519. if (i < 0)
  66520. break;
  66521. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  66522. && ! isIdentifierChar (list [i + attributeName.length()]))
  66523. {
  66524. i = list.indexOfChar (i, T(':'));
  66525. if (i < 0)
  66526. break;
  66527. int end = list.indexOfChar (i, T(';'));
  66528. if (end < 0)
  66529. end = 0x7ffff;
  66530. return list.substring (i + 1, end).trim();
  66531. }
  66532. ++i;
  66533. }
  66534. return defaultValue;
  66535. }
  66536. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  66537. {
  66538. const tchar* const s = (const tchar*) source;
  66539. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66540. ++index;
  66541. int start = index;
  66542. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  66543. ++index;
  66544. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  66545. ++index;
  66546. if ((s[index] == T('e') || s[index] == T('E'))
  66547. && (CharacterFunctions::isDigit (s[index + 1])
  66548. || s[index + 1] == T('-')
  66549. || s[index + 1] == T('+')))
  66550. {
  66551. index += 2;
  66552. while (CharacterFunctions::isDigit (s[index]))
  66553. ++index;
  66554. }
  66555. if (allowUnits)
  66556. {
  66557. while (CharacterFunctions::isLetter (s[index]))
  66558. ++index;
  66559. }
  66560. if (index == start)
  66561. return false;
  66562. value = String (s + start, index - start);
  66563. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  66564. ++index;
  66565. return true;
  66566. }
  66567. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  66568. {
  66569. if (s [index] == T('#'))
  66570. {
  66571. uint32 hex [6];
  66572. zeromem (hex, sizeof (hex));
  66573. int numChars = 0;
  66574. for (int i = 6; --i >= 0;)
  66575. {
  66576. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  66577. if (hexValue >= 0)
  66578. hex [numChars++] = hexValue;
  66579. else
  66580. break;
  66581. }
  66582. if (numChars <= 3)
  66583. return Colour ((uint8) (hex [0] * 0x11),
  66584. (uint8) (hex [1] * 0x11),
  66585. (uint8) (hex [2] * 0x11));
  66586. else
  66587. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  66588. (uint8) ((hex [2] << 4) + hex [3]),
  66589. (uint8) ((hex [4] << 4) + hex [5]));
  66590. }
  66591. else if (s [index] == T('r')
  66592. && s [index + 1] == T('g')
  66593. && s [index + 2] == T('b'))
  66594. {
  66595. const int openBracket = s.indexOfChar (index, T('('));
  66596. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  66597. if (openBracket >= 3 && closeBracket > openBracket)
  66598. {
  66599. index = closeBracket;
  66600. StringArray tokens;
  66601. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  66602. tokens.trim();
  66603. tokens.removeEmptyStrings();
  66604. if (tokens[0].containsChar (T('%')))
  66605. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  66606. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  66607. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  66608. else
  66609. return Colour ((uint8) tokens[0].getIntValue(),
  66610. (uint8) tokens[1].getIntValue(),
  66611. (uint8) tokens[2].getIntValue());
  66612. }
  66613. }
  66614. return Colours::findColourForName (s, defaultColour);
  66615. }
  66616. static const AffineTransform parseTransform (String t)
  66617. {
  66618. AffineTransform result;
  66619. while (t.isNotEmpty())
  66620. {
  66621. StringArray tokens;
  66622. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  66623. .upToFirstOccurrenceOf (T(")"), false, false),
  66624. T(", "), 0);
  66625. tokens.removeEmptyStrings (true);
  66626. float numbers [6];
  66627. for (int i = 0; i < 6; ++i)
  66628. numbers[i] = tokens[i].getFloatValue();
  66629. AffineTransform trans;
  66630. if (t.startsWithIgnoreCase (T("matrix")))
  66631. {
  66632. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  66633. numbers[1], numbers[3], numbers[5]);
  66634. }
  66635. else if (t.startsWithIgnoreCase (T("translate")))
  66636. {
  66637. trans = trans.translated (numbers[0], numbers[1]);
  66638. }
  66639. else if (t.startsWithIgnoreCase (T("scale")))
  66640. {
  66641. if (tokens.size() == 1)
  66642. trans = trans.scaled (numbers[0], numbers[0]);
  66643. else
  66644. trans = trans.scaled (numbers[0], numbers[1]);
  66645. }
  66646. else if (t.startsWithIgnoreCase (T("rotate")))
  66647. {
  66648. if (tokens.size() != 3)
  66649. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  66650. else
  66651. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  66652. numbers[1], numbers[2]);
  66653. }
  66654. else if (t.startsWithIgnoreCase (T("skewX")))
  66655. {
  66656. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  66657. 0.0f, 1.0f, 0.0f);
  66658. }
  66659. else if (t.startsWithIgnoreCase (T("skewY")))
  66660. {
  66661. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  66662. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  66663. }
  66664. result = trans.followedBy (result);
  66665. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  66666. }
  66667. return result;
  66668. }
  66669. static void endpointToCentreParameters (const double x1, const double y1,
  66670. const double x2, const double y2,
  66671. const double angle,
  66672. const bool largeArc, const bool sweep,
  66673. double& rx, double& ry,
  66674. double& centreX, double& centreY,
  66675. double& startAngle, double& deltaAngle)
  66676. {
  66677. const double midX = (x1 - x2) * 0.5;
  66678. const double midY = (y1 - y2) * 0.5;
  66679. const double cosAngle = cos (angle);
  66680. const double sinAngle = sin (angle);
  66681. const double xp = cosAngle * midX + sinAngle * midY;
  66682. const double yp = cosAngle * midY - sinAngle * midX;
  66683. const double xp2 = xp * xp;
  66684. const double yp2 = yp * yp;
  66685. double rx2 = rx * rx;
  66686. double ry2 = ry * ry;
  66687. const double s = (xp2 / rx2) + (yp2 / ry2);
  66688. double c;
  66689. if (s <= 1.0)
  66690. {
  66691. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  66692. / (( rx2 * yp2) + (ry2 * xp2))));
  66693. if (largeArc == sweep)
  66694. c = -c;
  66695. }
  66696. else
  66697. {
  66698. const double s2 = sqrt (s);
  66699. rx *= s2;
  66700. ry *= s2;
  66701. rx2 = rx * rx;
  66702. ry2 = ry * ry;
  66703. c = 0;
  66704. }
  66705. const double cpx = ((rx * yp) / ry) * c;
  66706. const double cpy = ((-ry * xp) / rx) * c;
  66707. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  66708. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  66709. const double ux = (xp - cpx) / rx;
  66710. const double uy = (yp - cpy) / ry;
  66711. const double vx = (-xp - cpx) / rx;
  66712. const double vy = (-yp - cpy) / ry;
  66713. const double length = juce_hypot (ux, uy);
  66714. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  66715. if (uy < 0)
  66716. startAngle = -startAngle;
  66717. startAngle += double_Pi * 0.5;
  66718. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  66719. / (length * juce_hypot (vx, vy))));
  66720. if ((ux * vy) - (uy * vx) < 0)
  66721. deltaAngle = -deltaAngle;
  66722. if (sweep)
  66723. {
  66724. if (deltaAngle < 0)
  66725. deltaAngle += double_Pi * 2.0;
  66726. }
  66727. else
  66728. {
  66729. if (deltaAngle > 0)
  66730. deltaAngle -= double_Pi * 2.0;
  66731. }
  66732. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  66733. }
  66734. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  66735. {
  66736. forEachXmlChildElement (*parent, e)
  66737. {
  66738. if (e->compareAttribute (T("id"), id))
  66739. return e;
  66740. const XmlElement* const found = findElementForId (e, id);
  66741. if (found != 0)
  66742. return found;
  66743. }
  66744. return 0;
  66745. }
  66746. const SVGState& operator= (const SVGState&);
  66747. };
  66748. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  66749. {
  66750. SVGState state (&svgDocument);
  66751. return state.parseSVGElement (svgDocument);
  66752. }
  66753. END_JUCE_NAMESPACE
  66754. /********* End of inlined file: juce_SVGParser.cpp *********/
  66755. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  66756. BEGIN_JUCE_NAMESPACE
  66757. #if JUCE_MSVC
  66758. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  66759. #endif
  66760. DropShadowEffect::DropShadowEffect()
  66761. : offsetX (0),
  66762. offsetY (0),
  66763. radius (4),
  66764. opacity (0.6f)
  66765. {
  66766. }
  66767. DropShadowEffect::~DropShadowEffect()
  66768. {
  66769. }
  66770. void DropShadowEffect::setShadowProperties (const float newRadius,
  66771. const float newOpacity,
  66772. const int newShadowOffsetX,
  66773. const int newShadowOffsetY)
  66774. {
  66775. radius = jmax (1.1f, newRadius);
  66776. offsetX = newShadowOffsetX;
  66777. offsetY = newShadowOffsetY;
  66778. opacity = newOpacity;
  66779. }
  66780. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  66781. {
  66782. const int w = image.getWidth();
  66783. const int h = image.getHeight();
  66784. int lineStride, pixelStride;
  66785. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  66786. Image shadowImage (Image::SingleChannel, w, h, false);
  66787. int destStride, destPixelStride;
  66788. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  66789. const int filter = roundFloatToInt (63.0f / radius);
  66790. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  66791. for (int x = w; --x >= 0;)
  66792. {
  66793. int shadowAlpha = 0;
  66794. const PixelARGB* src = srcPixels + x;
  66795. uint8* shadowPix = shadowChannel + x;
  66796. for (int y = h; --y >= 0;)
  66797. {
  66798. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  66799. *shadowPix = (uint8) shadowAlpha;
  66800. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  66801. shadowPix += destStride;
  66802. }
  66803. }
  66804. for (int y = h; --y >= 0;)
  66805. {
  66806. int shadowAlpha = 0;
  66807. uint8* shadowPix = shadowChannel + y * destStride;
  66808. for (int x = w; --x >= 0;)
  66809. {
  66810. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  66811. *shadowPix++ = (uint8) shadowAlpha;
  66812. }
  66813. }
  66814. image.releasePixelDataReadOnly (srcPixels);
  66815. shadowImage.releasePixelDataReadWrite (shadowChannel);
  66816. g.setColour (Colours::black.withAlpha (opacity));
  66817. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  66818. g.setOpacity (1.0f);
  66819. g.drawImageAt (&image, 0, 0);
  66820. }
  66821. END_JUCE_NAMESPACE
  66822. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  66823. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  66824. BEGIN_JUCE_NAMESPACE
  66825. GlowEffect::GlowEffect()
  66826. : radius (2.0f),
  66827. colour (Colours::white)
  66828. {
  66829. }
  66830. GlowEffect::~GlowEffect()
  66831. {
  66832. }
  66833. void GlowEffect::setGlowProperties (const float newRadius,
  66834. const Colour& newColour)
  66835. {
  66836. radius = newRadius;
  66837. colour = newColour;
  66838. }
  66839. void GlowEffect::applyEffect (Image& image, Graphics& g)
  66840. {
  66841. const int w = image.getWidth();
  66842. const int h = image.getHeight();
  66843. Image temp (image.getFormat(), w, h, true);
  66844. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  66845. blurKernel.createGaussianBlur (radius);
  66846. blurKernel.rescaleAllValues (radius);
  66847. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  66848. g.setColour (colour);
  66849. g.drawImageAt (&temp, 0, 0, true);
  66850. g.setOpacity (1.0f);
  66851. g.drawImageAt (&image, 0, 0, false);
  66852. }
  66853. END_JUCE_NAMESPACE
  66854. /********* End of inlined file: juce_GlowEffect.cpp *********/
  66855. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66856. BEGIN_JUCE_NAMESPACE
  66857. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  66858. : opacity (opacity_)
  66859. {
  66860. }
  66861. ReduceOpacityEffect::~ReduceOpacityEffect()
  66862. {
  66863. }
  66864. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  66865. {
  66866. opacity = jlimit (0.0f, 1.0f, newOpacity);
  66867. }
  66868. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  66869. {
  66870. g.setOpacity (opacity);
  66871. g.drawImageAt (&image, 0, 0);
  66872. }
  66873. END_JUCE_NAMESPACE
  66874. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  66875. /********* Start of inlined file: juce_Font.cpp *********/
  66876. BEGIN_JUCE_NAMESPACE
  66877. static const float minFontHeight = 0.1f;
  66878. static const float maxFontHeight = 10000.0f;
  66879. static const float defaultFontHeight = 14.0f;
  66880. Font::Font() throw()
  66881. : typefaceName (Typeface::defaultTypefaceNameSans),
  66882. height (defaultFontHeight),
  66883. horizontalScale (1.0f),
  66884. kerning (0),
  66885. ascent (0),
  66886. styleFlags (Font::plain)
  66887. {
  66888. }
  66889. void Font::resetToDefaultState() throw()
  66890. {
  66891. typefaceName = Typeface::defaultTypefaceNameSans;
  66892. height = defaultFontHeight;
  66893. horizontalScale = 1.0f;
  66894. kerning = 0;
  66895. ascent = 0;
  66896. styleFlags = Font::plain;
  66897. typeface = 0;
  66898. }
  66899. Font::Font (const float fontHeight,
  66900. const int styleFlags_) throw()
  66901. : typefaceName (Typeface::defaultTypefaceNameSans),
  66902. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66903. horizontalScale (1.0f),
  66904. kerning (0),
  66905. ascent (0),
  66906. styleFlags (styleFlags_)
  66907. {
  66908. }
  66909. Font::Font (const String& typefaceName_,
  66910. const float fontHeight,
  66911. const int styleFlags_) throw()
  66912. : typefaceName (typefaceName_),
  66913. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  66914. horizontalScale (1.0f),
  66915. kerning (0),
  66916. ascent (0),
  66917. styleFlags (styleFlags_)
  66918. {
  66919. }
  66920. Font::Font (const Font& other) throw()
  66921. : typefaceName (other.typefaceName),
  66922. height (other.height),
  66923. horizontalScale (other.horizontalScale),
  66924. kerning (other.kerning),
  66925. ascent (other.ascent),
  66926. styleFlags (other.styleFlags),
  66927. typeface (other.typeface)
  66928. {
  66929. }
  66930. const Font& Font::operator= (const Font& other) throw()
  66931. {
  66932. if (this != &other)
  66933. {
  66934. typefaceName = other.typefaceName;
  66935. height = other.height;
  66936. styleFlags = other.styleFlags;
  66937. horizontalScale = other.horizontalScale;
  66938. kerning = other.kerning;
  66939. ascent = other.ascent;
  66940. typeface = other.typeface;
  66941. }
  66942. return *this;
  66943. }
  66944. Font::~Font() throw()
  66945. {
  66946. }
  66947. Font::Font (const Typeface& face) throw()
  66948. : height (11.0f),
  66949. horizontalScale (1.0f),
  66950. kerning (0),
  66951. ascent (0),
  66952. styleFlags (plain)
  66953. {
  66954. typefaceName = face.getName();
  66955. setBold (face.isBold());
  66956. setItalic (face.isItalic());
  66957. typeface = new Typeface (face);
  66958. }
  66959. bool Font::operator== (const Font& other) const throw()
  66960. {
  66961. return height == other.height
  66962. && horizontalScale == other.horizontalScale
  66963. && kerning == other.kerning
  66964. && styleFlags == other.styleFlags
  66965. && typefaceName == other.typefaceName;
  66966. }
  66967. bool Font::operator!= (const Font& other) const throw()
  66968. {
  66969. return ! operator== (other);
  66970. }
  66971. void Font::setTypefaceName (const String& faceName) throw()
  66972. {
  66973. typefaceName = faceName;
  66974. typeface = 0;
  66975. ascent = 0;
  66976. }
  66977. static String fallbackFont;
  66978. const String Font::getFallbackFontName() throw()
  66979. {
  66980. return fallbackFont;
  66981. }
  66982. void Font::setFallbackFontName (const String& name) throw()
  66983. {
  66984. fallbackFont = name;
  66985. }
  66986. void Font::setHeight (float newHeight) throw()
  66987. {
  66988. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  66989. }
  66990. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  66991. {
  66992. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  66993. horizontalScale *= (height / newHeight);
  66994. height = newHeight;
  66995. }
  66996. void Font::setStyleFlags (const int newFlags) throw()
  66997. {
  66998. if (styleFlags != newFlags)
  66999. {
  67000. styleFlags = newFlags;
  67001. typeface = 0;
  67002. ascent = 0;
  67003. }
  67004. }
  67005. void Font::setSizeAndStyle (const float newHeight,
  67006. const int newStyleFlags,
  67007. const float newHorizontalScale,
  67008. const float newKerningAmount) throw()
  67009. {
  67010. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  67011. horizontalScale = newHorizontalScale;
  67012. kerning = newKerningAmount;
  67013. setStyleFlags (newStyleFlags);
  67014. }
  67015. void Font::setHorizontalScale (const float scaleFactor) throw()
  67016. {
  67017. horizontalScale = scaleFactor;
  67018. }
  67019. void Font::setExtraKerningFactor (const float extraKerning) throw()
  67020. {
  67021. kerning = extraKerning;
  67022. }
  67023. void Font::setBold (const bool shouldBeBold) throw()
  67024. {
  67025. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  67026. : (styleFlags & ~bold));
  67027. }
  67028. bool Font::isBold() const throw()
  67029. {
  67030. return (styleFlags & bold) != 0;
  67031. }
  67032. void Font::setItalic (const bool shouldBeItalic) throw()
  67033. {
  67034. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  67035. : (styleFlags & ~italic));
  67036. }
  67037. bool Font::isItalic() const throw()
  67038. {
  67039. return (styleFlags & italic) != 0;
  67040. }
  67041. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  67042. {
  67043. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  67044. : (styleFlags & ~underlined));
  67045. }
  67046. bool Font::isUnderlined() const throw()
  67047. {
  67048. return (styleFlags & underlined) != 0;
  67049. }
  67050. float Font::getAscent() const throw()
  67051. {
  67052. if (ascent == 0)
  67053. ascent = getTypeface()->getAscent();
  67054. return height * ascent;
  67055. }
  67056. float Font::getDescent() const throw()
  67057. {
  67058. return height - getAscent();
  67059. }
  67060. int Font::getStringWidth (const String& text) const throw()
  67061. {
  67062. return roundFloatToInt (getStringWidthFloat (text));
  67063. }
  67064. float Font::getStringWidthFloat (const String& text) const throw()
  67065. {
  67066. float x = 0.0f;
  67067. if (text.isNotEmpty())
  67068. {
  67069. Typeface* const typeface = getTypeface();
  67070. const juce_wchar* t = (const juce_wchar*) text;
  67071. do
  67072. {
  67073. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  67074. if (glyph != 0)
  67075. x += kerning + glyph->getHorizontalSpacing (*t);
  67076. }
  67077. while (*t != 0);
  67078. x *= height;
  67079. x *= horizontalScale;
  67080. }
  67081. return x;
  67082. }
  67083. Typeface* Font::getTypeface() const throw()
  67084. {
  67085. if (typeface == 0)
  67086. typeface = Typeface::getTypefaceFor (*this);
  67087. return typeface;
  67088. }
  67089. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  67090. {
  67091. const StringArray names (findAllTypefaceNames());
  67092. for (int i = 0; i < names.size(); ++i)
  67093. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  67094. }
  67095. END_JUCE_NAMESPACE
  67096. /********* End of inlined file: juce_Font.cpp *********/
  67097. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  67098. BEGIN_JUCE_NAMESPACE
  67099. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  67100. class FontGlyphAlphaMap
  67101. {
  67102. public:
  67103. bool draw (const Graphics& g, float x, const float y) const throw()
  67104. {
  67105. if (bitmap1 == 0)
  67106. return false;
  67107. x += xOrigin;
  67108. const float xFloor = floorf (x);
  67109. const int intX = (int) xFloor;
  67110. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  67111. intX, (int) floorf (y + yOrigin), true);
  67112. return true;
  67113. }
  67114. juce_UseDebuggingNewOperator
  67115. private:
  67116. Image* bitmap1;
  67117. Image* bitmap2;
  67118. float xOrigin, yOrigin;
  67119. int lastAccessCount;
  67120. Typeface::Ptr typeface;
  67121. float height, horizontalScale;
  67122. juce_wchar character;
  67123. friend class GlyphCache;
  67124. FontGlyphAlphaMap() throw()
  67125. : bitmap1 (0),
  67126. bitmap2 (0),
  67127. lastAccessCount (0),
  67128. height (0),
  67129. horizontalScale (0),
  67130. character (0)
  67131. {
  67132. }
  67133. ~FontGlyphAlphaMap() throw()
  67134. {
  67135. delete bitmap1;
  67136. delete bitmap2;
  67137. }
  67138. class AlphaBitmapRenderer
  67139. {
  67140. uint8* const data;
  67141. const int stride;
  67142. uint8* lineStart;
  67143. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  67144. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  67145. public:
  67146. AlphaBitmapRenderer (uint8* const data_,
  67147. const int stride_) throw()
  67148. : data (data_),
  67149. stride (stride_)
  67150. {
  67151. }
  67152. forcedinline void setEdgeTableYPos (const int y) throw()
  67153. {
  67154. lineStart = data + (stride * y);
  67155. }
  67156. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67157. {
  67158. lineStart [x] = (uint8) alphaLevel;
  67159. }
  67160. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  67161. {
  67162. uint8* d = lineStart + x;
  67163. while (--width >= 0)
  67164. *d++ = (uint8) alphaLevel;
  67165. }
  67166. };
  67167. Image* createAlphaMapFromPath (const Path& path,
  67168. float& topLeftX, float& topLeftY,
  67169. float xScale, float yScale,
  67170. const float subPixelOffsetX) throw()
  67171. {
  67172. Image* im = 0;
  67173. float px, py, pw, ph;
  67174. path.getBounds (px, py, pw, ph);
  67175. topLeftX = floorf (px * xScale);
  67176. topLeftY = floorf (py * yScale);
  67177. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  67178. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  67179. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  67180. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  67181. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  67182. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  67183. int stride, pixelStride;
  67184. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  67185. jassert (pixelStride == 1);
  67186. AlphaBitmapRenderer renderer (pixels, stride);
  67187. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  67188. im->releasePixelDataReadWrite (pixels);
  67189. return im;
  67190. }
  67191. void generate (Typeface* const face,
  67192. const juce_wchar character_,
  67193. const float fontHeight,
  67194. const float fontHorizontalScale) throw()
  67195. {
  67196. character = character_;
  67197. typeface = face;
  67198. height = fontHeight;
  67199. horizontalScale = fontHorizontalScale;
  67200. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  67201. deleteAndZero (bitmap1);
  67202. deleteAndZero (bitmap2);
  67203. const float fontHScale = fontHeight * fontHorizontalScale;
  67204. if (glyphPath != 0 && ! glyphPath->isEmpty())
  67205. {
  67206. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  67207. if (fontHScale < 24.0f)
  67208. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  67209. }
  67210. else
  67211. {
  67212. xOrigin = yOrigin = 0;
  67213. }
  67214. }
  67215. };
  67216. static const int defaultNumGlyphsToCache = 120;
  67217. class GlyphCache;
  67218. static GlyphCache* cacheInstance = 0;
  67219. class GlyphCache : private DeletedAtShutdown
  67220. {
  67221. public:
  67222. static GlyphCache* getInstance() throw()
  67223. {
  67224. if (cacheInstance == 0)
  67225. cacheInstance = new GlyphCache();
  67226. return cacheInstance;
  67227. }
  67228. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  67229. const float fontHeight,
  67230. const float fontHorizontalScale,
  67231. const juce_wchar character) throw()
  67232. {
  67233. ++accessCounter;
  67234. int oldestCounter = INT_MAX;
  67235. int oldestIndex = 0;
  67236. for (int i = numGlyphs; --i >= 0;)
  67237. {
  67238. FontGlyphAlphaMap& g = glyphs[i];
  67239. if (g.character == character
  67240. && g.height == fontHeight
  67241. && g.typeface->hashCode() == typeface->hashCode()
  67242. && g.horizontalScale == fontHorizontalScale)
  67243. {
  67244. g.lastAccessCount = accessCounter;
  67245. ++hits;
  67246. return g;
  67247. }
  67248. if (oldestCounter > g.lastAccessCount)
  67249. {
  67250. oldestCounter = g.lastAccessCount;
  67251. oldestIndex = i;
  67252. }
  67253. }
  67254. ++misses;
  67255. if (hits + misses > (numGlyphs << 4))
  67256. {
  67257. if (misses * 2 > hits)
  67258. setCacheSize (numGlyphs + 32);
  67259. hits = 0;
  67260. misses = 0;
  67261. oldestIndex = 0;
  67262. }
  67263. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  67264. oldest.lastAccessCount = accessCounter;
  67265. oldest.generate (typeface,
  67266. character,
  67267. fontHeight,
  67268. fontHorizontalScale);
  67269. return oldest;
  67270. }
  67271. void setCacheSize (const int num) throw()
  67272. {
  67273. if (numGlyphs != num)
  67274. {
  67275. numGlyphs = num;
  67276. if (glyphs != 0)
  67277. delete[] glyphs;
  67278. glyphs = new FontGlyphAlphaMap [numGlyphs];
  67279. hits = 0;
  67280. misses = 0;
  67281. }
  67282. }
  67283. juce_UseDebuggingNewOperator
  67284. private:
  67285. FontGlyphAlphaMap* glyphs;
  67286. int numGlyphs, accessCounter;
  67287. int hits, misses;
  67288. GlyphCache() throw()
  67289. : glyphs (0),
  67290. numGlyphs (0),
  67291. accessCounter (0)
  67292. {
  67293. setCacheSize (defaultNumGlyphsToCache);
  67294. }
  67295. ~GlyphCache() throw()
  67296. {
  67297. delete[] glyphs;
  67298. jassert (cacheInstance == this);
  67299. cacheInstance = 0;
  67300. }
  67301. GlyphCache (const GlyphCache&);
  67302. const GlyphCache& operator= (const GlyphCache&);
  67303. };
  67304. PositionedGlyph::PositionedGlyph() throw()
  67305. {
  67306. }
  67307. void PositionedGlyph::draw (const Graphics& g) const throw()
  67308. {
  67309. if (! glyphInfo->isWhitespace())
  67310. {
  67311. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  67312. {
  67313. const FontGlyphAlphaMap& alphaMap
  67314. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  67315. fontHeight,
  67316. fontHorizontalScale,
  67317. getCharacter());
  67318. alphaMap.draw (g, x, y);
  67319. }
  67320. else
  67321. {
  67322. // that's a bit of a dodgy size, isn't it??
  67323. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  67324. draw (g, AffineTransform::identity);
  67325. }
  67326. }
  67327. }
  67328. void PositionedGlyph::draw (const Graphics& g,
  67329. const AffineTransform& transform) const throw()
  67330. {
  67331. if (! glyphInfo->isWhitespace())
  67332. {
  67333. g.fillPath (glyphInfo->getPath(),
  67334. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67335. .translated (x, y)
  67336. .followedBy (transform));
  67337. }
  67338. }
  67339. void PositionedGlyph::createPath (Path& path) const throw()
  67340. {
  67341. if (! glyphInfo->isWhitespace())
  67342. {
  67343. path.addPath (glyphInfo->getPath(),
  67344. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  67345. .translated (x, y));
  67346. }
  67347. }
  67348. bool PositionedGlyph::hitTest (float px, float py) const throw()
  67349. {
  67350. if (px >= getLeft() && px < getRight()
  67351. && py >= getTop() && py < getBottom()
  67352. && fontHeight > 0.0f
  67353. && ! glyphInfo->isWhitespace())
  67354. {
  67355. AffineTransform::translation (-x, -y)
  67356. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  67357. .transformPoint (px, py);
  67358. return glyphInfo->getPath().contains (px, py);
  67359. }
  67360. return false;
  67361. }
  67362. void PositionedGlyph::moveBy (const float deltaX,
  67363. const float deltaY) throw()
  67364. {
  67365. x += deltaX;
  67366. y += deltaY;
  67367. }
  67368. GlyphArrangement::GlyphArrangement() throw()
  67369. : numGlyphs (0),
  67370. numAllocated (0),
  67371. glyphs (0)
  67372. {
  67373. }
  67374. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  67375. : numGlyphs (0),
  67376. numAllocated (0),
  67377. glyphs (0)
  67378. {
  67379. addGlyphArrangement (other);
  67380. }
  67381. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  67382. {
  67383. if (this != &other)
  67384. {
  67385. clear();
  67386. addGlyphArrangement (other);
  67387. }
  67388. return *this;
  67389. }
  67390. GlyphArrangement::~GlyphArrangement() throw()
  67391. {
  67392. clear();
  67393. juce_free (glyphs);
  67394. }
  67395. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  67396. {
  67397. if (numAllocated <= minGlyphs)
  67398. {
  67399. numAllocated = minGlyphs + 2;
  67400. if (glyphs == 0)
  67401. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  67402. else
  67403. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  67404. }
  67405. }
  67406. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  67407. {
  67408. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  67409. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67410. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  67411. }
  67412. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  67413. {
  67414. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  67415. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  67416. }
  67417. void GlyphArrangement::clear() throw()
  67418. {
  67419. for (int i = numGlyphs; --i >= 0;)
  67420. decGlyphRefCount (i);
  67421. numGlyphs = 0;
  67422. }
  67423. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  67424. {
  67425. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  67426. return glyphs [index];
  67427. }
  67428. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  67429. {
  67430. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  67431. memcpy (glyphs + numGlyphs, other.glyphs,
  67432. other.numGlyphs * sizeof (PositionedGlyph));
  67433. for (int i = other.numGlyphs; --i >= 0;)
  67434. incGlyphRefCount (numGlyphs++);
  67435. }
  67436. void GlyphArrangement::removeLast() throw()
  67437. {
  67438. if (numGlyphs > 0)
  67439. decGlyphRefCount (--numGlyphs);
  67440. }
  67441. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  67442. {
  67443. jassert (startIndex >= 0);
  67444. if (startIndex < 0)
  67445. startIndex = 0;
  67446. if (num < 0 || startIndex + num >= numGlyphs)
  67447. {
  67448. while (numGlyphs > startIndex)
  67449. removeLast();
  67450. }
  67451. else if (num > 0)
  67452. {
  67453. int i;
  67454. for (i = startIndex; i < startIndex + num; ++i)
  67455. decGlyphRefCount (i);
  67456. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  67457. {
  67458. glyphs [startIndex] = glyphs [startIndex + num];
  67459. ++startIndex;
  67460. }
  67461. numGlyphs -= num;
  67462. }
  67463. }
  67464. void GlyphArrangement::addLineOfText (const Font& font,
  67465. const String& text,
  67466. const float xOffset,
  67467. const float yOffset) throw()
  67468. {
  67469. addCurtailedLineOfText (font, text,
  67470. xOffset, yOffset,
  67471. 1.0e10f, false);
  67472. }
  67473. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  67474. const String& text,
  67475. float xOffset,
  67476. const float yOffset,
  67477. const float maxWidthPixels,
  67478. const bool useEllipsis) throw()
  67479. {
  67480. const int textLen = text.length();
  67481. if (textLen > 0)
  67482. {
  67483. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  67484. Typeface* const typeface = font.getTypeface();
  67485. const float fontHeight = font.getHeight();
  67486. const float ascent = font.getAscent();
  67487. const float fontHorizontalScale = font.getHorizontalScale();
  67488. const float heightTimesScale = fontHorizontalScale * fontHeight;
  67489. const float kerningFactor = font.getExtraKerningFactor();
  67490. const float startX = xOffset;
  67491. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  67492. for (int i = 0; i < textLen; ++i)
  67493. {
  67494. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  67495. if (glyph != 0)
  67496. {
  67497. jassert (numAllocated > numGlyphs);
  67498. ensureNumGlyphsAllocated (numGlyphs);
  67499. PositionedGlyph& pg = glyphs [numGlyphs];
  67500. pg.glyphInfo = glyph;
  67501. pg.x = xOffset;
  67502. pg.y = yOffset;
  67503. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  67504. pg.fontHeight = fontHeight;
  67505. pg.fontAscent = ascent;
  67506. pg.fontHorizontalScale = fontHorizontalScale;
  67507. pg.isUnderlined = font.isUnderlined();
  67508. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  67509. if (xOffset - startX > maxWidthPixels + 1.0f)
  67510. {
  67511. // curtail the string if it's too wide..
  67512. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  67513. appendEllipsis (font, startX + maxWidthPixels);
  67514. break;
  67515. }
  67516. else
  67517. {
  67518. if (glyph->getTypeface() != 0)
  67519. glyph->getTypeface()->incReferenceCount();
  67520. ++numGlyphs;
  67521. }
  67522. }
  67523. }
  67524. }
  67525. }
  67526. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  67527. {
  67528. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  67529. if (dotGlyph != 0)
  67530. {
  67531. if (numGlyphs > 0)
  67532. {
  67533. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  67534. const float fontHeight = glyph.fontHeight;
  67535. const float fontHorizontalScale = glyph.fontHorizontalScale;
  67536. const float fontAscent = glyph.fontAscent;
  67537. const float dx = fontHeight * fontHorizontalScale
  67538. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  67539. float xOffset = 0.0f, yOffset = 0.0f;
  67540. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  67541. {
  67542. removeLast();
  67543. jassert (numAllocated > numGlyphs);
  67544. PositionedGlyph& pg = glyphs [numGlyphs];
  67545. xOffset = pg.x;
  67546. yOffset = pg.y;
  67547. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  67548. break;
  67549. }
  67550. for (int i = 3; --i >= 0;)
  67551. {
  67552. jassert (numAllocated > numGlyphs);
  67553. ensureNumGlyphsAllocated (numGlyphs);
  67554. PositionedGlyph& pg = glyphs [numGlyphs];
  67555. pg.glyphInfo = dotGlyph;
  67556. pg.x = xOffset;
  67557. pg.y = yOffset;
  67558. pg.w = dx;
  67559. pg.fontHeight = fontHeight;
  67560. pg.fontAscent = fontAscent;
  67561. pg.fontHorizontalScale = fontHorizontalScale;
  67562. pg.isUnderlined = font.isUnderlined();
  67563. xOffset += dx;
  67564. if (dotGlyph->getTypeface() != 0)
  67565. dotGlyph->getTypeface()->incReferenceCount();
  67566. ++numGlyphs;
  67567. }
  67568. }
  67569. }
  67570. }
  67571. void GlyphArrangement::addJustifiedText (const Font& font,
  67572. const String& text,
  67573. float x, float y,
  67574. const float maxLineWidth,
  67575. const Justification& horizontalLayout) throw()
  67576. {
  67577. int lineStartIndex = numGlyphs;
  67578. addLineOfText (font, text, x, y);
  67579. const float originalY = y;
  67580. while (lineStartIndex < numGlyphs)
  67581. {
  67582. int i = lineStartIndex;
  67583. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  67584. ++i;
  67585. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  67586. int lastWordBreakIndex = -1;
  67587. while (i < numGlyphs)
  67588. {
  67589. PositionedGlyph& pg = glyphs[i];
  67590. const juce_wchar c = pg.getCharacter();
  67591. if (c == T('\r') || c == T('\n'))
  67592. {
  67593. ++i;
  67594. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  67595. ++i;
  67596. break;
  67597. }
  67598. else if (pg.isWhitespace())
  67599. {
  67600. lastWordBreakIndex = i + 1;
  67601. }
  67602. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  67603. {
  67604. if (lastWordBreakIndex >= 0)
  67605. i = lastWordBreakIndex;
  67606. break;
  67607. }
  67608. ++i;
  67609. }
  67610. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  67611. float currentLineEndX = currentLineStartX;
  67612. for (int j = i; --j >= lineStartIndex;)
  67613. {
  67614. if (! glyphs[j].isWhitespace())
  67615. {
  67616. currentLineEndX = glyphs[j].getRight();
  67617. break;
  67618. }
  67619. }
  67620. float deltaX = 0.0f;
  67621. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  67622. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  67623. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  67624. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  67625. else if (horizontalLayout.testFlags (Justification::right))
  67626. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  67627. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  67628. x + deltaX - currentLineStartX, y - originalY);
  67629. lineStartIndex = i;
  67630. y += font.getHeight();
  67631. }
  67632. }
  67633. void GlyphArrangement::addFittedText (const Font& f,
  67634. const String& text,
  67635. float x, float y,
  67636. float width, float height,
  67637. const Justification& layout,
  67638. int maximumLines,
  67639. const float minimumHorizontalScale) throw()
  67640. {
  67641. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  67642. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  67643. if (text.containsAnyOf (T("\r\n")))
  67644. {
  67645. GlyphArrangement ga;
  67646. ga.addJustifiedText (f, text, x, y, width, layout);
  67647. float l, t, r, b;
  67648. ga.getBoundingBox (0, -1, l, t, r, b, false);
  67649. float dy = y - t;
  67650. if (layout.testFlags (Justification::verticallyCentred))
  67651. dy += (height - (b - t)) * 0.5f;
  67652. else if (layout.testFlags (Justification::bottom))
  67653. dy += height - (b - t);
  67654. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  67655. addGlyphArrangement (ga);
  67656. return;
  67657. }
  67658. int startIndex = numGlyphs;
  67659. addLineOfText (f, text.trim(), x, y);
  67660. if (numGlyphs > startIndex)
  67661. {
  67662. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67663. if (lineWidth <= 0)
  67664. return;
  67665. if (lineWidth * minimumHorizontalScale < width)
  67666. {
  67667. if (lineWidth > width)
  67668. {
  67669. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  67670. width / lineWidth);
  67671. }
  67672. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67673. x, y, width, height, layout);
  67674. }
  67675. else if (maximumLines <= 1)
  67676. {
  67677. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  67678. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  67679. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  67680. removeLast();
  67681. appendEllipsis (f, x + width);
  67682. justifyGlyphs (startIndex, numGlyphs - startIndex,
  67683. x, y, width, height, layout);
  67684. }
  67685. else
  67686. {
  67687. Font font (f);
  67688. String txt (text.trim());
  67689. const int length = txt.length();
  67690. int numLines = 1;
  67691. const int originalStartIndex = startIndex;
  67692. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  67693. maximumLines = 1;
  67694. maximumLines = jmin (maximumLines, length);
  67695. while (numLines < maximumLines)
  67696. {
  67697. ++numLines;
  67698. const float newFontHeight = height / (float)numLines;
  67699. if (newFontHeight < 8.0f)
  67700. break;
  67701. if (newFontHeight < font.getHeight())
  67702. {
  67703. font.setHeight (newFontHeight);
  67704. while (numGlyphs > startIndex)
  67705. removeLast();
  67706. addLineOfText (font, txt, x, y);
  67707. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  67708. }
  67709. if (numLines > lineWidth / width)
  67710. break;
  67711. }
  67712. if (numLines < 1)
  67713. numLines = 1;
  67714. float lineY = y;
  67715. float widthPerLine = lineWidth / numLines;
  67716. int lastLineStartIndex = 0;
  67717. for (int line = 0; line < numLines; ++line)
  67718. {
  67719. int i = startIndex;
  67720. lastLineStartIndex = i;
  67721. float lineStartX = glyphs[startIndex].getLeft();
  67722. while (i < numGlyphs)
  67723. {
  67724. lineWidth = (glyphs[i].getRight() - lineStartX);
  67725. if (lineWidth > widthPerLine)
  67726. {
  67727. // got to a point where the line's too long, so skip forward to find a
  67728. // good place to break it..
  67729. const int searchStartIndex = i;
  67730. while (i < numGlyphs)
  67731. {
  67732. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  67733. {
  67734. if (glyphs[i].isWhitespace()
  67735. || glyphs[i].getCharacter() == T('-'))
  67736. {
  67737. ++i;
  67738. break;
  67739. }
  67740. }
  67741. else
  67742. {
  67743. // can't find a suitable break, so try looking backwards..
  67744. i = searchStartIndex;
  67745. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  67746. {
  67747. if (glyphs[i - back].isWhitespace()
  67748. || glyphs[i - back].getCharacter() == T('-'))
  67749. {
  67750. i -= back - 1;
  67751. break;
  67752. }
  67753. }
  67754. break;
  67755. }
  67756. ++i;
  67757. }
  67758. break;
  67759. }
  67760. ++i;
  67761. }
  67762. int wsStart = i;
  67763. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  67764. --wsStart;
  67765. int wsEnd = i;
  67766. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  67767. ++wsEnd;
  67768. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  67769. i = jmax (wsStart, startIndex + 1);
  67770. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  67771. if (lineWidth > width)
  67772. {
  67773. stretchRangeOfGlyphs (startIndex, i - startIndex,
  67774. width / lineWidth);
  67775. }
  67776. justifyGlyphs (startIndex, i - startIndex,
  67777. x, lineY, width, font.getHeight(),
  67778. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67779. startIndex = i;
  67780. lineY += font.getHeight();
  67781. if (startIndex >= numGlyphs)
  67782. break;
  67783. }
  67784. if (startIndex < numGlyphs)
  67785. {
  67786. while (numGlyphs > startIndex)
  67787. removeLast();
  67788. if (startIndex - originalStartIndex > 4)
  67789. {
  67790. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  67791. appendEllipsis (font, lineStartX + width);
  67792. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  67793. if (lineWidth > width)
  67794. {
  67795. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67796. width / lineWidth);
  67797. }
  67798. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  67799. x, lineY - font.getHeight(), width, font.getHeight(),
  67800. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  67801. }
  67802. startIndex = numGlyphs;
  67803. }
  67804. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  67805. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  67806. }
  67807. }
  67808. }
  67809. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  67810. const float dx, const float dy) throw()
  67811. {
  67812. jassert (startIndex >= 0);
  67813. if (dx != 0.0f || dy != 0.0f)
  67814. {
  67815. if (num < 0 || startIndex + num > numGlyphs)
  67816. num = numGlyphs - startIndex;
  67817. while (--num >= 0)
  67818. {
  67819. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67820. glyphs [startIndex++].moveBy (dx, dy);
  67821. }
  67822. }
  67823. }
  67824. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  67825. const float horizontalScaleFactor) throw()
  67826. {
  67827. jassert (startIndex >= 0);
  67828. if (num < 0 || startIndex + num > numGlyphs)
  67829. num = numGlyphs - startIndex;
  67830. if (num > 0)
  67831. {
  67832. const float xAnchor = glyphs[startIndex].getLeft();
  67833. while (--num >= 0)
  67834. {
  67835. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  67836. PositionedGlyph& pg = glyphs[startIndex++];
  67837. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  67838. pg.fontHorizontalScale *= horizontalScaleFactor;
  67839. pg.w *= horizontalScaleFactor;
  67840. }
  67841. }
  67842. }
  67843. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  67844. float& left,
  67845. float& top,
  67846. float& right,
  67847. float& bottom,
  67848. const bool includeWhitespace) const throw()
  67849. {
  67850. jassert (startIndex >= 0);
  67851. if (num < 0 || startIndex + num > numGlyphs)
  67852. num = numGlyphs - startIndex;
  67853. left = 0.0f;
  67854. top = 0.0f;
  67855. right = 0.0f;
  67856. bottom = 0.0f;
  67857. bool isFirst = true;
  67858. while (--num >= 0)
  67859. {
  67860. const PositionedGlyph& pg = glyphs [startIndex++];
  67861. if (includeWhitespace || ! pg.isWhitespace())
  67862. {
  67863. if (isFirst)
  67864. {
  67865. isFirst = false;
  67866. left = pg.getLeft();
  67867. top = pg.getTop();
  67868. right = pg.getRight();
  67869. bottom = pg.getBottom();
  67870. }
  67871. else
  67872. {
  67873. left = jmin (left, pg.getLeft());
  67874. top = jmin (top, pg.getTop());
  67875. right = jmax (right, pg.getRight());
  67876. bottom = jmax (bottom, pg.getBottom());
  67877. }
  67878. }
  67879. }
  67880. }
  67881. void GlyphArrangement::justifyGlyphs (const int startIndex,
  67882. const int num,
  67883. const float x, const float y,
  67884. const float width, const float height,
  67885. const Justification& justification) throw()
  67886. {
  67887. jassert (num >= 0 && startIndex >= 0);
  67888. if (numGlyphs > 0 && num > 0)
  67889. {
  67890. float left, top, right, bottom;
  67891. getBoundingBox (startIndex, num, left, top, right, bottom,
  67892. ! justification.testFlags (Justification::horizontallyJustified
  67893. | Justification::horizontallyCentred));
  67894. float deltaX = 0.0f;
  67895. if (justification.testFlags (Justification::horizontallyJustified))
  67896. deltaX = x - left;
  67897. else if (justification.testFlags (Justification::horizontallyCentred))
  67898. deltaX = x + (width - (right - left)) * 0.5f - left;
  67899. else if (justification.testFlags (Justification::right))
  67900. deltaX = (x + width) - right;
  67901. else
  67902. deltaX = x - left;
  67903. float deltaY = 0.0f;
  67904. if (justification.testFlags (Justification::top))
  67905. deltaY = y - top;
  67906. else if (justification.testFlags (Justification::bottom))
  67907. deltaY = (y + height) - bottom;
  67908. else
  67909. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  67910. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  67911. if (justification.testFlags (Justification::horizontallyJustified))
  67912. {
  67913. int lineStart = 0;
  67914. float baseY = glyphs [startIndex].getBaselineY();
  67915. int i;
  67916. for (i = 0; i < num; ++i)
  67917. {
  67918. const float glyphY = glyphs [startIndex + i].getBaselineY();
  67919. if (glyphY != baseY)
  67920. {
  67921. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67922. lineStart = i;
  67923. baseY = glyphY;
  67924. }
  67925. }
  67926. if (i > lineStart)
  67927. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  67928. }
  67929. }
  67930. }
  67931. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  67932. {
  67933. if (start + num < numGlyphs
  67934. && glyphs [start + num - 1].getCharacter() != T('\r')
  67935. && glyphs [start + num - 1].getCharacter() != T('\n'))
  67936. {
  67937. int numSpaces = 0;
  67938. int spacesAtEnd = 0;
  67939. for (int i = 0; i < num; ++i)
  67940. {
  67941. if (glyphs [start + i].isWhitespace())
  67942. {
  67943. ++spacesAtEnd;
  67944. ++numSpaces;
  67945. }
  67946. else
  67947. {
  67948. spacesAtEnd = 0;
  67949. }
  67950. }
  67951. numSpaces -= spacesAtEnd;
  67952. if (numSpaces > 0)
  67953. {
  67954. const float startX = glyphs [start].getLeft();
  67955. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  67956. const float extraPaddingBetweenWords
  67957. = (targetWidth - (endX - startX)) / (float) numSpaces;
  67958. float deltaX = 0.0f;
  67959. for (int i = 0; i < num; ++i)
  67960. {
  67961. glyphs [start + i].moveBy (deltaX, 0.0);
  67962. if (glyphs [start + i].isWhitespace())
  67963. deltaX += extraPaddingBetweenWords;
  67964. }
  67965. }
  67966. }
  67967. }
  67968. void GlyphArrangement::draw (const Graphics& g) const throw()
  67969. {
  67970. for (int i = 0; i < numGlyphs; ++i)
  67971. {
  67972. glyphs[i].draw (g);
  67973. if (glyphs[i].isUnderlined)
  67974. {
  67975. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67976. juce_wchar nextChar = 0;
  67977. if (i < numGlyphs - 1
  67978. && glyphs[i + 1].y == glyphs[i].y)
  67979. {
  67980. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  67981. }
  67982. g.fillRect (glyphs[i].x,
  67983. glyphs[i].y + lineThickness * 2.0f,
  67984. glyphs[i].fontHeight
  67985. * glyphs[i].fontHorizontalScale
  67986. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  67987. lineThickness);
  67988. }
  67989. }
  67990. }
  67991. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  67992. {
  67993. for (int i = 0; i < numGlyphs; ++i)
  67994. {
  67995. glyphs[i].draw (g, transform);
  67996. if (glyphs[i].isUnderlined)
  67997. {
  67998. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  67999. juce_wchar nextChar = 0;
  68000. if (i < numGlyphs - 1
  68001. && glyphs[i + 1].y == glyphs[i].y)
  68002. {
  68003. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  68004. }
  68005. Path p;
  68006. p.addLineSegment (glyphs[i].x,
  68007. glyphs[i].y + lineThickness * 2.5f,
  68008. glyphs[i].x + glyphs[i].fontHeight
  68009. * glyphs[i].fontHorizontalScale
  68010. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  68011. glyphs[i].y + lineThickness * 2.5f,
  68012. lineThickness);
  68013. g.fillPath (p, transform);
  68014. }
  68015. }
  68016. }
  68017. void GlyphArrangement::createPath (Path& path) const throw()
  68018. {
  68019. for (int i = 0; i < numGlyphs; ++i)
  68020. glyphs[i].createPath (path);
  68021. }
  68022. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  68023. {
  68024. for (int i = 0; i < numGlyphs; ++i)
  68025. if (glyphs[i].hitTest (x, y))
  68026. return i;
  68027. return -1;
  68028. }
  68029. END_JUCE_NAMESPACE
  68030. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  68031. /********* Start of inlined file: juce_TextLayout.cpp *********/
  68032. BEGIN_JUCE_NAMESPACE
  68033. class TextLayoutToken
  68034. {
  68035. public:
  68036. String text;
  68037. Font font;
  68038. int x, y, w, h;
  68039. int line, lineHeight;
  68040. bool isWhitespace, isNewLine;
  68041. TextLayoutToken (const String& t,
  68042. const Font& f,
  68043. const bool isWhitespace_) throw()
  68044. : text (t),
  68045. font (f),
  68046. x(0),
  68047. y(0),
  68048. isWhitespace (isWhitespace_)
  68049. {
  68050. w = font.getStringWidth (t);
  68051. h = roundFloatToInt (f.getHeight());
  68052. isNewLine = t.containsAnyOf (T("\r\n"));
  68053. }
  68054. TextLayoutToken (const TextLayoutToken& other) throw()
  68055. : text (other.text),
  68056. font (other.font),
  68057. x (other.x),
  68058. y (other.y),
  68059. w (other.w),
  68060. h (other.h),
  68061. line (other.line),
  68062. lineHeight (other.lineHeight),
  68063. isWhitespace (other.isWhitespace),
  68064. isNewLine (other.isNewLine)
  68065. {
  68066. }
  68067. ~TextLayoutToken() throw()
  68068. {
  68069. }
  68070. void draw (Graphics& g,
  68071. const int xOffset,
  68072. const int yOffset) throw()
  68073. {
  68074. if (! isWhitespace)
  68075. {
  68076. g.setFont (font);
  68077. g.drawSingleLineText (text.trimEnd(),
  68078. xOffset + x,
  68079. yOffset + y + (lineHeight - h)
  68080. + roundFloatToInt (font.getAscent()));
  68081. }
  68082. }
  68083. juce_UseDebuggingNewOperator
  68084. };
  68085. TextLayout::TextLayout() throw()
  68086. : tokens (64),
  68087. totalLines (0)
  68088. {
  68089. }
  68090. TextLayout::TextLayout (const String& text,
  68091. const Font& font) throw()
  68092. : tokens (64),
  68093. totalLines (0)
  68094. {
  68095. appendText (text, font);
  68096. }
  68097. TextLayout::TextLayout (const TextLayout& other) throw()
  68098. : tokens (64),
  68099. totalLines (0)
  68100. {
  68101. *this = other;
  68102. }
  68103. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  68104. {
  68105. if (this != &other)
  68106. {
  68107. clear();
  68108. totalLines = other.totalLines;
  68109. for (int i = 0; i < other.tokens.size(); ++i)
  68110. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  68111. }
  68112. return *this;
  68113. }
  68114. TextLayout::~TextLayout() throw()
  68115. {
  68116. clear();
  68117. }
  68118. void TextLayout::clear() throw()
  68119. {
  68120. for (int i = tokens.size(); --i >= 0;)
  68121. {
  68122. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68123. delete t;
  68124. }
  68125. tokens.clear();
  68126. totalLines = 0;
  68127. }
  68128. void TextLayout::appendText (const String& text,
  68129. const Font& font) throw()
  68130. {
  68131. const tchar* t = text;
  68132. String currentString;
  68133. int lastCharType = 0;
  68134. for (;;)
  68135. {
  68136. const tchar c = *t++;
  68137. if (c == 0)
  68138. break;
  68139. int charType;
  68140. if (c == T('\r') || c == T('\n'))
  68141. {
  68142. charType = 0;
  68143. }
  68144. else if (CharacterFunctions::isWhitespace (c))
  68145. {
  68146. charType = 2;
  68147. }
  68148. else
  68149. {
  68150. charType = 1;
  68151. }
  68152. if (charType == 0 || charType != lastCharType)
  68153. {
  68154. if (currentString.isNotEmpty())
  68155. {
  68156. tokens.add (new TextLayoutToken (currentString, font,
  68157. lastCharType == 2 || lastCharType == 0));
  68158. }
  68159. currentString = String::charToString (c);
  68160. if (c == T('\r') && *t == T('\n'))
  68161. currentString += *t++;
  68162. }
  68163. else
  68164. {
  68165. currentString += c;
  68166. }
  68167. lastCharType = charType;
  68168. }
  68169. if (currentString.isNotEmpty())
  68170. tokens.add (new TextLayoutToken (currentString,
  68171. font,
  68172. lastCharType == 2));
  68173. }
  68174. void TextLayout::setText (const String& text, const Font& font) throw()
  68175. {
  68176. clear();
  68177. appendText (text, font);
  68178. }
  68179. void TextLayout::layout (int maxWidth,
  68180. const Justification& justification,
  68181. const bool attemptToBalanceLineLengths) throw()
  68182. {
  68183. if (attemptToBalanceLineLengths)
  68184. {
  68185. const int originalW = maxWidth;
  68186. int bestWidth = maxWidth;
  68187. float bestLineProportion = 0.0f;
  68188. while (maxWidth > originalW / 2)
  68189. {
  68190. layout (maxWidth, justification, false);
  68191. if (getNumLines() <= 1)
  68192. return;
  68193. const int lastLineW = getLineWidth (getNumLines() - 1);
  68194. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  68195. const float prop = lastLineW / (float) lastButOneLineW;
  68196. if (prop > 0.9f)
  68197. return;
  68198. if (prop > bestLineProportion)
  68199. {
  68200. bestLineProportion = prop;
  68201. bestWidth = maxWidth;
  68202. }
  68203. maxWidth -= 10;
  68204. }
  68205. layout (bestWidth, justification, false);
  68206. }
  68207. else
  68208. {
  68209. int x = 0;
  68210. int y = 0;
  68211. int h = 0;
  68212. totalLines = 0;
  68213. int i;
  68214. for (i = 0; i < tokens.size(); ++i)
  68215. {
  68216. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  68217. t->x = x;
  68218. t->y = y;
  68219. t->line = totalLines;
  68220. x += t->w;
  68221. h = jmax (h, t->h);
  68222. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  68223. if (nextTok == 0)
  68224. break;
  68225. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  68226. {
  68227. // finished a line, so go back and update the heights of the things on it
  68228. for (int j = i; j >= 0; --j)
  68229. {
  68230. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  68231. if (tok->line == totalLines)
  68232. tok->lineHeight = h;
  68233. else
  68234. break;
  68235. }
  68236. x = 0;
  68237. y += h;
  68238. h = 0;
  68239. ++totalLines;
  68240. }
  68241. }
  68242. // finished a line, so go back and update the heights of the things on it
  68243. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  68244. {
  68245. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  68246. if (t->line == totalLines)
  68247. t->lineHeight = h;
  68248. else
  68249. break;
  68250. }
  68251. ++totalLines;
  68252. if (! justification.testFlags (Justification::left))
  68253. {
  68254. int totalW = getWidth();
  68255. for (i = totalLines; --i >= 0;)
  68256. {
  68257. const int lineW = getLineWidth (i);
  68258. int dx = 0;
  68259. if (justification.testFlags (Justification::horizontallyCentred))
  68260. dx = (totalW - lineW) / 2;
  68261. else if (justification.testFlags (Justification::right))
  68262. dx = totalW - lineW;
  68263. for (int j = tokens.size(); --j >= 0;)
  68264. {
  68265. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  68266. if (t->line == i)
  68267. t->x += dx;
  68268. }
  68269. }
  68270. }
  68271. }
  68272. }
  68273. int TextLayout::getLineWidth (const int lineNumber) const throw()
  68274. {
  68275. int maxW = 0;
  68276. for (int i = tokens.size(); --i >= 0;)
  68277. {
  68278. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68279. if (t->line == lineNumber && ! t->isWhitespace)
  68280. maxW = jmax (maxW, t->x + t->w);
  68281. }
  68282. return maxW;
  68283. }
  68284. int TextLayout::getWidth() const throw()
  68285. {
  68286. int maxW = 0;
  68287. for (int i = tokens.size(); --i >= 0;)
  68288. {
  68289. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68290. if (! t->isWhitespace)
  68291. maxW = jmax (maxW, t->x + t->w);
  68292. }
  68293. return maxW;
  68294. }
  68295. int TextLayout::getHeight() const throw()
  68296. {
  68297. int maxH = 0;
  68298. for (int i = tokens.size(); --i >= 0;)
  68299. {
  68300. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  68301. if (! t->isWhitespace)
  68302. maxH = jmax (maxH, t->y + t->h);
  68303. }
  68304. return maxH;
  68305. }
  68306. void TextLayout::draw (Graphics& g,
  68307. const int xOffset,
  68308. const int yOffset) const throw()
  68309. {
  68310. for (int i = tokens.size(); --i >= 0;)
  68311. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  68312. }
  68313. void TextLayout::drawWithin (Graphics& g,
  68314. int x, int y, int w, int h,
  68315. const Justification& justification) const throw()
  68316. {
  68317. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  68318. x, y, w, h);
  68319. draw (g, x, y);
  68320. }
  68321. END_JUCE_NAMESPACE
  68322. /********* End of inlined file: juce_TextLayout.cpp *********/
  68323. /********* Start of inlined file: juce_Typeface.cpp *********/
  68324. BEGIN_JUCE_NAMESPACE
  68325. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  68326. const Path& shape,
  68327. const float horizontalSeparation,
  68328. Typeface* const typeface_) throw()
  68329. : character (character_),
  68330. path (shape),
  68331. width (horizontalSeparation),
  68332. typeface (typeface_)
  68333. {
  68334. }
  68335. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  68336. {
  68337. }
  68338. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  68339. {
  68340. if (subsequentCharacter != 0)
  68341. {
  68342. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  68343. const int numPairs = getNumKerningPairs();
  68344. for (int i = 0; i < numPairs; ++i)
  68345. if (pairs [i].character2 == subsequentCharacter)
  68346. return width + pairs [i].kerningAmount;
  68347. }
  68348. return width;
  68349. }
  68350. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  68351. const float extraKerningAmount) throw()
  68352. {
  68353. const int numPairs = getNumKerningPairs();
  68354. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  68355. KerningPair& p = getKerningPair (numPairs);
  68356. p.character2 = subsequentCharacter;
  68357. p.kerningAmount = extraKerningAmount;
  68358. }
  68359. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  68360. {
  68361. return ((KerningPair*) kerningPairs.getData()) [index];
  68362. }
  68363. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  68364. {
  68365. return kerningPairs.getSize() / sizeof (KerningPair);
  68366. }
  68367. const tchar* Typeface::defaultTypefaceNameSans = T("<Sans-Serif>");
  68368. const tchar* Typeface::defaultTypefaceNameSerif = T("<Serif>");
  68369. const tchar* Typeface::defaultTypefaceNameMono = T("<Monospaced>");
  68370. Typeface::Typeface() throw()
  68371. : hash (0),
  68372. isFullyPopulated (false)
  68373. {
  68374. zeromem (lookupTable, sizeof (lookupTable));
  68375. }
  68376. Typeface::Typeface (const Typeface& other)
  68377. : typefaceName (other.typefaceName),
  68378. ascent (other.ascent),
  68379. bold (other.bold),
  68380. italic (other.italic),
  68381. isFullyPopulated (other.isFullyPopulated),
  68382. defaultCharacter (other.defaultCharacter)
  68383. {
  68384. zeromem (lookupTable, sizeof (lookupTable));
  68385. for (int i = 0; i < other.glyphs.size(); ++i)
  68386. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68387. updateHashCode();
  68388. }
  68389. Typeface::Typeface (const String& faceName,
  68390. const bool bold,
  68391. const bool italic)
  68392. : isFullyPopulated (false)
  68393. {
  68394. zeromem (lookupTable, sizeof (lookupTable));
  68395. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  68396. updateHashCode();
  68397. }
  68398. Typeface::~Typeface()
  68399. {
  68400. clear();
  68401. }
  68402. const Typeface& Typeface::operator= (const Typeface& other) throw()
  68403. {
  68404. if (this != &other)
  68405. {
  68406. clear();
  68407. typefaceName = other.typefaceName;
  68408. ascent = other.ascent;
  68409. bold = other.bold;
  68410. italic = other.italic;
  68411. isFullyPopulated = other.isFullyPopulated;
  68412. defaultCharacter = other.defaultCharacter;
  68413. for (int i = 0; i < other.glyphs.size(); ++i)
  68414. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  68415. updateHashCode();
  68416. }
  68417. return *this;
  68418. }
  68419. void Typeface::updateHashCode() throw()
  68420. {
  68421. hash = typefaceName.hashCode();
  68422. if (bold)
  68423. hash ^= 0xffff;
  68424. if (italic)
  68425. hash ^= 0xffff0000;
  68426. }
  68427. void Typeface::clear() throw()
  68428. {
  68429. zeromem (lookupTable, sizeof (lookupTable));
  68430. typefaceName = String::empty;
  68431. bold = false;
  68432. italic = false;
  68433. for (int i = glyphs.size(); --i >= 0;)
  68434. {
  68435. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  68436. delete g;
  68437. }
  68438. glyphs.clear();
  68439. updateHashCode();
  68440. }
  68441. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  68442. {
  68443. zeromem (lookupTable, sizeof (lookupTable));
  68444. isFullyPopulated = true;
  68445. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  68446. BufferedInputStream in (&gzin, 32768, false);
  68447. typefaceName = in.readString();
  68448. bold = in.readBool();
  68449. italic = in.readBool();
  68450. ascent = in.readFloat();
  68451. defaultCharacter = (juce_wchar) in.readShort();
  68452. int i, numChars = in.readInt();
  68453. for (i = 0; i < numChars; ++i)
  68454. {
  68455. const juce_wchar c = (juce_wchar) in.readShort();
  68456. const float width = in.readFloat();
  68457. Path p;
  68458. p.loadPathFromStream (in);
  68459. addGlyph (c, p, width);
  68460. }
  68461. const int numKerningPairs = in.readInt();
  68462. for (i = 0; i < numKerningPairs; ++i)
  68463. {
  68464. const juce_wchar char1 = (juce_wchar) in.readShort();
  68465. const juce_wchar char2 = (juce_wchar) in.readShort();
  68466. addKerningPair (char1, char2, in.readFloat());
  68467. }
  68468. updateHashCode();
  68469. }
  68470. void Typeface::serialise (OutputStream& outputStream)
  68471. {
  68472. GZIPCompressorOutputStream out (&outputStream);
  68473. out.writeString (typefaceName);
  68474. out.writeBool (bold);
  68475. out.writeBool (italic);
  68476. out.writeFloat (ascent);
  68477. out.writeShort ((short) (unsigned short) defaultCharacter);
  68478. out.writeInt (glyphs.size());
  68479. int i, numKerningPairs = 0;
  68480. for (i = 0; i < glyphs.size(); ++i)
  68481. {
  68482. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68483. out.writeShort ((short) (unsigned short) g.character);
  68484. out.writeFloat (g.width);
  68485. g.path.writePathToStream (out);
  68486. numKerningPairs += g.getNumKerningPairs();
  68487. }
  68488. out.writeInt (numKerningPairs);
  68489. for (i = 0; i < glyphs.size(); ++i)
  68490. {
  68491. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  68492. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  68493. {
  68494. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  68495. out.writeShort ((short) (unsigned short) g.character);
  68496. out.writeShort ((short) (unsigned short) p.character2);
  68497. out.writeFloat (p.kerningAmount);
  68498. }
  68499. }
  68500. }
  68501. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  68502. {
  68503. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  68504. if (g != 0)
  68505. return &(g->path);
  68506. else
  68507. return 0;
  68508. }
  68509. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  68510. {
  68511. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  68512. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68513. for (int i = 0; i < glyphs.size(); ++i)
  68514. {
  68515. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68516. if (g->character == character)
  68517. return g;
  68518. }
  68519. if ((! isFullyPopulated)
  68520. && findAndAddSystemGlyph (character))
  68521. {
  68522. for (int i = 0; i < glyphs.size(); ++i)
  68523. {
  68524. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68525. if (g->character == character)
  68526. return g;
  68527. }
  68528. }
  68529. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  68530. {
  68531. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  68532. if (spaceGlyph != 0)
  68533. {
  68534. // Add a copy of the empty glyph, mapped onto this character
  68535. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  68536. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  68537. }
  68538. return spaceGlyph;
  68539. }
  68540. else if (character != defaultCharacter)
  68541. {
  68542. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  68543. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  68544. if (fallbackTypeface != 0 && fallbackTypeface != this)
  68545. return fallbackTypeface->getGlyph (character);
  68546. return getGlyph (defaultCharacter);
  68547. }
  68548. return 0;
  68549. }
  68550. void Typeface::addGlyph (const juce_wchar character,
  68551. const Path& path,
  68552. const float horizontalSpacing) throw()
  68553. {
  68554. #ifdef JUCE_DEBUG
  68555. for (int i = 0; i < glyphs.size(); ++i)
  68556. {
  68557. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  68558. if (g->character == character)
  68559. jassertfalse;
  68560. }
  68561. #endif
  68562. if (((unsigned int) character) < 128)
  68563. lookupTable [character] = (short) glyphs.size();
  68564. glyphs.add (new TypefaceGlyphInfo (character,
  68565. path,
  68566. horizontalSpacing,
  68567. this));
  68568. }
  68569. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  68570. {
  68571. if (glyphInfoToCopy != 0)
  68572. {
  68573. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  68574. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  68575. TypefaceGlyphInfo* const newOne
  68576. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  68577. glyphInfoToCopy->path,
  68578. glyphInfoToCopy->width,
  68579. this);
  68580. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  68581. glyphs.add (newOne);
  68582. }
  68583. }
  68584. void Typeface::addKerningPair (const juce_wchar char1,
  68585. const juce_wchar char2,
  68586. const float extraAmount) throw()
  68587. {
  68588. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  68589. if (g != 0)
  68590. g->addKerningPair (char2, extraAmount);
  68591. }
  68592. void Typeface::setName (const String& name) throw()
  68593. {
  68594. typefaceName = name;
  68595. updateHashCode();
  68596. }
  68597. void Typeface::setAscent (const float newAscent) throw()
  68598. {
  68599. ascent = newAscent;
  68600. }
  68601. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  68602. {
  68603. defaultCharacter = newDefaultCharacter;
  68604. }
  68605. void Typeface::setBold (const bool shouldBeBold) throw()
  68606. {
  68607. bold = shouldBeBold;
  68608. updateHashCode();
  68609. }
  68610. void Typeface::setItalic (const bool shouldBeItalic) throw()
  68611. {
  68612. italic = shouldBeItalic;
  68613. updateHashCode();
  68614. }
  68615. class TypefaceCache;
  68616. static TypefaceCache* typefaceCacheInstance = 0;
  68617. void clearUpDefaultFontNames() throw(); // in juce_LookAndFeel.cpp
  68618. class TypefaceCache : private DeletedAtShutdown
  68619. {
  68620. private:
  68621. struct CachedFace
  68622. {
  68623. CachedFace() throw()
  68624. : lastUsageCount (0),
  68625. flags (0)
  68626. {
  68627. }
  68628. String typefaceName;
  68629. int lastUsageCount;
  68630. int flags;
  68631. Typeface::Ptr typeFace;
  68632. };
  68633. int counter;
  68634. OwnedArray <CachedFace> faces;
  68635. TypefaceCache (const TypefaceCache&);
  68636. const TypefaceCache& operator= (const TypefaceCache&);
  68637. public:
  68638. TypefaceCache (int numToCache = 10)
  68639. : counter (1),
  68640. faces (2)
  68641. {
  68642. while (--numToCache >= 0)
  68643. {
  68644. CachedFace* const face = new CachedFace();
  68645. face->typeFace = new Typeface();
  68646. faces.add (face);
  68647. }
  68648. }
  68649. ~TypefaceCache()
  68650. {
  68651. faces.clear();
  68652. jassert (typefaceCacheInstance == this);
  68653. typefaceCacheInstance = 0;
  68654. clearUpDefaultFontNames();
  68655. }
  68656. static TypefaceCache* getInstance() throw()
  68657. {
  68658. if (typefaceCacheInstance == 0)
  68659. typefaceCacheInstance = new TypefaceCache();
  68660. return typefaceCacheInstance;
  68661. }
  68662. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  68663. {
  68664. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  68665. int i;
  68666. for (i = faces.size(); --i >= 0;)
  68667. {
  68668. CachedFace* const face = faces.getUnchecked(i);
  68669. if (face->flags == flags
  68670. && face->typefaceName == font.getTypefaceName())
  68671. {
  68672. face->lastUsageCount = ++counter;
  68673. return face->typeFace;
  68674. }
  68675. }
  68676. int replaceIndex = 0;
  68677. int bestLastUsageCount = INT_MAX;
  68678. for (i = faces.size(); --i >= 0;)
  68679. {
  68680. const int lu = faces.getUnchecked(i)->lastUsageCount;
  68681. if (bestLastUsageCount > lu)
  68682. {
  68683. bestLastUsageCount = lu;
  68684. replaceIndex = i;
  68685. }
  68686. }
  68687. CachedFace* const face = faces.getUnchecked (replaceIndex);
  68688. face->typefaceName = font.getTypefaceName();
  68689. face->flags = flags;
  68690. face->lastUsageCount = ++counter;
  68691. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  68692. return face->typeFace;
  68693. }
  68694. };
  68695. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  68696. {
  68697. return TypefaceCache::getInstance()->findTypefaceFor (font);
  68698. }
  68699. END_JUCE_NAMESPACE
  68700. /********* End of inlined file: juce_Typeface.cpp *********/
  68701. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  68702. BEGIN_JUCE_NAMESPACE
  68703. AffineTransform::AffineTransform() throw()
  68704. : mat00 (1.0f),
  68705. mat01 (0),
  68706. mat02 (0),
  68707. mat10 (0),
  68708. mat11 (1.0f),
  68709. mat12 (0)
  68710. {
  68711. }
  68712. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  68713. : mat00 (other.mat00),
  68714. mat01 (other.mat01),
  68715. mat02 (other.mat02),
  68716. mat10 (other.mat10),
  68717. mat11 (other.mat11),
  68718. mat12 (other.mat12)
  68719. {
  68720. }
  68721. AffineTransform::AffineTransform (const float mat00_,
  68722. const float mat01_,
  68723. const float mat02_,
  68724. const float mat10_,
  68725. const float mat11_,
  68726. const float mat12_) throw()
  68727. : mat00 (mat00_),
  68728. mat01 (mat01_),
  68729. mat02 (mat02_),
  68730. mat10 (mat10_),
  68731. mat11 (mat11_),
  68732. mat12 (mat12_)
  68733. {
  68734. }
  68735. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  68736. {
  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. return *this;
  68744. }
  68745. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  68746. {
  68747. return mat00 == other.mat00
  68748. && mat01 == other.mat01
  68749. && mat02 == other.mat02
  68750. && mat10 == other.mat10
  68751. && mat11 == other.mat11
  68752. && mat12 == other.mat12;
  68753. }
  68754. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  68755. {
  68756. return ! operator== (other);
  68757. }
  68758. bool AffineTransform::isIdentity() const throw()
  68759. {
  68760. return (mat01 == 0)
  68761. && (mat02 == 0)
  68762. && (mat10 == 0)
  68763. && (mat12 == 0)
  68764. && (mat00 == 1.0f)
  68765. && (mat11 == 1.0f);
  68766. }
  68767. const AffineTransform AffineTransform::identity;
  68768. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  68769. {
  68770. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  68771. other.mat00 * mat01 + other.mat01 * mat11,
  68772. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  68773. other.mat10 * mat00 + other.mat11 * mat10,
  68774. other.mat10 * mat01 + other.mat11 * mat11,
  68775. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  68776. }
  68777. const AffineTransform AffineTransform::followedBy (const float omat00,
  68778. const float omat01,
  68779. const float omat02,
  68780. const float omat10,
  68781. const float omat11,
  68782. const float omat12) const throw()
  68783. {
  68784. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  68785. omat00 * mat01 + omat01 * mat11,
  68786. omat00 * mat02 + omat01 * mat12 + omat02,
  68787. omat10 * mat00 + omat11 * mat10,
  68788. omat10 * mat01 + omat11 * mat11,
  68789. omat10 * mat02 + omat11 * mat12 + omat12);
  68790. }
  68791. const AffineTransform AffineTransform::translated (const float dx,
  68792. const float dy) const throw()
  68793. {
  68794. return followedBy (1.0f, 0, dx,
  68795. 0, 1.0f, dy);
  68796. }
  68797. const AffineTransform AffineTransform::translation (const float dx,
  68798. const float dy) throw()
  68799. {
  68800. return AffineTransform (1.0f, 0, dx,
  68801. 0, 1.0f, dy);
  68802. }
  68803. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  68804. {
  68805. const float cosRad = cosf (rad);
  68806. const float sinRad = sinf (rad);
  68807. return followedBy (cosRad, -sinRad, 0,
  68808. sinRad, cosRad, 0);
  68809. }
  68810. const AffineTransform AffineTransform::rotation (const float rad) throw()
  68811. {
  68812. const float cosRad = cosf (rad);
  68813. const float sinRad = sinf (rad);
  68814. return AffineTransform (cosRad, -sinRad, 0,
  68815. sinRad, cosRad, 0);
  68816. }
  68817. const AffineTransform AffineTransform::rotated (const float angle,
  68818. const float pivotX,
  68819. const float pivotY) const throw()
  68820. {
  68821. return translated (-pivotX, -pivotY)
  68822. .rotated (angle)
  68823. .translated (pivotX, pivotY);
  68824. }
  68825. const AffineTransform AffineTransform::rotation (const float angle,
  68826. const float pivotX,
  68827. const float pivotY) throw()
  68828. {
  68829. return translation (-pivotX, -pivotY)
  68830. .rotated (angle)
  68831. .translated (pivotX, pivotY);
  68832. }
  68833. const AffineTransform AffineTransform::scaled (const float factorX,
  68834. const float factorY) const throw()
  68835. {
  68836. return followedBy (factorX, 0, 0,
  68837. 0, factorY, 0);
  68838. }
  68839. const AffineTransform AffineTransform::scale (const float factorX,
  68840. const float factorY) throw()
  68841. {
  68842. return AffineTransform (factorX, 0, 0,
  68843. 0, factorY, 0);
  68844. }
  68845. const AffineTransform AffineTransform::sheared (const float shearX,
  68846. const float shearY) const throw()
  68847. {
  68848. return followedBy (1.0f, shearX, 0,
  68849. shearY, 1.0f, 0);
  68850. }
  68851. const AffineTransform AffineTransform::inverted() const throw()
  68852. {
  68853. double determinant = (mat00 * mat11 - mat10 * mat01);
  68854. if (determinant != 0.0)
  68855. {
  68856. determinant = 1.0 / determinant;
  68857. const float dst00 = (float) (mat11 * determinant);
  68858. const float dst10 = (float) (-mat10 * determinant);
  68859. const float dst01 = (float) (-mat01 * determinant);
  68860. const float dst11 = (float) (mat00 * determinant);
  68861. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  68862. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  68863. }
  68864. else
  68865. {
  68866. // singularity..
  68867. return *this;
  68868. }
  68869. }
  68870. bool AffineTransform::isSingularity() const throw()
  68871. {
  68872. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  68873. }
  68874. void AffineTransform::transformPoint (float& x,
  68875. float& y) const throw()
  68876. {
  68877. const float oldX = x;
  68878. x = mat00 * oldX + mat01 * y + mat02;
  68879. y = mat10 * oldX + mat11 * y + mat12;
  68880. }
  68881. void AffineTransform::transformPoint (double& x,
  68882. double& y) const throw()
  68883. {
  68884. const double oldX = x;
  68885. x = mat00 * oldX + mat01 * y + mat02;
  68886. y = mat10 * oldX + mat11 * y + mat12;
  68887. }
  68888. END_JUCE_NAMESPACE
  68889. /********* End of inlined file: juce_AffineTransform.cpp *********/
  68890. /********* Start of inlined file: juce_BorderSize.cpp *********/
  68891. BEGIN_JUCE_NAMESPACE
  68892. BorderSize::BorderSize() throw()
  68893. : top (0),
  68894. left (0),
  68895. bottom (0),
  68896. right (0)
  68897. {
  68898. }
  68899. BorderSize::BorderSize (const BorderSize& other) throw()
  68900. : top (other.top),
  68901. left (other.left),
  68902. bottom (other.bottom),
  68903. right (other.right)
  68904. {
  68905. }
  68906. BorderSize::BorderSize (const int topGap,
  68907. const int leftGap,
  68908. const int bottomGap,
  68909. const int rightGap) throw()
  68910. : top (topGap),
  68911. left (leftGap),
  68912. bottom (bottomGap),
  68913. right (rightGap)
  68914. {
  68915. }
  68916. BorderSize::BorderSize (const int allGaps) throw()
  68917. : top (allGaps),
  68918. left (allGaps),
  68919. bottom (allGaps),
  68920. right (allGaps)
  68921. {
  68922. }
  68923. BorderSize::~BorderSize() throw()
  68924. {
  68925. }
  68926. void BorderSize::setTop (const int newTopGap) throw()
  68927. {
  68928. top = newTopGap;
  68929. }
  68930. void BorderSize::setLeft (const int newLeftGap) throw()
  68931. {
  68932. left = newLeftGap;
  68933. }
  68934. void BorderSize::setBottom (const int newBottomGap) throw()
  68935. {
  68936. bottom = newBottomGap;
  68937. }
  68938. void BorderSize::setRight (const int newRightGap) throw()
  68939. {
  68940. right = newRightGap;
  68941. }
  68942. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  68943. {
  68944. return Rectangle (r.getX() + left,
  68945. r.getY() + top,
  68946. r.getWidth() - (left + right),
  68947. r.getHeight() - (top + bottom));
  68948. }
  68949. void BorderSize::subtractFrom (Rectangle& r) const throw()
  68950. {
  68951. r.setBounds (r.getX() + left,
  68952. r.getY() + top,
  68953. r.getWidth() - (left + right),
  68954. r.getHeight() - (top + bottom));
  68955. }
  68956. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  68957. {
  68958. return Rectangle (r.getX() - left,
  68959. r.getY() - top,
  68960. r.getWidth() + (left + right),
  68961. r.getHeight() + (top + bottom));
  68962. }
  68963. void BorderSize::addTo (Rectangle& r) const throw()
  68964. {
  68965. r.setBounds (r.getX() - left,
  68966. r.getY() - top,
  68967. r.getWidth() + (left + right),
  68968. r.getHeight() + (top + bottom));
  68969. }
  68970. bool BorderSize::operator== (const BorderSize& other) const throw()
  68971. {
  68972. return top == other.top
  68973. && left == other.left
  68974. && bottom == other.bottom
  68975. && right == other.right;
  68976. }
  68977. bool BorderSize::operator!= (const BorderSize& other) const throw()
  68978. {
  68979. return ! operator== (other);
  68980. }
  68981. END_JUCE_NAMESPACE
  68982. /********* End of inlined file: juce_BorderSize.cpp *********/
  68983. /********* Start of inlined file: juce_Line.cpp *********/
  68984. BEGIN_JUCE_NAMESPACE
  68985. static bool juce_lineIntersection (const float x1, const float y1,
  68986. const float x2, const float y2,
  68987. const float x3, const float y3,
  68988. const float x4, const float y4,
  68989. float& intersectionX,
  68990. float& intersectionY) throw()
  68991. {
  68992. if (x2 != x3 || y2 != y3)
  68993. {
  68994. const float dx1 = x2 - x1;
  68995. const float dy1 = y2 - y1;
  68996. const float dx2 = x4 - x3;
  68997. const float dy2 = y4 - y3;
  68998. const float divisor = dx1 * dy2 - dx2 * dy1;
  68999. if (divisor == 0)
  69000. {
  69001. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  69002. {
  69003. if (dy1 == 0 && dy2 != 0)
  69004. {
  69005. const float along = (y1 - y3) / dy2;
  69006. intersectionX = x3 + along * dx2;
  69007. intersectionY = y1;
  69008. return along >= 0 && along <= 1.0f;
  69009. }
  69010. else if (dy2 == 0 && dy1 != 0)
  69011. {
  69012. const float along = (y3 - y1) / dy1;
  69013. intersectionX = x1 + along * dx1;
  69014. intersectionY = y3;
  69015. return along >= 0 && along <= 1.0f;
  69016. }
  69017. else if (dx1 == 0 && dx2 != 0)
  69018. {
  69019. const float along = (x1 - x3) / dx2;
  69020. intersectionX = x1;
  69021. intersectionY = y3 + along * dy2;
  69022. return along >= 0 && along <= 1.0f;
  69023. }
  69024. else if (dx2 == 0 && dx1 != 0)
  69025. {
  69026. const float along = (x3 - x1) / dx1;
  69027. intersectionX = x3;
  69028. intersectionY = y1 + along * dy1;
  69029. return along >= 0 && along <= 1.0f;
  69030. }
  69031. }
  69032. intersectionX = 0.5f * (x2 + x3);
  69033. intersectionY = 0.5f * (y2 + y3);
  69034. return false;
  69035. }
  69036. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  69037. intersectionX = x1 + along1 * dx1;
  69038. intersectionY = y1 + along1 * dy1;
  69039. if (along1 < 0 || along1 > 1.0f)
  69040. return false;
  69041. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  69042. return along2 >= 0 && along2 <= 1.0f;
  69043. }
  69044. intersectionX = x2;
  69045. intersectionY = y2;
  69046. return true;
  69047. }
  69048. Line::Line() throw()
  69049. : startX (0.0f),
  69050. startY (0.0f),
  69051. endX (0.0f),
  69052. endY (0.0f)
  69053. {
  69054. }
  69055. Line::Line (const Line& other) throw()
  69056. : startX (other.startX),
  69057. startY (other.startY),
  69058. endX (other.endX),
  69059. endY (other.endY)
  69060. {
  69061. }
  69062. Line::Line (const float startX_, const float startY_,
  69063. const float endX_, const float endY_) throw()
  69064. : startX (startX_),
  69065. startY (startY_),
  69066. endX (endX_),
  69067. endY (endY_)
  69068. {
  69069. }
  69070. Line::Line (const Point& start,
  69071. const Point& end) throw()
  69072. : startX (start.getX()),
  69073. startY (start.getY()),
  69074. endX (end.getX()),
  69075. endY (end.getY())
  69076. {
  69077. }
  69078. const Line& Line::operator= (const Line& other) throw()
  69079. {
  69080. startX = other.startX;
  69081. startY = other.startY;
  69082. endX = other.endX;
  69083. endY = other.endY;
  69084. return *this;
  69085. }
  69086. Line::~Line() throw()
  69087. {
  69088. }
  69089. const Point Line::getStart() const throw()
  69090. {
  69091. return Point (startX, startY);
  69092. }
  69093. const Point Line::getEnd() const throw()
  69094. {
  69095. return Point (endX, endY);
  69096. }
  69097. void Line::setStart (const float newStartX,
  69098. const float newStartY) throw()
  69099. {
  69100. startX = newStartX;
  69101. startY = newStartY;
  69102. }
  69103. void Line::setStart (const Point& newStart) throw()
  69104. {
  69105. startX = newStart.getX();
  69106. startY = newStart.getY();
  69107. }
  69108. void Line::setEnd (const float newEndX,
  69109. const float newEndY) throw()
  69110. {
  69111. endX = newEndX;
  69112. endY = newEndY;
  69113. }
  69114. void Line::setEnd (const Point& newEnd) throw()
  69115. {
  69116. endX = newEnd.getX();
  69117. endY = newEnd.getY();
  69118. }
  69119. bool Line::operator== (const Line& other) const throw()
  69120. {
  69121. return startX == other.startX
  69122. && startY == other.startY
  69123. && endX == other.endX
  69124. && endY == other.endY;
  69125. }
  69126. bool Line::operator!= (const Line& other) const throw()
  69127. {
  69128. return startX != other.startX
  69129. || startY != other.startY
  69130. || endX != other.endX
  69131. || endY != other.endY;
  69132. }
  69133. void Line::applyTransform (const AffineTransform& transform) throw()
  69134. {
  69135. transform.transformPoint (startX, startY);
  69136. transform.transformPoint (endX, endY);
  69137. }
  69138. float Line::getLength() const throw()
  69139. {
  69140. return (float) juce_hypot (startX - endX,
  69141. startY - endY);
  69142. }
  69143. float Line::getAngle() const throw()
  69144. {
  69145. return atan2f (endX - startX,
  69146. endY - startY);
  69147. }
  69148. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  69149. {
  69150. const float alpha = distanceFromStart / getLength();
  69151. return Point (startX + (endX - startX) * alpha,
  69152. startY + (endY - startY) * alpha);
  69153. }
  69154. const Point Line::getPointAlongLine (const float offsetX,
  69155. const float offsetY) const throw()
  69156. {
  69157. const float dx = endX - startX;
  69158. const float dy = endY - startY;
  69159. const double length = juce_hypot (dx, dy);
  69160. if (length == 0)
  69161. return Point (startX, startY);
  69162. else
  69163. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  69164. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  69165. }
  69166. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  69167. {
  69168. return Point (startX + (endX - startX) * alpha,
  69169. startY + (endY - startY) * alpha);
  69170. }
  69171. float Line::getDistanceFromLine (const float x,
  69172. const float y) const throw()
  69173. {
  69174. const double dx = endX - startX;
  69175. const double dy = endY - startY;
  69176. const double length = dx * dx + dy * dy;
  69177. if (length > 0)
  69178. {
  69179. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  69180. if (prop >= 0.0f && prop < 1.0f)
  69181. {
  69182. return (float) juce_hypot (x - (startX + prop * dx),
  69183. y - (startY + prop * dy));
  69184. }
  69185. }
  69186. return (float) jmin (juce_hypot (x - startX, y - startY),
  69187. juce_hypot (x - endX, y - endY));
  69188. }
  69189. float Line::findNearestPointTo (const float x,
  69190. const float y) const throw()
  69191. {
  69192. const double dx = endX - startX;
  69193. const double dy = endY - startY;
  69194. const double length = dx * dx + dy * dy;
  69195. if (length <= 0.0)
  69196. return 0.0f;
  69197. return jlimit (0.0f, 1.0f,
  69198. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  69199. }
  69200. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  69201. {
  69202. const float length = getLength();
  69203. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  69204. getEnd());
  69205. }
  69206. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  69207. {
  69208. const float length = getLength();
  69209. return Line (getStart(),
  69210. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  69211. }
  69212. bool Line::clipToPath (const Path& path,
  69213. const bool keepSectionOutsidePath) throw()
  69214. {
  69215. const bool startInside = path.contains (startX, startY);
  69216. const bool endInside = path.contains (endX, endY);
  69217. if (startInside == endInside)
  69218. {
  69219. if (keepSectionOutsidePath != startInside)
  69220. {
  69221. // entirely outside the path
  69222. return false;
  69223. }
  69224. else
  69225. {
  69226. // entirely inside the path
  69227. startX = 0.0f;
  69228. startY = 0.0f;
  69229. endX = 0.0f;
  69230. endY = 0.0f;
  69231. return true;
  69232. }
  69233. }
  69234. else
  69235. {
  69236. bool changed = false;
  69237. PathFlatteningIterator iter (path, AffineTransform::identity);
  69238. while (iter.next())
  69239. {
  69240. float ix, iy;
  69241. if (intersects (Line (iter.x1, iter.y1,
  69242. iter.x2, iter.y2),
  69243. ix, iy))
  69244. {
  69245. if ((startInside && keepSectionOutsidePath)
  69246. || (endInside && ! keepSectionOutsidePath))
  69247. {
  69248. setStart (ix, iy);
  69249. }
  69250. else
  69251. {
  69252. setEnd (ix, iy);
  69253. }
  69254. changed = true;
  69255. }
  69256. }
  69257. return changed;
  69258. }
  69259. }
  69260. bool Line::intersects (const Line& line,
  69261. float& intersectionX,
  69262. float& intersectionY) const throw()
  69263. {
  69264. return juce_lineIntersection (startX, startY,
  69265. endX, endY,
  69266. line.startX, line.startY,
  69267. line.endX, line.endY,
  69268. intersectionX,
  69269. intersectionY);
  69270. }
  69271. bool Line::isVertical() const throw()
  69272. {
  69273. return startX == endX;
  69274. }
  69275. bool Line::isHorizontal() const throw()
  69276. {
  69277. return startY == endY;
  69278. }
  69279. bool Line::isPointAbove (const float x, const float y) const throw()
  69280. {
  69281. return startX != endX
  69282. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  69283. }
  69284. END_JUCE_NAMESPACE
  69285. /********* End of inlined file: juce_Line.cpp *********/
  69286. /********* Start of inlined file: juce_Path.cpp *********/
  69287. BEGIN_JUCE_NAMESPACE
  69288. // tests that some co-ords aren't NaNs
  69289. #define CHECK_COORDS_ARE_VALID(x, y) \
  69290. jassert (x == x && y == y);
  69291. const float Path::lineMarker = 100001.0f;
  69292. const float Path::moveMarker = 100002.0f;
  69293. const float Path::quadMarker = 100003.0f;
  69294. const float Path::cubicMarker = 100004.0f;
  69295. const float Path::closeSubPathMarker = 100005.0f;
  69296. static const int defaultGranularity = 32;
  69297. Path::Path() throw()
  69298. : ArrayAllocationBase <float> (defaultGranularity),
  69299. numElements (0),
  69300. pathXMin (0),
  69301. pathXMax (0),
  69302. pathYMin (0),
  69303. pathYMax (0),
  69304. useNonZeroWinding (true)
  69305. {
  69306. }
  69307. Path::~Path() throw()
  69308. {
  69309. }
  69310. Path::Path (const Path& other) throw()
  69311. : ArrayAllocationBase <float> (defaultGranularity),
  69312. numElements (other.numElements),
  69313. pathXMin (other.pathXMin),
  69314. pathXMax (other.pathXMax),
  69315. pathYMin (other.pathYMin),
  69316. pathYMax (other.pathYMax),
  69317. useNonZeroWinding (other.useNonZeroWinding)
  69318. {
  69319. if (numElements > 0)
  69320. {
  69321. setAllocatedSize (numElements);
  69322. memcpy (elements, other.elements, numElements * sizeof (float));
  69323. }
  69324. }
  69325. const Path& Path::operator= (const Path& other) throw()
  69326. {
  69327. if (this != &other)
  69328. {
  69329. ensureAllocatedSize (other.numElements);
  69330. numElements = other.numElements;
  69331. pathXMin = other.pathXMin;
  69332. pathXMax = other.pathXMax;
  69333. pathYMin = other.pathYMin;
  69334. pathYMax = other.pathYMax;
  69335. useNonZeroWinding = other.useNonZeroWinding;
  69336. if (numElements > 0)
  69337. memcpy (elements, other.elements, numElements * sizeof (float));
  69338. }
  69339. return *this;
  69340. }
  69341. void Path::clear() throw()
  69342. {
  69343. numElements = 0;
  69344. pathXMin = 0;
  69345. pathYMin = 0;
  69346. pathYMax = 0;
  69347. pathXMax = 0;
  69348. }
  69349. void Path::swapWithPath (Path& other)
  69350. {
  69351. swapVariables <int> (this->numAllocated, other.numAllocated);
  69352. swapVariables <float*> (this->elements, other.elements);
  69353. swapVariables <int> (this->numElements, other.numElements);
  69354. swapVariables <float> (this->pathXMin, other.pathXMin);
  69355. swapVariables <float> (this->pathXMax, other.pathXMax);
  69356. swapVariables <float> (this->pathYMin, other.pathYMin);
  69357. swapVariables <float> (this->pathYMax, other.pathYMax);
  69358. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  69359. }
  69360. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  69361. {
  69362. useNonZeroWinding = isNonZero;
  69363. }
  69364. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  69365. const bool preserveProportions) throw()
  69366. {
  69367. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  69368. }
  69369. bool Path::isEmpty() const throw()
  69370. {
  69371. int i = 0;
  69372. while (i < numElements)
  69373. {
  69374. const float type = elements [i++];
  69375. if (type == moveMarker)
  69376. {
  69377. i += 2;
  69378. }
  69379. else if (type == lineMarker
  69380. || type == quadMarker
  69381. || type == cubicMarker)
  69382. {
  69383. return false;
  69384. }
  69385. }
  69386. return true;
  69387. }
  69388. void Path::getBounds (float& x, float& y,
  69389. float& w, float& h) const throw()
  69390. {
  69391. x = pathXMin;
  69392. y = pathYMin;
  69393. w = pathXMax - pathXMin;
  69394. h = pathYMax - pathYMin;
  69395. }
  69396. void Path::getBoundsTransformed (const AffineTransform& transform,
  69397. float& x, float& y,
  69398. float& w, float& h) const throw()
  69399. {
  69400. float x1 = pathXMin;
  69401. float y1 = pathYMin;
  69402. transform.transformPoint (x1, y1);
  69403. float x2 = pathXMax;
  69404. float y2 = pathYMin;
  69405. transform.transformPoint (x2, y2);
  69406. float x3 = pathXMin;
  69407. float y3 = pathYMax;
  69408. transform.transformPoint (x3, y3);
  69409. float x4 = pathXMax;
  69410. float y4 = pathYMax;
  69411. transform.transformPoint (x4, y4);
  69412. x = jmin (x1, x2, x3, x4);
  69413. y = jmin (y1, y2, y3, y4);
  69414. w = jmax (x1, x2, x3, x4) - x;
  69415. h = jmax (y1, y2, y3, y4) - y;
  69416. }
  69417. void Path::startNewSubPath (const float x,
  69418. const float y) throw()
  69419. {
  69420. CHECK_COORDS_ARE_VALID (x, y);
  69421. if (numElements == 0)
  69422. {
  69423. pathXMin = pathXMax = x;
  69424. pathYMin = pathYMax = y;
  69425. }
  69426. else
  69427. {
  69428. pathXMin = jmin (pathXMin, x);
  69429. pathXMax = jmax (pathXMax, x);
  69430. pathYMin = jmin (pathYMin, y);
  69431. pathYMax = jmax (pathYMax, y);
  69432. }
  69433. ensureAllocatedSize (numElements + 3);
  69434. elements [numElements++] = moveMarker;
  69435. elements [numElements++] = x;
  69436. elements [numElements++] = y;
  69437. }
  69438. void Path::lineTo (const float x, const float y) throw()
  69439. {
  69440. CHECK_COORDS_ARE_VALID (x, y);
  69441. if (numElements == 0)
  69442. startNewSubPath (0, 0);
  69443. ensureAllocatedSize (numElements + 3);
  69444. elements [numElements++] = lineMarker;
  69445. elements [numElements++] = x;
  69446. elements [numElements++] = y;
  69447. pathXMin = jmin (pathXMin, x);
  69448. pathXMax = jmax (pathXMax, x);
  69449. pathYMin = jmin (pathYMin, y);
  69450. pathYMax = jmax (pathYMax, y);
  69451. }
  69452. void Path::quadraticTo (const float x1, const float y1,
  69453. const float x2, const float y2) throw()
  69454. {
  69455. CHECK_COORDS_ARE_VALID (x1, y1);
  69456. CHECK_COORDS_ARE_VALID (x2, y2);
  69457. if (numElements == 0)
  69458. startNewSubPath (0, 0);
  69459. ensureAllocatedSize (numElements + 5);
  69460. elements [numElements++] = quadMarker;
  69461. elements [numElements++] = x1;
  69462. elements [numElements++] = y1;
  69463. elements [numElements++] = x2;
  69464. elements [numElements++] = y2;
  69465. pathXMin = jmin (pathXMin, x1, x2);
  69466. pathXMax = jmax (pathXMax, x1, x2);
  69467. pathYMin = jmin (pathYMin, y1, y2);
  69468. pathYMax = jmax (pathYMax, y1, y2);
  69469. }
  69470. void Path::cubicTo (const float x1, const float y1,
  69471. const float x2, const float y2,
  69472. const float x3, const float y3) throw()
  69473. {
  69474. CHECK_COORDS_ARE_VALID (x1, y1);
  69475. CHECK_COORDS_ARE_VALID (x2, y2);
  69476. CHECK_COORDS_ARE_VALID (x3, y3);
  69477. if (numElements == 0)
  69478. startNewSubPath (0, 0);
  69479. ensureAllocatedSize (numElements + 7);
  69480. elements [numElements++] = cubicMarker;
  69481. elements [numElements++] = x1;
  69482. elements [numElements++] = y1;
  69483. elements [numElements++] = x2;
  69484. elements [numElements++] = y2;
  69485. elements [numElements++] = x3;
  69486. elements [numElements++] = y3;
  69487. pathXMin = jmin (pathXMin, x1, x2, x3);
  69488. pathXMax = jmax (pathXMax, x1, x2, x3);
  69489. pathYMin = jmin (pathYMin, y1, y2, y3);
  69490. pathYMax = jmax (pathYMax, y1, y2, y3);
  69491. }
  69492. void Path::closeSubPath() throw()
  69493. {
  69494. if (numElements > 0
  69495. && elements [numElements - 1] != closeSubPathMarker)
  69496. {
  69497. ensureAllocatedSize (numElements + 1);
  69498. elements [numElements++] = closeSubPathMarker;
  69499. }
  69500. }
  69501. const Point Path::getCurrentPosition() const
  69502. {
  69503. int i = numElements - 1;
  69504. if (i > 0 && elements[i] == closeSubPathMarker)
  69505. {
  69506. while (i >= 0)
  69507. {
  69508. if (elements[i] == moveMarker)
  69509. {
  69510. i += 2;
  69511. break;
  69512. }
  69513. --i;
  69514. }
  69515. }
  69516. if (i > 0)
  69517. return Point (elements [i - 1], elements [i]);
  69518. return Point (0.0f, 0.0f);
  69519. }
  69520. void Path::addRectangle (const float x, const float y,
  69521. const float w, const float h) throw()
  69522. {
  69523. startNewSubPath (x, y + h);
  69524. lineTo (x, y);
  69525. lineTo (x + w, y);
  69526. lineTo (x + w, y + h);
  69527. closeSubPath();
  69528. }
  69529. void Path::addRoundedRectangle (const float x, const float y,
  69530. const float w, const float h,
  69531. float csx,
  69532. float csy) throw()
  69533. {
  69534. csx = jmin (csx, w * 0.5f);
  69535. csy = jmin (csy, h * 0.5f);
  69536. const float cs45x = csx * 0.45f;
  69537. const float cs45y = csy * 0.45f;
  69538. const float x2 = x + w;
  69539. const float y2 = y + h;
  69540. startNewSubPath (x + csx, y);
  69541. lineTo (x2 - csx, y);
  69542. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  69543. lineTo (x2, y2 - csy);
  69544. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  69545. lineTo (x + csx, y2);
  69546. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  69547. lineTo (x, y + csy);
  69548. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  69549. closeSubPath();
  69550. }
  69551. void Path::addRoundedRectangle (const float x, const float y,
  69552. const float w, const float h,
  69553. float cs) throw()
  69554. {
  69555. addRoundedRectangle (x, y, w, h, cs, cs);
  69556. }
  69557. void Path::addTriangle (const float x1, const float y1,
  69558. const float x2, const float y2,
  69559. const float x3, const float y3) throw()
  69560. {
  69561. startNewSubPath (x1, y1);
  69562. lineTo (x2, y2);
  69563. lineTo (x3, y3);
  69564. closeSubPath();
  69565. }
  69566. void Path::addQuadrilateral (const float x1, const float y1,
  69567. const float x2, const float y2,
  69568. const float x3, const float y3,
  69569. const float x4, const float y4) throw()
  69570. {
  69571. startNewSubPath (x1, y1);
  69572. lineTo (x2, y2);
  69573. lineTo (x3, y3);
  69574. lineTo (x4, y4);
  69575. closeSubPath();
  69576. }
  69577. void Path::addEllipse (const float x, const float y,
  69578. const float w, const float h) throw()
  69579. {
  69580. const float hw = w * 0.5f;
  69581. const float hw55 = hw * 0.55f;
  69582. const float hh = h * 0.5f;
  69583. const float hh45 = hh * 0.55f;
  69584. const float cx = x + hw;
  69585. const float cy = y + hh;
  69586. startNewSubPath (cx, cy - hh);
  69587. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  69588. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  69589. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  69590. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  69591. closeSubPath();
  69592. }
  69593. void Path::addArc (const float x, const float y,
  69594. const float w, const float h,
  69595. const float fromRadians,
  69596. const float toRadians,
  69597. const bool startAsNewSubPath) throw()
  69598. {
  69599. const float radiusX = w / 2.0f;
  69600. const float radiusY = h / 2.0f;
  69601. addCentredArc (x + radiusX,
  69602. y + radiusY,
  69603. radiusX, radiusY,
  69604. 0.0f,
  69605. fromRadians, toRadians,
  69606. startAsNewSubPath);
  69607. }
  69608. static const float ellipseAngularIncrement = 0.05f;
  69609. void Path::addCentredArc (const float centreX, const float centreY,
  69610. const float radiusX, const float radiusY,
  69611. const float rotationOfEllipse,
  69612. const float fromRadians,
  69613. const float toRadians,
  69614. const bool startAsNewSubPath) throw()
  69615. {
  69616. if (radiusX > 0.0f && radiusY > 0.0f)
  69617. {
  69618. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  69619. float angle = fromRadians;
  69620. if (startAsNewSubPath)
  69621. {
  69622. float x = centreX + radiusX * sinf (angle);
  69623. float y = centreY - radiusY * cosf (angle);
  69624. if (rotationOfEllipse != 0)
  69625. rotation.transformPoint (x, y);
  69626. startNewSubPath (x, y);
  69627. }
  69628. if (fromRadians < toRadians)
  69629. {
  69630. if (startAsNewSubPath)
  69631. angle += ellipseAngularIncrement;
  69632. while (angle < toRadians)
  69633. {
  69634. float x = centreX + radiusX * sinf (angle);
  69635. float y = centreY - radiusY * cosf (angle);
  69636. if (rotationOfEllipse != 0)
  69637. rotation.transformPoint (x, y);
  69638. lineTo (x, y);
  69639. angle += ellipseAngularIncrement;
  69640. }
  69641. }
  69642. else
  69643. {
  69644. if (startAsNewSubPath)
  69645. angle -= ellipseAngularIncrement;
  69646. while (angle > toRadians)
  69647. {
  69648. float x = centreX + radiusX * sinf (angle);
  69649. float y = centreY - radiusY * cosf (angle);
  69650. if (rotationOfEllipse != 0)
  69651. rotation.transformPoint (x, y);
  69652. lineTo (x, y);
  69653. angle -= ellipseAngularIncrement;
  69654. }
  69655. }
  69656. float x = centreX + radiusX * sinf (toRadians);
  69657. float y = centreY - radiusY * cosf (toRadians);
  69658. if (rotationOfEllipse != 0)
  69659. rotation.transformPoint (x, y);
  69660. lineTo (x, y);
  69661. }
  69662. }
  69663. void Path::addPieSegment (const float x, const float y,
  69664. const float width, const float height,
  69665. const float fromRadians,
  69666. const float toRadians,
  69667. const float innerCircleProportionalSize)
  69668. {
  69669. float hw = width * 0.5f;
  69670. float hh = height * 0.5f;
  69671. const float centreX = x + hw;
  69672. const float centreY = y + hh;
  69673. startNewSubPath (centreX + hw * sinf (fromRadians),
  69674. centreY - hh * cosf (fromRadians));
  69675. addArc (x, y, width, height, fromRadians, toRadians);
  69676. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  69677. {
  69678. closeSubPath();
  69679. if (innerCircleProportionalSize > 0)
  69680. {
  69681. hw *= innerCircleProportionalSize;
  69682. hh *= innerCircleProportionalSize;
  69683. startNewSubPath (centreX + hw * sinf (toRadians),
  69684. centreY - hh * cosf (toRadians));
  69685. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69686. toRadians, fromRadians);
  69687. }
  69688. }
  69689. else
  69690. {
  69691. if (innerCircleProportionalSize > 0)
  69692. {
  69693. hw *= innerCircleProportionalSize;
  69694. hh *= innerCircleProportionalSize;
  69695. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  69696. toRadians, fromRadians);
  69697. }
  69698. else
  69699. {
  69700. lineTo (centreX, centreY);
  69701. }
  69702. }
  69703. closeSubPath();
  69704. }
  69705. static void perpendicularOffset (const float x1, const float y1,
  69706. const float x2, const float y2,
  69707. const float offsetX, const float offsetY,
  69708. float& resultX, float& resultY) throw()
  69709. {
  69710. const float dx = x2 - x1;
  69711. const float dy = y2 - y1;
  69712. const float len = juce_hypotf (dx, dy);
  69713. if (len == 0)
  69714. {
  69715. resultX = x1;
  69716. resultY = y1;
  69717. }
  69718. else
  69719. {
  69720. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  69721. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  69722. }
  69723. }
  69724. void Path::addLineSegment (const float startX, const float startY,
  69725. const float endX, const float endY,
  69726. float lineThickness) throw()
  69727. {
  69728. lineThickness *= 0.5f;
  69729. float x, y;
  69730. perpendicularOffset (startX, startY, endX, endY,
  69731. 0, lineThickness, x, y);
  69732. startNewSubPath (x, y);
  69733. perpendicularOffset (startX, startY, endX, endY,
  69734. 0, -lineThickness, x, y);
  69735. lineTo (x, y);
  69736. perpendicularOffset (endX, endY, startX, startY,
  69737. 0, lineThickness, x, y);
  69738. lineTo (x, y);
  69739. perpendicularOffset (endX, endY, startX, startY,
  69740. 0, -lineThickness, x, y);
  69741. lineTo (x, y);
  69742. closeSubPath();
  69743. }
  69744. void Path::addArrow (const float startX, const float startY,
  69745. const float endX, const float endY,
  69746. float lineThickness,
  69747. float arrowheadWidth,
  69748. float arrowheadLength) throw()
  69749. {
  69750. lineThickness *= 0.5f;
  69751. arrowheadWidth *= 0.5f;
  69752. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  69753. startY - endY));
  69754. float x, y;
  69755. perpendicularOffset (startX, startY, endX, endY,
  69756. 0, lineThickness, x, y);
  69757. startNewSubPath (x, y);
  69758. perpendicularOffset (startX, startY, endX, endY,
  69759. 0, -lineThickness, x, y);
  69760. lineTo (x, y);
  69761. perpendicularOffset (endX, endY, startX, startY,
  69762. arrowheadLength, lineThickness, x, y);
  69763. lineTo (x, y);
  69764. perpendicularOffset (endX, endY, startX, startY,
  69765. arrowheadLength, arrowheadWidth, x, y);
  69766. lineTo (x, y);
  69767. perpendicularOffset (endX, endY, startX, startY,
  69768. 0, 0, x, y);
  69769. lineTo (x, y);
  69770. perpendicularOffset (endX, endY, startX, startY,
  69771. arrowheadLength, -arrowheadWidth, x, y);
  69772. lineTo (x, y);
  69773. perpendicularOffset (endX, endY, startX, startY,
  69774. arrowheadLength, -lineThickness, x, y);
  69775. lineTo (x, y);
  69776. closeSubPath();
  69777. }
  69778. void Path::addStar (const float centreX,
  69779. const float centreY,
  69780. const int numberOfPoints,
  69781. const float innerRadius,
  69782. const float outerRadius,
  69783. const float startAngle)
  69784. {
  69785. jassert (numberOfPoints > 1); // this would be silly.
  69786. if (numberOfPoints > 1)
  69787. {
  69788. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  69789. for (int i = 0; i < numberOfPoints; ++i)
  69790. {
  69791. float angle = startAngle + i * angleBetweenPoints;
  69792. const float x = centreX + outerRadius * sinf (angle);
  69793. const float y = centreY - outerRadius * cosf (angle);
  69794. if (i == 0)
  69795. startNewSubPath (x, y);
  69796. else
  69797. lineTo (x, y);
  69798. angle += angleBetweenPoints * 0.5f;
  69799. lineTo (centreX + innerRadius * sinf (angle),
  69800. centreY - innerRadius * cosf (angle));
  69801. }
  69802. closeSubPath();
  69803. }
  69804. }
  69805. void Path::addBubble (float x, float y,
  69806. float w, float h,
  69807. float cs,
  69808. float tipX,
  69809. float tipY,
  69810. int whichSide,
  69811. float arrowPos,
  69812. float arrowWidth)
  69813. {
  69814. if (w > 1.0f && h > 1.0f)
  69815. {
  69816. cs = jmin (cs, w * 0.5f, h * 0.5f);
  69817. const float cs2 = 2.0f * cs;
  69818. startNewSubPath (x + cs, y);
  69819. if (whichSide == 0)
  69820. {
  69821. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69822. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69823. lineTo (arrowX1, y);
  69824. lineTo (tipX, tipY);
  69825. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  69826. }
  69827. lineTo (x + w - cs, y);
  69828. if (cs > 0.0f)
  69829. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  69830. if (whichSide == 3)
  69831. {
  69832. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69833. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69834. lineTo (x + w, arrowY1);
  69835. lineTo (tipX, tipY);
  69836. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  69837. }
  69838. lineTo (x + w, y + h - cs);
  69839. if (cs > 0.0f)
  69840. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  69841. if (whichSide == 2)
  69842. {
  69843. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  69844. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  69845. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  69846. lineTo (tipX, tipY);
  69847. lineTo (arrowX1, y + h);
  69848. }
  69849. lineTo (x + cs, y + h);
  69850. if (cs > 0.0f)
  69851. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  69852. if (whichSide == 1)
  69853. {
  69854. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  69855. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  69856. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  69857. lineTo (tipX, tipY);
  69858. lineTo (x, arrowY1);
  69859. }
  69860. lineTo (x, y + cs);
  69861. if (cs > 0.0f)
  69862. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  69863. closeSubPath();
  69864. }
  69865. }
  69866. void Path::addPath (const Path& other) throw()
  69867. {
  69868. int i = 0;
  69869. while (i < other.numElements)
  69870. {
  69871. const float type = other.elements [i++];
  69872. if (type == moveMarker)
  69873. {
  69874. startNewSubPath (other.elements [i],
  69875. other.elements [i + 1]);
  69876. i += 2;
  69877. }
  69878. else if (type == lineMarker)
  69879. {
  69880. lineTo (other.elements [i],
  69881. other.elements [i + 1]);
  69882. i += 2;
  69883. }
  69884. else if (type == quadMarker)
  69885. {
  69886. quadraticTo (other.elements [i],
  69887. other.elements [i + 1],
  69888. other.elements [i + 2],
  69889. other.elements [i + 3]);
  69890. i += 4;
  69891. }
  69892. else if (type == cubicMarker)
  69893. {
  69894. cubicTo (other.elements [i],
  69895. other.elements [i + 1],
  69896. other.elements [i + 2],
  69897. other.elements [i + 3],
  69898. other.elements [i + 4],
  69899. other.elements [i + 5]);
  69900. i += 6;
  69901. }
  69902. else if (type == closeSubPathMarker)
  69903. {
  69904. closeSubPath();
  69905. }
  69906. else
  69907. {
  69908. // something's gone wrong with the element list!
  69909. jassertfalse
  69910. }
  69911. }
  69912. }
  69913. void Path::addPath (const Path& other,
  69914. const AffineTransform& transformToApply) throw()
  69915. {
  69916. int i = 0;
  69917. while (i < other.numElements)
  69918. {
  69919. const float type = other.elements [i++];
  69920. if (type == closeSubPathMarker)
  69921. {
  69922. closeSubPath();
  69923. }
  69924. else
  69925. {
  69926. float x = other.elements [i++];
  69927. float y = other.elements [i++];
  69928. transformToApply.transformPoint (x, y);
  69929. if (type == moveMarker)
  69930. {
  69931. startNewSubPath (x, y);
  69932. }
  69933. else if (type == lineMarker)
  69934. {
  69935. lineTo (x, y);
  69936. }
  69937. else if (type == quadMarker)
  69938. {
  69939. float x2 = other.elements [i++];
  69940. float y2 = other.elements [i++];
  69941. transformToApply.transformPoint (x2, y2);
  69942. quadraticTo (x, y, x2, y2);
  69943. }
  69944. else if (type == cubicMarker)
  69945. {
  69946. float x2 = other.elements [i++];
  69947. float y2 = other.elements [i++];
  69948. float x3 = other.elements [i++];
  69949. float y3 = other.elements [i++];
  69950. transformToApply.transformPoint (x2, y2);
  69951. transformToApply.transformPoint (x3, y3);
  69952. cubicTo (x, y, x2, y2, x3, y3);
  69953. }
  69954. else
  69955. {
  69956. // something's gone wrong with the element list!
  69957. jassertfalse
  69958. }
  69959. }
  69960. }
  69961. }
  69962. void Path::applyTransform (const AffineTransform& transform) throw()
  69963. {
  69964. int i = 0;
  69965. pathYMin = pathXMin = 0;
  69966. pathYMax = pathXMax = 0;
  69967. bool setMaxMin = false;
  69968. while (i < numElements)
  69969. {
  69970. const float type = elements [i++];
  69971. if (type == moveMarker)
  69972. {
  69973. transform.transformPoint (elements [i],
  69974. elements [i + 1]);
  69975. if (setMaxMin)
  69976. {
  69977. pathXMin = jmin (pathXMin, elements [i]);
  69978. pathXMax = jmax (pathXMax, elements [i]);
  69979. pathYMin = jmin (pathYMin, elements [i + 1]);
  69980. pathYMax = jmax (pathYMax, elements [i + 1]);
  69981. }
  69982. else
  69983. {
  69984. pathXMin = pathXMax = elements [i];
  69985. pathYMin = pathYMax = elements [i + 1];
  69986. setMaxMin = true;
  69987. }
  69988. i += 2;
  69989. }
  69990. else if (type == lineMarker)
  69991. {
  69992. transform.transformPoint (elements [i],
  69993. elements [i + 1]);
  69994. pathXMin = jmin (pathXMin, elements [i]);
  69995. pathXMax = jmax (pathXMax, elements [i]);
  69996. pathYMin = jmin (pathYMin, elements [i + 1]);
  69997. pathYMax = jmax (pathYMax, elements [i + 1]);
  69998. i += 2;
  69999. }
  70000. else if (type == quadMarker)
  70001. {
  70002. transform.transformPoint (elements [i],
  70003. elements [i + 1]);
  70004. transform.transformPoint (elements [i + 2],
  70005. elements [i + 3]);
  70006. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  70007. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  70008. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  70009. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  70010. i += 4;
  70011. }
  70012. else if (type == cubicMarker)
  70013. {
  70014. transform.transformPoint (elements [i],
  70015. elements [i + 1]);
  70016. transform.transformPoint (elements [i + 2],
  70017. elements [i + 3]);
  70018. transform.transformPoint (elements [i + 4],
  70019. elements [i + 5]);
  70020. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  70021. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  70022. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  70023. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  70024. i += 6;
  70025. }
  70026. }
  70027. }
  70028. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  70029. const float w, const float h,
  70030. const bool preserveProportions,
  70031. const Justification& justification) const throw()
  70032. {
  70033. float sx, sy, sw, sh;
  70034. getBounds (sx, sy, sw, sh);
  70035. if (preserveProportions)
  70036. {
  70037. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  70038. return AffineTransform::identity;
  70039. float newW, newH;
  70040. const float srcRatio = sh / sw;
  70041. if (srcRatio > h / w)
  70042. {
  70043. newW = h / srcRatio;
  70044. newH = h;
  70045. }
  70046. else
  70047. {
  70048. newW = w;
  70049. newH = w * srcRatio;
  70050. }
  70051. float newXCentre = x;
  70052. float newYCentre = y;
  70053. if (justification.testFlags (Justification::left))
  70054. newXCentre += newW * 0.5f;
  70055. else if (justification.testFlags (Justification::right))
  70056. newXCentre += w - newW * 0.5f;
  70057. else
  70058. newXCentre += w * 0.5f;
  70059. if (justification.testFlags (Justification::top))
  70060. newYCentre += newH * 0.5f;
  70061. else if (justification.testFlags (Justification::bottom))
  70062. newYCentre += h - newH * 0.5f;
  70063. else
  70064. newYCentre += h * 0.5f;
  70065. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  70066. .scaled (newW / sw, newH / sh)
  70067. .translated (newXCentre, newYCentre);
  70068. }
  70069. else
  70070. {
  70071. return AffineTransform::translation (-sx, -sy)
  70072. .scaled (w / sw, h / sh)
  70073. .translated (x, y);
  70074. }
  70075. }
  70076. bool Path::contains (const float x, const float y, const float tolerence) const throw()
  70077. {
  70078. if (x <= pathXMin || x >= pathXMax
  70079. || y <= pathYMin || y >= pathYMax)
  70080. return false;
  70081. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70082. int positiveCrossings = 0;
  70083. int negativeCrossings = 0;
  70084. while (i.next())
  70085. {
  70086. if ((i.y1 <= y && i.y2 > y)
  70087. || (i.y2 <= y && i.y1 > y))
  70088. {
  70089. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  70090. if (intersectX <= x)
  70091. {
  70092. if (i.y1 < i.y2)
  70093. ++positiveCrossings;
  70094. else
  70095. ++negativeCrossings;
  70096. }
  70097. }
  70098. }
  70099. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  70100. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  70101. }
  70102. bool Path::intersectsLine (const float x1, const float y1,
  70103. const float x2, const float y2,
  70104. const float tolerence) throw()
  70105. {
  70106. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  70107. const Line line1 (x1, y1, x2, y2);
  70108. while (i.next())
  70109. {
  70110. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  70111. float ix, iy;
  70112. if (line1.intersects (line2, ix, iy))
  70113. return true;
  70114. }
  70115. return false;
  70116. }
  70117. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  70118. {
  70119. if (cornerRadius <= 0.01f)
  70120. return *this;
  70121. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  70122. int n = 0;
  70123. bool lastWasLine = false, firstWasLine = false;
  70124. Path p;
  70125. while (n < numElements)
  70126. {
  70127. const float type = elements [n++];
  70128. if (type == moveMarker)
  70129. {
  70130. indexOfPathStart = p.numElements;
  70131. indexOfPathStartThis = n - 1;
  70132. const float x = elements [n++];
  70133. const float y = elements [n++];
  70134. p.startNewSubPath (x, y);
  70135. lastWasLine = false;
  70136. firstWasLine = (elements [n] == lineMarker);
  70137. }
  70138. else if (type == lineMarker || type == closeSubPathMarker)
  70139. {
  70140. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  70141. if (type == lineMarker)
  70142. {
  70143. endX = elements [n++];
  70144. endY = elements [n++];
  70145. if (n > 8)
  70146. {
  70147. startX = elements [n - 8];
  70148. startY = elements [n - 7];
  70149. joinX = elements [n - 5];
  70150. joinY = elements [n - 4];
  70151. }
  70152. }
  70153. else
  70154. {
  70155. endX = elements [indexOfPathStartThis + 1];
  70156. endY = elements [indexOfPathStartThis + 2];
  70157. if (n > 6)
  70158. {
  70159. startX = elements [n - 6];
  70160. startY = elements [n - 5];
  70161. joinX = elements [n - 3];
  70162. joinY = elements [n - 2];
  70163. }
  70164. }
  70165. if (lastWasLine)
  70166. {
  70167. const double len1 = juce_hypot (startX - joinX,
  70168. startY - joinY);
  70169. if (len1 > 0)
  70170. {
  70171. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70172. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70173. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70174. }
  70175. const double len2 = juce_hypot (endX - joinX,
  70176. endY - joinY);
  70177. if (len2 > 0)
  70178. {
  70179. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70180. p.quadraticTo (joinX, joinY,
  70181. (float) (joinX + (endX - joinX) * propNeeded),
  70182. (float) (joinY + (endY - joinY) * propNeeded));
  70183. }
  70184. p.lineTo (endX, endY);
  70185. }
  70186. else if (type == lineMarker)
  70187. {
  70188. p.lineTo (endX, endY);
  70189. lastWasLine = true;
  70190. }
  70191. if (type == closeSubPathMarker)
  70192. {
  70193. if (firstWasLine)
  70194. {
  70195. startX = elements [n - 3];
  70196. startY = elements [n - 2];
  70197. joinX = endX;
  70198. joinY = endY;
  70199. endX = elements [indexOfPathStartThis + 4];
  70200. endY = elements [indexOfPathStartThis + 5];
  70201. const double len1 = juce_hypot (startX - joinX,
  70202. startY - joinY);
  70203. if (len1 > 0)
  70204. {
  70205. const double propNeeded = jmin (0.5, cornerRadius / len1);
  70206. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  70207. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  70208. }
  70209. const double len2 = juce_hypot (endX - joinX,
  70210. endY - joinY);
  70211. if (len2 > 0)
  70212. {
  70213. const double propNeeded = jmin (0.5, cornerRadius / len2);
  70214. endX = (float) (joinX + (endX - joinX) * propNeeded);
  70215. endY = (float) (joinY + (endY - joinY) * propNeeded);
  70216. p.quadraticTo (joinX, joinY, endX, endY);
  70217. p.elements [indexOfPathStart + 1] = endX;
  70218. p.elements [indexOfPathStart + 2] = endY;
  70219. }
  70220. }
  70221. p.closeSubPath();
  70222. }
  70223. }
  70224. else if (type == quadMarker)
  70225. {
  70226. lastWasLine = false;
  70227. const float x1 = elements [n++];
  70228. const float y1 = elements [n++];
  70229. const float x2 = elements [n++];
  70230. const float y2 = elements [n++];
  70231. p.quadraticTo (x1, y1, x2, y2);
  70232. }
  70233. else if (type == cubicMarker)
  70234. {
  70235. lastWasLine = false;
  70236. const float x1 = elements [n++];
  70237. const float y1 = elements [n++];
  70238. const float x2 = elements [n++];
  70239. const float y2 = elements [n++];
  70240. const float x3 = elements [n++];
  70241. const float y3 = elements [n++];
  70242. p.cubicTo (x1, y1, x2, y2, x3, y3);
  70243. }
  70244. }
  70245. return p;
  70246. }
  70247. void Path::loadPathFromStream (InputStream& source)
  70248. {
  70249. while (! source.isExhausted())
  70250. {
  70251. switch (source.readByte())
  70252. {
  70253. case 'm':
  70254. {
  70255. const float x = source.readFloat();
  70256. const float y = source.readFloat();
  70257. startNewSubPath (x, y);
  70258. break;
  70259. }
  70260. case 'l':
  70261. {
  70262. const float x = source.readFloat();
  70263. const float y = source.readFloat();
  70264. lineTo (x, y);
  70265. break;
  70266. }
  70267. case 'q':
  70268. {
  70269. const float x1 = source.readFloat();
  70270. const float y1 = source.readFloat();
  70271. const float x2 = source.readFloat();
  70272. const float y2 = source.readFloat();
  70273. quadraticTo (x1, y1, x2, y2);
  70274. break;
  70275. }
  70276. case 'b':
  70277. {
  70278. const float x1 = source.readFloat();
  70279. const float y1 = source.readFloat();
  70280. const float x2 = source.readFloat();
  70281. const float y2 = source.readFloat();
  70282. const float x3 = source.readFloat();
  70283. const float y3 = source.readFloat();
  70284. cubicTo (x1, y1, x2, y2, x3, y3);
  70285. break;
  70286. }
  70287. case 'c':
  70288. closeSubPath();
  70289. break;
  70290. case 'n':
  70291. useNonZeroWinding = true;
  70292. break;
  70293. case 'z':
  70294. useNonZeroWinding = false;
  70295. break;
  70296. case 'e':
  70297. return; // end of path marker
  70298. default:
  70299. jassertfalse // illegal char in the stream
  70300. break;
  70301. }
  70302. }
  70303. }
  70304. void Path::loadPathFromData (const unsigned char* const data,
  70305. const int numberOfBytes) throw()
  70306. {
  70307. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  70308. loadPathFromStream (in);
  70309. }
  70310. void Path::writePathToStream (OutputStream& dest) const
  70311. {
  70312. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  70313. int i = 0;
  70314. while (i < numElements)
  70315. {
  70316. const float type = elements [i++];
  70317. if (type == moveMarker)
  70318. {
  70319. dest.writeByte ('m');
  70320. dest.writeFloat (elements [i++]);
  70321. dest.writeFloat (elements [i++]);
  70322. }
  70323. else if (type == lineMarker)
  70324. {
  70325. dest.writeByte ('l');
  70326. dest.writeFloat (elements [i++]);
  70327. dest.writeFloat (elements [i++]);
  70328. }
  70329. else if (type == quadMarker)
  70330. {
  70331. dest.writeByte ('q');
  70332. dest.writeFloat (elements [i++]);
  70333. dest.writeFloat (elements [i++]);
  70334. dest.writeFloat (elements [i++]);
  70335. dest.writeFloat (elements [i++]);
  70336. }
  70337. else if (type == cubicMarker)
  70338. {
  70339. dest.writeByte ('b');
  70340. dest.writeFloat (elements [i++]);
  70341. dest.writeFloat (elements [i++]);
  70342. dest.writeFloat (elements [i++]);
  70343. dest.writeFloat (elements [i++]);
  70344. dest.writeFloat (elements [i++]);
  70345. dest.writeFloat (elements [i++]);
  70346. }
  70347. else if (type == closeSubPathMarker)
  70348. {
  70349. dest.writeByte ('c');
  70350. }
  70351. }
  70352. dest.writeByte ('e'); // marks the end-of-path
  70353. }
  70354. const String Path::toString() const
  70355. {
  70356. String s;
  70357. s.preallocateStorage (numElements * 4);
  70358. if (! useNonZeroWinding)
  70359. s << T("a ");
  70360. int i = 0;
  70361. float lastMarker = 0.0f;
  70362. while (i < numElements)
  70363. {
  70364. const float marker = elements [i++];
  70365. tchar markerChar = 0;
  70366. int numCoords = 0;
  70367. if (marker == moveMarker)
  70368. {
  70369. markerChar = T('m');
  70370. numCoords = 2;
  70371. }
  70372. else if (marker == lineMarker)
  70373. {
  70374. markerChar = T('l');
  70375. numCoords = 2;
  70376. }
  70377. else if (marker == quadMarker)
  70378. {
  70379. markerChar = T('q');
  70380. numCoords = 4;
  70381. }
  70382. else if (marker == cubicMarker)
  70383. {
  70384. markerChar = T('c');
  70385. numCoords = 6;
  70386. }
  70387. else
  70388. {
  70389. jassert (marker == closeSubPathMarker);
  70390. markerChar = T('z');
  70391. }
  70392. if (marker != lastMarker)
  70393. {
  70394. s << markerChar << T(' ');
  70395. lastMarker = marker;
  70396. }
  70397. while (--numCoords >= 0 && i < numElements)
  70398. {
  70399. String n (elements [i++], 3);
  70400. while (n.endsWithChar (T('0')))
  70401. n = n.dropLastCharacters (1);
  70402. if (n.endsWithChar (T('.')))
  70403. n = n.dropLastCharacters (1);
  70404. s << n << T(' ');
  70405. }
  70406. }
  70407. return s.trimEnd();
  70408. }
  70409. static const String nextToken (const tchar*& t)
  70410. {
  70411. while (CharacterFunctions::isWhitespace (*t))
  70412. ++t;
  70413. const tchar* const start = t;
  70414. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  70415. ++t;
  70416. const int length = (int) (t - start);
  70417. while (CharacterFunctions::isWhitespace (*t))
  70418. ++t;
  70419. return String (start, length);
  70420. }
  70421. void Path::restoreFromString (const String& stringVersion)
  70422. {
  70423. clear();
  70424. setUsingNonZeroWinding (true);
  70425. const tchar* t = stringVersion;
  70426. tchar marker = T('m');
  70427. int numValues = 2;
  70428. float values [6];
  70429. while (*t != 0)
  70430. {
  70431. const String token (nextToken (t));
  70432. const tchar firstChar = token[0];
  70433. int startNum = 0;
  70434. if (firstChar == T('m') || firstChar == T('l'))
  70435. {
  70436. marker = firstChar;
  70437. numValues = 2;
  70438. }
  70439. else if (firstChar == T('q'))
  70440. {
  70441. marker = firstChar;
  70442. numValues = 4;
  70443. }
  70444. else if (firstChar == T('c'))
  70445. {
  70446. marker = firstChar;
  70447. numValues = 6;
  70448. }
  70449. else if (firstChar == T('z'))
  70450. {
  70451. marker = firstChar;
  70452. numValues = 0;
  70453. }
  70454. else if (firstChar == T('a'))
  70455. {
  70456. setUsingNonZeroWinding (false);
  70457. continue;
  70458. }
  70459. else
  70460. {
  70461. ++startNum;
  70462. values [0] = token.getFloatValue();
  70463. }
  70464. for (int i = startNum; i < numValues; ++i)
  70465. values [i] = nextToken (t).getFloatValue();
  70466. switch (marker)
  70467. {
  70468. case T('m'):
  70469. startNewSubPath (values[0], values[1]);
  70470. break;
  70471. case T('l'):
  70472. lineTo (values[0], values[1]);
  70473. break;
  70474. case T('q'):
  70475. quadraticTo (values[0], values[1],
  70476. values[2], values[3]);
  70477. break;
  70478. case T('c'):
  70479. cubicTo (values[0], values[1],
  70480. values[2], values[3],
  70481. values[4], values[5]);
  70482. break;
  70483. case T('z'):
  70484. closeSubPath();
  70485. break;
  70486. default:
  70487. jassertfalse // illegal string format?
  70488. break;
  70489. }
  70490. }
  70491. }
  70492. Path::Iterator::Iterator (const Path& path_)
  70493. : path (path_),
  70494. index (0)
  70495. {
  70496. }
  70497. Path::Iterator::~Iterator()
  70498. {
  70499. }
  70500. bool Path::Iterator::next()
  70501. {
  70502. const float* const elements = path.elements;
  70503. if (index < path.numElements)
  70504. {
  70505. const float type = elements [index++];
  70506. if (type == moveMarker)
  70507. {
  70508. elementType = startNewSubPath;
  70509. x1 = elements [index++];
  70510. y1 = elements [index++];
  70511. }
  70512. else if (type == lineMarker)
  70513. {
  70514. elementType = lineTo;
  70515. x1 = elements [index++];
  70516. y1 = elements [index++];
  70517. }
  70518. else if (type == quadMarker)
  70519. {
  70520. elementType = quadraticTo;
  70521. x1 = elements [index++];
  70522. y1 = elements [index++];
  70523. x2 = elements [index++];
  70524. y2 = elements [index++];
  70525. }
  70526. else if (type == cubicMarker)
  70527. {
  70528. elementType = cubicTo;
  70529. x1 = elements [index++];
  70530. y1 = elements [index++];
  70531. x2 = elements [index++];
  70532. y2 = elements [index++];
  70533. x3 = elements [index++];
  70534. y3 = elements [index++];
  70535. }
  70536. else if (type == closeSubPathMarker)
  70537. {
  70538. elementType = closePath;
  70539. }
  70540. return true;
  70541. }
  70542. return false;
  70543. }
  70544. END_JUCE_NAMESPACE
  70545. /********* End of inlined file: juce_Path.cpp *********/
  70546. /********* Start of inlined file: juce_PathIterator.cpp *********/
  70547. BEGIN_JUCE_NAMESPACE
  70548. #if JUCE_MSVC
  70549. #pragma optimize ("t", on)
  70550. #endif
  70551. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  70552. const AffineTransform& transform_,
  70553. float tolerence_) throw()
  70554. : x2 (0),
  70555. y2 (0),
  70556. closesSubPath (false),
  70557. subPathIndex (-1),
  70558. path (path_),
  70559. transform (transform_),
  70560. points (path_.elements),
  70561. tolerence (tolerence_ * tolerence_),
  70562. subPathCloseX (0),
  70563. subPathCloseY (0),
  70564. index (0),
  70565. stackSize (32)
  70566. {
  70567. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  70568. isIdentityTransform = transform.isIdentity();
  70569. stackPos = stackBase;
  70570. }
  70571. PathFlatteningIterator::~PathFlatteningIterator() throw()
  70572. {
  70573. juce_free (stackBase);
  70574. }
  70575. bool PathFlatteningIterator::next() throw()
  70576. {
  70577. x1 = x2;
  70578. y1 = y2;
  70579. float x3 = 0;
  70580. float y3 = 0;
  70581. float x4 = 0;
  70582. float y4 = 0;
  70583. float type;
  70584. for (;;)
  70585. {
  70586. if (stackPos == stackBase)
  70587. {
  70588. if (index >= path.numElements)
  70589. {
  70590. return false;
  70591. }
  70592. else
  70593. {
  70594. type = points [index++];
  70595. if (type != Path::closeSubPathMarker)
  70596. {
  70597. x2 = points [index++];
  70598. y2 = points [index++];
  70599. if (! isIdentityTransform)
  70600. transform.transformPoint (x2, y2);
  70601. if (type == Path::quadMarker)
  70602. {
  70603. x3 = points [index++];
  70604. y3 = points [index++];
  70605. if (! isIdentityTransform)
  70606. transform.transformPoint (x3, y3);
  70607. }
  70608. else if (type == Path::cubicMarker)
  70609. {
  70610. x3 = points [index++];
  70611. y3 = points [index++];
  70612. x4 = points [index++];
  70613. y4 = points [index++];
  70614. if (! isIdentityTransform)
  70615. {
  70616. transform.transformPoint (x3, y3);
  70617. transform.transformPoint (x4, y4);
  70618. }
  70619. }
  70620. }
  70621. }
  70622. }
  70623. else
  70624. {
  70625. type = *--stackPos;
  70626. if (type != Path::closeSubPathMarker)
  70627. {
  70628. x2 = *--stackPos;
  70629. y2 = *--stackPos;
  70630. if (type == Path::quadMarker)
  70631. {
  70632. x3 = *--stackPos;
  70633. y3 = *--stackPos;
  70634. }
  70635. else if (type == Path::cubicMarker)
  70636. {
  70637. x3 = *--stackPos;
  70638. y3 = *--stackPos;
  70639. x4 = *--stackPos;
  70640. y4 = *--stackPos;
  70641. }
  70642. }
  70643. }
  70644. if (type == Path::lineMarker)
  70645. {
  70646. ++subPathIndex;
  70647. closesSubPath = (stackPos == stackBase)
  70648. && (index < path.numElements)
  70649. && (points [index] == Path::closeSubPathMarker)
  70650. && x2 == subPathCloseX
  70651. && y2 == subPathCloseY;
  70652. return true;
  70653. }
  70654. else if (type == Path::quadMarker)
  70655. {
  70656. const int offset = (int) (stackPos - stackBase);
  70657. if (offset >= stackSize - 10)
  70658. {
  70659. stackSize <<= 1;
  70660. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70661. stackPos = stackBase + offset;
  70662. }
  70663. const float dx1 = x1 - x2;
  70664. const float dy1 = y1 - y2;
  70665. const float dx2 = x2 - x3;
  70666. const float dy2 = y2 - y3;
  70667. const float m1x = (x1 + x2) * 0.5f;
  70668. const float m1y = (y1 + y2) * 0.5f;
  70669. const float m2x = (x2 + x3) * 0.5f;
  70670. const float m2y = (y2 + y3) * 0.5f;
  70671. const float m3x = (m1x + m2x) * 0.5f;
  70672. const float m3y = (m1y + m2y) * 0.5f;
  70673. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  70674. {
  70675. *stackPos++ = y3;
  70676. *stackPos++ = x3;
  70677. *stackPos++ = m2y;
  70678. *stackPos++ = m2x;
  70679. *stackPos++ = Path::quadMarker;
  70680. *stackPos++ = m3y;
  70681. *stackPos++ = m3x;
  70682. *stackPos++ = m1y;
  70683. *stackPos++ = m1x;
  70684. *stackPos++ = Path::quadMarker;
  70685. }
  70686. else
  70687. {
  70688. *stackPos++ = y3;
  70689. *stackPos++ = x3;
  70690. *stackPos++ = Path::lineMarker;
  70691. *stackPos++ = m3y;
  70692. *stackPos++ = m3x;
  70693. *stackPos++ = Path::lineMarker;
  70694. }
  70695. jassert (stackPos < stackBase + stackSize);
  70696. }
  70697. else if (type == Path::cubicMarker)
  70698. {
  70699. const int offset = (int) (stackPos - stackBase);
  70700. if (offset >= stackSize - 16)
  70701. {
  70702. stackSize <<= 1;
  70703. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  70704. stackPos = stackBase + offset;
  70705. }
  70706. const float dx1 = x1 - x2;
  70707. const float dy1 = y1 - y2;
  70708. const float dx2 = x2 - x3;
  70709. const float dy2 = y2 - y3;
  70710. const float dx3 = x3 - x4;
  70711. const float dy3 = y3 - y4;
  70712. const float m1x = (x1 + x2) * 0.5f;
  70713. const float m1y = (y1 + y2) * 0.5f;
  70714. const float m2x = (x3 + x2) * 0.5f;
  70715. const float m2y = (y3 + y2) * 0.5f;
  70716. const float m3x = (x3 + x4) * 0.5f;
  70717. const float m3y = (y3 + y4) * 0.5f;
  70718. const float m4x = (m1x + m2x) * 0.5f;
  70719. const float m4y = (m1y + m2y) * 0.5f;
  70720. const float m5x = (m3x + m2x) * 0.5f;
  70721. const float m5y = (m3y + m2y) * 0.5f;
  70722. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  70723. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  70724. {
  70725. *stackPos++ = y4;
  70726. *stackPos++ = x4;
  70727. *stackPos++ = m3y;
  70728. *stackPos++ = m3x;
  70729. *stackPos++ = m5y;
  70730. *stackPos++ = m5x;
  70731. *stackPos++ = Path::cubicMarker;
  70732. *stackPos++ = (m4y + m5y) * 0.5f;
  70733. *stackPos++ = (m4x + m5x) * 0.5f;
  70734. *stackPos++ = m4y;
  70735. *stackPos++ = m4x;
  70736. *stackPos++ = m1y;
  70737. *stackPos++ = m1x;
  70738. *stackPos++ = Path::cubicMarker;
  70739. }
  70740. else
  70741. {
  70742. *stackPos++ = y4;
  70743. *stackPos++ = x4;
  70744. *stackPos++ = Path::lineMarker;
  70745. *stackPos++ = m5y;
  70746. *stackPos++ = m5x;
  70747. *stackPos++ = Path::lineMarker;
  70748. *stackPos++ = m4y;
  70749. *stackPos++ = m4x;
  70750. *stackPos++ = Path::lineMarker;
  70751. }
  70752. }
  70753. else if (type == Path::closeSubPathMarker)
  70754. {
  70755. if (x2 != subPathCloseX || y2 != subPathCloseY)
  70756. {
  70757. x1 = x2;
  70758. y1 = y2;
  70759. x2 = subPathCloseX;
  70760. y2 = subPathCloseY;
  70761. closesSubPath = true;
  70762. return true;
  70763. }
  70764. }
  70765. else
  70766. {
  70767. jassert (type == Path::moveMarker);
  70768. subPathIndex = -1;
  70769. subPathCloseX = x1 = x2;
  70770. subPathCloseY = y1 = y2;
  70771. }
  70772. }
  70773. }
  70774. END_JUCE_NAMESPACE
  70775. /********* End of inlined file: juce_PathIterator.cpp *********/
  70776. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  70777. BEGIN_JUCE_NAMESPACE
  70778. PathStrokeType::PathStrokeType (const float strokeThickness,
  70779. const JointStyle jointStyle_,
  70780. const EndCapStyle endStyle_) throw()
  70781. : thickness (strokeThickness),
  70782. jointStyle (jointStyle_),
  70783. endStyle (endStyle_)
  70784. {
  70785. }
  70786. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  70787. : thickness (other.thickness),
  70788. jointStyle (other.jointStyle),
  70789. endStyle (other.endStyle)
  70790. {
  70791. }
  70792. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  70793. {
  70794. thickness = other.thickness;
  70795. jointStyle = other.jointStyle;
  70796. endStyle = other.endStyle;
  70797. return *this;
  70798. }
  70799. PathStrokeType::~PathStrokeType() throw()
  70800. {
  70801. }
  70802. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  70803. {
  70804. return thickness == other.thickness
  70805. && jointStyle == other.jointStyle
  70806. && endStyle == other.endStyle;
  70807. }
  70808. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  70809. {
  70810. return ! operator== (other);
  70811. }
  70812. static bool lineIntersection (const float x1, const float y1,
  70813. const float x2, const float y2,
  70814. const float x3, const float y3,
  70815. const float x4, const float y4,
  70816. float& intersectionX,
  70817. float& intersectionY,
  70818. float& distanceBeyondLine1EndSquared) throw()
  70819. {
  70820. if (x2 != x3 || y2 != y3)
  70821. {
  70822. const float dx1 = x2 - x1;
  70823. const float dy1 = y2 - y1;
  70824. const float dx2 = x4 - x3;
  70825. const float dy2 = y4 - y3;
  70826. const float divisor = dx1 * dy2 - dx2 * dy1;
  70827. if (divisor == 0)
  70828. {
  70829. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  70830. {
  70831. if (dy1 == 0 && dy2 != 0)
  70832. {
  70833. const float along = (y1 - y3) / dy2;
  70834. intersectionX = x3 + along * dx2;
  70835. intersectionY = y1;
  70836. distanceBeyondLine1EndSquared = intersectionX - x2;
  70837. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70838. if ((x2 > x1) == (intersectionX < x2))
  70839. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70840. return along >= 0 && along <= 1.0f;
  70841. }
  70842. else if (dy2 == 0 && dy1 != 0)
  70843. {
  70844. const float along = (y3 - y1) / dy1;
  70845. intersectionX = x1 + along * dx1;
  70846. intersectionY = y3;
  70847. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  70848. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70849. if (along < 1.0f)
  70850. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70851. return along >= 0 && along <= 1.0f;
  70852. }
  70853. else if (dx1 == 0 && dx2 != 0)
  70854. {
  70855. const float along = (x1 - x3) / dx2;
  70856. intersectionX = x1;
  70857. intersectionY = y3 + along * dy2;
  70858. distanceBeyondLine1EndSquared = intersectionY - y2;
  70859. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70860. if ((y2 > y1) == (intersectionY < y2))
  70861. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70862. return along >= 0 && along <= 1.0f;
  70863. }
  70864. else if (dx2 == 0 && dx1 != 0)
  70865. {
  70866. const float along = (x3 - x1) / dx1;
  70867. intersectionX = x3;
  70868. intersectionY = y1 + along * dy1;
  70869. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  70870. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70871. if (along < 1.0f)
  70872. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70873. return along >= 0 && along <= 1.0f;
  70874. }
  70875. }
  70876. intersectionX = 0.5f * (x2 + x3);
  70877. intersectionY = 0.5f * (y2 + y3);
  70878. distanceBeyondLine1EndSquared = 0.0f;
  70879. return false;
  70880. }
  70881. else
  70882. {
  70883. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  70884. intersectionX = x1 + along1 * dx1;
  70885. intersectionY = y1 + along1 * dy1;
  70886. if (along1 >= 0 && along1 <= 1.0f)
  70887. {
  70888. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  70889. if (along2 >= 0 && along2 <= divisor)
  70890. {
  70891. distanceBeyondLine1EndSquared = 0.0f;
  70892. return true;
  70893. }
  70894. }
  70895. distanceBeyondLine1EndSquared = along1 - 1.0f;
  70896. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  70897. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  70898. if (along1 < 1.0f)
  70899. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  70900. return false;
  70901. }
  70902. }
  70903. intersectionX = x2;
  70904. intersectionY = y2;
  70905. distanceBeyondLine1EndSquared = 0.0f;
  70906. return true;
  70907. }
  70908. // part of stroke drawing stuff
  70909. static void addEdgeAndJoint (Path& destPath,
  70910. const PathStrokeType::JointStyle style,
  70911. const float maxMiterExtensionSquared, const float width,
  70912. const float x1, const float y1,
  70913. const float x2, const float y2,
  70914. const float x3, const float y3,
  70915. const float x4, const float y4,
  70916. const float midX, const float midY) throw()
  70917. {
  70918. if (style == PathStrokeType::beveled
  70919. || (x3 == x4 && y3 == y4)
  70920. || (x1 == x2 && y1 == y2))
  70921. {
  70922. destPath.lineTo (x2, y2);
  70923. destPath.lineTo (x3, y3);
  70924. }
  70925. else
  70926. {
  70927. float jx, jy, distanceBeyondLine1EndSquared;
  70928. // if they intersect, use this point..
  70929. if (lineIntersection (x1, y1, x2, y2,
  70930. x3, y3, x4, y4,
  70931. jx, jy, distanceBeyondLine1EndSquared))
  70932. {
  70933. destPath.lineTo (jx, jy);
  70934. }
  70935. else
  70936. {
  70937. if (style == PathStrokeType::mitered)
  70938. {
  70939. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  70940. && distanceBeyondLine1EndSquared > 0.0f)
  70941. {
  70942. destPath.lineTo (jx, jy);
  70943. }
  70944. else
  70945. {
  70946. // the end sticks out too far, so just use a blunt joint
  70947. destPath.lineTo (x2, y2);
  70948. destPath.lineTo (x3, y3);
  70949. }
  70950. }
  70951. else
  70952. {
  70953. // curved joints
  70954. float angle = atan2f (x2 - midX, y2 - midY);
  70955. float angle2 = atan2f (x3 - midX, y3 - midY);
  70956. while (angle < angle2 - 0.01f)
  70957. angle2 -= float_Pi * 2.0f;
  70958. destPath.lineTo (x2, y2);
  70959. while (angle > angle2)
  70960. {
  70961. destPath.lineTo (midX + width * sinf (angle),
  70962. midY + width * cosf (angle));
  70963. angle -= 0.1f;
  70964. }
  70965. destPath.lineTo (x3, y3);
  70966. }
  70967. }
  70968. }
  70969. }
  70970. static inline void addLineEnd (Path& destPath,
  70971. const PathStrokeType::EndCapStyle style,
  70972. const float x1, const float y1,
  70973. const float x2, const float y2,
  70974. const float width) throw()
  70975. {
  70976. if (style == PathStrokeType::butt)
  70977. {
  70978. destPath.lineTo (x2, y2);
  70979. }
  70980. else
  70981. {
  70982. float offx1, offy1, offx2, offy2;
  70983. float dx = x2 - x1;
  70984. float dy = y2 - y1;
  70985. const float len = juce_hypotf (dx, dy);
  70986. if (len == 0)
  70987. {
  70988. offx1 = offx2 = x1;
  70989. offy1 = offy2 = y1;
  70990. }
  70991. else
  70992. {
  70993. const float offset = width / len;
  70994. dx *= offset;
  70995. dy *= offset;
  70996. offx1 = x1 + dy;
  70997. offy1 = y1 - dx;
  70998. offx2 = x2 + dy;
  70999. offy2 = y2 - dx;
  71000. }
  71001. if (style == PathStrokeType::square)
  71002. {
  71003. // sqaure ends
  71004. destPath.lineTo (offx1, offy1);
  71005. destPath.lineTo (offx2, offy2);
  71006. destPath.lineTo (x2, y2);
  71007. }
  71008. else
  71009. {
  71010. // rounded ends
  71011. const float midx = (offx1 + offx2) * 0.5f;
  71012. const float midy = (offy1 + offy2) * 0.5f;
  71013. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  71014. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  71015. midx, midy);
  71016. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  71017. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  71018. x2, y2);
  71019. }
  71020. }
  71021. }
  71022. struct LineSection
  71023. {
  71024. LineSection() throw() {}
  71025. LineSection (int) throw() {}
  71026. float x1, y1, x2, y2; // original line
  71027. float lx1, ly1, lx2, ly2; // the left-hand stroke
  71028. float rx1, ry1, rx2, ry2; // the right-hand stroke
  71029. };
  71030. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  71031. const bool isClosed,
  71032. const float width, const float maxMiterExtensionSquared,
  71033. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  71034. {
  71035. jassert (subPath.size() > 0);
  71036. const LineSection& firstLine = subPath.getReference (0);
  71037. float lastX1 = firstLine.lx1;
  71038. float lastY1 = firstLine.ly1;
  71039. float lastX2 = firstLine.lx2;
  71040. float lastY2 = firstLine.ly2;
  71041. if (isClosed)
  71042. {
  71043. destPath.startNewSubPath (lastX1, lastY1);
  71044. }
  71045. else
  71046. {
  71047. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  71048. addLineEnd (destPath, endStyle,
  71049. firstLine.rx2, firstLine.ry2,
  71050. lastX1, lastY1,
  71051. width);
  71052. }
  71053. int i;
  71054. for (i = 1; i < subPath.size(); ++i)
  71055. {
  71056. const LineSection& l = subPath.getReference (i);
  71057. addEdgeAndJoint (destPath, jointStyle,
  71058. maxMiterExtensionSquared, width,
  71059. lastX1, lastY1, lastX2, lastY2,
  71060. l.lx1, l.ly1, l.lx2, l.ly2,
  71061. l.x1, l.y1);
  71062. lastX1 = l.lx1;
  71063. lastY1 = l.ly1;
  71064. lastX2 = l.lx2;
  71065. lastY2 = l.ly2;
  71066. }
  71067. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  71068. if (isClosed)
  71069. {
  71070. const LineSection& l = subPath.getReference (0);
  71071. addEdgeAndJoint (destPath, jointStyle,
  71072. maxMiterExtensionSquared, width,
  71073. lastX1, lastY1, lastX2, lastY2,
  71074. l.lx1, l.ly1, l.lx2, l.ly2,
  71075. l.x1, l.y1);
  71076. destPath.closeSubPath();
  71077. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  71078. }
  71079. else
  71080. {
  71081. destPath.lineTo (lastX2, lastY2);
  71082. addLineEnd (destPath, endStyle,
  71083. lastX2, lastY2,
  71084. lastLine.rx1, lastLine.ry1,
  71085. width);
  71086. }
  71087. lastX1 = lastLine.rx1;
  71088. lastY1 = lastLine.ry1;
  71089. lastX2 = lastLine.rx2;
  71090. lastY2 = lastLine.ry2;
  71091. for (i = subPath.size() - 1; --i >= 0;)
  71092. {
  71093. const LineSection& l = subPath.getReference (i);
  71094. addEdgeAndJoint (destPath, jointStyle,
  71095. maxMiterExtensionSquared, width,
  71096. lastX1, lastY1, lastX2, lastY2,
  71097. l.rx1, l.ry1, l.rx2, l.ry2,
  71098. l.x2, l.y2);
  71099. lastX1 = l.rx1;
  71100. lastY1 = l.ry1;
  71101. lastX2 = l.rx2;
  71102. lastY2 = l.ry2;
  71103. }
  71104. if (isClosed)
  71105. {
  71106. addEdgeAndJoint (destPath, jointStyle,
  71107. maxMiterExtensionSquared, width,
  71108. lastX1, lastY1, lastX2, lastY2,
  71109. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  71110. lastLine.x2, lastLine.y2);
  71111. }
  71112. else
  71113. {
  71114. // do the last line
  71115. destPath.lineTo (lastX2, lastY2);
  71116. }
  71117. destPath.closeSubPath();
  71118. }
  71119. void PathStrokeType::createStrokedPath (Path& destPath,
  71120. const Path& source,
  71121. const AffineTransform& transform,
  71122. const float extraAccuracy) const throw()
  71123. {
  71124. if (thickness <= 0)
  71125. {
  71126. destPath.clear();
  71127. return;
  71128. }
  71129. const Path* sourcePath = &source;
  71130. Path temp;
  71131. if (sourcePath == &destPath)
  71132. {
  71133. destPath.swapWithPath (temp);
  71134. sourcePath = &temp;
  71135. }
  71136. else
  71137. {
  71138. destPath.clear();
  71139. }
  71140. destPath.setUsingNonZeroWinding (true);
  71141. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  71142. const float width = 0.5f * thickness;
  71143. // Iterate the path, creating a list of the
  71144. // left/right-hand lines along either side of it...
  71145. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  71146. Array <LineSection> subPath;
  71147. LineSection l;
  71148. l.x1 = 0;
  71149. l.y1 = 0;
  71150. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  71151. while (it.next())
  71152. {
  71153. if (it.subPathIndex == 0)
  71154. {
  71155. if (subPath.size() > 0)
  71156. {
  71157. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71158. subPath.clearQuick();
  71159. }
  71160. l.x1 = it.x1;
  71161. l.y1 = it.y1;
  71162. }
  71163. l.x2 = it.x2;
  71164. l.y2 = it.y2;
  71165. float dx = l.x2 - l.x1;
  71166. float dy = l.y2 - l.y1;
  71167. const float hypotSquared = dx*dx + dy*dy;
  71168. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  71169. {
  71170. const float len = sqrtf (hypotSquared);
  71171. if (len == 0)
  71172. {
  71173. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  71174. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  71175. }
  71176. else
  71177. {
  71178. const float offset = width / len;
  71179. dx *= offset;
  71180. dy *= offset;
  71181. l.rx2 = l.x1 - dy;
  71182. l.ry2 = l.y1 + dx;
  71183. l.lx1 = l.x1 + dy;
  71184. l.ly1 = l.y1 - dx;
  71185. l.lx2 = l.x2 + dy;
  71186. l.ly2 = l.y2 - dx;
  71187. l.rx1 = l.x2 - dy;
  71188. l.ry1 = l.y2 + dx;
  71189. }
  71190. subPath.add (l);
  71191. if (it.closesSubPath)
  71192. {
  71193. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71194. subPath.clearQuick();
  71195. }
  71196. else
  71197. {
  71198. l.x1 = it.x2;
  71199. l.y1 = it.y2;
  71200. }
  71201. }
  71202. }
  71203. if (subPath.size() > 0)
  71204. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  71205. }
  71206. void PathStrokeType::createDashedStroke (Path& destPath,
  71207. const Path& sourcePath,
  71208. const float* dashLengths,
  71209. int numDashLengths,
  71210. const AffineTransform& transform,
  71211. const float extraAccuracy) const throw()
  71212. {
  71213. if (thickness <= 0)
  71214. return;
  71215. // this should really be an even number..
  71216. jassert ((numDashLengths & 1) == 0);
  71217. Path newDestPath;
  71218. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  71219. bool first = true;
  71220. int dashNum = 0;
  71221. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  71222. float dx = 0.0f, dy = 0.0f;
  71223. for (;;)
  71224. {
  71225. const bool isSolid = ((dashNum & 1) == 0);
  71226. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  71227. jassert (dashLen > 0); // must be a positive increment!
  71228. if (dashLen <= 0)
  71229. break;
  71230. pos += dashLen;
  71231. while (pos > lineEndPos)
  71232. {
  71233. if (! it.next())
  71234. {
  71235. if (isSolid && ! first)
  71236. newDestPath.lineTo (it.x2, it.y2);
  71237. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  71238. return;
  71239. }
  71240. if (isSolid && ! first)
  71241. newDestPath.lineTo (it.x1, it.y1);
  71242. else
  71243. newDestPath.startNewSubPath (it.x1, it.y1);
  71244. dx = it.x2 - it.x1;
  71245. dy = it.y2 - it.y1;
  71246. lineLen = juce_hypotf (dx, dy);
  71247. lineEndPos += lineLen;
  71248. first = it.closesSubPath;
  71249. }
  71250. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  71251. if (isSolid)
  71252. newDestPath.lineTo (it.x1 + dx * alpha,
  71253. it.y1 + dy * alpha);
  71254. else
  71255. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  71256. it.y1 + dy * alpha);
  71257. }
  71258. }
  71259. END_JUCE_NAMESPACE
  71260. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  71261. /********* Start of inlined file: juce_Point.cpp *********/
  71262. BEGIN_JUCE_NAMESPACE
  71263. Point::Point() throw()
  71264. : x (0.0f),
  71265. y (0.0f)
  71266. {
  71267. }
  71268. Point::Point (const Point& other) throw()
  71269. : x (other.x),
  71270. y (other.y)
  71271. {
  71272. }
  71273. const Point& Point::operator= (const Point& other) throw()
  71274. {
  71275. x = other.x;
  71276. y = other.y;
  71277. return *this;
  71278. }
  71279. Point::Point (const float x_,
  71280. const float y_) throw()
  71281. : x (x_),
  71282. y (y_)
  71283. {
  71284. }
  71285. Point::~Point() throw()
  71286. {
  71287. }
  71288. void Point::setXY (const float x_,
  71289. const float y_) throw()
  71290. {
  71291. x = x_;
  71292. y = y_;
  71293. }
  71294. void Point::applyTransform (const AffineTransform& transform) throw()
  71295. {
  71296. transform.transformPoint (x, y);
  71297. }
  71298. END_JUCE_NAMESPACE
  71299. /********* End of inlined file: juce_Point.cpp *********/
  71300. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  71301. BEGIN_JUCE_NAMESPACE
  71302. PositionedRectangle::PositionedRectangle() throw()
  71303. : x (0.0),
  71304. y (0.0),
  71305. w (0.0),
  71306. h (0.0),
  71307. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71308. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  71309. wMode (absoluteSize),
  71310. hMode (absoluteSize)
  71311. {
  71312. }
  71313. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  71314. : x (other.x),
  71315. y (other.y),
  71316. w (other.w),
  71317. h (other.h),
  71318. xMode (other.xMode),
  71319. yMode (other.yMode),
  71320. wMode (other.wMode),
  71321. hMode (other.hMode)
  71322. {
  71323. }
  71324. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  71325. {
  71326. if (this != &other)
  71327. {
  71328. x = other.x;
  71329. y = other.y;
  71330. w = other.w;
  71331. h = other.h;
  71332. xMode = other.xMode;
  71333. yMode = other.yMode;
  71334. wMode = other.wMode;
  71335. hMode = other.hMode;
  71336. }
  71337. return *this;
  71338. }
  71339. PositionedRectangle::~PositionedRectangle() throw()
  71340. {
  71341. }
  71342. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  71343. {
  71344. return x == other.x
  71345. && y == other.y
  71346. && w == other.w
  71347. && h == other.h
  71348. && xMode == other.xMode
  71349. && yMode == other.yMode
  71350. && wMode == other.wMode
  71351. && hMode == other.hMode;
  71352. }
  71353. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  71354. {
  71355. return ! operator== (other);
  71356. }
  71357. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  71358. {
  71359. StringArray tokens;
  71360. tokens.addTokens (stringVersion, false);
  71361. decodePosString (tokens [0], xMode, x);
  71362. decodePosString (tokens [1], yMode, y);
  71363. decodeSizeString (tokens [2], wMode, w);
  71364. decodeSizeString (tokens [3], hMode, h);
  71365. }
  71366. const String PositionedRectangle::toString() const throw()
  71367. {
  71368. String s;
  71369. s.preallocateStorage (12);
  71370. addPosDescription (s, xMode, x);
  71371. s << T(' ');
  71372. addPosDescription (s, yMode, y);
  71373. s << T(' ');
  71374. addSizeDescription (s, wMode, w);
  71375. s << T(' ');
  71376. addSizeDescription (s, hMode, h);
  71377. return s;
  71378. }
  71379. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  71380. {
  71381. jassert (! target.isEmpty());
  71382. double x_, y_, w_, h_;
  71383. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71384. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71385. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  71386. roundDoubleToInt (w_), roundDoubleToInt (h_));
  71387. }
  71388. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  71389. double& x_, double& y_,
  71390. double& w_, double& h_) const throw()
  71391. {
  71392. jassert (! target.isEmpty());
  71393. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  71394. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  71395. }
  71396. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  71397. {
  71398. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  71399. }
  71400. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  71401. const Rectangle& target) throw()
  71402. {
  71403. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  71404. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  71405. }
  71406. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  71407. const double newW, const double newH,
  71408. const Rectangle& target) throw()
  71409. {
  71410. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  71411. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  71412. }
  71413. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  71414. {
  71415. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  71416. updateFrom (comp.getBounds(), Rectangle());
  71417. else
  71418. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  71419. }
  71420. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  71421. {
  71422. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71423. }
  71424. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  71425. {
  71426. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  71427. | absoluteFromParentBottomRight
  71428. | absoluteFromParentCentre
  71429. | proportionOfParentSize));
  71430. }
  71431. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  71432. {
  71433. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  71434. }
  71435. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  71436. {
  71437. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  71438. | absoluteFromParentBottomRight
  71439. | absoluteFromParentCentre
  71440. | proportionOfParentSize));
  71441. }
  71442. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  71443. {
  71444. return (SizeMode) wMode;
  71445. }
  71446. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  71447. {
  71448. return (SizeMode) hMode;
  71449. }
  71450. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  71451. const PositionMode xMode_,
  71452. const AnchorPoint yAnchor,
  71453. const PositionMode yMode_,
  71454. const SizeMode widthMode,
  71455. const SizeMode heightMode,
  71456. const Rectangle& target) throw()
  71457. {
  71458. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  71459. {
  71460. double tx, tw;
  71461. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  71462. xMode = (uint8) (xAnchor | xMode_);
  71463. wMode = (uint8) widthMode;
  71464. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  71465. }
  71466. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  71467. {
  71468. double ty, th;
  71469. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  71470. yMode = (uint8) (yAnchor | yMode_);
  71471. hMode = (uint8) heightMode;
  71472. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  71473. }
  71474. }
  71475. bool PositionedRectangle::isPositionAbsolute() const throw()
  71476. {
  71477. return xMode == absoluteFromParentTopLeft
  71478. && yMode == absoluteFromParentTopLeft
  71479. && wMode == absoluteSize
  71480. && hMode == absoluteSize;
  71481. }
  71482. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  71483. {
  71484. if ((mode & proportionOfParentSize) != 0)
  71485. {
  71486. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71487. }
  71488. else
  71489. {
  71490. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71491. if ((mode & absoluteFromParentBottomRight) != 0)
  71492. s << T('R');
  71493. else if ((mode & absoluteFromParentCentre) != 0)
  71494. s << T('C');
  71495. }
  71496. if ((mode & anchorAtRightOrBottom) != 0)
  71497. s << T('r');
  71498. else if ((mode & anchorAtCentre) != 0)
  71499. s << T('c');
  71500. }
  71501. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  71502. {
  71503. if (mode == proportionalSize)
  71504. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  71505. else if (mode == parentSizeMinusAbsolute)
  71506. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  71507. else
  71508. s << (roundDoubleToInt (value * 100.0) / 100.0);
  71509. }
  71510. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  71511. {
  71512. if (s.containsChar (T('r')))
  71513. mode = anchorAtRightOrBottom;
  71514. else if (s.containsChar (T('c')))
  71515. mode = anchorAtCentre;
  71516. else
  71517. mode = anchorAtLeftOrTop;
  71518. if (s.containsChar (T('%')))
  71519. {
  71520. mode |= proportionOfParentSize;
  71521. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  71522. }
  71523. else
  71524. {
  71525. if (s.containsChar (T('R')))
  71526. mode |= absoluteFromParentBottomRight;
  71527. else if (s.containsChar (T('C')))
  71528. mode |= absoluteFromParentCentre;
  71529. else
  71530. mode |= absoluteFromParentTopLeft;
  71531. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  71532. }
  71533. }
  71534. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  71535. {
  71536. if (s.containsChar (T('%')))
  71537. {
  71538. mode = proportionalSize;
  71539. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  71540. }
  71541. else if (s.containsChar (T('M')))
  71542. {
  71543. mode = parentSizeMinusAbsolute;
  71544. value = s.getDoubleValue();
  71545. }
  71546. else
  71547. {
  71548. mode = absoluteSize;
  71549. value = s.getDoubleValue();
  71550. }
  71551. }
  71552. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  71553. const double x_, const double w_,
  71554. const uint8 xMode_, const uint8 wMode_,
  71555. const int parentPos,
  71556. const int parentSize) const throw()
  71557. {
  71558. if (wMode_ == proportionalSize)
  71559. wOut = roundDoubleToInt (w_ * parentSize);
  71560. else if (wMode_ == parentSizeMinusAbsolute)
  71561. wOut = jmax (0, parentSize - roundDoubleToInt (w_));
  71562. else
  71563. wOut = roundDoubleToInt (w_);
  71564. if ((xMode_ & proportionOfParentSize) != 0)
  71565. xOut = parentPos + x_ * parentSize;
  71566. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71567. xOut = (parentPos + parentSize) - x_;
  71568. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71569. xOut = x_ + (parentPos + parentSize / 2);
  71570. else
  71571. xOut = x_ + parentPos;
  71572. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71573. xOut -= wOut;
  71574. else if ((xMode_ & anchorAtCentre) != 0)
  71575. xOut -= wOut / 2;
  71576. }
  71577. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  71578. double x_, const double w_,
  71579. const uint8 xMode_, const uint8 wMode_,
  71580. const int parentPos,
  71581. const int parentSize) const throw()
  71582. {
  71583. if (wMode_ == proportionalSize)
  71584. {
  71585. if (parentSize > 0)
  71586. wOut = w_ / parentSize;
  71587. }
  71588. else if (wMode_ == parentSizeMinusAbsolute)
  71589. wOut = parentSize - w_;
  71590. else
  71591. wOut = w_;
  71592. if ((xMode_ & anchorAtRightOrBottom) != 0)
  71593. x_ += w_;
  71594. else if ((xMode_ & anchorAtCentre) != 0)
  71595. x_ += w_ / 2;
  71596. if ((xMode_ & proportionOfParentSize) != 0)
  71597. {
  71598. if (parentSize > 0)
  71599. xOut = (x_ - parentPos) / parentSize;
  71600. }
  71601. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  71602. xOut = (parentPos + parentSize) - x_;
  71603. else if ((xMode_ & absoluteFromParentCentre) != 0)
  71604. xOut = x_ - (parentPos + parentSize / 2);
  71605. else
  71606. xOut = x_ - parentPos;
  71607. }
  71608. END_JUCE_NAMESPACE
  71609. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  71610. /********* Start of inlined file: juce_Rectangle.cpp *********/
  71611. BEGIN_JUCE_NAMESPACE
  71612. Rectangle::Rectangle() throw()
  71613. : x (0),
  71614. y (0),
  71615. w (0),
  71616. h (0)
  71617. {
  71618. }
  71619. Rectangle::Rectangle (const int x_, const int y_,
  71620. const int w_, const int h_) throw()
  71621. : x (x_),
  71622. y (y_),
  71623. w (w_),
  71624. h (h_)
  71625. {
  71626. }
  71627. Rectangle::Rectangle (const int w_, const int h_) throw()
  71628. : x (0),
  71629. y (0),
  71630. w (w_),
  71631. h (h_)
  71632. {
  71633. }
  71634. Rectangle::Rectangle (const Rectangle& other) throw()
  71635. : x (other.x),
  71636. y (other.y),
  71637. w (other.w),
  71638. h (other.h)
  71639. {
  71640. }
  71641. Rectangle::~Rectangle() throw()
  71642. {
  71643. }
  71644. bool Rectangle::isEmpty() const throw()
  71645. {
  71646. return w <= 0 || h <= 0;
  71647. }
  71648. void Rectangle::setBounds (const int x_,
  71649. const int y_,
  71650. const int w_,
  71651. const int h_) throw()
  71652. {
  71653. x = x_;
  71654. y = y_;
  71655. w = w_;
  71656. h = h_;
  71657. }
  71658. void Rectangle::setPosition (const int x_,
  71659. const int y_) throw()
  71660. {
  71661. x = x_;
  71662. y = y_;
  71663. }
  71664. void Rectangle::setSize (const int w_,
  71665. const int h_) throw()
  71666. {
  71667. w = w_;
  71668. h = h_;
  71669. }
  71670. void Rectangle::setLeft (const int newLeft) throw()
  71671. {
  71672. w = jmax (0, x + w - newLeft);
  71673. x = newLeft;
  71674. }
  71675. void Rectangle::setTop (const int newTop) throw()
  71676. {
  71677. h = jmax (0, y + h - newTop);
  71678. y = newTop;
  71679. }
  71680. void Rectangle::setRight (const int newRight) throw()
  71681. {
  71682. x = jmin (x, newRight);
  71683. w = newRight - x;
  71684. }
  71685. void Rectangle::setBottom (const int newBottom) throw()
  71686. {
  71687. y = jmin (y, newBottom);
  71688. h = newBottom - y;
  71689. }
  71690. void Rectangle::translate (const int dx,
  71691. const int dy) throw()
  71692. {
  71693. x += dx;
  71694. y += dy;
  71695. }
  71696. const Rectangle Rectangle::translated (const int dx,
  71697. const int dy) const throw()
  71698. {
  71699. return Rectangle (x + dx, y + dy, w, h);
  71700. }
  71701. void Rectangle::expand (const int deltaX,
  71702. const int deltaY) throw()
  71703. {
  71704. const int nw = jmax (0, w + deltaX + deltaX);
  71705. const int nh = jmax (0, h + deltaY + deltaY);
  71706. setBounds (x - deltaX,
  71707. y - deltaY,
  71708. nw, nh);
  71709. }
  71710. const Rectangle Rectangle::expanded (const int deltaX,
  71711. const int deltaY) const throw()
  71712. {
  71713. const int nw = jmax (0, w + deltaX + deltaX);
  71714. const int nh = jmax (0, h + deltaY + deltaY);
  71715. return Rectangle (x - deltaX,
  71716. y - deltaY,
  71717. nw, nh);
  71718. }
  71719. void Rectangle::reduce (const int deltaX,
  71720. const int deltaY) throw()
  71721. {
  71722. expand (-deltaX, -deltaY);
  71723. }
  71724. const Rectangle Rectangle::reduced (const int deltaX,
  71725. const int deltaY) const throw()
  71726. {
  71727. return expanded (-deltaX, -deltaY);
  71728. }
  71729. bool Rectangle::operator== (const Rectangle& other) const throw()
  71730. {
  71731. return x == other.x
  71732. && y == other.y
  71733. && w == other.w
  71734. && h == other.h;
  71735. }
  71736. bool Rectangle::operator!= (const Rectangle& other) const throw()
  71737. {
  71738. return x != other.x
  71739. || y != other.y
  71740. || w != other.w
  71741. || h != other.h;
  71742. }
  71743. bool Rectangle::contains (const int px,
  71744. const int py) const throw()
  71745. {
  71746. return px >= x
  71747. && py >= y
  71748. && px < x + w
  71749. && py < y + h;
  71750. }
  71751. bool Rectangle::contains (const Rectangle& other) const throw()
  71752. {
  71753. return x <= other.x
  71754. && y <= other.y
  71755. && x + w >= other.x + other.w
  71756. && y + h >= other.y + other.h;
  71757. }
  71758. bool Rectangle::intersects (const Rectangle& other) const throw()
  71759. {
  71760. return x + w > other.x
  71761. && y + h > other.y
  71762. && x < other.x + other.w
  71763. && y < other.y + other.h
  71764. && w > 0
  71765. && h > 0;
  71766. }
  71767. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  71768. {
  71769. const int nx = jmax (x, other.x);
  71770. const int ny = jmax (y, other.y);
  71771. const int nw = jmin (x + w, other.x + other.w) - nx;
  71772. const int nh = jmin (y + h, other.y + other.h) - ny;
  71773. if (nw >= 0 && nh >= 0)
  71774. return Rectangle (nx, ny, nw, nh);
  71775. else
  71776. return Rectangle();
  71777. }
  71778. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  71779. {
  71780. const int maxX = jmax (x1, x);
  71781. w1 = jmin (x1 + w1, x + w) - maxX;
  71782. if (w1 > 0)
  71783. {
  71784. const int maxY = jmax (y1, y);
  71785. h1 = jmin (y1 + h1, y + h) - maxY;
  71786. if (h1 > 0)
  71787. {
  71788. x1 = maxX;
  71789. y1 = maxY;
  71790. return true;
  71791. }
  71792. }
  71793. return false;
  71794. }
  71795. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  71796. int x2, int y2, int w2, int h2) throw()
  71797. {
  71798. const int x = jmax (x1, x2);
  71799. w1 = jmin (x1 + w1, x2 + w2) - x;
  71800. if (w1 > 0)
  71801. {
  71802. const int y = jmax (y1, y2);
  71803. h1 = jmin (y1 + h1, y2 + h2) - y;
  71804. if (h1 > 0)
  71805. {
  71806. x1 = x;
  71807. y1 = y;
  71808. return true;
  71809. }
  71810. }
  71811. return false;
  71812. }
  71813. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  71814. {
  71815. const int newX = jmin (x, other.x);
  71816. const int newY = jmin (y, other.y);
  71817. return Rectangle (newX, newY,
  71818. jmax (x + w, other.x + other.w) - newX,
  71819. jmax (y + h, other.y + other.h) - newY);
  71820. }
  71821. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  71822. {
  71823. if (x == other.x && getRight() == other.getRight()
  71824. && (other.getBottom() >= y && other.y <= getBottom()))
  71825. {
  71826. const int newY = jmin (y, other.y);
  71827. h = jmax (getBottom(), other.getBottom()) - newY;
  71828. y = newY;
  71829. return true;
  71830. }
  71831. else if (y == other.y && getBottom() == other.getBottom()
  71832. && (other.getRight() >= x && other.x <= getRight()))
  71833. {
  71834. const int newX = jmin (x, other.x);
  71835. w = jmax (getRight(), other.getRight()) - newX;
  71836. x = newX;
  71837. return true;
  71838. }
  71839. return false;
  71840. }
  71841. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  71842. {
  71843. int inside = 0;
  71844. const int otherR = other.getRight();
  71845. if (x >= other.x && x < otherR)
  71846. inside = 1;
  71847. const int otherB = other.getBottom();
  71848. if (y >= other.y && y < otherB)
  71849. inside |= 2;
  71850. const int r = x + w;
  71851. if (r >= other.x && r < otherR)
  71852. inside |= 4;
  71853. const int b = y + h;
  71854. if (b >= other.y && b < otherB)
  71855. inside |= 8;
  71856. switch (inside)
  71857. {
  71858. case 1 + 2 + 8:
  71859. w = r - otherR;
  71860. x = otherR;
  71861. return true;
  71862. case 1 + 2 + 4:
  71863. h = b - otherB;
  71864. y = otherB;
  71865. return true;
  71866. case 2 + 4 + 8:
  71867. w = other.x - x;
  71868. return true;
  71869. case 1 + 4 + 8:
  71870. h = other.y - y;
  71871. return true;
  71872. }
  71873. return false;
  71874. }
  71875. const String Rectangle::toString() const throw()
  71876. {
  71877. String s;
  71878. s.preallocateStorage (16);
  71879. s << x << T(' ')
  71880. << y << T(' ')
  71881. << w << T(' ')
  71882. << h;
  71883. return s;
  71884. }
  71885. const Rectangle Rectangle::fromString (const String& stringVersion)
  71886. {
  71887. StringArray toks;
  71888. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  71889. return Rectangle (toks[0].trim().getIntValue(),
  71890. toks[1].trim().getIntValue(),
  71891. toks[2].trim().getIntValue(),
  71892. toks[3].trim().getIntValue());
  71893. }
  71894. END_JUCE_NAMESPACE
  71895. /********* End of inlined file: juce_Rectangle.cpp *********/
  71896. /********* Start of inlined file: juce_RectangleList.cpp *********/
  71897. BEGIN_JUCE_NAMESPACE
  71898. RectangleList::RectangleList() throw()
  71899. {
  71900. }
  71901. RectangleList::RectangleList (const Rectangle& rect) throw()
  71902. {
  71903. if (! rect.isEmpty())
  71904. rects.add (rect);
  71905. }
  71906. RectangleList::RectangleList (const RectangleList& other) throw()
  71907. : rects (other.rects)
  71908. {
  71909. }
  71910. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  71911. {
  71912. if (this != &other)
  71913. rects = other.rects;
  71914. return *this;
  71915. }
  71916. RectangleList::~RectangleList() throw()
  71917. {
  71918. }
  71919. void RectangleList::clear() throw()
  71920. {
  71921. rects.clearQuick();
  71922. }
  71923. const Rectangle RectangleList::getRectangle (const int index) const throw()
  71924. {
  71925. if (((unsigned int) index) < (unsigned int) rects.size())
  71926. return rects.getReference (index);
  71927. return Rectangle();
  71928. }
  71929. bool RectangleList::isEmpty() const throw()
  71930. {
  71931. return rects.size() == 0;
  71932. }
  71933. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  71934. : current (0),
  71935. owner (list),
  71936. index (list.rects.size())
  71937. {
  71938. }
  71939. RectangleList::Iterator::~Iterator() throw()
  71940. {
  71941. }
  71942. bool RectangleList::Iterator::next() throw()
  71943. {
  71944. if (--index >= 0)
  71945. {
  71946. current = & (owner.rects.getReference (index));
  71947. return true;
  71948. }
  71949. return false;
  71950. }
  71951. void RectangleList::add (const Rectangle& rect) throw()
  71952. {
  71953. if (! rect.isEmpty())
  71954. {
  71955. if (rects.size() == 0)
  71956. {
  71957. rects.add (rect);
  71958. }
  71959. else
  71960. {
  71961. bool anyOverlaps = false;
  71962. int i;
  71963. for (i = rects.size(); --i >= 0;)
  71964. {
  71965. Rectangle& ourRect = rects.getReference (i);
  71966. if (rect.intersects (ourRect))
  71967. {
  71968. if (rect.contains (ourRect))
  71969. rects.remove (i);
  71970. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  71971. anyOverlaps = true;
  71972. }
  71973. }
  71974. if (anyOverlaps && rects.size() > 0)
  71975. {
  71976. RectangleList r (rect);
  71977. for (i = rects.size(); --i >= 0;)
  71978. {
  71979. const Rectangle& ourRect = rects.getReference (i);
  71980. if (rect.intersects (ourRect))
  71981. {
  71982. r.subtract (ourRect);
  71983. if (r.rects.size() == 0)
  71984. return;
  71985. }
  71986. }
  71987. for (i = r.getNumRectangles(); --i >= 0;)
  71988. rects.add (r.rects.getReference (i));
  71989. }
  71990. else
  71991. {
  71992. rects.add (rect);
  71993. }
  71994. }
  71995. }
  71996. }
  71997. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  71998. {
  71999. rects.add (rect);
  72000. }
  72001. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  72002. {
  72003. if (rects.size() == 0)
  72004. {
  72005. if (w > 0 && h > 0)
  72006. rects.add (Rectangle (x, y, w, h));
  72007. }
  72008. else
  72009. {
  72010. add (Rectangle (x, y, w, h));
  72011. }
  72012. }
  72013. void RectangleList::add (const RectangleList& other) throw()
  72014. {
  72015. for (int i = 0; i < other.rects.size(); ++i)
  72016. add (other.rects.getReference (i));
  72017. }
  72018. void RectangleList::subtract (const Rectangle& rect) throw()
  72019. {
  72020. const int originalNumRects = rects.size();
  72021. if (originalNumRects > 0)
  72022. {
  72023. const int x1 = rect.x;
  72024. const int y1 = rect.y;
  72025. const int x2 = x1 + rect.w;
  72026. const int y2 = y1 + rect.h;
  72027. for (int i = getNumRectangles(); --i >= 0;)
  72028. {
  72029. Rectangle& r = rects.getReference (i);
  72030. const int rx1 = r.x;
  72031. const int ry1 = r.y;
  72032. const int rx2 = rx1 + r.w;
  72033. const int ry2 = ry1 + r.h;
  72034. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  72035. {
  72036. if (x1 > rx1 && x1 < rx2)
  72037. {
  72038. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  72039. {
  72040. r.w = x1 - rx1;
  72041. }
  72042. else
  72043. {
  72044. r.x = x1;
  72045. r.w = rx2 - x1;
  72046. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  72047. i += 2;
  72048. }
  72049. }
  72050. else if (x2 > rx1 && x2 < rx2)
  72051. {
  72052. r.x = x2;
  72053. r.w = rx2 - x2;
  72054. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  72055. {
  72056. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  72057. i += 2;
  72058. }
  72059. }
  72060. else if (y1 > ry1 && y1 < ry2)
  72061. {
  72062. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  72063. {
  72064. r.h = y1 - ry1;
  72065. }
  72066. else
  72067. {
  72068. r.y = y1;
  72069. r.h = ry2 - y1;
  72070. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  72071. i += 2;
  72072. }
  72073. }
  72074. else if (y2 > ry1 && y2 < ry2)
  72075. {
  72076. r.y = y2;
  72077. r.h = ry2 - y2;
  72078. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  72079. {
  72080. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  72081. i += 2;
  72082. }
  72083. }
  72084. else
  72085. {
  72086. rects.remove (i);
  72087. }
  72088. }
  72089. }
  72090. if (rects.size() > originalNumRects + 10)
  72091. consolidate();
  72092. }
  72093. }
  72094. void RectangleList::subtract (const RectangleList& otherList) throw()
  72095. {
  72096. for (int i = otherList.rects.size(); --i >= 0;)
  72097. subtract (otherList.rects.getReference (i));
  72098. }
  72099. bool RectangleList::clipTo (const Rectangle& rect) throw()
  72100. {
  72101. bool notEmpty = false;
  72102. if (rect.isEmpty())
  72103. {
  72104. clear();
  72105. }
  72106. else
  72107. {
  72108. for (int i = rects.size(); --i >= 0;)
  72109. {
  72110. Rectangle& r = rects.getReference (i);
  72111. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72112. rects.remove (i);
  72113. else
  72114. notEmpty = true;
  72115. }
  72116. }
  72117. return notEmpty;
  72118. }
  72119. bool RectangleList::clipTo (const RectangleList& other) throw()
  72120. {
  72121. if (rects.size() == 0)
  72122. return false;
  72123. RectangleList result;
  72124. for (int j = 0; j < rects.size(); ++j)
  72125. {
  72126. const Rectangle& rect = rects.getReference (j);
  72127. for (int i = other.rects.size(); --i >= 0;)
  72128. {
  72129. Rectangle r (other.rects.getReference (i));
  72130. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72131. result.rects.add (r);
  72132. }
  72133. }
  72134. swapWith (result);
  72135. return ! isEmpty();
  72136. }
  72137. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  72138. {
  72139. destRegion.clear();
  72140. if (! rect.isEmpty())
  72141. {
  72142. for (int i = rects.size(); --i >= 0;)
  72143. {
  72144. Rectangle r (rects.getReference (i));
  72145. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  72146. destRegion.rects.add (r);
  72147. }
  72148. }
  72149. return destRegion.rects.size() > 0;
  72150. }
  72151. void RectangleList::swapWith (RectangleList& otherList) throw()
  72152. {
  72153. rects.swapWithArray (otherList.rects);
  72154. }
  72155. void RectangleList::consolidate() throw()
  72156. {
  72157. int i;
  72158. for (i = 0; i < getNumRectangles() - 1; ++i)
  72159. {
  72160. Rectangle& r = rects.getReference (i);
  72161. const int rx1 = r.x;
  72162. const int ry1 = r.y;
  72163. const int rx2 = rx1 + r.w;
  72164. const int ry2 = ry1 + r.h;
  72165. for (int j = rects.size(); --j > i;)
  72166. {
  72167. Rectangle& r2 = rects.getReference (j);
  72168. const int jrx1 = r2.x;
  72169. const int jry1 = r2.y;
  72170. const int jrx2 = jrx1 + r2.w;
  72171. const int jry2 = jry1 + r2.h;
  72172. // if the vertical edges of any blocks are touching and their horizontals don't
  72173. // line up, split them horizontally..
  72174. if (jrx1 == rx2 || jrx2 == rx1)
  72175. {
  72176. if (jry1 > ry1 && jry1 < ry2)
  72177. {
  72178. r.h = jry1 - ry1;
  72179. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  72180. i = -1;
  72181. break;
  72182. }
  72183. if (jry2 > ry1 && jry2 < ry2)
  72184. {
  72185. r.h = jry2 - ry1;
  72186. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  72187. i = -1;
  72188. break;
  72189. }
  72190. else if (ry1 > jry1 && ry1 < jry2)
  72191. {
  72192. r2.h = ry1 - jry1;
  72193. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  72194. i = -1;
  72195. break;
  72196. }
  72197. else if (ry2 > jry1 && ry2 < jry2)
  72198. {
  72199. r2.h = ry2 - jry1;
  72200. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  72201. i = -1;
  72202. break;
  72203. }
  72204. }
  72205. }
  72206. }
  72207. for (i = 0; i < rects.size() - 1; ++i)
  72208. {
  72209. Rectangle& r = rects.getReference (i);
  72210. for (int j = rects.size(); --j > i;)
  72211. {
  72212. if (r.enlargeIfAdjacent (rects.getReference (j)))
  72213. {
  72214. rects.remove (j);
  72215. i = -1;
  72216. break;
  72217. }
  72218. }
  72219. }
  72220. }
  72221. bool RectangleList::containsPoint (const int x, const int y) const throw()
  72222. {
  72223. for (int i = getNumRectangles(); --i >= 0;)
  72224. if (rects.getReference (i).contains (x, y))
  72225. return true;
  72226. return false;
  72227. }
  72228. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  72229. {
  72230. if (rects.size() > 1)
  72231. {
  72232. RectangleList r (rectangleToCheck);
  72233. for (int i = rects.size(); --i >= 0;)
  72234. {
  72235. r.subtract (rects.getReference (i));
  72236. if (r.rects.size() == 0)
  72237. return true;
  72238. }
  72239. }
  72240. else if (rects.size() > 0)
  72241. {
  72242. return rects.getReference (0).contains (rectangleToCheck);
  72243. }
  72244. return false;
  72245. }
  72246. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  72247. {
  72248. for (int i = rects.size(); --i >= 0;)
  72249. if (rects.getReference (i).intersects (rectangleToCheck))
  72250. return true;
  72251. return false;
  72252. }
  72253. bool RectangleList::intersects (const RectangleList& other) const throw()
  72254. {
  72255. for (int i = rects.size(); --i >= 0;)
  72256. if (other.intersectsRectangle (rects.getReference (i)))
  72257. return true;
  72258. return false;
  72259. }
  72260. const Rectangle RectangleList::getBounds() const throw()
  72261. {
  72262. if (rects.size() <= 1)
  72263. {
  72264. if (rects.size() == 0)
  72265. return Rectangle();
  72266. else
  72267. return rects.getReference (0);
  72268. }
  72269. else
  72270. {
  72271. const Rectangle& r = rects.getReference (0);
  72272. int minX = r.x;
  72273. int minY = r.y;
  72274. int maxX = minX + r.w;
  72275. int maxY = minY + r.h;
  72276. for (int i = rects.size(); --i > 0;)
  72277. {
  72278. const Rectangle& r2 = rects.getReference (i);
  72279. minX = jmin (minX, r2.x);
  72280. minY = jmin (minY, r2.y);
  72281. maxX = jmax (maxX, r2.getRight());
  72282. maxY = jmax (maxY, r2.getBottom());
  72283. }
  72284. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  72285. }
  72286. }
  72287. void RectangleList::offsetAll (const int dx, const int dy) throw()
  72288. {
  72289. for (int i = rects.size(); --i >= 0;)
  72290. {
  72291. Rectangle& r = rects.getReference (i);
  72292. r.x += dx;
  72293. r.y += dy;
  72294. }
  72295. }
  72296. const Path RectangleList::toPath() const throw()
  72297. {
  72298. Path p;
  72299. for (int i = rects.size(); --i >= 0;)
  72300. {
  72301. const Rectangle& r = rects.getReference (i);
  72302. p.addRectangle ((float) r.x,
  72303. (float) r.y,
  72304. (float) r.w,
  72305. (float) r.h);
  72306. }
  72307. return p;
  72308. }
  72309. END_JUCE_NAMESPACE
  72310. /********* End of inlined file: juce_RectangleList.cpp *********/
  72311. /********* Start of inlined file: juce_Image.cpp *********/
  72312. BEGIN_JUCE_NAMESPACE
  72313. static const int fullAlphaThreshold = 253;
  72314. Image::Image (const PixelFormat format_,
  72315. const int imageWidth_,
  72316. const int imageHeight_)
  72317. : format (format_),
  72318. imageWidth (imageWidth_),
  72319. imageHeight (imageHeight_),
  72320. imageData (0)
  72321. {
  72322. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72323. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72324. // actual image will be at least 1x1.
  72325. }
  72326. Image::Image (const PixelFormat format_,
  72327. const int imageWidth_,
  72328. const int imageHeight_,
  72329. const bool clearImage)
  72330. : format (format_),
  72331. imageWidth (imageWidth_),
  72332. imageHeight (imageHeight_)
  72333. {
  72334. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  72335. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  72336. // actual image will be at least 1x1.
  72337. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72338. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  72339. const int dataSize = lineStride * jmax (1, imageHeight_);
  72340. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  72341. : juce_malloc (dataSize));
  72342. }
  72343. Image::Image (const Image& other)
  72344. : format (other.format),
  72345. imageWidth (other.imageWidth),
  72346. imageHeight (other.imageHeight)
  72347. {
  72348. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  72349. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  72350. const int dataSize = lineStride * jmax (1, imageHeight);
  72351. imageData = (uint8*) juce_malloc (dataSize);
  72352. int ls, ps;
  72353. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72354. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  72355. other.releasePixelDataReadOnly (srcData);
  72356. }
  72357. Image::~Image()
  72358. {
  72359. juce_free (imageData);
  72360. }
  72361. LowLevelGraphicsContext* Image::createLowLevelContext()
  72362. {
  72363. return new LowLevelGraphicsSoftwareRenderer (*this);
  72364. }
  72365. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  72366. {
  72367. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72368. w = w;
  72369. h = h;
  72370. ls = lineStride;
  72371. ps = pixelStride;
  72372. return imageData + x * pixelStride + y * lineStride;
  72373. }
  72374. void Image::releasePixelDataReadWrite (void*)
  72375. {
  72376. }
  72377. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  72378. {
  72379. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72380. w = w;
  72381. h = h;
  72382. ls = lineStride;
  72383. ps = pixelStride;
  72384. return imageData + x * pixelStride + y * lineStride;
  72385. }
  72386. void Image::releasePixelDataReadOnly (const void*) const
  72387. {
  72388. }
  72389. void Image::setPixelData (int x, int y, int w, int h,
  72390. const uint8* sourcePixelData, int sourceLineStride)
  72391. {
  72392. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  72393. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  72394. {
  72395. int ls, ps;
  72396. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  72397. for (int i = 0; i < h; ++i)
  72398. {
  72399. memcpy (dest + ls * i,
  72400. sourcePixelData + sourceLineStride * i,
  72401. w * pixelStride);
  72402. }
  72403. releasePixelDataReadWrite (dest);
  72404. }
  72405. }
  72406. void Image::clear (int dx, int dy, int dw, int dh,
  72407. const Colour& colourToClearTo)
  72408. {
  72409. const PixelARGB col (colourToClearTo.getPixelARGB());
  72410. int ls, ps;
  72411. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  72412. uint8* dest = dstData;
  72413. while (--dh >= 0)
  72414. {
  72415. uint8* line = dest;
  72416. dest += ls;
  72417. if (isARGB())
  72418. {
  72419. for (int x = dw; --x >= 0;)
  72420. {
  72421. ((PixelARGB*) line)->set (col);
  72422. line += ps;
  72423. }
  72424. }
  72425. else if (isRGB())
  72426. {
  72427. for (int x = dw; --x >= 0;)
  72428. {
  72429. ((PixelRGB*) line)->set (col);
  72430. line += ps;
  72431. }
  72432. }
  72433. else
  72434. {
  72435. for (int x = dw; --x >= 0;)
  72436. {
  72437. *line = col.getAlpha();
  72438. line += ps;
  72439. }
  72440. }
  72441. }
  72442. releasePixelDataReadWrite (dstData);
  72443. }
  72444. Image* Image::createCopy (int newWidth, int newHeight,
  72445. const Graphics::ResamplingQuality quality) const
  72446. {
  72447. if (newWidth < 0)
  72448. newWidth = imageWidth;
  72449. if (newHeight < 0)
  72450. newHeight = imageHeight;
  72451. Image* const newImage = new Image (format, newWidth, newHeight, true);
  72452. Graphics g (*newImage);
  72453. g.setImageResamplingQuality (quality);
  72454. g.drawImage (this,
  72455. 0, 0, newWidth, newHeight,
  72456. 0, 0, imageWidth, imageHeight,
  72457. false);
  72458. return newImage;
  72459. }
  72460. const Colour Image::getPixelAt (const int x, const int y) const
  72461. {
  72462. Colour c;
  72463. if (((unsigned int) x) < (unsigned int) imageWidth
  72464. && ((unsigned int) y) < (unsigned int) imageHeight)
  72465. {
  72466. int ls, ps;
  72467. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  72468. if (isARGB())
  72469. {
  72470. PixelARGB p (*(const PixelARGB*) pixels);
  72471. p.unpremultiply();
  72472. c = Colour (p.getARGB());
  72473. }
  72474. else if (isRGB())
  72475. c = Colour (((const PixelRGB*) pixels)->getARGB());
  72476. else
  72477. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  72478. releasePixelDataReadOnly (pixels);
  72479. }
  72480. return c;
  72481. }
  72482. void Image::setPixelAt (const int x, const int y,
  72483. const Colour& colour)
  72484. {
  72485. if (((unsigned int) x) < (unsigned int) imageWidth
  72486. && ((unsigned int) y) < (unsigned int) imageHeight)
  72487. {
  72488. int ls, ps;
  72489. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72490. const PixelARGB col (colour.getPixelARGB());
  72491. if (isARGB())
  72492. ((PixelARGB*) pixels)->set (col);
  72493. else if (isRGB())
  72494. ((PixelRGB*) pixels)->set (col);
  72495. else
  72496. *pixels = col.getAlpha();
  72497. releasePixelDataReadWrite (pixels);
  72498. }
  72499. }
  72500. void Image::multiplyAlphaAt (const int x, const int y,
  72501. const float multiplier)
  72502. {
  72503. if (((unsigned int) x) < (unsigned int) imageWidth
  72504. && ((unsigned int) y) < (unsigned int) imageHeight
  72505. && hasAlphaChannel())
  72506. {
  72507. int ls, ps;
  72508. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  72509. if (isARGB())
  72510. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  72511. else
  72512. *pixels = (uint8) (*pixels * multiplier);
  72513. releasePixelDataReadWrite (pixels);
  72514. }
  72515. }
  72516. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  72517. {
  72518. if (hasAlphaChannel())
  72519. {
  72520. int ls, ps;
  72521. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72522. if (isARGB())
  72523. {
  72524. for (int y = 0; y < imageHeight; ++y)
  72525. {
  72526. uint8* p = pixels + y * ls;
  72527. for (int x = 0; x < imageWidth; ++x)
  72528. {
  72529. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  72530. p += ps;
  72531. }
  72532. }
  72533. }
  72534. else
  72535. {
  72536. for (int y = 0; y < imageHeight; ++y)
  72537. {
  72538. uint8* p = pixels + y * ls;
  72539. for (int x = 0; x < imageWidth; ++x)
  72540. {
  72541. *p = (uint8) (*p * amountToMultiplyBy);
  72542. p += ps;
  72543. }
  72544. }
  72545. }
  72546. releasePixelDataReadWrite (pixels);
  72547. }
  72548. else
  72549. {
  72550. jassertfalse // can't do this without an alpha-channel!
  72551. }
  72552. }
  72553. void Image::desaturate()
  72554. {
  72555. if (isARGB() || isRGB())
  72556. {
  72557. int ls, ps;
  72558. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  72559. if (isARGB())
  72560. {
  72561. for (int y = 0; y < imageHeight; ++y)
  72562. {
  72563. uint8* p = pixels + y * ls;
  72564. for (int x = 0; x < imageWidth; ++x)
  72565. {
  72566. ((PixelARGB*) p)->desaturate();
  72567. p += ps;
  72568. }
  72569. }
  72570. }
  72571. else
  72572. {
  72573. for (int y = 0; y < imageHeight; ++y)
  72574. {
  72575. uint8* p = pixels + y * ls;
  72576. for (int x = 0; x < imageWidth; ++x)
  72577. {
  72578. ((PixelRGB*) p)->desaturate();
  72579. p += ps;
  72580. }
  72581. }
  72582. }
  72583. releasePixelDataReadWrite (pixels);
  72584. }
  72585. }
  72586. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  72587. {
  72588. if (hasAlphaChannel())
  72589. {
  72590. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  72591. SparseSet <int> pixelsOnRow;
  72592. int ls, ps;
  72593. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  72594. for (int y = 0; y < imageHeight; ++y)
  72595. {
  72596. pixelsOnRow.clear();
  72597. const uint8* lineData = pixels + ls * y;
  72598. if (isARGB())
  72599. {
  72600. for (int x = 0; x < imageWidth; ++x)
  72601. {
  72602. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  72603. pixelsOnRow.addRange (x, 1);
  72604. lineData += ps;
  72605. }
  72606. }
  72607. else
  72608. {
  72609. for (int x = 0; x < imageWidth; ++x)
  72610. {
  72611. if (*lineData >= threshold)
  72612. pixelsOnRow.addRange (x, 1);
  72613. lineData += ps;
  72614. }
  72615. }
  72616. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  72617. {
  72618. int x, w;
  72619. if (pixelsOnRow.getRange (i, x, w))
  72620. result.add (Rectangle (x, y, w, 1));
  72621. }
  72622. result.consolidate();
  72623. }
  72624. releasePixelDataReadOnly (pixels);
  72625. }
  72626. else
  72627. {
  72628. result.add (0, 0, imageWidth, imageHeight);
  72629. }
  72630. }
  72631. void Image::moveImageSection (int dx, int dy,
  72632. int sx, int sy,
  72633. int w, int h)
  72634. {
  72635. if (dx < 0)
  72636. {
  72637. w += dx;
  72638. sx -= dx;
  72639. dx = 0;
  72640. }
  72641. if (dy < 0)
  72642. {
  72643. h += dy;
  72644. sy -= dy;
  72645. dy = 0;
  72646. }
  72647. if (sx < 0)
  72648. {
  72649. w += sx;
  72650. dx -= sx;
  72651. sx = 0;
  72652. }
  72653. if (sy < 0)
  72654. {
  72655. h += sy;
  72656. dy -= sy;
  72657. sy = 0;
  72658. }
  72659. const int minX = jmin (dx, sx);
  72660. const int minY = jmin (dy, sy);
  72661. w = jmin (w, getWidth() - jmax (sx, dx));
  72662. h = jmin (h, getHeight() - jmax (sy, dy));
  72663. if (w > 0 && h > 0)
  72664. {
  72665. const int maxX = jmax (dx, sx) + w;
  72666. const int maxY = jmax (dy, sy) + h;
  72667. int ls, ps;
  72668. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  72669. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  72670. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  72671. const int lineSize = ps * w;
  72672. if (dy > sy)
  72673. {
  72674. while (--h >= 0)
  72675. {
  72676. const int offset = h * ls;
  72677. memmove (dst + offset, src + offset, lineSize);
  72678. }
  72679. }
  72680. else if (dst != src)
  72681. {
  72682. while (--h >= 0)
  72683. {
  72684. memmove (dst, src, lineSize);
  72685. dst += ls;
  72686. src += ls;
  72687. }
  72688. }
  72689. releasePixelDataReadWrite (pixels);
  72690. }
  72691. }
  72692. END_JUCE_NAMESPACE
  72693. /********* End of inlined file: juce_Image.cpp *********/
  72694. /********* Start of inlined file: juce_ImageCache.cpp *********/
  72695. BEGIN_JUCE_NAMESPACE
  72696. struct CachedImageInfo
  72697. {
  72698. Image* image;
  72699. int64 hashCode;
  72700. int refCount;
  72701. unsigned int releaseTime;
  72702. juce_UseDebuggingNewOperator
  72703. };
  72704. static ImageCache* instance = 0;
  72705. static int cacheTimeout = 5000;
  72706. ImageCache::ImageCache() throw()
  72707. : images (4)
  72708. {
  72709. }
  72710. ImageCache::~ImageCache()
  72711. {
  72712. const ScopedLock sl (lock);
  72713. for (int i = images.size(); --i >= 0;)
  72714. {
  72715. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  72716. delete ci->image;
  72717. delete ci;
  72718. }
  72719. images.clear();
  72720. jassert (instance == this);
  72721. instance = 0;
  72722. }
  72723. Image* ImageCache::getFromHashCode (const int64 hashCode)
  72724. {
  72725. if (instance != 0)
  72726. {
  72727. const ScopedLock sl (instance->lock);
  72728. for (int i = instance->images.size(); --i >= 0;)
  72729. {
  72730. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72731. if (ci->hashCode == hashCode)
  72732. {
  72733. atomicIncrement (ci->refCount);
  72734. return ci->image;
  72735. }
  72736. }
  72737. }
  72738. return 0;
  72739. }
  72740. void ImageCache::addImageToCache (Image* const image,
  72741. const int64 hashCode)
  72742. {
  72743. if (image != 0)
  72744. {
  72745. if (instance == 0)
  72746. instance = new ImageCache();
  72747. CachedImageInfo* const newC = new CachedImageInfo();
  72748. newC->hashCode = hashCode;
  72749. newC->image = image;
  72750. newC->refCount = 1;
  72751. newC->releaseTime = 0;
  72752. const ScopedLock sl (instance->lock);
  72753. instance->images.add (newC);
  72754. }
  72755. }
  72756. void ImageCache::release (Image* const imageToRelease)
  72757. {
  72758. if (imageToRelease != 0 && instance != 0)
  72759. {
  72760. const ScopedLock sl (instance->lock);
  72761. for (int i = instance->images.size(); --i >= 0;)
  72762. {
  72763. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72764. if (ci->image == imageToRelease)
  72765. {
  72766. if (--(ci->refCount) == 0)
  72767. ci->releaseTime = Time::getApproximateMillisecondCounter();
  72768. if (! instance->isTimerRunning())
  72769. instance->startTimer (999);
  72770. break;
  72771. }
  72772. }
  72773. }
  72774. }
  72775. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  72776. {
  72777. if (instance != 0)
  72778. {
  72779. const ScopedLock sl (instance->lock);
  72780. for (int i = instance->images.size(); --i >= 0;)
  72781. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  72782. return true;
  72783. }
  72784. return false;
  72785. }
  72786. void ImageCache::incReferenceCount (Image* const image)
  72787. {
  72788. if (instance != 0)
  72789. {
  72790. const ScopedLock sl (instance->lock);
  72791. for (int i = instance->images.size(); --i >= 0;)
  72792. {
  72793. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  72794. if (ci->image == image)
  72795. {
  72796. ci->refCount++;
  72797. return;
  72798. }
  72799. }
  72800. }
  72801. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  72802. }
  72803. void ImageCache::timerCallback()
  72804. {
  72805. int numberStillNeedingReleasing = 0;
  72806. const unsigned int now = Time::getApproximateMillisecondCounter();
  72807. const ScopedLock sl (lock);
  72808. for (int i = images.size(); --i >= 0;)
  72809. {
  72810. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  72811. if (ci->refCount <= 0)
  72812. {
  72813. if (now > ci->releaseTime + cacheTimeout
  72814. || now < ci->releaseTime - 1000)
  72815. {
  72816. images.remove (i);
  72817. delete ci->image;
  72818. delete ci;
  72819. }
  72820. else
  72821. {
  72822. ++numberStillNeedingReleasing;
  72823. }
  72824. }
  72825. }
  72826. if (numberStillNeedingReleasing == 0)
  72827. stopTimer();
  72828. }
  72829. Image* ImageCache::getFromFile (const File& file)
  72830. {
  72831. const int64 hashCode = file.getFullPathName().hashCode64();
  72832. Image* image = getFromHashCode (hashCode);
  72833. if (image == 0)
  72834. {
  72835. image = ImageFileFormat::loadFrom (file);
  72836. addImageToCache (image, hashCode);
  72837. }
  72838. return image;
  72839. }
  72840. Image* ImageCache::getFromMemory (const void* imageData,
  72841. const int dataSize)
  72842. {
  72843. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  72844. Image* image = getFromHashCode (hashCode);
  72845. if (image == 0)
  72846. {
  72847. image = ImageFileFormat::loadFrom (imageData, dataSize);
  72848. addImageToCache (image, hashCode);
  72849. }
  72850. return image;
  72851. }
  72852. void ImageCache::setCacheTimeout (const int millisecs)
  72853. {
  72854. cacheTimeout = millisecs;
  72855. }
  72856. END_JUCE_NAMESPACE
  72857. /********* End of inlined file: juce_ImageCache.cpp *********/
  72858. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  72859. BEGIN_JUCE_NAMESPACE
  72860. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  72861. : size (size_)
  72862. {
  72863. values = new float* [size];
  72864. for (int i = size; --i >= 0;)
  72865. values[i] = new float [size];
  72866. clear();
  72867. }
  72868. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  72869. {
  72870. for (int i = size; --i >= 0;)
  72871. delete[] values[i];
  72872. delete[] values;
  72873. }
  72874. void ImageConvolutionKernel::setKernelValue (const int x,
  72875. const int y,
  72876. const float value) throw()
  72877. {
  72878. if (((unsigned int) x) < (unsigned int) size
  72879. && ((unsigned int) y) < (unsigned int) size)
  72880. {
  72881. values[x][y] = value;
  72882. }
  72883. else
  72884. {
  72885. jassertfalse
  72886. }
  72887. }
  72888. void ImageConvolutionKernel::clear() throw()
  72889. {
  72890. for (int y = size; --y >= 0;)
  72891. for (int x = size; --x >= 0;)
  72892. values[x][y] = 0;
  72893. }
  72894. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  72895. {
  72896. double currentTotal = 0.0;
  72897. for (int y = size; --y >= 0;)
  72898. for (int x = size; --x >= 0;)
  72899. currentTotal += values[x][y];
  72900. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  72901. }
  72902. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  72903. {
  72904. for (int y = size; --y >= 0;)
  72905. for (int x = size; --x >= 0;)
  72906. values[x][y] *= multiplier;
  72907. }
  72908. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  72909. {
  72910. const double radiusFactor = -1.0 / (radius * radius * 2);
  72911. const int centre = size >> 1;
  72912. for (int y = size; --y >= 0;)
  72913. {
  72914. for (int x = size; --x >= 0;)
  72915. {
  72916. const int cx = x - centre;
  72917. const int cy = y - centre;
  72918. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  72919. }
  72920. }
  72921. setOverallSum (1.0f);
  72922. }
  72923. void ImageConvolutionKernel::applyToImage (Image& destImage,
  72924. const Image* sourceImage,
  72925. int dx,
  72926. int dy,
  72927. int dw,
  72928. int dh) const
  72929. {
  72930. Image* imageCreated = 0;
  72931. if (sourceImage == 0)
  72932. {
  72933. sourceImage = imageCreated = destImage.createCopy();
  72934. }
  72935. else
  72936. {
  72937. jassert (sourceImage->getWidth() == destImage.getWidth()
  72938. && sourceImage->getHeight() == destImage.getHeight()
  72939. && sourceImage->getFormat() == destImage.getFormat());
  72940. if (sourceImage->getWidth() != destImage.getWidth()
  72941. || sourceImage->getHeight() != destImage.getHeight()
  72942. || sourceImage->getFormat() != destImage.getFormat())
  72943. return;
  72944. }
  72945. const int imageWidth = destImage.getWidth();
  72946. const int imageHeight = destImage.getHeight();
  72947. if (dx >= imageWidth || dy >= imageHeight)
  72948. return;
  72949. if (dx + dw > imageWidth)
  72950. dw = imageWidth - dx;
  72951. if (dy + dh > imageHeight)
  72952. dh = imageHeight - dy;
  72953. const int dx2 = dx + dw;
  72954. const int dy2 = dy + dh;
  72955. int lineStride, pixelStride;
  72956. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  72957. uint8* line = pixels;
  72958. int srcLineStride, srcPixelStride;
  72959. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  72960. if (pixelStride == 4)
  72961. {
  72962. for (int y = dy; y < dy2; ++y)
  72963. {
  72964. uint8* dest = line;
  72965. line += lineStride;
  72966. for (int x = dx; x < dx2; ++x)
  72967. {
  72968. float c1 = 0;
  72969. float c2 = 0;
  72970. float c3 = 0;
  72971. float c4 = 0;
  72972. for (int yy = 0; yy < size; ++yy)
  72973. {
  72974. const int sy = y + yy - (size >> 1);
  72975. if (sy >= imageHeight)
  72976. break;
  72977. if (sy >= 0)
  72978. {
  72979. int sx = x - (size >> 1);
  72980. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  72981. for (int xx = 0; xx < size; ++xx)
  72982. {
  72983. if (sx >= imageWidth)
  72984. break;
  72985. if (sx >= 0)
  72986. {
  72987. const float kernelMult = values[xx][yy];
  72988. c1 += kernelMult * *src++;
  72989. c2 += kernelMult * *src++;
  72990. c3 += kernelMult * *src++;
  72991. c4 += kernelMult * *src++;
  72992. }
  72993. else
  72994. {
  72995. src += 4;
  72996. }
  72997. ++sx;
  72998. }
  72999. }
  73000. }
  73001. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  73002. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  73003. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  73004. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  73005. }
  73006. }
  73007. }
  73008. else if (pixelStride == 3)
  73009. {
  73010. for (int y = dy; y < dy2; ++y)
  73011. {
  73012. uint8* dest = line;
  73013. line += lineStride;
  73014. for (int x = dx; x < dx2; ++x)
  73015. {
  73016. float c1 = 0;
  73017. float c2 = 0;
  73018. float c3 = 0;
  73019. for (int yy = 0; yy < size; ++yy)
  73020. {
  73021. const int sy = y + yy - (size >> 1);
  73022. if (sy >= imageHeight)
  73023. break;
  73024. if (sy >= 0)
  73025. {
  73026. int sx = x - (size >> 1);
  73027. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  73028. for (int xx = 0; xx < size; ++xx)
  73029. {
  73030. if (sx >= imageWidth)
  73031. break;
  73032. if (sx >= 0)
  73033. {
  73034. const float kernelMult = values[xx][yy];
  73035. c1 += kernelMult * *src++;
  73036. c2 += kernelMult * *src++;
  73037. c3 += kernelMult * *src++;
  73038. }
  73039. else
  73040. {
  73041. src += 3;
  73042. }
  73043. ++sx;
  73044. }
  73045. }
  73046. }
  73047. *dest++ = (uint8) roundFloatToInt (c1);
  73048. *dest++ = (uint8) roundFloatToInt (c2);
  73049. *dest++ = (uint8) roundFloatToInt (c3);
  73050. }
  73051. }
  73052. }
  73053. sourceImage->releasePixelDataReadOnly (srcPixels);
  73054. destImage.releasePixelDataReadWrite (pixels);
  73055. if (imageCreated != 0)
  73056. delete imageCreated;
  73057. }
  73058. END_JUCE_NAMESPACE
  73059. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  73060. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  73061. BEGIN_JUCE_NAMESPACE
  73062. /********* Start of inlined file: juce_GIFLoader.h *********/
  73063. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  73064. #define __JUCE_GIFLOADER_JUCEHEADER__
  73065. #ifndef DOXYGEN
  73066. static const int maxGifCode = 1 << 12;
  73067. /**
  73068. Used internally by ImageFileFormat - don't use this class directly in your
  73069. application.
  73070. @see ImageFileFormat
  73071. */
  73072. class GIFLoader
  73073. {
  73074. public:
  73075. GIFLoader (InputStream& in);
  73076. ~GIFLoader() throw();
  73077. Image* getImage() const throw() { return image; }
  73078. private:
  73079. Image* image;
  73080. InputStream& input;
  73081. uint8 buffer [300];
  73082. uint8 palette [256][4];
  73083. bool dataBlockIsZero, fresh, finished;
  73084. int currentBit, lastBit, lastByteIndex;
  73085. int codeSize, setCodeSize;
  73086. int maxCode, maxCodeSize;
  73087. int firstcode, oldcode;
  73088. int clearCode, end_code;
  73089. int table [2] [maxGifCode];
  73090. int stack [2 * maxGifCode];
  73091. int *sp;
  73092. bool getSizeFromHeader (int& width, int& height);
  73093. bool readPalette (const int numCols);
  73094. int readDataBlock (unsigned char* dest);
  73095. int processExtension (int type, int& transparent);
  73096. int readLZWByte (bool initialise, int input_code_size);
  73097. int getCode (int code_size, bool initialise);
  73098. bool readImage (int width, int height,
  73099. int interlace, int transparent);
  73100. GIFLoader (const GIFLoader&);
  73101. const GIFLoader& operator= (const GIFLoader&);
  73102. };
  73103. #endif // DOXYGEN
  73104. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  73105. /********* End of inlined file: juce_GIFLoader.h *********/
  73106. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  73107. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  73108. PNGImageFormat::PNGImageFormat() throw() {}
  73109. PNGImageFormat::~PNGImageFormat() throw() {}
  73110. const String PNGImageFormat::getFormatName()
  73111. {
  73112. return T("PNG");
  73113. }
  73114. bool PNGImageFormat::canUnderstand (InputStream& in)
  73115. {
  73116. const int bytesNeeded = 4;
  73117. char header [bytesNeeded];
  73118. return in.read (header, bytesNeeded) == bytesNeeded
  73119. && header[1] == 'P'
  73120. && header[2] == 'N'
  73121. && header[3] == 'G';
  73122. }
  73123. Image* PNGImageFormat::decodeImage (InputStream& in)
  73124. {
  73125. return juce_loadPNGImageFromStream (in);
  73126. }
  73127. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  73128. OutputStream& destStream)
  73129. {
  73130. return juce_writePNGImageToStream (sourceImage, destStream);
  73131. }
  73132. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  73133. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  73134. JPEGImageFormat::JPEGImageFormat() throw()
  73135. : quality (-1.0f)
  73136. {
  73137. }
  73138. JPEGImageFormat::~JPEGImageFormat() throw() {}
  73139. void JPEGImageFormat::setQuality (const float newQuality)
  73140. {
  73141. quality = newQuality;
  73142. }
  73143. const String JPEGImageFormat::getFormatName()
  73144. {
  73145. return T("JPEG");
  73146. }
  73147. bool JPEGImageFormat::canUnderstand (InputStream& in)
  73148. {
  73149. const int bytesNeeded = 10;
  73150. uint8 header [bytesNeeded];
  73151. if (in.read (header, bytesNeeded) == bytesNeeded)
  73152. {
  73153. return header[0] == 0xff
  73154. && header[1] == 0xd8
  73155. && header[2] == 0xff
  73156. && (header[3] == 0xe0 || header[3] == 0xe1);
  73157. }
  73158. return false;
  73159. }
  73160. Image* JPEGImageFormat::decodeImage (InputStream& in)
  73161. {
  73162. return juce_loadJPEGImageFromStream (in);
  73163. }
  73164. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  73165. OutputStream& destStream)
  73166. {
  73167. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  73168. }
  73169. class GIFImageFormat : public ImageFileFormat
  73170. {
  73171. public:
  73172. GIFImageFormat() throw() {}
  73173. ~GIFImageFormat() throw() {}
  73174. const String getFormatName()
  73175. {
  73176. return T("GIF");
  73177. }
  73178. bool canUnderstand (InputStream& in)
  73179. {
  73180. const int bytesNeeded = 4;
  73181. char header [bytesNeeded];
  73182. return (in.read (header, bytesNeeded) == bytesNeeded)
  73183. && header[0] == 'G'
  73184. && header[1] == 'I'
  73185. && header[2] == 'F';
  73186. }
  73187. Image* decodeImage (InputStream& in)
  73188. {
  73189. GIFLoader* const loader = new GIFLoader (in);
  73190. Image* const im = loader->getImage();
  73191. delete loader;
  73192. return im;
  73193. }
  73194. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  73195. {
  73196. return false;
  73197. }
  73198. };
  73199. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  73200. {
  73201. static PNGImageFormat png;
  73202. static JPEGImageFormat jpg;
  73203. static GIFImageFormat gif;
  73204. ImageFileFormat* formats[4];
  73205. int numFormats = 0;
  73206. formats [numFormats++] = &png;
  73207. formats [numFormats++] = &jpg;
  73208. formats [numFormats++] = &gif;
  73209. const int64 streamPos = input.getPosition();
  73210. for (int i = 0; i < numFormats; ++i)
  73211. {
  73212. const bool found = formats[i]->canUnderstand (input);
  73213. input.setPosition (streamPos);
  73214. if (found)
  73215. return formats[i];
  73216. }
  73217. return 0;
  73218. }
  73219. Image* ImageFileFormat::loadFrom (InputStream& input)
  73220. {
  73221. ImageFileFormat* const format = findImageFormatForStream (input);
  73222. if (format != 0)
  73223. return format->decodeImage (input);
  73224. return 0;
  73225. }
  73226. Image* ImageFileFormat::loadFrom (const File& file)
  73227. {
  73228. InputStream* const in = file.createInputStream();
  73229. if (in != 0)
  73230. {
  73231. BufferedInputStream b (in, 8192, true);
  73232. return loadFrom (b);
  73233. }
  73234. return 0;
  73235. }
  73236. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  73237. {
  73238. if (rawData != 0 && numBytes > 4)
  73239. {
  73240. MemoryInputStream stream (rawData, numBytes, false);
  73241. return loadFrom (stream);
  73242. }
  73243. return 0;
  73244. }
  73245. END_JUCE_NAMESPACE
  73246. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  73247. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  73248. BEGIN_JUCE_NAMESPACE
  73249. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  73250. {
  73251. return (b << 8) | a;
  73252. }
  73253. GIFLoader::GIFLoader (InputStream& in)
  73254. : image (0),
  73255. input (in),
  73256. dataBlockIsZero (false),
  73257. fresh (false),
  73258. finished (false)
  73259. {
  73260. currentBit = lastBit = lastByteIndex = 0;
  73261. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  73262. firstcode = oldcode = 0;
  73263. clearCode = end_code = 0;
  73264. int imageWidth, imageHeight;
  73265. int transparent = -1;
  73266. if (! getSizeFromHeader (imageWidth, imageHeight))
  73267. return;
  73268. if ((imageWidth <= 0) || (imageHeight <= 0))
  73269. return;
  73270. unsigned char buf [16];
  73271. if (in.read (buf, 3) != 3)
  73272. return;
  73273. int numColours = 2 << (buf[0] & 7);
  73274. if ((buf[0] & 0x80) != 0)
  73275. readPalette (numColours);
  73276. for (;;)
  73277. {
  73278. if (input.read (buf, 1) != 1)
  73279. break;
  73280. if (buf[0] == ';')
  73281. break;
  73282. if (buf[0] == '!')
  73283. {
  73284. if (input.read (buf, 1) != 1)
  73285. break;
  73286. if (processExtension (buf[0], transparent) < 0)
  73287. break;
  73288. continue;
  73289. }
  73290. if (buf[0] != ',')
  73291. continue;
  73292. if (input.read (buf, 9) != 9)
  73293. break;
  73294. imageWidth = makeWord (buf[4], buf[5]);
  73295. imageHeight = makeWord (buf[6], buf[7]);
  73296. numColours = 2 << (buf[8] & 7);
  73297. if ((buf[8] & 0x80) != 0)
  73298. if (! readPalette (numColours))
  73299. break;
  73300. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  73301. imageWidth, imageHeight, (transparent >= 0));
  73302. readImage (imageWidth, imageHeight,
  73303. (buf[8] & 0x40) != 0,
  73304. transparent);
  73305. break;
  73306. }
  73307. }
  73308. GIFLoader::~GIFLoader() throw()
  73309. {
  73310. }
  73311. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  73312. {
  73313. unsigned char b [8];
  73314. if (input.read (b, 6) == 6)
  73315. {
  73316. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  73317. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  73318. {
  73319. if (input.read (b, 4) == 4)
  73320. {
  73321. w = makeWord (b[0], b[1]);
  73322. h = makeWord (b[2], b[3]);
  73323. return true;
  73324. }
  73325. }
  73326. }
  73327. return false;
  73328. }
  73329. bool GIFLoader::readPalette (const int numCols)
  73330. {
  73331. unsigned char rgb[4];
  73332. for (int i = 0; i < numCols; ++i)
  73333. {
  73334. input.read (rgb, 3);
  73335. palette [i][0] = rgb[0];
  73336. palette [i][1] = rgb[1];
  73337. palette [i][2] = rgb[2];
  73338. palette [i][3] = 0xff;
  73339. }
  73340. return true;
  73341. }
  73342. int GIFLoader::readDataBlock (unsigned char* const dest)
  73343. {
  73344. unsigned char n;
  73345. if (input.read (&n, 1) == 1)
  73346. {
  73347. dataBlockIsZero = (n == 0);
  73348. if (dataBlockIsZero || (input.read (dest, n) == n))
  73349. return n;
  73350. }
  73351. return -1;
  73352. }
  73353. int GIFLoader::processExtension (const int type, int& transparent)
  73354. {
  73355. unsigned char b [300];
  73356. int n = 0;
  73357. if (type == 0xf9)
  73358. {
  73359. n = readDataBlock (b);
  73360. if (n < 0)
  73361. return 1;
  73362. if ((b[0] & 0x1) != 0)
  73363. transparent = b[3];
  73364. }
  73365. do
  73366. {
  73367. n = readDataBlock (b);
  73368. }
  73369. while (n > 0);
  73370. return n;
  73371. }
  73372. int GIFLoader::getCode (const int codeSize, const bool initialise)
  73373. {
  73374. if (initialise)
  73375. {
  73376. currentBit = 0;
  73377. lastBit = 0;
  73378. finished = false;
  73379. return 0;
  73380. }
  73381. if ((currentBit + codeSize) >= lastBit)
  73382. {
  73383. if (finished)
  73384. return -1;
  73385. buffer[0] = buffer [lastByteIndex - 2];
  73386. buffer[1] = buffer [lastByteIndex - 1];
  73387. const int n = readDataBlock (&buffer[2]);
  73388. if (n == 0)
  73389. finished = true;
  73390. lastByteIndex = 2 + n;
  73391. currentBit = (currentBit - lastBit) + 16;
  73392. lastBit = (2 + n) * 8 ;
  73393. }
  73394. int result = 0;
  73395. int i = currentBit;
  73396. for (int j = 0; j < codeSize; ++j)
  73397. {
  73398. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  73399. ++i;
  73400. }
  73401. currentBit += codeSize;
  73402. return result;
  73403. }
  73404. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  73405. {
  73406. int code, incode, i;
  73407. if (initialise)
  73408. {
  73409. setCodeSize = inputCodeSize;
  73410. codeSize = setCodeSize + 1;
  73411. clearCode = 1 << setCodeSize;
  73412. end_code = clearCode + 1;
  73413. maxCodeSize = 2 * clearCode;
  73414. maxCode = clearCode + 2;
  73415. getCode (0, true);
  73416. fresh = true;
  73417. for (i = 0; i < clearCode; ++i)
  73418. {
  73419. table[0][i] = 0;
  73420. table[1][i] = i;
  73421. }
  73422. for (; i < maxGifCode; ++i)
  73423. {
  73424. table[0][i] = 0;
  73425. table[1][i] = 0;
  73426. }
  73427. sp = stack;
  73428. return 0;
  73429. }
  73430. else if (fresh)
  73431. {
  73432. fresh = false;
  73433. do
  73434. {
  73435. firstcode = oldcode
  73436. = getCode (codeSize, false);
  73437. }
  73438. while (firstcode == clearCode);
  73439. return firstcode;
  73440. }
  73441. if (sp > stack)
  73442. return *--sp;
  73443. while ((code = getCode (codeSize, false)) >= 0)
  73444. {
  73445. if (code == clearCode)
  73446. {
  73447. for (i = 0; i < clearCode; ++i)
  73448. {
  73449. table[0][i] = 0;
  73450. table[1][i] = i;
  73451. }
  73452. for (; i < maxGifCode; ++i)
  73453. {
  73454. table[0][i] = 0;
  73455. table[1][i] = 0;
  73456. }
  73457. codeSize = setCodeSize + 1;
  73458. maxCodeSize = 2 * clearCode;
  73459. maxCode = clearCode + 2;
  73460. sp = stack;
  73461. firstcode = oldcode = getCode (codeSize, false);
  73462. return firstcode;
  73463. }
  73464. else if (code == end_code)
  73465. {
  73466. if (dataBlockIsZero)
  73467. return -2;
  73468. unsigned char buf [260];
  73469. int n;
  73470. while ((n = readDataBlock (buf)) > 0)
  73471. {}
  73472. if (n != 0)
  73473. return -2;
  73474. }
  73475. incode = code;
  73476. if (code >= maxCode)
  73477. {
  73478. *sp++ = firstcode;
  73479. code = oldcode;
  73480. }
  73481. while (code >= clearCode)
  73482. {
  73483. *sp++ = table[1][code];
  73484. if (code == table[0][code])
  73485. return -2;
  73486. code = table[0][code];
  73487. }
  73488. *sp++ = firstcode = table[1][code];
  73489. if ((code = maxCode) < maxGifCode)
  73490. {
  73491. table[0][code] = oldcode;
  73492. table[1][code] = firstcode;
  73493. ++maxCode;
  73494. if ((maxCode >= maxCodeSize)
  73495. && (maxCodeSize < maxGifCode))
  73496. {
  73497. maxCodeSize <<= 1;
  73498. ++codeSize;
  73499. }
  73500. }
  73501. oldcode = incode;
  73502. if (sp > stack)
  73503. return *--sp;
  73504. }
  73505. return code;
  73506. }
  73507. bool GIFLoader::readImage (const int width, const int height,
  73508. const int interlace, const int transparent)
  73509. {
  73510. unsigned char c;
  73511. if (input.read (&c, 1) != 1
  73512. || readLZWByte (true, c) < 0)
  73513. return false;
  73514. if (transparent >= 0)
  73515. {
  73516. palette [transparent][0] = 0;
  73517. palette [transparent][1] = 0;
  73518. palette [transparent][2] = 0;
  73519. palette [transparent][3] = 0;
  73520. }
  73521. int index;
  73522. int xpos = 0, ypos = 0, pass = 0;
  73523. int stride, pixelStride;
  73524. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  73525. uint8* p = pixels;
  73526. const bool hasAlpha = image->hasAlphaChannel();
  73527. while ((index = readLZWByte (false, c)) >= 0)
  73528. {
  73529. const uint8* const paletteEntry = palette [index];
  73530. if (hasAlpha)
  73531. {
  73532. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  73533. paletteEntry[0],
  73534. paletteEntry[1],
  73535. paletteEntry[2]);
  73536. ((PixelARGB*) p)->premultiply();
  73537. p += pixelStride;
  73538. }
  73539. else
  73540. {
  73541. ((PixelRGB*) p)->setARGB (0,
  73542. paletteEntry[0],
  73543. paletteEntry[1],
  73544. paletteEntry[2]);
  73545. p += pixelStride;
  73546. }
  73547. ++xpos;
  73548. if (xpos == width)
  73549. {
  73550. xpos = 0;
  73551. if (interlace)
  73552. {
  73553. switch (pass)
  73554. {
  73555. case 0:
  73556. case 1:
  73557. ypos += 8;
  73558. break;
  73559. case 2:
  73560. ypos += 4;
  73561. break;
  73562. case 3:
  73563. ypos += 2;
  73564. break;
  73565. }
  73566. while (ypos >= height)
  73567. {
  73568. ++pass;
  73569. switch (pass)
  73570. {
  73571. case 1:
  73572. ypos = 4;
  73573. break;
  73574. case 2:
  73575. ypos = 2;
  73576. break;
  73577. case 3:
  73578. ypos = 1;
  73579. break;
  73580. default:
  73581. return true;
  73582. }
  73583. }
  73584. }
  73585. else
  73586. {
  73587. ++ypos;
  73588. }
  73589. p = pixels + xpos * pixelStride + ypos * stride;
  73590. }
  73591. if (ypos >= height)
  73592. break;
  73593. }
  73594. image->releasePixelDataReadWrite (pixels);
  73595. return true;
  73596. }
  73597. END_JUCE_NAMESPACE
  73598. /********* End of inlined file: juce_GIFLoader.cpp *********/
  73599. #endif
  73600. //==============================================================================
  73601. // some files include lots of library code, so leave them to the end to avoid cluttering
  73602. // up the build for the clean files.
  73603. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73604. namespace zlibNamespace
  73605. {
  73606. #if JUCE_INCLUDE_ZLIB_CODE
  73607. #undef OS_CODE
  73608. #undef fdopen
  73609. /********* Start of inlined file: zlib.h *********/
  73610. #ifndef ZLIB_H
  73611. #define ZLIB_H
  73612. /********* Start of inlined file: zconf.h *********/
  73613. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73614. #ifndef ZCONF_H
  73615. #define ZCONF_H
  73616. // *** Just a few hacks here to make it compile nicely with Juce..
  73617. #define Z_PREFIX 1
  73618. #undef __MACTYPES__
  73619. #ifdef _MSC_VER
  73620. #pragma warning (disable : 4131 4127 4244 4267)
  73621. #endif
  73622. /*
  73623. * If you *really* need a unique prefix for all types and library functions,
  73624. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  73625. */
  73626. #ifdef Z_PREFIX
  73627. # define deflateInit_ z_deflateInit_
  73628. # define deflate z_deflate
  73629. # define deflateEnd z_deflateEnd
  73630. # define inflateInit_ z_inflateInit_
  73631. # define inflate z_inflate
  73632. # define inflateEnd z_inflateEnd
  73633. # define deflateInit2_ z_deflateInit2_
  73634. # define deflateSetDictionary z_deflateSetDictionary
  73635. # define deflateCopy z_deflateCopy
  73636. # define deflateReset z_deflateReset
  73637. # define deflateParams z_deflateParams
  73638. # define deflateBound z_deflateBound
  73639. # define deflatePrime z_deflatePrime
  73640. # define inflateInit2_ z_inflateInit2_
  73641. # define inflateSetDictionary z_inflateSetDictionary
  73642. # define inflateSync z_inflateSync
  73643. # define inflateSyncPoint z_inflateSyncPoint
  73644. # define inflateCopy z_inflateCopy
  73645. # define inflateReset z_inflateReset
  73646. # define inflateBack z_inflateBack
  73647. # define inflateBackEnd z_inflateBackEnd
  73648. # define compress z_compress
  73649. # define compress2 z_compress2
  73650. # define compressBound z_compressBound
  73651. # define uncompress z_uncompress
  73652. # define adler32 z_adler32
  73653. # define crc32 z_crc32
  73654. # define get_crc_table z_get_crc_table
  73655. # define zError z_zError
  73656. # define alloc_func z_alloc_func
  73657. # define free_func z_free_func
  73658. # define in_func z_in_func
  73659. # define out_func z_out_func
  73660. # define Byte z_Byte
  73661. # define uInt z_uInt
  73662. # define uLong z_uLong
  73663. # define Bytef z_Bytef
  73664. # define charf z_charf
  73665. # define intf z_intf
  73666. # define uIntf z_uIntf
  73667. # define uLongf z_uLongf
  73668. # define voidpf z_voidpf
  73669. # define voidp z_voidp
  73670. #endif
  73671. #if defined(__MSDOS__) && !defined(MSDOS)
  73672. # define MSDOS
  73673. #endif
  73674. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  73675. # define OS2
  73676. #endif
  73677. #if defined(_WINDOWS) && !defined(WINDOWS)
  73678. # define WINDOWS
  73679. #endif
  73680. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  73681. # ifndef WIN32
  73682. # define WIN32
  73683. # endif
  73684. #endif
  73685. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  73686. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  73687. # ifndef SYS16BIT
  73688. # define SYS16BIT
  73689. # endif
  73690. # endif
  73691. #endif
  73692. /*
  73693. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  73694. * than 64k bytes at a time (needed on systems with 16-bit int).
  73695. */
  73696. #ifdef SYS16BIT
  73697. # define MAXSEG_64K
  73698. #endif
  73699. #ifdef MSDOS
  73700. # define UNALIGNED_OK
  73701. #endif
  73702. #ifdef __STDC_VERSION__
  73703. # ifndef STDC
  73704. # define STDC
  73705. # endif
  73706. # if __STDC_VERSION__ >= 199901L
  73707. # ifndef STDC99
  73708. # define STDC99
  73709. # endif
  73710. # endif
  73711. #endif
  73712. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  73713. # define STDC
  73714. #endif
  73715. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  73716. # define STDC
  73717. #endif
  73718. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  73719. # define STDC
  73720. #endif
  73721. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  73722. # define STDC
  73723. #endif
  73724. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  73725. # define STDC
  73726. #endif
  73727. #ifndef STDC
  73728. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  73729. # define const /* note: need a more gentle solution here */
  73730. # endif
  73731. #endif
  73732. /* Some Mac compilers merge all .h files incorrectly: */
  73733. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  73734. # define NO_DUMMY_DECL
  73735. #endif
  73736. /* Maximum value for memLevel in deflateInit2 */
  73737. #ifndef MAX_MEM_LEVEL
  73738. # ifdef MAXSEG_64K
  73739. # define MAX_MEM_LEVEL 8
  73740. # else
  73741. # define MAX_MEM_LEVEL 9
  73742. # endif
  73743. #endif
  73744. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  73745. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  73746. * created by gzip. (Files created by minigzip can still be extracted by
  73747. * gzip.)
  73748. */
  73749. #ifndef MAX_WBITS
  73750. # define MAX_WBITS 15 /* 32K LZ77 window */
  73751. #endif
  73752. /* The memory requirements for deflate are (in bytes):
  73753. (1 << (windowBits+2)) + (1 << (memLevel+9))
  73754. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  73755. plus a few kilobytes for small objects. For example, if you want to reduce
  73756. the default memory requirements from 256K to 128K, compile with
  73757. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  73758. Of course this will generally degrade compression (there's no free lunch).
  73759. The memory requirements for inflate are (in bytes) 1 << windowBits
  73760. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  73761. for small objects.
  73762. */
  73763. /* Type declarations */
  73764. #ifndef OF /* function prototypes */
  73765. # ifdef STDC
  73766. # define OF(args) args
  73767. # else
  73768. # define OF(args) ()
  73769. # endif
  73770. #endif
  73771. /* The following definitions for FAR are needed only for MSDOS mixed
  73772. * model programming (small or medium model with some far allocations).
  73773. * This was tested only with MSC; for other MSDOS compilers you may have
  73774. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  73775. * just define FAR to be empty.
  73776. */
  73777. #ifdef SYS16BIT
  73778. # if defined(M_I86SM) || defined(M_I86MM)
  73779. /* MSC small or medium model */
  73780. # define SMALL_MEDIUM
  73781. # ifdef _MSC_VER
  73782. # define FAR _far
  73783. # else
  73784. # define FAR far
  73785. # endif
  73786. # endif
  73787. # if (defined(__SMALL__) || defined(__MEDIUM__))
  73788. /* Turbo C small or medium model */
  73789. # define SMALL_MEDIUM
  73790. # ifdef __BORLANDC__
  73791. # define FAR _far
  73792. # else
  73793. # define FAR far
  73794. # endif
  73795. # endif
  73796. #endif
  73797. #if defined(WINDOWS) || defined(WIN32)
  73798. /* If building or using zlib as a DLL, define ZLIB_DLL.
  73799. * This is not mandatory, but it offers a little performance increase.
  73800. */
  73801. # ifdef ZLIB_DLL
  73802. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  73803. # ifdef ZLIB_INTERNAL
  73804. # define ZEXTERN extern __declspec(dllexport)
  73805. # else
  73806. # define ZEXTERN extern __declspec(dllimport)
  73807. # endif
  73808. # endif
  73809. # endif /* ZLIB_DLL */
  73810. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  73811. * define ZLIB_WINAPI.
  73812. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  73813. */
  73814. # ifdef ZLIB_WINAPI
  73815. # ifdef FAR
  73816. # undef FAR
  73817. # endif
  73818. # include <windows.h>
  73819. /* No need for _export, use ZLIB.DEF instead. */
  73820. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  73821. # define ZEXPORT WINAPI
  73822. # ifdef WIN32
  73823. # define ZEXPORTVA WINAPIV
  73824. # else
  73825. # define ZEXPORTVA FAR CDECL
  73826. # endif
  73827. # endif
  73828. #endif
  73829. #if defined (__BEOS__)
  73830. # ifdef ZLIB_DLL
  73831. # ifdef ZLIB_INTERNAL
  73832. # define ZEXPORT __declspec(dllexport)
  73833. # define ZEXPORTVA __declspec(dllexport)
  73834. # else
  73835. # define ZEXPORT __declspec(dllimport)
  73836. # define ZEXPORTVA __declspec(dllimport)
  73837. # endif
  73838. # endif
  73839. #endif
  73840. #ifndef ZEXTERN
  73841. # define ZEXTERN extern
  73842. #endif
  73843. #ifndef ZEXPORT
  73844. # define ZEXPORT
  73845. #endif
  73846. #ifndef ZEXPORTVA
  73847. # define ZEXPORTVA
  73848. #endif
  73849. #ifndef FAR
  73850. # define FAR
  73851. #endif
  73852. #if !defined(__MACTYPES__)
  73853. typedef unsigned char Byte; /* 8 bits */
  73854. #endif
  73855. typedef unsigned int uInt; /* 16 bits or more */
  73856. typedef unsigned long uLong; /* 32 bits or more */
  73857. #ifdef SMALL_MEDIUM
  73858. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  73859. # define Bytef Byte FAR
  73860. #else
  73861. typedef Byte FAR Bytef;
  73862. #endif
  73863. typedef char FAR charf;
  73864. typedef int FAR intf;
  73865. typedef uInt FAR uIntf;
  73866. typedef uLong FAR uLongf;
  73867. #ifdef STDC
  73868. typedef void const *voidpc;
  73869. typedef void FAR *voidpf;
  73870. typedef void *voidp;
  73871. #else
  73872. typedef Byte const *voidpc;
  73873. typedef Byte FAR *voidpf;
  73874. typedef Byte *voidp;
  73875. #endif
  73876. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  73877. # include <sys/types.h> /* for off_t */
  73878. # include <unistd.h> /* for SEEK_* and off_t */
  73879. # ifdef VMS
  73880. # include <unixio.h> /* for off_t */
  73881. # endif
  73882. # define z_off_t off_t
  73883. #endif
  73884. #ifndef SEEK_SET
  73885. # define SEEK_SET 0 /* Seek from beginning of file. */
  73886. # define SEEK_CUR 1 /* Seek from current position. */
  73887. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  73888. #endif
  73889. #ifndef z_off_t
  73890. # define z_off_t long
  73891. #endif
  73892. #if defined(__OS400__)
  73893. # define NO_vsnprintf
  73894. #endif
  73895. #if defined(__MVS__)
  73896. # define NO_vsnprintf
  73897. # ifdef FAR
  73898. # undef FAR
  73899. # endif
  73900. #endif
  73901. /* MVS linker does not support external names larger than 8 bytes */
  73902. #if defined(__MVS__)
  73903. # pragma map(deflateInit_,"DEIN")
  73904. # pragma map(deflateInit2_,"DEIN2")
  73905. # pragma map(deflateEnd,"DEEND")
  73906. # pragma map(deflateBound,"DEBND")
  73907. # pragma map(inflateInit_,"ININ")
  73908. # pragma map(inflateInit2_,"ININ2")
  73909. # pragma map(inflateEnd,"INEND")
  73910. # pragma map(inflateSync,"INSY")
  73911. # pragma map(inflateSetDictionary,"INSEDI")
  73912. # pragma map(compressBound,"CMBND")
  73913. # pragma map(inflate_table,"INTABL")
  73914. # pragma map(inflate_fast,"INFA")
  73915. # pragma map(inflate_copyright,"INCOPY")
  73916. #endif
  73917. #endif /* ZCONF_H */
  73918. /********* End of inlined file: zconf.h *********/
  73919. #ifdef __cplusplus
  73920. extern "C" {
  73921. #endif
  73922. #define ZLIB_VERSION "1.2.3"
  73923. #define ZLIB_VERNUM 0x1230
  73924. /*
  73925. The 'zlib' compression library provides in-memory compression and
  73926. decompression functions, including integrity checks of the uncompressed
  73927. data. This version of the library supports only one compression method
  73928. (deflation) but other algorithms will be added later and will have the same
  73929. stream interface.
  73930. Compression can be done in a single step if the buffers are large
  73931. enough (for example if an input file is mmap'ed), or can be done by
  73932. repeated calls of the compression function. In the latter case, the
  73933. application must provide more input and/or consume the output
  73934. (providing more output space) before each call.
  73935. The compressed data format used by default by the in-memory functions is
  73936. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  73937. around a deflate stream, which is itself documented in RFC 1951.
  73938. The library also supports reading and writing files in gzip (.gz) format
  73939. with an interface similar to that of stdio using the functions that start
  73940. with "gz". The gzip format is different from the zlib format. gzip is a
  73941. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  73942. This library can optionally read and write gzip streams in memory as well.
  73943. The zlib format was designed to be compact and fast for use in memory
  73944. and on communications channels. The gzip format was designed for single-
  73945. file compression on file systems, has a larger header than zlib to maintain
  73946. directory information, and uses a different, slower check method than zlib.
  73947. The library does not install any signal handler. The decoder checks
  73948. the consistency of the compressed data, so the library should never
  73949. crash even in case of corrupted input.
  73950. */
  73951. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  73952. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  73953. struct internal_state;
  73954. typedef struct z_stream_s {
  73955. Bytef *next_in; /* next input byte */
  73956. uInt avail_in; /* number of bytes available at next_in */
  73957. uLong total_in; /* total nb of input bytes read so far */
  73958. Bytef *next_out; /* next output byte should be put there */
  73959. uInt avail_out; /* remaining free space at next_out */
  73960. uLong total_out; /* total nb of bytes output so far */
  73961. char *msg; /* last error message, NULL if no error */
  73962. struct internal_state FAR *state; /* not visible by applications */
  73963. alloc_func zalloc; /* used to allocate the internal state */
  73964. free_func zfree; /* used to free the internal state */
  73965. voidpf opaque; /* private data object passed to zalloc and zfree */
  73966. int data_type; /* best guess about the data type: binary or text */
  73967. uLong adler; /* adler32 value of the uncompressed data */
  73968. uLong reserved; /* reserved for future use */
  73969. } z_stream;
  73970. typedef z_stream FAR *z_streamp;
  73971. /*
  73972. gzip header information passed to and from zlib routines. See RFC 1952
  73973. for more details on the meanings of these fields.
  73974. */
  73975. typedef struct gz_header_s {
  73976. int text; /* true if compressed data believed to be text */
  73977. uLong time; /* modification time */
  73978. int xflags; /* extra flags (not used when writing a gzip file) */
  73979. int os; /* operating system */
  73980. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  73981. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  73982. uInt extra_max; /* space at extra (only when reading header) */
  73983. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  73984. uInt name_max; /* space at name (only when reading header) */
  73985. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  73986. uInt comm_max; /* space at comment (only when reading header) */
  73987. int hcrc; /* true if there was or will be a header crc */
  73988. int done; /* true when done reading gzip header (not used
  73989. when writing a gzip file) */
  73990. } gz_header;
  73991. typedef gz_header FAR *gz_headerp;
  73992. /*
  73993. The application must update next_in and avail_in when avail_in has
  73994. dropped to zero. It must update next_out and avail_out when avail_out
  73995. has dropped to zero. The application must initialize zalloc, zfree and
  73996. opaque before calling the init function. All other fields are set by the
  73997. compression library and must not be updated by the application.
  73998. The opaque value provided by the application will be passed as the first
  73999. parameter for calls of zalloc and zfree. This can be useful for custom
  74000. memory management. The compression library attaches no meaning to the
  74001. opaque value.
  74002. zalloc must return Z_NULL if there is not enough memory for the object.
  74003. If zlib is used in a multi-threaded application, zalloc and zfree must be
  74004. thread safe.
  74005. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  74006. exactly 65536 bytes, but will not be required to allocate more than this
  74007. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  74008. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  74009. have their offset normalized to zero. The default allocation function
  74010. provided by this library ensures this (see zutil.c). To reduce memory
  74011. requirements and avoid any allocation of 64K objects, at the expense of
  74012. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  74013. The fields total_in and total_out can be used for statistics or
  74014. progress reports. After compression, total_in holds the total size of
  74015. the uncompressed data and may be saved for use in the decompressor
  74016. (particularly if the decompressor wants to decompress everything in
  74017. a single step).
  74018. */
  74019. /* constants */
  74020. #define Z_NO_FLUSH 0
  74021. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  74022. #define Z_SYNC_FLUSH 2
  74023. #define Z_FULL_FLUSH 3
  74024. #define Z_FINISH 4
  74025. #define Z_BLOCK 5
  74026. /* Allowed flush values; see deflate() and inflate() below for details */
  74027. #define Z_OK 0
  74028. #define Z_STREAM_END 1
  74029. #define Z_NEED_DICT 2
  74030. #define Z_ERRNO (-1)
  74031. #define Z_STREAM_ERROR (-2)
  74032. #define Z_DATA_ERROR (-3)
  74033. #define Z_MEM_ERROR (-4)
  74034. #define Z_BUF_ERROR (-5)
  74035. #define Z_VERSION_ERROR (-6)
  74036. /* Return codes for the compression/decompression functions. Negative
  74037. * values are errors, positive values are used for special but normal events.
  74038. */
  74039. #define Z_NO_COMPRESSION 0
  74040. #define Z_BEST_SPEED 1
  74041. #define Z_BEST_COMPRESSION 9
  74042. #define Z_DEFAULT_COMPRESSION (-1)
  74043. /* compression levels */
  74044. #define Z_FILTERED 1
  74045. #define Z_HUFFMAN_ONLY 2
  74046. #define Z_RLE 3
  74047. #define Z_FIXED 4
  74048. #define Z_DEFAULT_STRATEGY 0
  74049. /* compression strategy; see deflateInit2() below for details */
  74050. #define Z_BINARY 0
  74051. #define Z_TEXT 1
  74052. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  74053. #define Z_UNKNOWN 2
  74054. /* Possible values of the data_type field (though see inflate()) */
  74055. #define Z_DEFLATED 8
  74056. /* The deflate compression method (the only one supported in this version) */
  74057. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  74058. #define zlib_version zlibVersion()
  74059. /* for compatibility with versions < 1.0.2 */
  74060. /* basic functions */
  74061. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  74062. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  74063. If the first character differs, the library code actually used is
  74064. not compatible with the zlib.h header file used by the application.
  74065. This check is automatically made by deflateInit and inflateInit.
  74066. */
  74067. /*
  74068. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  74069. Initializes the internal stream state for compression. The fields
  74070. zalloc, zfree and opaque must be initialized before by the caller.
  74071. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  74072. use default allocation functions.
  74073. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  74074. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  74075. all (the input data is simply copied a block at a time).
  74076. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  74077. compression (currently equivalent to level 6).
  74078. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  74079. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  74080. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  74081. with the version assumed by the caller (ZLIB_VERSION).
  74082. msg is set to null if there is no error message. deflateInit does not
  74083. perform any compression: this will be done by deflate().
  74084. */
  74085. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  74086. /*
  74087. deflate compresses as much data as possible, and stops when the input
  74088. buffer becomes empty or the output buffer becomes full. It may introduce some
  74089. output latency (reading input without producing any output) except when
  74090. forced to flush.
  74091. The detailed semantics are as follows. deflate performs one or both of the
  74092. following actions:
  74093. - Compress more input starting at next_in and update next_in and avail_in
  74094. accordingly. If not all input can be processed (because there is not
  74095. enough room in the output buffer), next_in and avail_in are updated and
  74096. processing will resume at this point for the next call of deflate().
  74097. - Provide more output starting at next_out and update next_out and avail_out
  74098. accordingly. This action is forced if the parameter flush is non zero.
  74099. Forcing flush frequently degrades the compression ratio, so this parameter
  74100. should be set only when necessary (in interactive applications).
  74101. Some output may be provided even if flush is not set.
  74102. Before the call of deflate(), the application should ensure that at least
  74103. one of the actions is possible, by providing more input and/or consuming
  74104. more output, and updating avail_in or avail_out accordingly; avail_out
  74105. should never be zero before the call. The application can consume the
  74106. compressed output when it wants, for example when the output buffer is full
  74107. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  74108. and with zero avail_out, it must be called again after making room in the
  74109. output buffer because there might be more output pending.
  74110. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  74111. decide how much data to accumualte before producing output, in order to
  74112. maximize compression.
  74113. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  74114. flushed to the output buffer and the output is aligned on a byte boundary, so
  74115. that the decompressor can get all input data available so far. (In particular
  74116. avail_in is zero after the call if enough output space has been provided
  74117. before the call.) Flushing may degrade compression for some compression
  74118. algorithms and so it should be used only when necessary.
  74119. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  74120. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  74121. restart from this point if previous compressed data has been damaged or if
  74122. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  74123. compression.
  74124. If deflate returns with avail_out == 0, this function must be called again
  74125. with the same value of the flush parameter and more output space (updated
  74126. avail_out), until the flush is complete (deflate returns with non-zero
  74127. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  74128. avail_out is greater than six to avoid repeated flush markers due to
  74129. avail_out == 0 on return.
  74130. If the parameter flush is set to Z_FINISH, pending input is processed,
  74131. pending output is flushed and deflate returns with Z_STREAM_END if there
  74132. was enough output space; if deflate returns with Z_OK, this function must be
  74133. called again with Z_FINISH and more output space (updated avail_out) but no
  74134. more input data, until it returns with Z_STREAM_END or an error. After
  74135. deflate has returned Z_STREAM_END, the only possible operations on the
  74136. stream are deflateReset or deflateEnd.
  74137. Z_FINISH can be used immediately after deflateInit if all the compression
  74138. is to be done in a single step. In this case, avail_out must be at least
  74139. the value returned by deflateBound (see below). If deflate does not return
  74140. Z_STREAM_END, then it must be called again as described above.
  74141. deflate() sets strm->adler to the adler32 checksum of all input read
  74142. so far (that is, total_in bytes).
  74143. deflate() may update strm->data_type if it can make a good guess about
  74144. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  74145. binary. This field is only for information purposes and does not affect
  74146. the compression algorithm in any manner.
  74147. deflate() returns Z_OK if some progress has been made (more input
  74148. processed or more output produced), Z_STREAM_END if all input has been
  74149. consumed and all output has been produced (only when flush is set to
  74150. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  74151. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  74152. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  74153. fatal, and deflate() can be called again with more input and more output
  74154. space to continue compressing.
  74155. */
  74156. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  74157. /*
  74158. All dynamically allocated data structures for this stream are freed.
  74159. This function discards any unprocessed input and does not flush any
  74160. pending output.
  74161. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  74162. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  74163. prematurely (some input or output was discarded). In the error case,
  74164. msg may be set but then points to a static string (which must not be
  74165. deallocated).
  74166. */
  74167. /*
  74168. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  74169. Initializes the internal stream state for decompression. The fields
  74170. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  74171. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  74172. value depends on the compression method), inflateInit determines the
  74173. compression method from the zlib header and allocates all data structures
  74174. accordingly; otherwise the allocation will be deferred to the first call of
  74175. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  74176. use default allocation functions.
  74177. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74178. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  74179. version assumed by the caller. msg is set to null if there is no error
  74180. message. inflateInit does not perform any decompression apart from reading
  74181. the zlib header if present: this will be done by inflate(). (So next_in and
  74182. avail_in may be modified, but next_out and avail_out are unchanged.)
  74183. */
  74184. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  74185. /*
  74186. inflate decompresses as much data as possible, and stops when the input
  74187. buffer becomes empty or the output buffer becomes full. It may introduce
  74188. some output latency (reading input without producing any output) except when
  74189. forced to flush.
  74190. The detailed semantics are as follows. inflate performs one or both of the
  74191. following actions:
  74192. - Decompress more input starting at next_in and update next_in and avail_in
  74193. accordingly. If not all input can be processed (because there is not
  74194. enough room in the output buffer), next_in is updated and processing
  74195. will resume at this point for the next call of inflate().
  74196. - Provide more output starting at next_out and update next_out and avail_out
  74197. accordingly. inflate() provides as much output as possible, until there
  74198. is no more input data or no more space in the output buffer (see below
  74199. about the flush parameter).
  74200. Before the call of inflate(), the application should ensure that at least
  74201. one of the actions is possible, by providing more input and/or consuming
  74202. more output, and updating the next_* and avail_* values accordingly.
  74203. The application can consume the uncompressed output when it wants, for
  74204. example when the output buffer is full (avail_out == 0), or after each
  74205. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  74206. must be called again after making room in the output buffer because there
  74207. might be more output pending.
  74208. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  74209. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  74210. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  74211. if and when it gets to the next deflate block boundary. When decoding the
  74212. zlib or gzip format, this will cause inflate() to return immediately after
  74213. the header and before the first block. When doing a raw inflate, inflate()
  74214. will go ahead and process the first block, and will return when it gets to
  74215. the end of that block, or when it runs out of data.
  74216. The Z_BLOCK option assists in appending to or combining deflate streams.
  74217. Also to assist in this, on return inflate() will set strm->data_type to the
  74218. number of unused bits in the last byte taken from strm->next_in, plus 64
  74219. if inflate() is currently decoding the last block in the deflate stream,
  74220. plus 128 if inflate() returned immediately after decoding an end-of-block
  74221. code or decoding the complete header up to just before the first byte of the
  74222. deflate stream. The end-of-block will not be indicated until all of the
  74223. uncompressed data from that block has been written to strm->next_out. The
  74224. number of unused bits may in general be greater than seven, except when
  74225. bit 7 of data_type is set, in which case the number of unused bits will be
  74226. less than eight.
  74227. inflate() should normally be called until it returns Z_STREAM_END or an
  74228. error. However if all decompression is to be performed in a single step
  74229. (a single call of inflate), the parameter flush should be set to
  74230. Z_FINISH. In this case all pending input is processed and all pending
  74231. output is flushed; avail_out must be large enough to hold all the
  74232. uncompressed data. (The size of the uncompressed data may have been saved
  74233. by the compressor for this purpose.) The next operation on this stream must
  74234. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  74235. is never required, but can be used to inform inflate that a faster approach
  74236. may be used for the single inflate() call.
  74237. In this implementation, inflate() always flushes as much output as
  74238. possible to the output buffer, and always uses the faster approach on the
  74239. first call. So the only effect of the flush parameter in this implementation
  74240. is on the return value of inflate(), as noted below, or when it returns early
  74241. because Z_BLOCK is used.
  74242. If a preset dictionary is needed after this call (see inflateSetDictionary
  74243. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  74244. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  74245. strm->adler to the adler32 checksum of all output produced so far (that is,
  74246. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  74247. below. At the end of the stream, inflate() checks that its computed adler32
  74248. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  74249. only if the checksum is correct.
  74250. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  74251. deflate data. The header type is detected automatically. Any information
  74252. contained in the gzip header is not retained, so applications that need that
  74253. information should instead use raw inflate, see inflateInit2() below, or
  74254. inflateBack() and perform their own processing of the gzip header and
  74255. trailer.
  74256. inflate() returns Z_OK if some progress has been made (more input processed
  74257. or more output produced), Z_STREAM_END if the end of the compressed data has
  74258. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  74259. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  74260. corrupted (input stream not conforming to the zlib format or incorrect check
  74261. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  74262. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  74263. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  74264. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  74265. inflate() can be called again with more input and more output space to
  74266. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  74267. call inflateSync() to look for a good compression block if a partial recovery
  74268. of the data is desired.
  74269. */
  74270. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  74271. /*
  74272. All dynamically allocated data structures for this stream are freed.
  74273. This function discards any unprocessed input and does not flush any
  74274. pending output.
  74275. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  74276. was inconsistent. In the error case, msg may be set but then points to a
  74277. static string (which must not be deallocated).
  74278. */
  74279. /* Advanced functions */
  74280. /*
  74281. The following functions are needed only in some special applications.
  74282. */
  74283. /*
  74284. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  74285. int level,
  74286. int method,
  74287. int windowBits,
  74288. int memLevel,
  74289. int strategy));
  74290. This is another version of deflateInit with more compression options. The
  74291. fields next_in, zalloc, zfree and opaque must be initialized before by
  74292. the caller.
  74293. The method parameter is the compression method. It must be Z_DEFLATED in
  74294. this version of the library.
  74295. The windowBits parameter is the base two logarithm of the window size
  74296. (the size of the history buffer). It should be in the range 8..15 for this
  74297. version of the library. Larger values of this parameter result in better
  74298. compression at the expense of memory usage. The default value is 15 if
  74299. deflateInit is used instead.
  74300. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  74301. determines the window size. deflate() will then generate raw deflate data
  74302. with no zlib header or trailer, and will not compute an adler32 check value.
  74303. windowBits can also be greater than 15 for optional gzip encoding. Add
  74304. 16 to windowBits to write a simple gzip header and trailer around the
  74305. compressed data instead of a zlib wrapper. The gzip header will have no
  74306. file name, no extra data, no comment, no modification time (set to zero),
  74307. no header crc, and the operating system will be set to 255 (unknown). If a
  74308. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  74309. The memLevel parameter specifies how much memory should be allocated
  74310. for the internal compression state. memLevel=1 uses minimum memory but
  74311. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  74312. for optimal speed. The default value is 8. See zconf.h for total memory
  74313. usage as a function of windowBits and memLevel.
  74314. The strategy parameter is used to tune the compression algorithm. Use the
  74315. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  74316. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  74317. string match), or Z_RLE to limit match distances to one (run-length
  74318. encoding). Filtered data consists mostly of small values with a somewhat
  74319. random distribution. In this case, the compression algorithm is tuned to
  74320. compress them better. The effect of Z_FILTERED is to force more Huffman
  74321. coding and less string matching; it is somewhat intermediate between
  74322. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  74323. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  74324. parameter only affects the compression ratio but not the correctness of the
  74325. compressed output even if it is not set appropriately. Z_FIXED prevents the
  74326. use of dynamic Huffman codes, allowing for a simpler decoder for special
  74327. applications.
  74328. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74329. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  74330. method). msg is set to null if there is no error message. deflateInit2 does
  74331. not perform any compression: this will be done by deflate().
  74332. */
  74333. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  74334. const Bytef *dictionary,
  74335. uInt dictLength));
  74336. /*
  74337. Initializes the compression dictionary from the given byte sequence
  74338. without producing any compressed output. This function must be called
  74339. immediately after deflateInit, deflateInit2 or deflateReset, before any
  74340. call of deflate. The compressor and decompressor must use exactly the same
  74341. dictionary (see inflateSetDictionary).
  74342. The dictionary should consist of strings (byte sequences) that are likely
  74343. to be encountered later in the data to be compressed, with the most commonly
  74344. used strings preferably put towards the end of the dictionary. Using a
  74345. dictionary is most useful when the data to be compressed is short and can be
  74346. predicted with good accuracy; the data can then be compressed better than
  74347. with the default empty dictionary.
  74348. Depending on the size of the compression data structures selected by
  74349. deflateInit or deflateInit2, a part of the dictionary may in effect be
  74350. discarded, for example if the dictionary is larger than the window size in
  74351. deflate or deflate2. Thus the strings most likely to be useful should be
  74352. put at the end of the dictionary, not at the front. In addition, the
  74353. current implementation of deflate will use at most the window size minus
  74354. 262 bytes of the provided dictionary.
  74355. Upon return of this function, strm->adler is set to the adler32 value
  74356. of the dictionary; the decompressor may later use this value to determine
  74357. which dictionary has been used by the compressor. (The adler32 value
  74358. applies to the whole dictionary even if only a subset of the dictionary is
  74359. actually used by the compressor.) If a raw deflate was requested, then the
  74360. adler32 value is not computed and strm->adler is not set.
  74361. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  74362. parameter is invalid (such as NULL dictionary) or the stream state is
  74363. inconsistent (for example if deflate has already been called for this stream
  74364. or if the compression method is bsort). deflateSetDictionary does not
  74365. perform any compression: this will be done by deflate().
  74366. */
  74367. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  74368. z_streamp source));
  74369. /*
  74370. Sets the destination stream as a complete copy of the source stream.
  74371. This function can be useful when several compression strategies will be
  74372. tried, for example when there are several ways of pre-processing the input
  74373. data with a filter. The streams that will be discarded should then be freed
  74374. by calling deflateEnd. Note that deflateCopy duplicates the internal
  74375. compression state which can be quite large, so this strategy is slow and
  74376. can consume lots of memory.
  74377. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74378. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74379. (such as zalloc being NULL). msg is left unchanged in both source and
  74380. destination.
  74381. */
  74382. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  74383. /*
  74384. This function is equivalent to deflateEnd followed by deflateInit,
  74385. but does not free and reallocate all the internal compression state.
  74386. The stream will keep the same compression level and any other attributes
  74387. that may have been set by deflateInit2.
  74388. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74389. stream state was inconsistent (such as zalloc or state being NULL).
  74390. */
  74391. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  74392. int level,
  74393. int strategy));
  74394. /*
  74395. Dynamically update the compression level and compression strategy. The
  74396. interpretation of level and strategy is as in deflateInit2. This can be
  74397. used to switch between compression and straight copy of the input data, or
  74398. to switch to a different kind of input data requiring a different
  74399. strategy. If the compression level is changed, the input available so far
  74400. is compressed with the old level (and may be flushed); the new level will
  74401. take effect only at the next call of deflate().
  74402. Before the call of deflateParams, the stream state must be set as for
  74403. a call of deflate(), since the currently available input may have to
  74404. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  74405. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  74406. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  74407. if strm->avail_out was zero.
  74408. */
  74409. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  74410. int good_length,
  74411. int max_lazy,
  74412. int nice_length,
  74413. int max_chain));
  74414. /*
  74415. Fine tune deflate's internal compression parameters. This should only be
  74416. used by someone who understands the algorithm used by zlib's deflate for
  74417. searching for the best matching string, and even then only by the most
  74418. fanatic optimizer trying to squeeze out the last compressed bit for their
  74419. specific input data. Read the deflate.c source code for the meaning of the
  74420. max_lazy, good_length, nice_length, and max_chain parameters.
  74421. deflateTune() can be called after deflateInit() or deflateInit2(), and
  74422. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  74423. */
  74424. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  74425. uLong sourceLen));
  74426. /*
  74427. deflateBound() returns an upper bound on the compressed size after
  74428. deflation of sourceLen bytes. It must be called after deflateInit()
  74429. or deflateInit2(). This would be used to allocate an output buffer
  74430. for deflation in a single pass, and so would be called before deflate().
  74431. */
  74432. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  74433. int bits,
  74434. int value));
  74435. /*
  74436. deflatePrime() inserts bits in the deflate output stream. The intent
  74437. is that this function is used to start off the deflate output with the
  74438. bits leftover from a previous deflate stream when appending to it. As such,
  74439. this function can only be used for raw deflate, and must be used before the
  74440. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  74441. less than or equal to 16, and that many of the least significant bits of
  74442. value will be inserted in the output.
  74443. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74444. stream state was inconsistent.
  74445. */
  74446. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  74447. gz_headerp head));
  74448. /*
  74449. deflateSetHeader() provides gzip header information for when a gzip
  74450. stream is requested by deflateInit2(). deflateSetHeader() may be called
  74451. after deflateInit2() or deflateReset() and before the first call of
  74452. deflate(). The text, time, os, extra field, name, and comment information
  74453. in the provided gz_header structure are written to the gzip header (xflag is
  74454. ignored -- the extra flags are set according to the compression level). The
  74455. caller must assure that, if not Z_NULL, name and comment are terminated with
  74456. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  74457. available there. If hcrc is true, a gzip header crc is included. Note that
  74458. the current versions of the command-line version of gzip (up through version
  74459. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  74460. gzip file" and give up.
  74461. If deflateSetHeader is not used, the default gzip header has text false,
  74462. the time set to zero, and os set to 255, with no extra, name, or comment
  74463. fields. The gzip header is returned to the default state by deflateReset().
  74464. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74465. stream state was inconsistent.
  74466. */
  74467. /*
  74468. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  74469. int windowBits));
  74470. This is another version of inflateInit with an extra parameter. The
  74471. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  74472. before by the caller.
  74473. The windowBits parameter is the base two logarithm of the maximum window
  74474. size (the size of the history buffer). It should be in the range 8..15 for
  74475. this version of the library. The default value is 15 if inflateInit is used
  74476. instead. windowBits must be greater than or equal to the windowBits value
  74477. provided to deflateInit2() while compressing, or it must be equal to 15 if
  74478. deflateInit2() was not used. If a compressed stream with a larger window
  74479. size is given as input, inflate() will return with the error code
  74480. Z_DATA_ERROR instead of trying to allocate a larger window.
  74481. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  74482. determines the window size. inflate() will then process raw deflate data,
  74483. not looking for a zlib or gzip header, not generating a check value, and not
  74484. looking for any check values for comparison at the end of the stream. This
  74485. is for use with other formats that use the deflate compressed data format
  74486. such as zip. Those formats provide their own check values. If a custom
  74487. format is developed using the raw deflate format for compressed data, it is
  74488. recommended that a check value such as an adler32 or a crc32 be applied to
  74489. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  74490. most applications, the zlib format should be used as is. Note that comments
  74491. above on the use in deflateInit2() applies to the magnitude of windowBits.
  74492. windowBits can also be greater than 15 for optional gzip decoding. Add
  74493. 32 to windowBits to enable zlib and gzip decoding with automatic header
  74494. detection, or add 16 to decode only the gzip format (the zlib format will
  74495. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  74496. a crc32 instead of an adler32.
  74497. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74498. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  74499. is set to null if there is no error message. inflateInit2 does not perform
  74500. any decompression apart from reading the zlib header if present: this will
  74501. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  74502. and avail_out are unchanged.)
  74503. */
  74504. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  74505. const Bytef *dictionary,
  74506. uInt dictLength));
  74507. /*
  74508. Initializes the decompression dictionary from the given uncompressed byte
  74509. sequence. This function must be called immediately after a call of inflate,
  74510. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  74511. can be determined from the adler32 value returned by that call of inflate.
  74512. The compressor and decompressor must use exactly the same dictionary (see
  74513. deflateSetDictionary). For raw inflate, this function can be called
  74514. immediately after inflateInit2() or inflateReset() and before any call of
  74515. inflate() to set the dictionary. The application must insure that the
  74516. dictionary that was used for compression is provided.
  74517. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  74518. parameter is invalid (such as NULL dictionary) or the stream state is
  74519. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  74520. expected one (incorrect adler32 value). inflateSetDictionary does not
  74521. perform any decompression: this will be done by subsequent calls of
  74522. inflate().
  74523. */
  74524. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  74525. /*
  74526. Skips invalid compressed data until a full flush point (see above the
  74527. description of deflate with Z_FULL_FLUSH) can be found, or until all
  74528. available input is skipped. No output is provided.
  74529. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  74530. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  74531. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  74532. case, the application may save the current current value of total_in which
  74533. indicates where valid compressed data was found. In the error case, the
  74534. application may repeatedly call inflateSync, providing more input each time,
  74535. until success or end of the input data.
  74536. */
  74537. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  74538. z_streamp source));
  74539. /*
  74540. Sets the destination stream as a complete copy of the source stream.
  74541. This function can be useful when randomly accessing a large stream. The
  74542. first pass through the stream can periodically record the inflate state,
  74543. allowing restarting inflate at those points when randomly accessing the
  74544. stream.
  74545. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  74546. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  74547. (such as zalloc being NULL). msg is left unchanged in both source and
  74548. destination.
  74549. */
  74550. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  74551. /*
  74552. This function is equivalent to inflateEnd followed by inflateInit,
  74553. but does not free and reallocate all the internal decompression state.
  74554. The stream will keep attributes that may have been set by inflateInit2.
  74555. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  74556. stream state was inconsistent (such as zalloc or state being NULL).
  74557. */
  74558. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  74559. int bits,
  74560. int value));
  74561. /*
  74562. This function inserts bits in the inflate input stream. The intent is
  74563. that this function is used to start inflating at a bit position in the
  74564. middle of a byte. The provided bits will be used before any bytes are used
  74565. from next_in. This function should only be used with raw inflate, and
  74566. should be used before the first inflate() call after inflateInit2() or
  74567. inflateReset(). bits must be less than or equal to 16, and that many of the
  74568. least significant bits of value will be inserted in the input.
  74569. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  74570. stream state was inconsistent.
  74571. */
  74572. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  74573. gz_headerp head));
  74574. /*
  74575. inflateGetHeader() requests that gzip header information be stored in the
  74576. provided gz_header structure. inflateGetHeader() may be called after
  74577. inflateInit2() or inflateReset(), and before the first call of inflate().
  74578. As inflate() processes the gzip stream, head->done is zero until the header
  74579. is completed, at which time head->done is set to one. If a zlib stream is
  74580. being decoded, then head->done is set to -1 to indicate that there will be
  74581. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  74582. force inflate() to return immediately after header processing is complete
  74583. and before any actual data is decompressed.
  74584. The text, time, xflags, and os fields are filled in with the gzip header
  74585. contents. hcrc is set to true if there is a header CRC. (The header CRC
  74586. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  74587. contains the maximum number of bytes to write to extra. Once done is true,
  74588. extra_len contains the actual extra field length, and extra contains the
  74589. extra field, or that field truncated if extra_max is less than extra_len.
  74590. If name is not Z_NULL, then up to name_max characters are written there,
  74591. terminated with a zero unless the length is greater than name_max. If
  74592. comment is not Z_NULL, then up to comm_max characters are written there,
  74593. terminated with a zero unless the length is greater than comm_max. When
  74594. any of extra, name, or comment are not Z_NULL and the respective field is
  74595. not present in the header, then that field is set to Z_NULL to signal its
  74596. absence. This allows the use of deflateSetHeader() with the returned
  74597. structure to duplicate the header. However if those fields are set to
  74598. allocated memory, then the application will need to save those pointers
  74599. elsewhere so that they can be eventually freed.
  74600. If inflateGetHeader is not used, then the header information is simply
  74601. discarded. The header is always checked for validity, including the header
  74602. CRC if present. inflateReset() will reset the process to discard the header
  74603. information. The application would need to call inflateGetHeader() again to
  74604. retrieve the header from the next gzip stream.
  74605. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  74606. stream state was inconsistent.
  74607. */
  74608. /*
  74609. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  74610. unsigned char FAR *window));
  74611. Initialize the internal stream state for decompression using inflateBack()
  74612. calls. The fields zalloc, zfree and opaque in strm must be initialized
  74613. before the call. If zalloc and zfree are Z_NULL, then the default library-
  74614. derived memory allocation routines are used. windowBits is the base two
  74615. logarithm of the window size, in the range 8..15. window is a caller
  74616. supplied buffer of that size. Except for special applications where it is
  74617. assured that deflate was used with small window sizes, windowBits must be 15
  74618. and a 32K byte window must be supplied to be able to decompress general
  74619. deflate streams.
  74620. See inflateBack() for the usage of these routines.
  74621. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  74622. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  74623. be allocated, or Z_VERSION_ERROR if the version of the library does not
  74624. match the version of the header file.
  74625. */
  74626. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  74627. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  74628. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  74629. in_func in, void FAR *in_desc,
  74630. out_func out, void FAR *out_desc));
  74631. /*
  74632. inflateBack() does a raw inflate with a single call using a call-back
  74633. interface for input and output. This is more efficient than inflate() for
  74634. file i/o applications in that it avoids copying between the output and the
  74635. sliding window by simply making the window itself the output buffer. This
  74636. function trusts the application to not change the output buffer passed by
  74637. the output function, at least until inflateBack() returns.
  74638. inflateBackInit() must be called first to allocate the internal state
  74639. and to initialize the state with the user-provided window buffer.
  74640. inflateBack() may then be used multiple times to inflate a complete, raw
  74641. deflate stream with each call. inflateBackEnd() is then called to free
  74642. the allocated state.
  74643. A raw deflate stream is one with no zlib or gzip header or trailer.
  74644. This routine would normally be used in a utility that reads zip or gzip
  74645. files and writes out uncompressed files. The utility would decode the
  74646. header and process the trailer on its own, hence this routine expects
  74647. only the raw deflate stream to decompress. This is different from the
  74648. normal behavior of inflate(), which expects either a zlib or gzip header and
  74649. trailer around the deflate stream.
  74650. inflateBack() uses two subroutines supplied by the caller that are then
  74651. called by inflateBack() for input and output. inflateBack() calls those
  74652. routines until it reads a complete deflate stream and writes out all of the
  74653. uncompressed data, or until it encounters an error. The function's
  74654. parameters and return types are defined above in the in_func and out_func
  74655. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  74656. number of bytes of provided input, and a pointer to that input in buf. If
  74657. there is no input available, in() must return zero--buf is ignored in that
  74658. case--and inflateBack() will return a buffer error. inflateBack() will call
  74659. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  74660. should return zero on success, or non-zero on failure. If out() returns
  74661. non-zero, inflateBack() will return with an error. Neither in() nor out()
  74662. are permitted to change the contents of the window provided to
  74663. inflateBackInit(), which is also the buffer that out() uses to write from.
  74664. The length written by out() will be at most the window size. Any non-zero
  74665. amount of input may be provided by in().
  74666. For convenience, inflateBack() can be provided input on the first call by
  74667. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  74668. in() will be called. Therefore strm->next_in must be initialized before
  74669. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  74670. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  74671. must also be initialized, and then if strm->avail_in is not zero, input will
  74672. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  74673. The in_desc and out_desc parameters of inflateBack() is passed as the
  74674. first parameter of in() and out() respectively when they are called. These
  74675. descriptors can be optionally used to pass any information that the caller-
  74676. supplied in() and out() functions need to do their job.
  74677. On return, inflateBack() will set strm->next_in and strm->avail_in to
  74678. pass back any unused input that was provided by the last in() call. The
  74679. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  74680. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  74681. error in the deflate stream (in which case strm->msg is set to indicate the
  74682. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  74683. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  74684. distinguished using strm->next_in which will be Z_NULL only if in() returned
  74685. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  74686. out() returning non-zero. (in() will always be called before out(), so
  74687. strm->next_in is assured to be defined if out() returns non-zero.) Note
  74688. that inflateBack() cannot return Z_OK.
  74689. */
  74690. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  74691. /*
  74692. All memory allocated by inflateBackInit() is freed.
  74693. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  74694. state was inconsistent.
  74695. */
  74696. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  74697. /* Return flags indicating compile-time options.
  74698. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  74699. 1.0: size of uInt
  74700. 3.2: size of uLong
  74701. 5.4: size of voidpf (pointer)
  74702. 7.6: size of z_off_t
  74703. Compiler, assembler, and debug options:
  74704. 8: DEBUG
  74705. 9: ASMV or ASMINF -- use ASM code
  74706. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  74707. 11: 0 (reserved)
  74708. One-time table building (smaller code, but not thread-safe if true):
  74709. 12: BUILDFIXED -- build static block decoding tables when needed
  74710. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  74711. 14,15: 0 (reserved)
  74712. Library content (indicates missing functionality):
  74713. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  74714. deflate code when not needed)
  74715. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  74716. and decode gzip streams (to avoid linking crc code)
  74717. 18-19: 0 (reserved)
  74718. Operation variations (changes in library functionality):
  74719. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  74720. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  74721. 22,23: 0 (reserved)
  74722. The sprintf variant used by gzprintf (zero is best):
  74723. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  74724. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  74725. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  74726. Remainder:
  74727. 27-31: 0 (reserved)
  74728. */
  74729. /* utility functions */
  74730. /*
  74731. The following utility functions are implemented on top of the
  74732. basic stream-oriented functions. To simplify the interface, some
  74733. default options are assumed (compression level and memory usage,
  74734. standard memory allocation functions). The source code of these
  74735. utility functions can easily be modified if you need special options.
  74736. */
  74737. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  74738. const Bytef *source, uLong sourceLen));
  74739. /*
  74740. Compresses the source buffer into the destination buffer. sourceLen is
  74741. the byte length of the source buffer. Upon entry, destLen is the total
  74742. size of the destination buffer, which must be at least the value returned
  74743. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74744. compressed buffer.
  74745. This function can be used to compress a whole file at once if the
  74746. input file is mmap'ed.
  74747. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  74748. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74749. buffer.
  74750. */
  74751. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  74752. const Bytef *source, uLong sourceLen,
  74753. int level));
  74754. /*
  74755. Compresses the source buffer into the destination buffer. The level
  74756. parameter has the same meaning as in deflateInit. sourceLen is the byte
  74757. length of the source buffer. Upon entry, destLen is the total size of the
  74758. destination buffer, which must be at least the value returned by
  74759. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  74760. compressed buffer.
  74761. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  74762. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  74763. Z_STREAM_ERROR if the level parameter is invalid.
  74764. */
  74765. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  74766. /*
  74767. compressBound() returns an upper bound on the compressed size after
  74768. compress() or compress2() on sourceLen bytes. It would be used before
  74769. a compress() or compress2() call to allocate the destination buffer.
  74770. */
  74771. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  74772. const Bytef *source, uLong sourceLen));
  74773. /*
  74774. Decompresses the source buffer into the destination buffer. sourceLen is
  74775. the byte length of the source buffer. Upon entry, destLen is the total
  74776. size of the destination buffer, which must be large enough to hold the
  74777. entire uncompressed data. (The size of the uncompressed data must have
  74778. been saved previously by the compressor and transmitted to the decompressor
  74779. by some mechanism outside the scope of this compression library.)
  74780. Upon exit, destLen is the actual size of the compressed buffer.
  74781. This function can be used to decompress a whole file at once if the
  74782. input file is mmap'ed.
  74783. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  74784. enough memory, Z_BUF_ERROR if there was not enough room in the output
  74785. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  74786. */
  74787. typedef voidp gzFile;
  74788. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  74789. /*
  74790. Opens a gzip (.gz) file for reading or writing. The mode parameter
  74791. is as in fopen ("rb" or "wb") but can also include a compression level
  74792. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  74793. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  74794. as in "wb1R". (See the description of deflateInit2 for more information
  74795. about the strategy parameter.)
  74796. gzopen can be used to read a file which is not in gzip format; in this
  74797. case gzread will directly read from the file without decompression.
  74798. gzopen returns NULL if the file could not be opened or if there was
  74799. insufficient memory to allocate the (de)compression state; errno
  74800. can be checked to distinguish the two cases (if errno is zero, the
  74801. zlib error is Z_MEM_ERROR). */
  74802. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  74803. /*
  74804. gzdopen() associates a gzFile with the file descriptor fd. File
  74805. descriptors are obtained from calls like open, dup, creat, pipe or
  74806. fileno (in the file has been previously opened with fopen).
  74807. The mode parameter is as in gzopen.
  74808. The next call of gzclose on the returned gzFile will also close the
  74809. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  74810. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  74811. gzdopen returns NULL if there was insufficient memory to allocate
  74812. the (de)compression state.
  74813. */
  74814. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  74815. /*
  74816. Dynamically update the compression level or strategy. See the description
  74817. of deflateInit2 for the meaning of these parameters.
  74818. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  74819. opened for writing.
  74820. */
  74821. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  74822. /*
  74823. Reads the given number of uncompressed bytes from the compressed file.
  74824. If the input file was not in gzip format, gzread copies the given number
  74825. of bytes into the buffer.
  74826. gzread returns the number of uncompressed bytes actually read (0 for
  74827. end of file, -1 for error). */
  74828. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  74829. voidpc buf, unsigned len));
  74830. /*
  74831. Writes the given number of uncompressed bytes into the compressed file.
  74832. gzwrite returns the number of uncompressed bytes actually written
  74833. (0 in case of error).
  74834. */
  74835. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  74836. /*
  74837. Converts, formats, and writes the args to the compressed file under
  74838. control of the format string, as in fprintf. gzprintf returns the number of
  74839. uncompressed bytes actually written (0 in case of error). The number of
  74840. uncompressed bytes written is limited to 4095. The caller should assure that
  74841. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  74842. return an error (0) with nothing written. In this case, there may also be a
  74843. buffer overflow with unpredictable consequences, which is possible only if
  74844. zlib was compiled with the insecure functions sprintf() or vsprintf()
  74845. because the secure snprintf() or vsnprintf() functions were not available.
  74846. */
  74847. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  74848. /*
  74849. Writes the given null-terminated string to the compressed file, excluding
  74850. the terminating null character.
  74851. gzputs returns the number of characters written, or -1 in case of error.
  74852. */
  74853. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  74854. /*
  74855. Reads bytes from the compressed file until len-1 characters are read, or
  74856. a newline character is read and transferred to buf, or an end-of-file
  74857. condition is encountered. The string is then terminated with a null
  74858. character.
  74859. gzgets returns buf, or Z_NULL in case of error.
  74860. */
  74861. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  74862. /*
  74863. Writes c, converted to an unsigned char, into the compressed file.
  74864. gzputc returns the value that was written, or -1 in case of error.
  74865. */
  74866. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  74867. /*
  74868. Reads one byte from the compressed file. gzgetc returns this byte
  74869. or -1 in case of end of file or error.
  74870. */
  74871. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  74872. /*
  74873. Push one character back onto the stream to be read again later.
  74874. Only one character of push-back is allowed. gzungetc() returns the
  74875. character pushed, or -1 on failure. gzungetc() will fail if a
  74876. character has been pushed but not read yet, or if c is -1. The pushed
  74877. character will be discarded if the stream is repositioned with gzseek()
  74878. or gzrewind().
  74879. */
  74880. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  74881. /*
  74882. Flushes all pending output into the compressed file. The parameter
  74883. flush is as in the deflate() function. The return value is the zlib
  74884. error number (see function gzerror below). gzflush returns Z_OK if
  74885. the flush parameter is Z_FINISH and all output could be flushed.
  74886. gzflush should be called only when strictly necessary because it can
  74887. degrade compression.
  74888. */
  74889. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  74890. z_off_t offset, int whence));
  74891. /*
  74892. Sets the starting position for the next gzread or gzwrite on the
  74893. given compressed file. The offset represents a number of bytes in the
  74894. uncompressed data stream. The whence parameter is defined as in lseek(2);
  74895. the value SEEK_END is not supported.
  74896. If the file is opened for reading, this function is emulated but can be
  74897. extremely slow. If the file is opened for writing, only forward seeks are
  74898. supported; gzseek then compresses a sequence of zeroes up to the new
  74899. starting position.
  74900. gzseek returns the resulting offset location as measured in bytes from
  74901. the beginning of the uncompressed stream, or -1 in case of error, in
  74902. particular if the file is opened for writing and the new starting position
  74903. would be before the current position.
  74904. */
  74905. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  74906. /*
  74907. Rewinds the given file. This function is supported only for reading.
  74908. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  74909. */
  74910. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  74911. /*
  74912. Returns the starting position for the next gzread or gzwrite on the
  74913. given compressed file. This position represents a number of bytes in the
  74914. uncompressed data stream.
  74915. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  74916. */
  74917. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  74918. /*
  74919. Returns 1 when EOF has previously been detected reading the given
  74920. input stream, otherwise zero.
  74921. */
  74922. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  74923. /*
  74924. Returns 1 if file is being read directly without decompression, otherwise
  74925. zero.
  74926. */
  74927. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  74928. /*
  74929. Flushes all pending output if necessary, closes the compressed file
  74930. and deallocates all the (de)compression state. The return value is the zlib
  74931. error number (see function gzerror below).
  74932. */
  74933. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  74934. /*
  74935. Returns the error message for the last error which occurred on the
  74936. given compressed file. errnum is set to zlib error number. If an
  74937. error occurred in the file system and not in the compression library,
  74938. errnum is set to Z_ERRNO and the application may consult errno
  74939. to get the exact error code.
  74940. */
  74941. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  74942. /*
  74943. Clears the error and end-of-file flags for file. This is analogous to the
  74944. clearerr() function in stdio. This is useful for continuing to read a gzip
  74945. file that is being written concurrently.
  74946. */
  74947. /* checksum functions */
  74948. /*
  74949. These functions are not related to compression but are exported
  74950. anyway because they might be useful in applications using the
  74951. compression library.
  74952. */
  74953. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  74954. /*
  74955. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  74956. return the updated checksum. If buf is NULL, this function returns
  74957. the required initial value for the checksum.
  74958. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  74959. much faster. Usage example:
  74960. uLong adler = adler32(0L, Z_NULL, 0);
  74961. while (read_buffer(buffer, length) != EOF) {
  74962. adler = adler32(adler, buffer, length);
  74963. }
  74964. if (adler != original_adler) error();
  74965. */
  74966. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  74967. z_off_t len2));
  74968. /*
  74969. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  74970. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  74971. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  74972. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  74973. */
  74974. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  74975. /*
  74976. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  74977. updated CRC-32. If buf is NULL, this function returns the required initial
  74978. value for the for the crc. Pre- and post-conditioning (one's complement) is
  74979. performed within this function so it shouldn't be done by the application.
  74980. Usage example:
  74981. uLong crc = crc32(0L, Z_NULL, 0);
  74982. while (read_buffer(buffer, length) != EOF) {
  74983. crc = crc32(crc, buffer, length);
  74984. }
  74985. if (crc != original_crc) error();
  74986. */
  74987. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  74988. /*
  74989. Combine two CRC-32 check values into one. For two sequences of bytes,
  74990. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  74991. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  74992. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  74993. len2.
  74994. */
  74995. /* various hacks, don't look :) */
  74996. /* deflateInit and inflateInit are macros to allow checking the zlib version
  74997. * and the compiler's view of z_stream:
  74998. */
  74999. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  75000. const char *version, int stream_size));
  75001. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  75002. const char *version, int stream_size));
  75003. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  75004. int windowBits, int memLevel,
  75005. int strategy, const char *version,
  75006. int stream_size));
  75007. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  75008. const char *version, int stream_size));
  75009. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  75010. unsigned char FAR *window,
  75011. const char *version,
  75012. int stream_size));
  75013. #define deflateInit(strm, level) \
  75014. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  75015. #define inflateInit(strm) \
  75016. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  75017. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  75018. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  75019. (strategy), ZLIB_VERSION, sizeof(z_stream))
  75020. #define inflateInit2(strm, windowBits) \
  75021. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  75022. #define inflateBackInit(strm, windowBits, window) \
  75023. inflateBackInit_((strm), (windowBits), (window), \
  75024. ZLIB_VERSION, sizeof(z_stream))
  75025. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  75026. struct internal_state {int dummy;}; /* hack for buggy compilers */
  75027. #endif
  75028. ZEXTERN const char * ZEXPORT zError OF((int));
  75029. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  75030. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  75031. #ifdef __cplusplus
  75032. }
  75033. #endif
  75034. #endif /* ZLIB_H */
  75035. /********* End of inlined file: zlib.h *********/
  75036. #undef OS_CODE
  75037. #else
  75038. #include <zlib.h>
  75039. #endif
  75040. }
  75041. BEGIN_JUCE_NAMESPACE
  75042. using namespace zlibNamespace;
  75043. // internal helper object that holds the zlib structures so they don't have to be
  75044. // included publicly.
  75045. class GZIPCompressorHelper
  75046. {
  75047. private:
  75048. z_stream* stream;
  75049. uint8* data;
  75050. int dataSize, compLevel, strategy;
  75051. bool setParams;
  75052. public:
  75053. bool finished, shouldFinish;
  75054. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  75055. : data (0),
  75056. dataSize (0),
  75057. compLevel (compressionLevel),
  75058. strategy (0),
  75059. setParams (true),
  75060. finished (false),
  75061. shouldFinish (false)
  75062. {
  75063. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  75064. if (deflateInit2 (stream,
  75065. compLevel,
  75066. Z_DEFLATED,
  75067. nowrap ? -MAX_WBITS : MAX_WBITS,
  75068. 8,
  75069. strategy) != Z_OK)
  75070. {
  75071. juce_free (stream);
  75072. stream = 0;
  75073. }
  75074. }
  75075. ~GZIPCompressorHelper()
  75076. {
  75077. if (stream != 0)
  75078. {
  75079. deflateEnd (stream);
  75080. juce_free (stream);
  75081. }
  75082. }
  75083. bool needsInput() const throw()
  75084. {
  75085. return dataSize <= 0;
  75086. }
  75087. void setInput (uint8* const newData, const int size) throw()
  75088. {
  75089. data = newData;
  75090. dataSize = size;
  75091. }
  75092. int doNextBlock (uint8* const dest, const int destSize) throw()
  75093. {
  75094. if (stream != 0)
  75095. {
  75096. stream->next_in = data;
  75097. stream->next_out = dest;
  75098. stream->avail_in = dataSize;
  75099. stream->avail_out = destSize;
  75100. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  75101. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  75102. setParams = false;
  75103. switch (result)
  75104. {
  75105. case Z_STREAM_END:
  75106. finished = true;
  75107. case Z_OK:
  75108. data += dataSize - stream->avail_in;
  75109. dataSize = stream->avail_in;
  75110. return destSize - stream->avail_out;
  75111. default:
  75112. break;
  75113. }
  75114. }
  75115. return 0;
  75116. }
  75117. };
  75118. const int gzipCompBufferSize = 32768;
  75119. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  75120. int compressionLevel,
  75121. const bool deleteDestStream_,
  75122. const bool noWrap)
  75123. : destStream (destStream_),
  75124. deleteDestStream (deleteDestStream_)
  75125. {
  75126. if (compressionLevel < 1 || compressionLevel > 9)
  75127. compressionLevel = -1;
  75128. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  75129. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  75130. }
  75131. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  75132. {
  75133. flush();
  75134. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75135. delete h;
  75136. juce_free (buffer);
  75137. if (deleteDestStream)
  75138. delete destStream;
  75139. }
  75140. void GZIPCompressorOutputStream::flush()
  75141. {
  75142. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75143. if (! h->finished)
  75144. {
  75145. h->shouldFinish = true;
  75146. while (! h->finished)
  75147. doNextBlock();
  75148. }
  75149. destStream->flush();
  75150. }
  75151. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  75152. {
  75153. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75154. if (! h->finished)
  75155. {
  75156. h->setInput ((uint8*) destBuffer, howMany);
  75157. while (! h->needsInput())
  75158. {
  75159. if (! doNextBlock())
  75160. return false;
  75161. }
  75162. }
  75163. return true;
  75164. }
  75165. bool GZIPCompressorOutputStream::doNextBlock()
  75166. {
  75167. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  75168. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  75169. if (len > 0)
  75170. return destStream->write (buffer, len);
  75171. else
  75172. return true;
  75173. }
  75174. int64 GZIPCompressorOutputStream::getPosition()
  75175. {
  75176. return destStream->getPosition();
  75177. }
  75178. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  75179. {
  75180. jassertfalse // can't do it!
  75181. return false;
  75182. }
  75183. END_JUCE_NAMESPACE
  75184. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  75185. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  75186. #if JUCE_MSVC
  75187. #pragma warning (push)
  75188. #pragma warning (disable: 4309 4305)
  75189. #endif
  75190. namespace zlibNamespace
  75191. {
  75192. #if JUCE_INCLUDE_ZLIB_CODE
  75193. extern "C"
  75194. {
  75195. #undef OS_CODE
  75196. #undef fdopen
  75197. #define ZLIB_INTERNAL
  75198. #define NO_DUMMY_DECL
  75199. /********* Start of inlined file: adler32.c *********/
  75200. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75201. #define ZLIB_INTERNAL
  75202. #define BASE 65521UL /* largest prime smaller than 65536 */
  75203. #define NMAX 5552
  75204. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  75205. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  75206. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  75207. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  75208. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  75209. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  75210. /* use NO_DIVIDE if your processor does not do division in hardware */
  75211. #ifdef NO_DIVIDE
  75212. # define MOD(a) \
  75213. do { \
  75214. if (a >= (BASE << 16)) a -= (BASE << 16); \
  75215. if (a >= (BASE << 15)) a -= (BASE << 15); \
  75216. if (a >= (BASE << 14)) a -= (BASE << 14); \
  75217. if (a >= (BASE << 13)) a -= (BASE << 13); \
  75218. if (a >= (BASE << 12)) a -= (BASE << 12); \
  75219. if (a >= (BASE << 11)) a -= (BASE << 11); \
  75220. if (a >= (BASE << 10)) a -= (BASE << 10); \
  75221. if (a >= (BASE << 9)) a -= (BASE << 9); \
  75222. if (a >= (BASE << 8)) a -= (BASE << 8); \
  75223. if (a >= (BASE << 7)) a -= (BASE << 7); \
  75224. if (a >= (BASE << 6)) a -= (BASE << 6); \
  75225. if (a >= (BASE << 5)) a -= (BASE << 5); \
  75226. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75227. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75228. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75229. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75230. if (a >= BASE) a -= BASE; \
  75231. } while (0)
  75232. # define MOD4(a) \
  75233. do { \
  75234. if (a >= (BASE << 4)) a -= (BASE << 4); \
  75235. if (a >= (BASE << 3)) a -= (BASE << 3); \
  75236. if (a >= (BASE << 2)) a -= (BASE << 2); \
  75237. if (a >= (BASE << 1)) a -= (BASE << 1); \
  75238. if (a >= BASE) a -= BASE; \
  75239. } while (0)
  75240. #else
  75241. # define MOD(a) a %= BASE
  75242. # define MOD4(a) a %= BASE
  75243. #endif
  75244. /* ========================================================================= */
  75245. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  75246. {
  75247. unsigned long sum2;
  75248. unsigned n;
  75249. /* split Adler-32 into component sums */
  75250. sum2 = (adler >> 16) & 0xffff;
  75251. adler &= 0xffff;
  75252. /* in case user likes doing a byte at a time, keep it fast */
  75253. if (len == 1) {
  75254. adler += buf[0];
  75255. if (adler >= BASE)
  75256. adler -= BASE;
  75257. sum2 += adler;
  75258. if (sum2 >= BASE)
  75259. sum2 -= BASE;
  75260. return adler | (sum2 << 16);
  75261. }
  75262. /* initial Adler-32 value (deferred check for len == 1 speed) */
  75263. if (buf == Z_NULL)
  75264. return 1L;
  75265. /* in case short lengths are provided, keep it somewhat fast */
  75266. if (len < 16) {
  75267. while (len--) {
  75268. adler += *buf++;
  75269. sum2 += adler;
  75270. }
  75271. if (adler >= BASE)
  75272. adler -= BASE;
  75273. MOD4(sum2); /* only added so many BASE's */
  75274. return adler | (sum2 << 16);
  75275. }
  75276. /* do length NMAX blocks -- requires just one modulo operation */
  75277. while (len >= NMAX) {
  75278. len -= NMAX;
  75279. n = NMAX / 16; /* NMAX is divisible by 16 */
  75280. do {
  75281. DO16(buf); /* 16 sums unrolled */
  75282. buf += 16;
  75283. } while (--n);
  75284. MOD(adler);
  75285. MOD(sum2);
  75286. }
  75287. /* do remaining bytes (less than NMAX, still just one modulo) */
  75288. if (len) { /* avoid modulos if none remaining */
  75289. while (len >= 16) {
  75290. len -= 16;
  75291. DO16(buf);
  75292. buf += 16;
  75293. }
  75294. while (len--) {
  75295. adler += *buf++;
  75296. sum2 += adler;
  75297. }
  75298. MOD(adler);
  75299. MOD(sum2);
  75300. }
  75301. /* return recombined sums */
  75302. return adler | (sum2 << 16);
  75303. }
  75304. /* ========================================================================= */
  75305. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  75306. {
  75307. unsigned long sum1;
  75308. unsigned long sum2;
  75309. unsigned rem;
  75310. /* the derivation of this formula is left as an exercise for the reader */
  75311. rem = (unsigned)(len2 % BASE);
  75312. sum1 = adler1 & 0xffff;
  75313. sum2 = rem * sum1;
  75314. MOD(sum2);
  75315. sum1 += (adler2 & 0xffff) + BASE - 1;
  75316. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  75317. if (sum1 > BASE) sum1 -= BASE;
  75318. if (sum1 > BASE) sum1 -= BASE;
  75319. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  75320. if (sum2 > BASE) sum2 -= BASE;
  75321. return sum1 | (sum2 << 16);
  75322. }
  75323. /********* End of inlined file: adler32.c *********/
  75324. /********* Start of inlined file: compress.c *********/
  75325. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75326. #define ZLIB_INTERNAL
  75327. /* ===========================================================================
  75328. Compresses the source buffer into the destination buffer. The level
  75329. parameter has the same meaning as in deflateInit. sourceLen is the byte
  75330. length of the source buffer. Upon entry, destLen is the total size of the
  75331. destination buffer, which must be at least 0.1% larger than sourceLen plus
  75332. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  75333. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  75334. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  75335. Z_STREAM_ERROR if the level parameter is invalid.
  75336. */
  75337. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  75338. uLong sourceLen, int level)
  75339. {
  75340. z_stream stream;
  75341. int err;
  75342. stream.next_in = (Bytef*)source;
  75343. stream.avail_in = (uInt)sourceLen;
  75344. #ifdef MAXSEG_64K
  75345. /* Check for source > 64K on 16-bit machine: */
  75346. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  75347. #endif
  75348. stream.next_out = dest;
  75349. stream.avail_out = (uInt)*destLen;
  75350. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  75351. stream.zalloc = (alloc_func)0;
  75352. stream.zfree = (free_func)0;
  75353. stream.opaque = (voidpf)0;
  75354. err = deflateInit(&stream, level);
  75355. if (err != Z_OK) return err;
  75356. err = deflate(&stream, Z_FINISH);
  75357. if (err != Z_STREAM_END) {
  75358. deflateEnd(&stream);
  75359. return err == Z_OK ? Z_BUF_ERROR : err;
  75360. }
  75361. *destLen = stream.total_out;
  75362. err = deflateEnd(&stream);
  75363. return err;
  75364. }
  75365. /* ===========================================================================
  75366. */
  75367. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  75368. {
  75369. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  75370. }
  75371. /* ===========================================================================
  75372. If the default memLevel or windowBits for deflateInit() is changed, then
  75373. this function needs to be updated.
  75374. */
  75375. uLong ZEXPORT compressBound (uLong sourceLen)
  75376. {
  75377. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  75378. }
  75379. /********* End of inlined file: compress.c *********/
  75380. #undef DO1
  75381. #undef DO8
  75382. /********* Start of inlined file: crc32.c *********/
  75383. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75384. /*
  75385. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  75386. protection on the static variables used to control the first-use generation
  75387. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  75388. first call get_crc_table() to initialize the tables before allowing more than
  75389. one thread to use crc32().
  75390. */
  75391. #ifdef MAKECRCH
  75392. # include <stdio.h>
  75393. # ifndef DYNAMIC_CRC_TABLE
  75394. # define DYNAMIC_CRC_TABLE
  75395. # endif /* !DYNAMIC_CRC_TABLE */
  75396. #endif /* MAKECRCH */
  75397. /********* Start of inlined file: zutil.h *********/
  75398. /* WARNING: this file should *not* be used by applications. It is
  75399. part of the implementation of the compression library and is
  75400. subject to change. Applications should only use zlib.h.
  75401. */
  75402. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  75403. #ifndef ZUTIL_H
  75404. #define ZUTIL_H
  75405. #define ZLIB_INTERNAL
  75406. #ifdef STDC
  75407. # ifndef _WIN32_WCE
  75408. # include <stddef.h>
  75409. # endif
  75410. # include <string.h>
  75411. # include <stdlib.h>
  75412. #endif
  75413. #ifdef NO_ERRNO_H
  75414. # ifdef _WIN32_WCE
  75415. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  75416. * errno. We define it as a global variable to simplify porting.
  75417. * Its value is always 0 and should not be used. We rename it to
  75418. * avoid conflict with other libraries that use the same workaround.
  75419. */
  75420. # define errno z_errno
  75421. # endif
  75422. extern int errno;
  75423. #else
  75424. # ifndef _WIN32_WCE
  75425. # include <errno.h>
  75426. # endif
  75427. #endif
  75428. #ifndef local
  75429. # define local static
  75430. #endif
  75431. /* compile with -Dlocal if your debugger can't find static symbols */
  75432. typedef unsigned char uch;
  75433. typedef uch FAR uchf;
  75434. typedef unsigned short ush;
  75435. typedef ush FAR ushf;
  75436. typedef unsigned long ulg;
  75437. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  75438. /* (size given to avoid silly warnings with Visual C++) */
  75439. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  75440. #define ERR_RETURN(strm,err) \
  75441. return (strm->msg = (char*)ERR_MSG(err), (err))
  75442. /* To be used only when the state is known to be valid */
  75443. /* common constants */
  75444. #ifndef DEF_WBITS
  75445. # define DEF_WBITS MAX_WBITS
  75446. #endif
  75447. /* default windowBits for decompression. MAX_WBITS is for compression only */
  75448. #if MAX_MEM_LEVEL >= 8
  75449. # define DEF_MEM_LEVEL 8
  75450. #else
  75451. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  75452. #endif
  75453. /* default memLevel */
  75454. #define STORED_BLOCK 0
  75455. #define STATIC_TREES 1
  75456. #define DYN_TREES 2
  75457. /* The three kinds of block type */
  75458. #define MIN_MATCH 3
  75459. #define MAX_MATCH 258
  75460. /* The minimum and maximum match lengths */
  75461. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  75462. /* target dependencies */
  75463. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  75464. # define OS_CODE 0x00
  75465. # if defined(__TURBOC__) || defined(__BORLANDC__)
  75466. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  75467. /* Allow compilation with ANSI keywords only enabled */
  75468. void _Cdecl farfree( void *block );
  75469. void *_Cdecl farmalloc( unsigned long nbytes );
  75470. # else
  75471. # include <alloc.h>
  75472. # endif
  75473. # else /* MSC or DJGPP */
  75474. # include <malloc.h>
  75475. # endif
  75476. #endif
  75477. #ifdef AMIGA
  75478. # define OS_CODE 0x01
  75479. #endif
  75480. #if defined(VAXC) || defined(VMS)
  75481. # define OS_CODE 0x02
  75482. # define F_OPEN(name, mode) \
  75483. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  75484. #endif
  75485. #if defined(ATARI) || defined(atarist)
  75486. # define OS_CODE 0x05
  75487. #endif
  75488. #ifdef OS2
  75489. # define OS_CODE 0x06
  75490. # ifdef M_I86
  75491. #include <malloc.h>
  75492. # endif
  75493. #endif
  75494. #if defined(MACOS) || TARGET_OS_MAC
  75495. # define OS_CODE 0x07
  75496. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  75497. # include <unix.h> /* for fdopen */
  75498. # else
  75499. # ifndef fdopen
  75500. # define fdopen(fd,mode) NULL /* No fdopen() */
  75501. # endif
  75502. # endif
  75503. #endif
  75504. #ifdef TOPS20
  75505. # define OS_CODE 0x0a
  75506. #endif
  75507. #ifdef WIN32
  75508. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  75509. # define OS_CODE 0x0b
  75510. # endif
  75511. #endif
  75512. #ifdef __50SERIES /* Prime/PRIMOS */
  75513. # define OS_CODE 0x0f
  75514. #endif
  75515. #if defined(_BEOS_) || defined(RISCOS)
  75516. # define fdopen(fd,mode) NULL /* No fdopen() */
  75517. #endif
  75518. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  75519. # if defined(_WIN32_WCE)
  75520. # define fdopen(fd,mode) NULL /* No fdopen() */
  75521. # ifndef _PTRDIFF_T_DEFINED
  75522. typedef int ptrdiff_t;
  75523. # define _PTRDIFF_T_DEFINED
  75524. # endif
  75525. # else
  75526. # define fdopen(fd,type) _fdopen(fd,type)
  75527. # endif
  75528. #endif
  75529. /* common defaults */
  75530. #ifndef OS_CODE
  75531. # define OS_CODE 0x03 /* assume Unix */
  75532. #endif
  75533. #ifndef F_OPEN
  75534. # define F_OPEN(name, mode) fopen((name), (mode))
  75535. #endif
  75536. /* functions */
  75537. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  75538. # ifndef HAVE_VSNPRINTF
  75539. # define HAVE_VSNPRINTF
  75540. # endif
  75541. #endif
  75542. #if defined(__CYGWIN__)
  75543. # ifndef HAVE_VSNPRINTF
  75544. # define HAVE_VSNPRINTF
  75545. # endif
  75546. #endif
  75547. #ifndef HAVE_VSNPRINTF
  75548. # ifdef MSDOS
  75549. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  75550. but for now we just assume it doesn't. */
  75551. # define NO_vsnprintf
  75552. # endif
  75553. # ifdef __TURBOC__
  75554. # define NO_vsnprintf
  75555. # endif
  75556. # ifdef WIN32
  75557. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  75558. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  75559. # define vsnprintf _vsnprintf
  75560. # endif
  75561. # endif
  75562. # ifdef __SASC
  75563. # define NO_vsnprintf
  75564. # endif
  75565. #endif
  75566. #ifdef VMS
  75567. # define NO_vsnprintf
  75568. #endif
  75569. #if defined(pyr)
  75570. # define NO_MEMCPY
  75571. #endif
  75572. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  75573. /* Use our own functions for small and medium model with MSC <= 5.0.
  75574. * You may have to use the same strategy for Borland C (untested).
  75575. * The __SC__ check is for Symantec.
  75576. */
  75577. # define NO_MEMCPY
  75578. #endif
  75579. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  75580. # define HAVE_MEMCPY
  75581. #endif
  75582. #ifdef HAVE_MEMCPY
  75583. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  75584. # define zmemcpy _fmemcpy
  75585. # define zmemcmp _fmemcmp
  75586. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  75587. # else
  75588. # define zmemcpy memcpy
  75589. # define zmemcmp memcmp
  75590. # define zmemzero(dest, len) memset(dest, 0, len)
  75591. # endif
  75592. #else
  75593. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  75594. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  75595. extern void zmemzero OF((Bytef* dest, uInt len));
  75596. #endif
  75597. /* Diagnostic functions */
  75598. #ifdef DEBUG
  75599. # include <stdio.h>
  75600. extern int z_verbose;
  75601. extern void z_error OF((const char *m));
  75602. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  75603. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  75604. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  75605. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  75606. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  75607. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  75608. #else
  75609. # define Assert(cond,msg)
  75610. # define Trace(x)
  75611. # define Tracev(x)
  75612. # define Tracevv(x)
  75613. # define Tracec(c,x)
  75614. # define Tracecv(c,x)
  75615. #endif
  75616. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  75617. void zcfree OF((voidpf opaque, voidpf ptr));
  75618. #define ZALLOC(strm, items, size) \
  75619. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  75620. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  75621. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  75622. #endif /* ZUTIL_H */
  75623. /********* End of inlined file: zutil.h *********/
  75624. /* for STDC and FAR definitions */
  75625. #define local static
  75626. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  75627. #ifndef NOBYFOUR
  75628. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  75629. # include <limits.h>
  75630. # define BYFOUR
  75631. # if (UINT_MAX == 0xffffffffUL)
  75632. typedef unsigned int u4;
  75633. # else
  75634. # if (ULONG_MAX == 0xffffffffUL)
  75635. typedef unsigned long u4;
  75636. # else
  75637. # if (USHRT_MAX == 0xffffffffUL)
  75638. typedef unsigned short u4;
  75639. # else
  75640. # undef BYFOUR /* can't find a four-byte integer type! */
  75641. # endif
  75642. # endif
  75643. # endif
  75644. # endif /* STDC */
  75645. #endif /* !NOBYFOUR */
  75646. /* Definitions for doing the crc four data bytes at a time. */
  75647. #ifdef BYFOUR
  75648. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  75649. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  75650. local unsigned long crc32_little OF((unsigned long,
  75651. const unsigned char FAR *, unsigned));
  75652. local unsigned long crc32_big OF((unsigned long,
  75653. const unsigned char FAR *, unsigned));
  75654. # define TBLS 8
  75655. #else
  75656. # define TBLS 1
  75657. #endif /* BYFOUR */
  75658. /* Local functions for crc concatenation */
  75659. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  75660. unsigned long vec));
  75661. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  75662. #ifdef DYNAMIC_CRC_TABLE
  75663. local volatile int crc_table_empty = 1;
  75664. local unsigned long FAR crc_table[TBLS][256];
  75665. local void make_crc_table OF((void));
  75666. #ifdef MAKECRCH
  75667. local void write_table OF((FILE *, const unsigned long FAR *));
  75668. #endif /* MAKECRCH */
  75669. /*
  75670. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  75671. 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.
  75672. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  75673. with the lowest powers in the most significant bit. Then adding polynomials
  75674. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  75675. one. If we call the above polynomial p, and represent a byte as the
  75676. polynomial q, also with the lowest power in the most significant bit (so the
  75677. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  75678. where a mod b means the remainder after dividing a by b.
  75679. This calculation is done using the shift-register method of multiplying and
  75680. taking the remainder. The register is initialized to zero, and for each
  75681. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  75682. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  75683. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  75684. out is a one). We start with the highest power (least significant bit) of
  75685. q and repeat for all eight bits of q.
  75686. The first table is simply the CRC of all possible eight bit values. This is
  75687. all the information needed to generate CRCs on data a byte at a time for all
  75688. combinations of CRC register values and incoming bytes. The remaining tables
  75689. allow for word-at-a-time CRC calculation for both big-endian and little-
  75690. endian machines, where a word is four bytes.
  75691. */
  75692. local void make_crc_table()
  75693. {
  75694. unsigned long c;
  75695. int n, k;
  75696. unsigned long poly; /* polynomial exclusive-or pattern */
  75697. /* terms of polynomial defining this crc (except x^32): */
  75698. static volatile int first = 1; /* flag to limit concurrent making */
  75699. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  75700. /* See if another task is already doing this (not thread-safe, but better
  75701. than nothing -- significantly reduces duration of vulnerability in
  75702. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  75703. if (first) {
  75704. first = 0;
  75705. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  75706. poly = 0UL;
  75707. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  75708. poly |= 1UL << (31 - p[n]);
  75709. /* generate a crc for every 8-bit value */
  75710. for (n = 0; n < 256; n++) {
  75711. c = (unsigned long)n;
  75712. for (k = 0; k < 8; k++)
  75713. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  75714. crc_table[0][n] = c;
  75715. }
  75716. #ifdef BYFOUR
  75717. /* generate crc for each value followed by one, two, and three zeros,
  75718. and then the byte reversal of those as well as the first table */
  75719. for (n = 0; n < 256; n++) {
  75720. c = crc_table[0][n];
  75721. crc_table[4][n] = REV(c);
  75722. for (k = 1; k < 4; k++) {
  75723. c = crc_table[0][c & 0xff] ^ (c >> 8);
  75724. crc_table[k][n] = c;
  75725. crc_table[k + 4][n] = REV(c);
  75726. }
  75727. }
  75728. #endif /* BYFOUR */
  75729. crc_table_empty = 0;
  75730. }
  75731. else { /* not first */
  75732. /* wait for the other guy to finish (not efficient, but rare) */
  75733. while (crc_table_empty)
  75734. ;
  75735. }
  75736. #ifdef MAKECRCH
  75737. /* write out CRC tables to crc32.h */
  75738. {
  75739. FILE *out;
  75740. out = fopen("crc32.h", "w");
  75741. if (out == NULL) return;
  75742. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  75743. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  75744. fprintf(out, "local const unsigned long FAR ");
  75745. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  75746. write_table(out, crc_table[0]);
  75747. # ifdef BYFOUR
  75748. fprintf(out, "#ifdef BYFOUR\n");
  75749. for (k = 1; k < 8; k++) {
  75750. fprintf(out, " },\n {\n");
  75751. write_table(out, crc_table[k]);
  75752. }
  75753. fprintf(out, "#endif\n");
  75754. # endif /* BYFOUR */
  75755. fprintf(out, " }\n};\n");
  75756. fclose(out);
  75757. }
  75758. #endif /* MAKECRCH */
  75759. }
  75760. #ifdef MAKECRCH
  75761. local void write_table(out, table)
  75762. FILE *out;
  75763. const unsigned long FAR *table;
  75764. {
  75765. int n;
  75766. for (n = 0; n < 256; n++)
  75767. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  75768. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  75769. }
  75770. #endif /* MAKECRCH */
  75771. #else /* !DYNAMIC_CRC_TABLE */
  75772. /* ========================================================================
  75773. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  75774. */
  75775. /********* Start of inlined file: crc32.h *********/
  75776. local const unsigned long FAR crc_table[TBLS][256] =
  75777. {
  75778. {
  75779. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  75780. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  75781. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  75782. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  75783. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  75784. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  75785. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  75786. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  75787. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  75788. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  75789. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  75790. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  75791. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  75792. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  75793. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  75794. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  75795. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  75796. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  75797. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  75798. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  75799. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  75800. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  75801. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  75802. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  75803. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  75804. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  75805. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  75806. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  75807. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  75808. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  75809. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  75810. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  75811. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  75812. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  75813. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  75814. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  75815. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  75816. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  75817. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  75818. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  75819. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  75820. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  75821. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  75822. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  75823. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  75824. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  75825. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  75826. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  75827. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  75828. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  75829. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  75830. 0x2d02ef8dUL
  75831. #ifdef BYFOUR
  75832. },
  75833. {
  75834. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  75835. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  75836. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  75837. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  75838. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  75839. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  75840. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  75841. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  75842. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  75843. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  75844. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  75845. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  75846. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  75847. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  75848. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  75849. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  75850. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  75851. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  75852. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  75853. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  75854. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  75855. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  75856. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  75857. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  75858. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  75859. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  75860. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  75861. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  75862. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  75863. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  75864. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  75865. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  75866. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  75867. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  75868. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  75869. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  75870. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  75871. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  75872. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  75873. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  75874. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  75875. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  75876. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  75877. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  75878. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  75879. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  75880. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  75881. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  75882. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  75883. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  75884. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  75885. 0x9324fd72UL
  75886. },
  75887. {
  75888. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  75889. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  75890. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  75891. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  75892. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  75893. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  75894. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  75895. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  75896. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  75897. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  75898. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  75899. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  75900. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  75901. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  75902. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  75903. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  75904. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  75905. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  75906. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  75907. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  75908. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  75909. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  75910. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  75911. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  75912. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  75913. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  75914. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  75915. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  75916. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  75917. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  75918. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  75919. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  75920. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  75921. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  75922. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  75923. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  75924. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  75925. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  75926. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  75927. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  75928. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  75929. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  75930. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  75931. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  75932. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  75933. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  75934. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  75935. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  75936. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  75937. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  75938. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  75939. 0xbe9834edUL
  75940. },
  75941. {
  75942. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  75943. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  75944. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  75945. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  75946. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  75947. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  75948. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  75949. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  75950. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  75951. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  75952. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  75953. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  75954. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  75955. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  75956. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  75957. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  75958. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  75959. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  75960. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  75961. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  75962. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  75963. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  75964. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  75965. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  75966. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  75967. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  75968. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  75969. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  75970. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  75971. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  75972. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  75973. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  75974. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  75975. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  75976. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  75977. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  75978. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  75979. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  75980. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  75981. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  75982. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  75983. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  75984. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  75985. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  75986. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  75987. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  75988. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  75989. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  75990. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  75991. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  75992. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  75993. 0xde0506f1UL
  75994. },
  75995. {
  75996. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  75997. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  75998. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  75999. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  76000. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  76001. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  76002. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  76003. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  76004. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  76005. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  76006. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  76007. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  76008. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  76009. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  76010. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  76011. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  76012. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  76013. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  76014. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  76015. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  76016. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  76017. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  76018. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  76019. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  76020. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  76021. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  76022. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  76023. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  76024. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  76025. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  76026. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  76027. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  76028. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  76029. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  76030. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  76031. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  76032. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  76033. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  76034. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  76035. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  76036. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  76037. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  76038. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  76039. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  76040. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  76041. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  76042. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  76043. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  76044. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  76045. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  76046. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  76047. 0x8def022dUL
  76048. },
  76049. {
  76050. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  76051. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  76052. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  76053. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  76054. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  76055. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  76056. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  76057. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  76058. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  76059. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  76060. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  76061. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  76062. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  76063. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  76064. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  76065. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  76066. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  76067. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  76068. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  76069. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  76070. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  76071. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  76072. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  76073. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  76074. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  76075. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  76076. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  76077. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  76078. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  76079. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  76080. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  76081. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  76082. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  76083. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  76084. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  76085. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  76086. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  76087. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  76088. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  76089. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  76090. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  76091. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  76092. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  76093. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  76094. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  76095. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  76096. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  76097. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  76098. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  76099. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  76100. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  76101. 0x72fd2493UL
  76102. },
  76103. {
  76104. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  76105. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  76106. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  76107. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  76108. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  76109. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  76110. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  76111. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  76112. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  76113. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  76114. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  76115. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  76116. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  76117. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  76118. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  76119. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  76120. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  76121. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  76122. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  76123. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  76124. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  76125. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  76126. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  76127. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  76128. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  76129. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  76130. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  76131. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  76132. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  76133. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  76134. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  76135. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  76136. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  76137. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  76138. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  76139. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  76140. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  76141. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  76142. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  76143. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  76144. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  76145. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  76146. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  76147. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  76148. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  76149. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  76150. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  76151. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  76152. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  76153. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  76154. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  76155. 0xed3498beUL
  76156. },
  76157. {
  76158. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  76159. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  76160. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  76161. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  76162. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  76163. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  76164. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  76165. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  76166. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  76167. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  76168. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  76169. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  76170. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  76171. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  76172. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  76173. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  76174. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  76175. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  76176. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  76177. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  76178. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  76179. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  76180. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  76181. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  76182. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  76183. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  76184. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  76185. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  76186. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  76187. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  76188. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  76189. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  76190. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  76191. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  76192. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  76193. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  76194. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  76195. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  76196. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  76197. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  76198. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  76199. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  76200. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  76201. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  76202. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  76203. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  76204. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  76205. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  76206. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  76207. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  76208. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  76209. 0xf10605deUL
  76210. #endif
  76211. }
  76212. };
  76213. /********* End of inlined file: crc32.h *********/
  76214. #endif /* DYNAMIC_CRC_TABLE */
  76215. /* =========================================================================
  76216. * This function can be used by asm versions of crc32()
  76217. */
  76218. const unsigned long FAR * ZEXPORT get_crc_table()
  76219. {
  76220. #ifdef DYNAMIC_CRC_TABLE
  76221. if (crc_table_empty)
  76222. make_crc_table();
  76223. #endif /* DYNAMIC_CRC_TABLE */
  76224. return (const unsigned long FAR *)crc_table;
  76225. }
  76226. /* ========================================================================= */
  76227. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  76228. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  76229. /* ========================================================================= */
  76230. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76231. {
  76232. if (buf == Z_NULL) return 0UL;
  76233. #ifdef DYNAMIC_CRC_TABLE
  76234. if (crc_table_empty)
  76235. make_crc_table();
  76236. #endif /* DYNAMIC_CRC_TABLE */
  76237. #ifdef BYFOUR
  76238. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  76239. u4 endian;
  76240. endian = 1;
  76241. if (*((unsigned char *)(&endian)))
  76242. return crc32_little(crc, buf, len);
  76243. else
  76244. return crc32_big(crc, buf, len);
  76245. }
  76246. #endif /* BYFOUR */
  76247. crc = crc ^ 0xffffffffUL;
  76248. while (len >= 8) {
  76249. DO8;
  76250. len -= 8;
  76251. }
  76252. if (len) do {
  76253. DO1;
  76254. } while (--len);
  76255. return crc ^ 0xffffffffUL;
  76256. }
  76257. #ifdef BYFOUR
  76258. /* ========================================================================= */
  76259. #define DOLIT4 c ^= *buf4++; \
  76260. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  76261. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  76262. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  76263. /* ========================================================================= */
  76264. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76265. {
  76266. register u4 c;
  76267. register const u4 FAR *buf4;
  76268. c = (u4)crc;
  76269. c = ~c;
  76270. while (len && ((ptrdiff_t)buf & 3)) {
  76271. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76272. len--;
  76273. }
  76274. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76275. while (len >= 32) {
  76276. DOLIT32;
  76277. len -= 32;
  76278. }
  76279. while (len >= 4) {
  76280. DOLIT4;
  76281. len -= 4;
  76282. }
  76283. buf = (const unsigned char FAR *)buf4;
  76284. if (len) do {
  76285. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  76286. } while (--len);
  76287. c = ~c;
  76288. return (unsigned long)c;
  76289. }
  76290. /* ========================================================================= */
  76291. #define DOBIG4 c ^= *++buf4; \
  76292. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  76293. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  76294. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  76295. /* ========================================================================= */
  76296. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  76297. {
  76298. register u4 c;
  76299. register const u4 FAR *buf4;
  76300. c = REV((u4)crc);
  76301. c = ~c;
  76302. while (len && ((ptrdiff_t)buf & 3)) {
  76303. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76304. len--;
  76305. }
  76306. buf4 = (const u4 FAR *)(const void FAR *)buf;
  76307. buf4--;
  76308. while (len >= 32) {
  76309. DOBIG32;
  76310. len -= 32;
  76311. }
  76312. while (len >= 4) {
  76313. DOBIG4;
  76314. len -= 4;
  76315. }
  76316. buf4++;
  76317. buf = (const unsigned char FAR *)buf4;
  76318. if (len) do {
  76319. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  76320. } while (--len);
  76321. c = ~c;
  76322. return (unsigned long)(REV(c));
  76323. }
  76324. #endif /* BYFOUR */
  76325. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  76326. /* ========================================================================= */
  76327. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  76328. {
  76329. unsigned long sum;
  76330. sum = 0;
  76331. while (vec) {
  76332. if (vec & 1)
  76333. sum ^= *mat;
  76334. vec >>= 1;
  76335. mat++;
  76336. }
  76337. return sum;
  76338. }
  76339. /* ========================================================================= */
  76340. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  76341. {
  76342. int n;
  76343. for (n = 0; n < GF2_DIM; n++)
  76344. square[n] = gf2_matrix_times(mat, mat[n]);
  76345. }
  76346. /* ========================================================================= */
  76347. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  76348. {
  76349. int n;
  76350. unsigned long row;
  76351. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  76352. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  76353. /* degenerate case */
  76354. if (len2 == 0)
  76355. return crc1;
  76356. /* put operator for one zero bit in odd */
  76357. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  76358. row = 1;
  76359. for (n = 1; n < GF2_DIM; n++) {
  76360. odd[n] = row;
  76361. row <<= 1;
  76362. }
  76363. /* put operator for two zero bits in even */
  76364. gf2_matrix_square(even, odd);
  76365. /* put operator for four zero bits in odd */
  76366. gf2_matrix_square(odd, even);
  76367. /* apply len2 zeros to crc1 (first square will put the operator for one
  76368. zero byte, eight zero bits, in even) */
  76369. do {
  76370. /* apply zeros operator for this bit of len2 */
  76371. gf2_matrix_square(even, odd);
  76372. if (len2 & 1)
  76373. crc1 = gf2_matrix_times(even, crc1);
  76374. len2 >>= 1;
  76375. /* if no more bits set, then done */
  76376. if (len2 == 0)
  76377. break;
  76378. /* another iteration of the loop with odd and even swapped */
  76379. gf2_matrix_square(odd, even);
  76380. if (len2 & 1)
  76381. crc1 = gf2_matrix_times(odd, crc1);
  76382. len2 >>= 1;
  76383. /* if no more bits set, then done */
  76384. } while (len2 != 0);
  76385. /* return combined crc */
  76386. crc1 ^= crc2;
  76387. return crc1;
  76388. }
  76389. /********* End of inlined file: crc32.c *********/
  76390. /********* Start of inlined file: deflate.c *********/
  76391. /*
  76392. * ALGORITHM
  76393. *
  76394. * The "deflation" process depends on being able to identify portions
  76395. * of the input text which are identical to earlier input (within a
  76396. * sliding window trailing behind the input currently being processed).
  76397. *
  76398. * The most straightforward technique turns out to be the fastest for
  76399. * most input files: try all possible matches and select the longest.
  76400. * The key feature of this algorithm is that insertions into the string
  76401. * dictionary are very simple and thus fast, and deletions are avoided
  76402. * completely. Insertions are performed at each input character, whereas
  76403. * string matches are performed only when the previous match ends. So it
  76404. * is preferable to spend more time in matches to allow very fast string
  76405. * insertions and avoid deletions. The matching algorithm for small
  76406. * strings is inspired from that of Rabin & Karp. A brute force approach
  76407. * is used to find longer strings when a small match has been found.
  76408. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  76409. * (by Leonid Broukhis).
  76410. * A previous version of this file used a more sophisticated algorithm
  76411. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  76412. * time, but has a larger average cost, uses more memory and is patented.
  76413. * However the F&G algorithm may be faster for some highly redundant
  76414. * files if the parameter max_chain_length (described below) is too large.
  76415. *
  76416. * ACKNOWLEDGEMENTS
  76417. *
  76418. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  76419. * I found it in 'freeze' written by Leonid Broukhis.
  76420. * Thanks to many people for bug reports and testing.
  76421. *
  76422. * REFERENCES
  76423. *
  76424. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  76425. * Available in http://www.ietf.org/rfc/rfc1951.txt
  76426. *
  76427. * A description of the Rabin and Karp algorithm is given in the book
  76428. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  76429. *
  76430. * Fiala,E.R., and Greene,D.H.
  76431. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  76432. *
  76433. */
  76434. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76435. /********* Start of inlined file: deflate.h *********/
  76436. /* WARNING: this file should *not* be used by applications. It is
  76437. part of the implementation of the compression library and is
  76438. subject to change. Applications should only use zlib.h.
  76439. */
  76440. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  76441. #ifndef DEFLATE_H
  76442. #define DEFLATE_H
  76443. /* define NO_GZIP when compiling if you want to disable gzip header and
  76444. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  76445. the crc code when it is not needed. For shared libraries, gzip encoding
  76446. should be left enabled. */
  76447. #ifndef NO_GZIP
  76448. # define GZIP
  76449. #endif
  76450. #define NO_DUMMY_DECL
  76451. /* ===========================================================================
  76452. * Internal compression state.
  76453. */
  76454. #define LENGTH_CODES 29
  76455. /* number of length codes, not counting the special END_BLOCK code */
  76456. #define LITERALS 256
  76457. /* number of literal bytes 0..255 */
  76458. #define L_CODES (LITERALS+1+LENGTH_CODES)
  76459. /* number of Literal or Length codes, including the END_BLOCK code */
  76460. #define D_CODES 30
  76461. /* number of distance codes */
  76462. #define BL_CODES 19
  76463. /* number of codes used to transfer the bit lengths */
  76464. #define HEAP_SIZE (2*L_CODES+1)
  76465. /* maximum heap size */
  76466. #define MAX_BITS 15
  76467. /* All codes must not exceed MAX_BITS bits */
  76468. #define INIT_STATE 42
  76469. #define EXTRA_STATE 69
  76470. #define NAME_STATE 73
  76471. #define COMMENT_STATE 91
  76472. #define HCRC_STATE 103
  76473. #define BUSY_STATE 113
  76474. #define FINISH_STATE 666
  76475. /* Stream status */
  76476. /* Data structure describing a single value and its code string. */
  76477. typedef struct ct_data_s {
  76478. union {
  76479. ush freq; /* frequency count */
  76480. ush code; /* bit string */
  76481. } fc;
  76482. union {
  76483. ush dad; /* father node in Huffman tree */
  76484. ush len; /* length of bit string */
  76485. } dl;
  76486. } FAR ct_data;
  76487. #define Freq fc.freq
  76488. #define Code fc.code
  76489. #define Dad dl.dad
  76490. #define Len dl.len
  76491. typedef struct static_tree_desc_s static_tree_desc;
  76492. typedef struct tree_desc_s {
  76493. ct_data *dyn_tree; /* the dynamic tree */
  76494. int max_code; /* largest code with non zero frequency */
  76495. static_tree_desc *stat_desc; /* the corresponding static tree */
  76496. } FAR tree_desc;
  76497. typedef ush Pos;
  76498. typedef Pos FAR Posf;
  76499. typedef unsigned IPos;
  76500. /* A Pos is an index in the character window. We use short instead of int to
  76501. * save space in the various tables. IPos is used only for parameter passing.
  76502. */
  76503. typedef struct internal_state {
  76504. z_streamp strm; /* pointer back to this zlib stream */
  76505. int status; /* as the name implies */
  76506. Bytef *pending_buf; /* output still pending */
  76507. ulg pending_buf_size; /* size of pending_buf */
  76508. Bytef *pending_out; /* next pending byte to output to the stream */
  76509. uInt pending; /* nb of bytes in the pending buffer */
  76510. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76511. gz_headerp gzhead; /* gzip header information to write */
  76512. uInt gzindex; /* where in extra, name, or comment */
  76513. Byte method; /* STORED (for zip only) or DEFLATED */
  76514. int last_flush; /* value of flush param for previous deflate call */
  76515. /* used by deflate.c: */
  76516. uInt w_size; /* LZ77 window size (32K by default) */
  76517. uInt w_bits; /* log2(w_size) (8..16) */
  76518. uInt w_mask; /* w_size - 1 */
  76519. Bytef *window;
  76520. /* Sliding window. Input bytes are read into the second half of the window,
  76521. * and move to the first half later to keep a dictionary of at least wSize
  76522. * bytes. With this organization, matches are limited to a distance of
  76523. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  76524. * performed with a length multiple of the block size. Also, it limits
  76525. * the window size to 64K, which is quite useful on MSDOS.
  76526. * To do: use the user input buffer as sliding window.
  76527. */
  76528. ulg window_size;
  76529. /* Actual size of window: 2*wSize, except when the user input buffer
  76530. * is directly used as sliding window.
  76531. */
  76532. Posf *prev;
  76533. /* Link to older string with same hash index. To limit the size of this
  76534. * array to 64K, this link is maintained only for the last 32K strings.
  76535. * An index in this array is thus a window index modulo 32K.
  76536. */
  76537. Posf *head; /* Heads of the hash chains or NIL. */
  76538. uInt ins_h; /* hash index of string to be inserted */
  76539. uInt hash_size; /* number of elements in hash table */
  76540. uInt hash_bits; /* log2(hash_size) */
  76541. uInt hash_mask; /* hash_size-1 */
  76542. uInt hash_shift;
  76543. /* Number of bits by which ins_h must be shifted at each input
  76544. * step. It must be such that after MIN_MATCH steps, the oldest
  76545. * byte no longer takes part in the hash key, that is:
  76546. * hash_shift * MIN_MATCH >= hash_bits
  76547. */
  76548. long block_start;
  76549. /* Window position at the beginning of the current output block. Gets
  76550. * negative when the window is moved backwards.
  76551. */
  76552. uInt match_length; /* length of best match */
  76553. IPos prev_match; /* previous match */
  76554. int match_available; /* set if previous match exists */
  76555. uInt strstart; /* start of string to insert */
  76556. uInt match_start; /* start of matching string */
  76557. uInt lookahead; /* number of valid bytes ahead in window */
  76558. uInt prev_length;
  76559. /* Length of the best match at previous step. Matches not greater than this
  76560. * are discarded. This is used in the lazy match evaluation.
  76561. */
  76562. uInt max_chain_length;
  76563. /* To speed up deflation, hash chains are never searched beyond this
  76564. * length. A higher limit improves compression ratio but degrades the
  76565. * speed.
  76566. */
  76567. uInt max_lazy_match;
  76568. /* Attempt to find a better match only when the current match is strictly
  76569. * smaller than this value. This mechanism is used only for compression
  76570. * levels >= 4.
  76571. */
  76572. # define max_insert_length max_lazy_match
  76573. /* Insert new strings in the hash table only if the match length is not
  76574. * greater than this length. This saves time but degrades compression.
  76575. * max_insert_length is used only for compression levels <= 3.
  76576. */
  76577. int level; /* compression level (1..9) */
  76578. int strategy; /* favor or force Huffman coding*/
  76579. uInt good_match;
  76580. /* Use a faster search when the previous match is longer than this */
  76581. int nice_match; /* Stop searching when current match exceeds this */
  76582. /* used by trees.c: */
  76583. /* Didn't use ct_data typedef below to supress compiler warning */
  76584. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  76585. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  76586. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  76587. struct tree_desc_s l_desc; /* desc. for literal tree */
  76588. struct tree_desc_s d_desc; /* desc. for distance tree */
  76589. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  76590. ush bl_count[MAX_BITS+1];
  76591. /* number of codes at each bit length for an optimal tree */
  76592. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  76593. int heap_len; /* number of elements in the heap */
  76594. int heap_max; /* element of largest frequency */
  76595. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  76596. * The same heap array is used to build all trees.
  76597. */
  76598. uch depth[2*L_CODES+1];
  76599. /* Depth of each subtree used as tie breaker for trees of equal frequency
  76600. */
  76601. uchf *l_buf; /* buffer for literals or lengths */
  76602. uInt lit_bufsize;
  76603. /* Size of match buffer for literals/lengths. There are 4 reasons for
  76604. * limiting lit_bufsize to 64K:
  76605. * - frequencies can be kept in 16 bit counters
  76606. * - if compression is not successful for the first block, all input
  76607. * data is still in the window so we can still emit a stored block even
  76608. * when input comes from standard input. (This can also be done for
  76609. * all blocks if lit_bufsize is not greater than 32K.)
  76610. * - if compression is not successful for a file smaller than 64K, we can
  76611. * even emit a stored file instead of a stored block (saving 5 bytes).
  76612. * This is applicable only for zip (not gzip or zlib).
  76613. * - creating new Huffman trees less frequently may not provide fast
  76614. * adaptation to changes in the input data statistics. (Take for
  76615. * example a binary file with poorly compressible code followed by
  76616. * a highly compressible string table.) Smaller buffer sizes give
  76617. * fast adaptation but have of course the overhead of transmitting
  76618. * trees more frequently.
  76619. * - I can't count above 4
  76620. */
  76621. uInt last_lit; /* running index in l_buf */
  76622. ushf *d_buf;
  76623. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  76624. * the same number of elements. To use different lengths, an extra flag
  76625. * array would be necessary.
  76626. */
  76627. ulg opt_len; /* bit length of current block with optimal trees */
  76628. ulg static_len; /* bit length of current block with static trees */
  76629. uInt matches; /* number of string matches in current block */
  76630. int last_eob_len; /* bit length of EOB code for last block */
  76631. #ifdef DEBUG
  76632. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  76633. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  76634. #endif
  76635. ush bi_buf;
  76636. /* Output buffer. bits are inserted starting at the bottom (least
  76637. * significant bits).
  76638. */
  76639. int bi_valid;
  76640. /* Number of valid bits in bi_buf. All bits above the last valid bit
  76641. * are always zero.
  76642. */
  76643. } FAR deflate_state;
  76644. /* Output a byte on the stream.
  76645. * IN assertion: there is enough room in pending_buf.
  76646. */
  76647. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  76648. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76649. /* Minimum amount of lookahead, except at the end of the input file.
  76650. * See deflate.c for comments about the MIN_MATCH+1.
  76651. */
  76652. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  76653. /* In order to simplify the code, particularly on 16 bit machines, match
  76654. * distances are limited to MAX_DIST instead of WSIZE.
  76655. */
  76656. /* in trees.c */
  76657. void _tr_init OF((deflate_state *s));
  76658. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  76659. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76660. int eof));
  76661. void _tr_align OF((deflate_state *s));
  76662. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  76663. int eof));
  76664. #define d_code(dist) \
  76665. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  76666. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  76667. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  76668. * used.
  76669. */
  76670. #ifndef DEBUG
  76671. /* Inline versions of _tr_tally for speed: */
  76672. #if defined(GEN_TREES_H) || !defined(STDC)
  76673. extern uch _length_code[];
  76674. extern uch _dist_code[];
  76675. #else
  76676. extern const uch _length_code[];
  76677. extern const uch _dist_code[];
  76678. #endif
  76679. # define _tr_tally_lit(s, c, flush) \
  76680. { uch cc = (c); \
  76681. s->d_buf[s->last_lit] = 0; \
  76682. s->l_buf[s->last_lit++] = cc; \
  76683. s->dyn_ltree[cc].Freq++; \
  76684. flush = (s->last_lit == s->lit_bufsize-1); \
  76685. }
  76686. # define _tr_tally_dist(s, distance, length, flush) \
  76687. { uch len = (length); \
  76688. ush dist = (distance); \
  76689. s->d_buf[s->last_lit] = dist; \
  76690. s->l_buf[s->last_lit++] = len; \
  76691. dist--; \
  76692. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  76693. s->dyn_dtree[d_code(dist)].Freq++; \
  76694. flush = (s->last_lit == s->lit_bufsize-1); \
  76695. }
  76696. #else
  76697. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  76698. # define _tr_tally_dist(s, distance, length, flush) \
  76699. flush = _tr_tally(s, distance, length)
  76700. #endif
  76701. #endif /* DEFLATE_H */
  76702. /********* End of inlined file: deflate.h *********/
  76703. const char deflate_copyright[] =
  76704. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  76705. /*
  76706. If you use the zlib library in a product, an acknowledgment is welcome
  76707. in the documentation of your product. If for some reason you cannot
  76708. include such an acknowledgment, I would appreciate that you keep this
  76709. copyright string in the executable of your product.
  76710. */
  76711. /* ===========================================================================
  76712. * Function prototypes.
  76713. */
  76714. typedef enum {
  76715. need_more, /* block not completed, need more input or more output */
  76716. block_done, /* block flush performed */
  76717. finish_started, /* finish started, need only more output at next deflate */
  76718. finish_done /* finish done, accept no more input or output */
  76719. } block_state;
  76720. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  76721. /* Compression function. Returns the block state after the call. */
  76722. local void fill_window OF((deflate_state *s));
  76723. local block_state deflate_stored OF((deflate_state *s, int flush));
  76724. local block_state deflate_fast OF((deflate_state *s, int flush));
  76725. #ifndef FASTEST
  76726. local block_state deflate_slow OF((deflate_state *s, int flush));
  76727. #endif
  76728. local void lm_init OF((deflate_state *s));
  76729. local void putShortMSB OF((deflate_state *s, uInt b));
  76730. local void flush_pending OF((z_streamp strm));
  76731. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  76732. #ifndef FASTEST
  76733. #ifdef ASMV
  76734. void match_init OF((void)); /* asm code initialization */
  76735. uInt longest_match OF((deflate_state *s, IPos cur_match));
  76736. #else
  76737. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  76738. #endif
  76739. #endif
  76740. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  76741. #ifdef DEBUG
  76742. local void check_match OF((deflate_state *s, IPos start, IPos match,
  76743. int length));
  76744. #endif
  76745. /* ===========================================================================
  76746. * Local data
  76747. */
  76748. #define NIL 0
  76749. /* Tail of hash chains */
  76750. #ifndef TOO_FAR
  76751. # define TOO_FAR 4096
  76752. #endif
  76753. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  76754. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  76755. /* Minimum amount of lookahead, except at the end of the input file.
  76756. * See deflate.c for comments about the MIN_MATCH+1.
  76757. */
  76758. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  76759. * the desired pack level (0..9). The values given below have been tuned to
  76760. * exclude worst case performance for pathological files. Better values may be
  76761. * found for specific files.
  76762. */
  76763. typedef struct config_s {
  76764. ush good_length; /* reduce lazy search above this match length */
  76765. ush max_lazy; /* do not perform lazy search above this match length */
  76766. ush nice_length; /* quit search above this match length */
  76767. ush max_chain;
  76768. compress_func func;
  76769. } config;
  76770. #ifdef FASTEST
  76771. local const config configuration_table[2] = {
  76772. /* good lazy nice chain */
  76773. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76774. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  76775. #else
  76776. local const config configuration_table[10] = {
  76777. /* good lazy nice chain */
  76778. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  76779. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  76780. /* 2 */ {4, 5, 16, 8, deflate_fast},
  76781. /* 3 */ {4, 6, 32, 32, deflate_fast},
  76782. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  76783. /* 5 */ {8, 16, 32, 32, deflate_slow},
  76784. /* 6 */ {8, 16, 128, 128, deflate_slow},
  76785. /* 7 */ {8, 32, 128, 256, deflate_slow},
  76786. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  76787. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  76788. #endif
  76789. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  76790. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  76791. * meaning.
  76792. */
  76793. #define EQUAL 0
  76794. /* result of memcmp for equal strings */
  76795. #ifndef NO_DUMMY_DECL
  76796. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  76797. #endif
  76798. /* ===========================================================================
  76799. * Update a hash value with the given input byte
  76800. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  76801. * input characters, so that a running hash key can be computed from the
  76802. * previous key instead of complete recalculation each time.
  76803. */
  76804. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  76805. /* ===========================================================================
  76806. * Insert string str in the dictionary and set match_head to the previous head
  76807. * of the hash chain (the most recent string with same hash key). Return
  76808. * the previous length of the hash chain.
  76809. * If this file is compiled with -DFASTEST, the compression level is forced
  76810. * to 1, and no hash chains are maintained.
  76811. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  76812. * input characters and the first MIN_MATCH bytes of str are valid
  76813. * (except for the last MIN_MATCH-1 bytes of the input file).
  76814. */
  76815. #ifdef FASTEST
  76816. #define INSERT_STRING(s, str, match_head) \
  76817. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76818. match_head = s->head[s->ins_h], \
  76819. s->head[s->ins_h] = (Pos)(str))
  76820. #else
  76821. #define INSERT_STRING(s, str, match_head) \
  76822. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  76823. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  76824. s->head[s->ins_h] = (Pos)(str))
  76825. #endif
  76826. /* ===========================================================================
  76827. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  76828. * prev[] will be initialized on the fly.
  76829. */
  76830. #define CLEAR_HASH(s) \
  76831. s->head[s->hash_size-1] = NIL; \
  76832. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  76833. /* ========================================================================= */
  76834. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  76835. {
  76836. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  76837. Z_DEFAULT_STRATEGY, version, stream_size);
  76838. /* To do: ignore strm->next_in if we use it as window */
  76839. }
  76840. /* ========================================================================= */
  76841. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  76842. {
  76843. deflate_state *s;
  76844. int wrap = 1;
  76845. static const char my_version[] = ZLIB_VERSION;
  76846. ushf *overlay;
  76847. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  76848. * output size for (length,distance) codes is <= 24 bits.
  76849. */
  76850. if (version == Z_NULL || version[0] != my_version[0] ||
  76851. stream_size != sizeof(z_stream)) {
  76852. return Z_VERSION_ERROR;
  76853. }
  76854. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76855. strm->msg = Z_NULL;
  76856. if (strm->zalloc == (alloc_func)0) {
  76857. strm->zalloc = zcalloc;
  76858. strm->opaque = (voidpf)0;
  76859. }
  76860. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76861. #ifdef FASTEST
  76862. if (level != 0) level = 1;
  76863. #else
  76864. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  76865. #endif
  76866. if (windowBits < 0) { /* suppress zlib wrapper */
  76867. wrap = 0;
  76868. windowBits = -windowBits;
  76869. }
  76870. #ifdef GZIP
  76871. else if (windowBits > 15) {
  76872. wrap = 2; /* write gzip wrapper instead */
  76873. windowBits -= 16;
  76874. }
  76875. #endif
  76876. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  76877. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  76878. strategy < 0 || strategy > Z_FIXED) {
  76879. return Z_STREAM_ERROR;
  76880. }
  76881. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  76882. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  76883. if (s == Z_NULL) return Z_MEM_ERROR;
  76884. strm->state = (struct internal_state FAR *)s;
  76885. s->strm = strm;
  76886. s->wrap = wrap;
  76887. s->gzhead = Z_NULL;
  76888. s->w_bits = windowBits;
  76889. s->w_size = 1 << s->w_bits;
  76890. s->w_mask = s->w_size - 1;
  76891. s->hash_bits = memLevel + 7;
  76892. s->hash_size = 1 << s->hash_bits;
  76893. s->hash_mask = s->hash_size - 1;
  76894. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  76895. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  76896. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  76897. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  76898. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  76899. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  76900. s->pending_buf = (uchf *) overlay;
  76901. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  76902. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  76903. s->pending_buf == Z_NULL) {
  76904. s->status = FINISH_STATE;
  76905. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  76906. deflateEnd (strm);
  76907. return Z_MEM_ERROR;
  76908. }
  76909. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  76910. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  76911. s->level = level;
  76912. s->strategy = strategy;
  76913. s->method = (Byte)method;
  76914. return deflateReset(strm);
  76915. }
  76916. /* ========================================================================= */
  76917. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  76918. {
  76919. deflate_state *s;
  76920. uInt length = dictLength;
  76921. uInt n;
  76922. IPos hash_head = 0;
  76923. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  76924. strm->state->wrap == 2 ||
  76925. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  76926. return Z_STREAM_ERROR;
  76927. s = strm->state;
  76928. if (s->wrap)
  76929. strm->adler = adler32(strm->adler, dictionary, dictLength);
  76930. if (length < MIN_MATCH) return Z_OK;
  76931. if (length > MAX_DIST(s)) {
  76932. length = MAX_DIST(s);
  76933. dictionary += dictLength - length; /* use the tail of the dictionary */
  76934. }
  76935. zmemcpy(s->window, dictionary, length);
  76936. s->strstart = length;
  76937. s->block_start = (long)length;
  76938. /* Insert all strings in the hash table (except for the last two bytes).
  76939. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  76940. * call of fill_window.
  76941. */
  76942. s->ins_h = s->window[0];
  76943. UPDATE_HASH(s, s->ins_h, s->window[1]);
  76944. for (n = 0; n <= length - MIN_MATCH; n++) {
  76945. INSERT_STRING(s, n, hash_head);
  76946. }
  76947. if (hash_head) hash_head = 0; /* to make compiler happy */
  76948. return Z_OK;
  76949. }
  76950. /* ========================================================================= */
  76951. int ZEXPORT deflateReset (z_streamp strm)
  76952. {
  76953. deflate_state *s;
  76954. if (strm == Z_NULL || strm->state == Z_NULL ||
  76955. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  76956. return Z_STREAM_ERROR;
  76957. }
  76958. strm->total_in = strm->total_out = 0;
  76959. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  76960. strm->data_type = Z_UNKNOWN;
  76961. s = (deflate_state *)strm->state;
  76962. s->pending = 0;
  76963. s->pending_out = s->pending_buf;
  76964. if (s->wrap < 0) {
  76965. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  76966. }
  76967. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  76968. strm->adler =
  76969. #ifdef GZIP
  76970. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  76971. #endif
  76972. adler32(0L, Z_NULL, 0);
  76973. s->last_flush = Z_NO_FLUSH;
  76974. _tr_init(s);
  76975. lm_init(s);
  76976. return Z_OK;
  76977. }
  76978. /* ========================================================================= */
  76979. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  76980. {
  76981. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76982. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  76983. strm->state->gzhead = head;
  76984. return Z_OK;
  76985. }
  76986. /* ========================================================================= */
  76987. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  76988. {
  76989. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76990. strm->state->bi_valid = bits;
  76991. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  76992. return Z_OK;
  76993. }
  76994. /* ========================================================================= */
  76995. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  76996. {
  76997. deflate_state *s;
  76998. compress_func func;
  76999. int err = Z_OK;
  77000. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77001. s = strm->state;
  77002. #ifdef FASTEST
  77003. if (level != 0) level = 1;
  77004. #else
  77005. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  77006. #endif
  77007. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  77008. return Z_STREAM_ERROR;
  77009. }
  77010. func = configuration_table[s->level].func;
  77011. if (func != configuration_table[level].func && strm->total_in != 0) {
  77012. /* Flush the last buffer: */
  77013. err = deflate(strm, Z_PARTIAL_FLUSH);
  77014. }
  77015. if (s->level != level) {
  77016. s->level = level;
  77017. s->max_lazy_match = configuration_table[level].max_lazy;
  77018. s->good_match = configuration_table[level].good_length;
  77019. s->nice_match = configuration_table[level].nice_length;
  77020. s->max_chain_length = configuration_table[level].max_chain;
  77021. }
  77022. s->strategy = strategy;
  77023. return err;
  77024. }
  77025. /* ========================================================================= */
  77026. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  77027. {
  77028. deflate_state *s;
  77029. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77030. s = strm->state;
  77031. s->good_match = good_length;
  77032. s->max_lazy_match = max_lazy;
  77033. s->nice_match = nice_length;
  77034. s->max_chain_length = max_chain;
  77035. return Z_OK;
  77036. }
  77037. /* =========================================================================
  77038. * For the default windowBits of 15 and memLevel of 8, this function returns
  77039. * a close to exact, as well as small, upper bound on the compressed size.
  77040. * They are coded as constants here for a reason--if the #define's are
  77041. * changed, then this function needs to be changed as well. The return
  77042. * value for 15 and 8 only works for those exact settings.
  77043. *
  77044. * For any setting other than those defaults for windowBits and memLevel,
  77045. * the value returned is a conservative worst case for the maximum expansion
  77046. * resulting from using fixed blocks instead of stored blocks, which deflate
  77047. * can emit on compressed data for some combinations of the parameters.
  77048. *
  77049. * This function could be more sophisticated to provide closer upper bounds
  77050. * for every combination of windowBits and memLevel, as well as wrap.
  77051. * But even the conservative upper bound of about 14% expansion does not
  77052. * seem onerous for output buffer allocation.
  77053. */
  77054. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  77055. {
  77056. deflate_state *s;
  77057. uLong destLen;
  77058. /* conservative upper bound */
  77059. destLen = sourceLen +
  77060. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  77061. /* if can't get parameters, return conservative bound */
  77062. if (strm == Z_NULL || strm->state == Z_NULL)
  77063. return destLen;
  77064. /* if not default parameters, return conservative bound */
  77065. s = strm->state;
  77066. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  77067. return destLen;
  77068. /* default settings: return tight bound for that case */
  77069. return compressBound(sourceLen);
  77070. }
  77071. /* =========================================================================
  77072. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  77073. * IN assertion: the stream state is correct and there is enough room in
  77074. * pending_buf.
  77075. */
  77076. local void putShortMSB (deflate_state *s, uInt b)
  77077. {
  77078. put_byte(s, (Byte)(b >> 8));
  77079. put_byte(s, (Byte)(b & 0xff));
  77080. }
  77081. /* =========================================================================
  77082. * Flush as much pending output as possible. All deflate() output goes
  77083. * through this function so some applications may wish to modify it
  77084. * to avoid allocating a large strm->next_out buffer and copying into it.
  77085. * (See also read_buf()).
  77086. */
  77087. local void flush_pending (z_streamp strm)
  77088. {
  77089. unsigned len = strm->state->pending;
  77090. if (len > strm->avail_out) len = strm->avail_out;
  77091. if (len == 0) return;
  77092. zmemcpy(strm->next_out, strm->state->pending_out, len);
  77093. strm->next_out += len;
  77094. strm->state->pending_out += len;
  77095. strm->total_out += len;
  77096. strm->avail_out -= len;
  77097. strm->state->pending -= len;
  77098. if (strm->state->pending == 0) {
  77099. strm->state->pending_out = strm->state->pending_buf;
  77100. }
  77101. }
  77102. /* ========================================================================= */
  77103. int ZEXPORT deflate (z_streamp strm, int flush)
  77104. {
  77105. int old_flush; /* value of flush param for previous deflate call */
  77106. deflate_state *s;
  77107. if (strm == Z_NULL || strm->state == Z_NULL ||
  77108. flush > Z_FINISH || flush < 0) {
  77109. return Z_STREAM_ERROR;
  77110. }
  77111. s = strm->state;
  77112. if (strm->next_out == Z_NULL ||
  77113. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  77114. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  77115. ERR_RETURN(strm, Z_STREAM_ERROR);
  77116. }
  77117. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  77118. s->strm = strm; /* just in case */
  77119. old_flush = s->last_flush;
  77120. s->last_flush = flush;
  77121. /* Write the header */
  77122. if (s->status == INIT_STATE) {
  77123. #ifdef GZIP
  77124. if (s->wrap == 2) {
  77125. strm->adler = crc32(0L, Z_NULL, 0);
  77126. put_byte(s, 31);
  77127. put_byte(s, 139);
  77128. put_byte(s, 8);
  77129. if (s->gzhead == NULL) {
  77130. put_byte(s, 0);
  77131. put_byte(s, 0);
  77132. put_byte(s, 0);
  77133. put_byte(s, 0);
  77134. put_byte(s, 0);
  77135. put_byte(s, s->level == 9 ? 2 :
  77136. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77137. 4 : 0));
  77138. put_byte(s, OS_CODE);
  77139. s->status = BUSY_STATE;
  77140. }
  77141. else {
  77142. put_byte(s, (s->gzhead->text ? 1 : 0) +
  77143. (s->gzhead->hcrc ? 2 : 0) +
  77144. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  77145. (s->gzhead->name == Z_NULL ? 0 : 8) +
  77146. (s->gzhead->comment == Z_NULL ? 0 : 16)
  77147. );
  77148. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  77149. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  77150. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  77151. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  77152. put_byte(s, s->level == 9 ? 2 :
  77153. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  77154. 4 : 0));
  77155. put_byte(s, s->gzhead->os & 0xff);
  77156. if (s->gzhead->extra != NULL) {
  77157. put_byte(s, s->gzhead->extra_len & 0xff);
  77158. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  77159. }
  77160. if (s->gzhead->hcrc)
  77161. strm->adler = crc32(strm->adler, s->pending_buf,
  77162. s->pending);
  77163. s->gzindex = 0;
  77164. s->status = EXTRA_STATE;
  77165. }
  77166. }
  77167. else
  77168. #endif
  77169. {
  77170. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  77171. uInt level_flags;
  77172. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  77173. level_flags = 0;
  77174. else if (s->level < 6)
  77175. level_flags = 1;
  77176. else if (s->level == 6)
  77177. level_flags = 2;
  77178. else
  77179. level_flags = 3;
  77180. header |= (level_flags << 6);
  77181. if (s->strstart != 0) header |= PRESET_DICT;
  77182. header += 31 - (header % 31);
  77183. s->status = BUSY_STATE;
  77184. putShortMSB(s, header);
  77185. /* Save the adler32 of the preset dictionary: */
  77186. if (s->strstart != 0) {
  77187. putShortMSB(s, (uInt)(strm->adler >> 16));
  77188. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77189. }
  77190. strm->adler = adler32(0L, Z_NULL, 0);
  77191. }
  77192. }
  77193. #ifdef GZIP
  77194. if (s->status == EXTRA_STATE) {
  77195. if (s->gzhead->extra != NULL) {
  77196. uInt beg = s->pending; /* start of bytes to update crc */
  77197. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  77198. if (s->pending == s->pending_buf_size) {
  77199. if (s->gzhead->hcrc && s->pending > beg)
  77200. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77201. s->pending - beg);
  77202. flush_pending(strm);
  77203. beg = s->pending;
  77204. if (s->pending == s->pending_buf_size)
  77205. break;
  77206. }
  77207. put_byte(s, s->gzhead->extra[s->gzindex]);
  77208. s->gzindex++;
  77209. }
  77210. if (s->gzhead->hcrc && s->pending > beg)
  77211. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77212. s->pending - beg);
  77213. if (s->gzindex == s->gzhead->extra_len) {
  77214. s->gzindex = 0;
  77215. s->status = NAME_STATE;
  77216. }
  77217. }
  77218. else
  77219. s->status = NAME_STATE;
  77220. }
  77221. if (s->status == NAME_STATE) {
  77222. if (s->gzhead->name != NULL) {
  77223. uInt beg = s->pending; /* start of bytes to update crc */
  77224. int val;
  77225. do {
  77226. if (s->pending == s->pending_buf_size) {
  77227. if (s->gzhead->hcrc && s->pending > beg)
  77228. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77229. s->pending - beg);
  77230. flush_pending(strm);
  77231. beg = s->pending;
  77232. if (s->pending == s->pending_buf_size) {
  77233. val = 1;
  77234. break;
  77235. }
  77236. }
  77237. val = s->gzhead->name[s->gzindex++];
  77238. put_byte(s, val);
  77239. } while (val != 0);
  77240. if (s->gzhead->hcrc && s->pending > beg)
  77241. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77242. s->pending - beg);
  77243. if (val == 0) {
  77244. s->gzindex = 0;
  77245. s->status = COMMENT_STATE;
  77246. }
  77247. }
  77248. else
  77249. s->status = COMMENT_STATE;
  77250. }
  77251. if (s->status == COMMENT_STATE) {
  77252. if (s->gzhead->comment != NULL) {
  77253. uInt beg = s->pending; /* start of bytes to update crc */
  77254. int val;
  77255. do {
  77256. if (s->pending == s->pending_buf_size) {
  77257. if (s->gzhead->hcrc && s->pending > beg)
  77258. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77259. s->pending - beg);
  77260. flush_pending(strm);
  77261. beg = s->pending;
  77262. if (s->pending == s->pending_buf_size) {
  77263. val = 1;
  77264. break;
  77265. }
  77266. }
  77267. val = s->gzhead->comment[s->gzindex++];
  77268. put_byte(s, val);
  77269. } while (val != 0);
  77270. if (s->gzhead->hcrc && s->pending > beg)
  77271. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  77272. s->pending - beg);
  77273. if (val == 0)
  77274. s->status = HCRC_STATE;
  77275. }
  77276. else
  77277. s->status = HCRC_STATE;
  77278. }
  77279. if (s->status == HCRC_STATE) {
  77280. if (s->gzhead->hcrc) {
  77281. if (s->pending + 2 > s->pending_buf_size)
  77282. flush_pending(strm);
  77283. if (s->pending + 2 <= s->pending_buf_size) {
  77284. put_byte(s, (Byte)(strm->adler & 0xff));
  77285. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77286. strm->adler = crc32(0L, Z_NULL, 0);
  77287. s->status = BUSY_STATE;
  77288. }
  77289. }
  77290. else
  77291. s->status = BUSY_STATE;
  77292. }
  77293. #endif
  77294. /* Flush as much pending output as possible */
  77295. if (s->pending != 0) {
  77296. flush_pending(strm);
  77297. if (strm->avail_out == 0) {
  77298. /* Since avail_out is 0, deflate will be called again with
  77299. * more output space, but possibly with both pending and
  77300. * avail_in equal to zero. There won't be anything to do,
  77301. * but this is not an error situation so make sure we
  77302. * return OK instead of BUF_ERROR at next call of deflate:
  77303. */
  77304. s->last_flush = -1;
  77305. return Z_OK;
  77306. }
  77307. /* Make sure there is something to do and avoid duplicate consecutive
  77308. * flushes. For repeated and useless calls with Z_FINISH, we keep
  77309. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  77310. */
  77311. } else if (strm->avail_in == 0 && flush <= old_flush &&
  77312. flush != Z_FINISH) {
  77313. ERR_RETURN(strm, Z_BUF_ERROR);
  77314. }
  77315. /* User must not provide more input after the first FINISH: */
  77316. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  77317. ERR_RETURN(strm, Z_BUF_ERROR);
  77318. }
  77319. /* Start a new block or continue the current one.
  77320. */
  77321. if (strm->avail_in != 0 || s->lookahead != 0 ||
  77322. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  77323. block_state bstate;
  77324. bstate = (*(configuration_table[s->level].func))(s, flush);
  77325. if (bstate == finish_started || bstate == finish_done) {
  77326. s->status = FINISH_STATE;
  77327. }
  77328. if (bstate == need_more || bstate == finish_started) {
  77329. if (strm->avail_out == 0) {
  77330. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  77331. }
  77332. return Z_OK;
  77333. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  77334. * of deflate should use the same flush parameter to make sure
  77335. * that the flush is complete. So we don't have to output an
  77336. * empty block here, this will be done at next call. This also
  77337. * ensures that for a very small output buffer, we emit at most
  77338. * one empty block.
  77339. */
  77340. }
  77341. if (bstate == block_done) {
  77342. if (flush == Z_PARTIAL_FLUSH) {
  77343. _tr_align(s);
  77344. } else { /* FULL_FLUSH or SYNC_FLUSH */
  77345. _tr_stored_block(s, (char*)0, 0L, 0);
  77346. /* For a full flush, this empty block will be recognized
  77347. * as a special marker by inflate_sync().
  77348. */
  77349. if (flush == Z_FULL_FLUSH) {
  77350. CLEAR_HASH(s); /* forget history */
  77351. }
  77352. }
  77353. flush_pending(strm);
  77354. if (strm->avail_out == 0) {
  77355. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  77356. return Z_OK;
  77357. }
  77358. }
  77359. }
  77360. Assert(strm->avail_out > 0, "bug2");
  77361. if (flush != Z_FINISH) return Z_OK;
  77362. if (s->wrap <= 0) return Z_STREAM_END;
  77363. /* Write the trailer */
  77364. #ifdef GZIP
  77365. if (s->wrap == 2) {
  77366. put_byte(s, (Byte)(strm->adler & 0xff));
  77367. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  77368. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  77369. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  77370. put_byte(s, (Byte)(strm->total_in & 0xff));
  77371. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  77372. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  77373. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  77374. }
  77375. else
  77376. #endif
  77377. {
  77378. putShortMSB(s, (uInt)(strm->adler >> 16));
  77379. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  77380. }
  77381. flush_pending(strm);
  77382. /* If avail_out is zero, the application will call deflate again
  77383. * to flush the rest.
  77384. */
  77385. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  77386. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  77387. }
  77388. /* ========================================================================= */
  77389. int ZEXPORT deflateEnd (z_streamp strm)
  77390. {
  77391. int status;
  77392. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77393. status = strm->state->status;
  77394. if (status != INIT_STATE &&
  77395. status != EXTRA_STATE &&
  77396. status != NAME_STATE &&
  77397. status != COMMENT_STATE &&
  77398. status != HCRC_STATE &&
  77399. status != BUSY_STATE &&
  77400. status != FINISH_STATE) {
  77401. return Z_STREAM_ERROR;
  77402. }
  77403. /* Deallocate in reverse order of allocations: */
  77404. TRY_FREE(strm, strm->state->pending_buf);
  77405. TRY_FREE(strm, strm->state->head);
  77406. TRY_FREE(strm, strm->state->prev);
  77407. TRY_FREE(strm, strm->state->window);
  77408. ZFREE(strm, strm->state);
  77409. strm->state = Z_NULL;
  77410. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  77411. }
  77412. /* =========================================================================
  77413. * Copy the source state to the destination state.
  77414. * To simplify the source, this is not supported for 16-bit MSDOS (which
  77415. * doesn't have enough memory anyway to duplicate compression states).
  77416. */
  77417. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  77418. {
  77419. #ifdef MAXSEG_64K
  77420. return Z_STREAM_ERROR;
  77421. #else
  77422. deflate_state *ds;
  77423. deflate_state *ss;
  77424. ushf *overlay;
  77425. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  77426. return Z_STREAM_ERROR;
  77427. }
  77428. ss = source->state;
  77429. zmemcpy(dest, source, sizeof(z_stream));
  77430. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  77431. if (ds == Z_NULL) return Z_MEM_ERROR;
  77432. dest->state = (struct internal_state FAR *) ds;
  77433. zmemcpy(ds, ss, sizeof(deflate_state));
  77434. ds->strm = dest;
  77435. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  77436. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  77437. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  77438. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  77439. ds->pending_buf = (uchf *) overlay;
  77440. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  77441. ds->pending_buf == Z_NULL) {
  77442. deflateEnd (dest);
  77443. return Z_MEM_ERROR;
  77444. }
  77445. /* following zmemcpy do not work for 16-bit MSDOS */
  77446. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  77447. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  77448. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  77449. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  77450. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  77451. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  77452. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  77453. ds->l_desc.dyn_tree = ds->dyn_ltree;
  77454. ds->d_desc.dyn_tree = ds->dyn_dtree;
  77455. ds->bl_desc.dyn_tree = ds->bl_tree;
  77456. return Z_OK;
  77457. #endif /* MAXSEG_64K */
  77458. }
  77459. /* ===========================================================================
  77460. * Read a new buffer from the current input stream, update the adler32
  77461. * and total number of bytes read. All deflate() input goes through
  77462. * this function so some applications may wish to modify it to avoid
  77463. * allocating a large strm->next_in buffer and copying from it.
  77464. * (See also flush_pending()).
  77465. */
  77466. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  77467. {
  77468. unsigned len = strm->avail_in;
  77469. if (len > size) len = size;
  77470. if (len == 0) return 0;
  77471. strm->avail_in -= len;
  77472. if (strm->state->wrap == 1) {
  77473. strm->adler = adler32(strm->adler, strm->next_in, len);
  77474. }
  77475. #ifdef GZIP
  77476. else if (strm->state->wrap == 2) {
  77477. strm->adler = crc32(strm->adler, strm->next_in, len);
  77478. }
  77479. #endif
  77480. zmemcpy(buf, strm->next_in, len);
  77481. strm->next_in += len;
  77482. strm->total_in += len;
  77483. return (int)len;
  77484. }
  77485. /* ===========================================================================
  77486. * Initialize the "longest match" routines for a new zlib stream
  77487. */
  77488. local void lm_init (deflate_state *s)
  77489. {
  77490. s->window_size = (ulg)2L*s->w_size;
  77491. CLEAR_HASH(s);
  77492. /* Set the default configuration parameters:
  77493. */
  77494. s->max_lazy_match = configuration_table[s->level].max_lazy;
  77495. s->good_match = configuration_table[s->level].good_length;
  77496. s->nice_match = configuration_table[s->level].nice_length;
  77497. s->max_chain_length = configuration_table[s->level].max_chain;
  77498. s->strstart = 0;
  77499. s->block_start = 0L;
  77500. s->lookahead = 0;
  77501. s->match_length = s->prev_length = MIN_MATCH-1;
  77502. s->match_available = 0;
  77503. s->ins_h = 0;
  77504. #ifndef FASTEST
  77505. #ifdef ASMV
  77506. match_init(); /* initialize the asm code */
  77507. #endif
  77508. #endif
  77509. }
  77510. #ifndef FASTEST
  77511. /* ===========================================================================
  77512. * Set match_start to the longest match starting at the given string and
  77513. * return its length. Matches shorter or equal to prev_length are discarded,
  77514. * in which case the result is equal to prev_length and match_start is
  77515. * garbage.
  77516. * IN assertions: cur_match is the head of the hash chain for the current
  77517. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  77518. * OUT assertion: the match length is not greater than s->lookahead.
  77519. */
  77520. #ifndef ASMV
  77521. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  77522. * match.S. The code will be functionally equivalent.
  77523. */
  77524. local uInt longest_match(deflate_state *s, IPos cur_match)
  77525. {
  77526. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  77527. register Bytef *scan = s->window + s->strstart; /* current string */
  77528. register Bytef *match; /* matched string */
  77529. register int len; /* length of current match */
  77530. int best_len = s->prev_length; /* best match length so far */
  77531. int nice_match = s->nice_match; /* stop if match long enough */
  77532. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  77533. s->strstart - (IPos)MAX_DIST(s) : NIL;
  77534. /* Stop when cur_match becomes <= limit. To simplify the code,
  77535. * we prevent matches with the string of window index 0.
  77536. */
  77537. Posf *prev = s->prev;
  77538. uInt wmask = s->w_mask;
  77539. #ifdef UNALIGNED_OK
  77540. /* Compare two bytes at a time. Note: this is not always beneficial.
  77541. * Try with and without -DUNALIGNED_OK to check.
  77542. */
  77543. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  77544. register ush scan_start = *(ushf*)scan;
  77545. register ush scan_end = *(ushf*)(scan+best_len-1);
  77546. #else
  77547. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77548. register Byte scan_end1 = scan[best_len-1];
  77549. register Byte scan_end = scan[best_len];
  77550. #endif
  77551. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77552. * It is easy to get rid of this optimization if necessary.
  77553. */
  77554. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77555. /* Do not waste too much time if we already have a good match: */
  77556. if (s->prev_length >= s->good_match) {
  77557. chain_length >>= 2;
  77558. }
  77559. /* Do not look for matches beyond the end of the input. This is necessary
  77560. * to make deflate deterministic.
  77561. */
  77562. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  77563. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77564. do {
  77565. Assert(cur_match < s->strstart, "no future");
  77566. match = s->window + cur_match;
  77567. /* Skip to next match if the match length cannot increase
  77568. * or if the match length is less than 2. Note that the checks below
  77569. * for insufficient lookahead only occur occasionally for performance
  77570. * reasons. Therefore uninitialized memory will be accessed, and
  77571. * conditional jumps will be made that depend on those values.
  77572. * However the length of the match is limited to the lookahead, so
  77573. * the output of deflate is not affected by the uninitialized values.
  77574. */
  77575. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  77576. /* This code assumes sizeof(unsigned short) == 2. Do not use
  77577. * UNALIGNED_OK if your compiler uses a different size.
  77578. */
  77579. if (*(ushf*)(match+best_len-1) != scan_end ||
  77580. *(ushf*)match != scan_start) continue;
  77581. /* It is not necessary to compare scan[2] and match[2] since they are
  77582. * always equal when the other bytes match, given that the hash keys
  77583. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  77584. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  77585. * lookahead only every 4th comparison; the 128th check will be made
  77586. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  77587. * necessary to put more guard bytes at the end of the window, or
  77588. * to check more often for insufficient lookahead.
  77589. */
  77590. Assert(scan[2] == match[2], "scan[2]?");
  77591. scan++, match++;
  77592. do {
  77593. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77594. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77595. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77596. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  77597. scan < strend);
  77598. /* The funny "do {}" generates better code on most compilers */
  77599. /* Here, scan <= window+strstart+257 */
  77600. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77601. if (*scan == *match) scan++;
  77602. len = (MAX_MATCH - 1) - (int)(strend-scan);
  77603. scan = strend - (MAX_MATCH-1);
  77604. #else /* UNALIGNED_OK */
  77605. if (match[best_len] != scan_end ||
  77606. match[best_len-1] != scan_end1 ||
  77607. *match != *scan ||
  77608. *++match != scan[1]) continue;
  77609. /* The check at best_len-1 can be removed because it will be made
  77610. * again later. (This heuristic is not always a win.)
  77611. * It is not necessary to compare scan[2] and match[2] since they
  77612. * are always equal when the other bytes match, given that
  77613. * the hash keys are equal and that HASH_BITS >= 8.
  77614. */
  77615. scan += 2, match++;
  77616. Assert(*scan == *match, "match[2]?");
  77617. /* We check for insufficient lookahead only every 8th comparison;
  77618. * the 256th check will be made at strstart+258.
  77619. */
  77620. do {
  77621. } while (*++scan == *++match && *++scan == *++match &&
  77622. *++scan == *++match && *++scan == *++match &&
  77623. *++scan == *++match && *++scan == *++match &&
  77624. *++scan == *++match && *++scan == *++match &&
  77625. scan < strend);
  77626. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77627. len = MAX_MATCH - (int)(strend - scan);
  77628. scan = strend - MAX_MATCH;
  77629. #endif /* UNALIGNED_OK */
  77630. if (len > best_len) {
  77631. s->match_start = cur_match;
  77632. best_len = len;
  77633. if (len >= nice_match) break;
  77634. #ifdef UNALIGNED_OK
  77635. scan_end = *(ushf*)(scan+best_len-1);
  77636. #else
  77637. scan_end1 = scan[best_len-1];
  77638. scan_end = scan[best_len];
  77639. #endif
  77640. }
  77641. } while ((cur_match = prev[cur_match & wmask]) > limit
  77642. && --chain_length != 0);
  77643. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  77644. return s->lookahead;
  77645. }
  77646. #endif /* ASMV */
  77647. #endif /* FASTEST */
  77648. /* ---------------------------------------------------------------------------
  77649. * Optimized version for level == 1 or strategy == Z_RLE only
  77650. */
  77651. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  77652. {
  77653. register Bytef *scan = s->window + s->strstart; /* current string */
  77654. register Bytef *match; /* matched string */
  77655. register int len; /* length of current match */
  77656. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  77657. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  77658. * It is easy to get rid of this optimization if necessary.
  77659. */
  77660. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  77661. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  77662. Assert(cur_match < s->strstart, "no future");
  77663. match = s->window + cur_match;
  77664. /* Return failure if the match length is less than 2:
  77665. */
  77666. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  77667. /* The check at best_len-1 can be removed because it will be made
  77668. * again later. (This heuristic is not always a win.)
  77669. * It is not necessary to compare scan[2] and match[2] since they
  77670. * are always equal when the other bytes match, given that
  77671. * the hash keys are equal and that HASH_BITS >= 8.
  77672. */
  77673. scan += 2, match += 2;
  77674. Assert(*scan == *match, "match[2]?");
  77675. /* We check for insufficient lookahead only every 8th comparison;
  77676. * the 256th check will be made at strstart+258.
  77677. */
  77678. do {
  77679. } while (*++scan == *++match && *++scan == *++match &&
  77680. *++scan == *++match && *++scan == *++match &&
  77681. *++scan == *++match && *++scan == *++match &&
  77682. *++scan == *++match && *++scan == *++match &&
  77683. scan < strend);
  77684. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  77685. len = MAX_MATCH - (int)(strend - scan);
  77686. if (len < MIN_MATCH) return MIN_MATCH - 1;
  77687. s->match_start = cur_match;
  77688. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  77689. }
  77690. #ifdef DEBUG
  77691. /* ===========================================================================
  77692. * Check that the match at match_start is indeed a match.
  77693. */
  77694. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  77695. {
  77696. /* check that the match is indeed a match */
  77697. if (zmemcmp(s->window + match,
  77698. s->window + start, length) != EQUAL) {
  77699. fprintf(stderr, " start %u, match %u, length %d\n",
  77700. start, match, length);
  77701. do {
  77702. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  77703. } while (--length != 0);
  77704. z_error("invalid match");
  77705. }
  77706. if (z_verbose > 1) {
  77707. fprintf(stderr,"\\[%d,%d]", start-match, length);
  77708. do { putc(s->window[start++], stderr); } while (--length != 0);
  77709. }
  77710. }
  77711. #else
  77712. # define check_match(s, start, match, length)
  77713. #endif /* DEBUG */
  77714. /* ===========================================================================
  77715. * Fill the window when the lookahead becomes insufficient.
  77716. * Updates strstart and lookahead.
  77717. *
  77718. * IN assertion: lookahead < MIN_LOOKAHEAD
  77719. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  77720. * At least one byte has been read, or avail_in == 0; reads are
  77721. * performed for at least two bytes (required for the zip translate_eol
  77722. * option -- not supported here).
  77723. */
  77724. local void fill_window (deflate_state *s)
  77725. {
  77726. register unsigned n, m;
  77727. register Posf *p;
  77728. unsigned more; /* Amount of free space at the end of the window. */
  77729. uInt wsize = s->w_size;
  77730. do {
  77731. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  77732. /* Deal with !@#$% 64K limit: */
  77733. if (sizeof(int) <= 2) {
  77734. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  77735. more = wsize;
  77736. } else if (more == (unsigned)(-1)) {
  77737. /* Very unlikely, but possible on 16 bit machine if
  77738. * strstart == 0 && lookahead == 1 (input done a byte at time)
  77739. */
  77740. more--;
  77741. }
  77742. }
  77743. /* If the window is almost full and there is insufficient lookahead,
  77744. * move the upper half to the lower one to make room in the upper half.
  77745. */
  77746. if (s->strstart >= wsize+MAX_DIST(s)) {
  77747. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  77748. s->match_start -= wsize;
  77749. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  77750. s->block_start -= (long) wsize;
  77751. /* Slide the hash table (could be avoided with 32 bit values
  77752. at the expense of memory usage). We slide even when level == 0
  77753. to keep the hash table consistent if we switch back to level > 0
  77754. later. (Using level 0 permanently is not an optimal usage of
  77755. zlib, so we don't care about this pathological case.)
  77756. */
  77757. /* %%% avoid this when Z_RLE */
  77758. n = s->hash_size;
  77759. p = &s->head[n];
  77760. do {
  77761. m = *--p;
  77762. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77763. } while (--n);
  77764. n = wsize;
  77765. #ifndef FASTEST
  77766. p = &s->prev[n];
  77767. do {
  77768. m = *--p;
  77769. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  77770. /* If n is not on any hash chain, prev[n] is garbage but
  77771. * its value will never be used.
  77772. */
  77773. } while (--n);
  77774. #endif
  77775. more += wsize;
  77776. }
  77777. if (s->strm->avail_in == 0) return;
  77778. /* If there was no sliding:
  77779. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  77780. * more == window_size - lookahead - strstart
  77781. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  77782. * => more >= window_size - 2*WSIZE + 2
  77783. * In the BIG_MEM or MMAP case (not yet supported),
  77784. * window_size == input_size + MIN_LOOKAHEAD &&
  77785. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  77786. * Otherwise, window_size == 2*WSIZE so more >= 2.
  77787. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  77788. */
  77789. Assert(more >= 2, "more < 2");
  77790. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  77791. s->lookahead += n;
  77792. /* Initialize the hash value now that we have some input: */
  77793. if (s->lookahead >= MIN_MATCH) {
  77794. s->ins_h = s->window[s->strstart];
  77795. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77796. #if MIN_MATCH != 3
  77797. Call UPDATE_HASH() MIN_MATCH-3 more times
  77798. #endif
  77799. }
  77800. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  77801. * but this is not important since only literal bytes will be emitted.
  77802. */
  77803. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  77804. }
  77805. /* ===========================================================================
  77806. * Flush the current block, with given end-of-file flag.
  77807. * IN assertion: strstart is set to the end of the current match.
  77808. */
  77809. #define FLUSH_BLOCK_ONLY(s, eof) { \
  77810. _tr_flush_block(s, (s->block_start >= 0L ? \
  77811. (charf *)&s->window[(unsigned)s->block_start] : \
  77812. (charf *)Z_NULL), \
  77813. (ulg)((long)s->strstart - s->block_start), \
  77814. (eof)); \
  77815. s->block_start = s->strstart; \
  77816. flush_pending(s->strm); \
  77817. Tracev((stderr,"[FLUSH]")); \
  77818. }
  77819. /* Same but force premature exit if necessary. */
  77820. #define FLUSH_BLOCK(s, eof) { \
  77821. FLUSH_BLOCK_ONLY(s, eof); \
  77822. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  77823. }
  77824. /* ===========================================================================
  77825. * Copy without compression as much as possible from the input stream, return
  77826. * the current block state.
  77827. * This function does not insert new strings in the dictionary since
  77828. * uncompressible data is probably not useful. This function is used
  77829. * only for the level=0 compression option.
  77830. * NOTE: this function should be optimized to avoid extra copying from
  77831. * window to pending_buf.
  77832. */
  77833. local block_state deflate_stored(deflate_state *s, int flush)
  77834. {
  77835. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  77836. * to pending_buf_size, and each stored block has a 5 byte header:
  77837. */
  77838. ulg max_block_size = 0xffff;
  77839. ulg max_start;
  77840. if (max_block_size > s->pending_buf_size - 5) {
  77841. max_block_size = s->pending_buf_size - 5;
  77842. }
  77843. /* Copy as much as possible from input to output: */
  77844. for (;;) {
  77845. /* Fill the window as much as possible: */
  77846. if (s->lookahead <= 1) {
  77847. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  77848. s->block_start >= (long)s->w_size, "slide too late");
  77849. fill_window(s);
  77850. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  77851. if (s->lookahead == 0) break; /* flush the current block */
  77852. }
  77853. Assert(s->block_start >= 0L, "block gone");
  77854. s->strstart += s->lookahead;
  77855. s->lookahead = 0;
  77856. /* Emit a stored block if pending_buf will be full: */
  77857. max_start = s->block_start + max_block_size;
  77858. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  77859. /* strstart == 0 is possible when wraparound on 16-bit machine */
  77860. s->lookahead = (uInt)(s->strstart - max_start);
  77861. s->strstart = (uInt)max_start;
  77862. FLUSH_BLOCK(s, 0);
  77863. }
  77864. /* Flush if we may have to slide, otherwise block_start may become
  77865. * negative and the data will be gone:
  77866. */
  77867. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  77868. FLUSH_BLOCK(s, 0);
  77869. }
  77870. }
  77871. FLUSH_BLOCK(s, flush == Z_FINISH);
  77872. return flush == Z_FINISH ? finish_done : block_done;
  77873. }
  77874. /* ===========================================================================
  77875. * Compress as much as possible from the input stream, return the current
  77876. * block state.
  77877. * This function does not perform lazy evaluation of matches and inserts
  77878. * new strings in the dictionary only for unmatched strings or for short
  77879. * matches. It is used only for the fast compression options.
  77880. */
  77881. local block_state deflate_fast(deflate_state *s, int flush)
  77882. {
  77883. IPos hash_head = NIL; /* head of the hash chain */
  77884. int bflush; /* set if current block must be flushed */
  77885. for (;;) {
  77886. /* Make sure that we always have enough lookahead, except
  77887. * at the end of the input file. We need MAX_MATCH bytes
  77888. * for the next match, plus MIN_MATCH bytes to insert the
  77889. * string following the next match.
  77890. */
  77891. if (s->lookahead < MIN_LOOKAHEAD) {
  77892. fill_window(s);
  77893. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77894. return need_more;
  77895. }
  77896. if (s->lookahead == 0) break; /* flush the current block */
  77897. }
  77898. /* Insert the string window[strstart .. strstart+2] in the
  77899. * dictionary, and set hash_head to the head of the hash chain:
  77900. */
  77901. if (s->lookahead >= MIN_MATCH) {
  77902. INSERT_STRING(s, s->strstart, hash_head);
  77903. }
  77904. /* Find the longest match, discarding those <= prev_length.
  77905. * At this point we have always match_length < MIN_MATCH
  77906. */
  77907. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  77908. /* To simplify the code, we prevent matches with the string
  77909. * of window index 0 (in particular we have to avoid a match
  77910. * of the string with itself at the start of the input file).
  77911. */
  77912. #ifdef FASTEST
  77913. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  77914. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  77915. s->match_length = longest_match_fast (s, hash_head);
  77916. }
  77917. #else
  77918. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  77919. s->match_length = longest_match (s, hash_head);
  77920. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  77921. s->match_length = longest_match_fast (s, hash_head);
  77922. }
  77923. #endif
  77924. /* longest_match() or longest_match_fast() sets match_start */
  77925. }
  77926. if (s->match_length >= MIN_MATCH) {
  77927. check_match(s, s->strstart, s->match_start, s->match_length);
  77928. _tr_tally_dist(s, s->strstart - s->match_start,
  77929. s->match_length - MIN_MATCH, bflush);
  77930. s->lookahead -= s->match_length;
  77931. /* Insert new strings in the hash table only if the match length
  77932. * is not too large. This saves time but degrades compression.
  77933. */
  77934. #ifndef FASTEST
  77935. if (s->match_length <= s->max_insert_length &&
  77936. s->lookahead >= MIN_MATCH) {
  77937. s->match_length--; /* string at strstart already in table */
  77938. do {
  77939. s->strstart++;
  77940. INSERT_STRING(s, s->strstart, hash_head);
  77941. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  77942. * always MIN_MATCH bytes ahead.
  77943. */
  77944. } while (--s->match_length != 0);
  77945. s->strstart++;
  77946. } else
  77947. #endif
  77948. {
  77949. s->strstart += s->match_length;
  77950. s->match_length = 0;
  77951. s->ins_h = s->window[s->strstart];
  77952. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  77953. #if MIN_MATCH != 3
  77954. Call UPDATE_HASH() MIN_MATCH-3 more times
  77955. #endif
  77956. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  77957. * matter since it will be recomputed at next deflate call.
  77958. */
  77959. }
  77960. } else {
  77961. /* No match, output a literal byte */
  77962. Tracevv((stderr,"%c", s->window[s->strstart]));
  77963. _tr_tally_lit (s, s->window[s->strstart], bflush);
  77964. s->lookahead--;
  77965. s->strstart++;
  77966. }
  77967. if (bflush) FLUSH_BLOCK(s, 0);
  77968. }
  77969. FLUSH_BLOCK(s, flush == Z_FINISH);
  77970. return flush == Z_FINISH ? finish_done : block_done;
  77971. }
  77972. #ifndef FASTEST
  77973. /* ===========================================================================
  77974. * Same as above, but achieves better compression. We use a lazy
  77975. * evaluation for matches: a match is finally adopted only if there is
  77976. * no better match at the next window position.
  77977. */
  77978. local block_state deflate_slow(deflate_state *s, int flush)
  77979. {
  77980. IPos hash_head = NIL; /* head of hash chain */
  77981. int bflush; /* set if current block must be flushed */
  77982. /* Process the input block. */
  77983. for (;;) {
  77984. /* Make sure that we always have enough lookahead, except
  77985. * at the end of the input file. We need MAX_MATCH bytes
  77986. * for the next match, plus MIN_MATCH bytes to insert the
  77987. * string following the next match.
  77988. */
  77989. if (s->lookahead < MIN_LOOKAHEAD) {
  77990. fill_window(s);
  77991. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  77992. return need_more;
  77993. }
  77994. if (s->lookahead == 0) break; /* flush the current block */
  77995. }
  77996. /* Insert the string window[strstart .. strstart+2] in the
  77997. * dictionary, and set hash_head to the head of the hash chain:
  77998. */
  77999. if (s->lookahead >= MIN_MATCH) {
  78000. INSERT_STRING(s, s->strstart, hash_head);
  78001. }
  78002. /* Find the longest match, discarding those <= prev_length.
  78003. */
  78004. s->prev_length = s->match_length, s->prev_match = s->match_start;
  78005. s->match_length = MIN_MATCH-1;
  78006. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  78007. s->strstart - hash_head <= MAX_DIST(s)) {
  78008. /* To simplify the code, we prevent matches with the string
  78009. * of window index 0 (in particular we have to avoid a match
  78010. * of the string with itself at the start of the input file).
  78011. */
  78012. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  78013. s->match_length = longest_match (s, hash_head);
  78014. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  78015. s->match_length = longest_match_fast (s, hash_head);
  78016. }
  78017. /* longest_match() or longest_match_fast() sets match_start */
  78018. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  78019. #if TOO_FAR <= 32767
  78020. || (s->match_length == MIN_MATCH &&
  78021. s->strstart - s->match_start > TOO_FAR)
  78022. #endif
  78023. )) {
  78024. /* If prev_match is also MIN_MATCH, match_start is garbage
  78025. * but we will ignore the current match anyway.
  78026. */
  78027. s->match_length = MIN_MATCH-1;
  78028. }
  78029. }
  78030. /* If there was a match at the previous step and the current
  78031. * match is not better, output the previous match:
  78032. */
  78033. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  78034. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  78035. /* Do not insert strings in hash table beyond this. */
  78036. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  78037. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  78038. s->prev_length - MIN_MATCH, bflush);
  78039. /* Insert in hash table all strings up to the end of the match.
  78040. * strstart-1 and strstart are already inserted. If there is not
  78041. * enough lookahead, the last two strings are not inserted in
  78042. * the hash table.
  78043. */
  78044. s->lookahead -= s->prev_length-1;
  78045. s->prev_length -= 2;
  78046. do {
  78047. if (++s->strstart <= max_insert) {
  78048. INSERT_STRING(s, s->strstart, hash_head);
  78049. }
  78050. } while (--s->prev_length != 0);
  78051. s->match_available = 0;
  78052. s->match_length = MIN_MATCH-1;
  78053. s->strstart++;
  78054. if (bflush) FLUSH_BLOCK(s, 0);
  78055. } else if (s->match_available) {
  78056. /* If there was no match at the previous position, output a
  78057. * single literal. If there was a match but the current match
  78058. * is longer, truncate the previous match to a single literal.
  78059. */
  78060. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78061. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78062. if (bflush) {
  78063. FLUSH_BLOCK_ONLY(s, 0);
  78064. }
  78065. s->strstart++;
  78066. s->lookahead--;
  78067. if (s->strm->avail_out == 0) return need_more;
  78068. } else {
  78069. /* There is no previous match to compare with, wait for
  78070. * the next step to decide.
  78071. */
  78072. s->match_available = 1;
  78073. s->strstart++;
  78074. s->lookahead--;
  78075. }
  78076. }
  78077. Assert (flush != Z_NO_FLUSH, "no flush?");
  78078. if (s->match_available) {
  78079. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  78080. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  78081. s->match_available = 0;
  78082. }
  78083. FLUSH_BLOCK(s, flush == Z_FINISH);
  78084. return flush == Z_FINISH ? finish_done : block_done;
  78085. }
  78086. #endif /* FASTEST */
  78087. #if 0
  78088. /* ===========================================================================
  78089. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  78090. * one. Do not maintain a hash table. (It will be regenerated if this run of
  78091. * deflate switches away from Z_RLE.)
  78092. */
  78093. local block_state deflate_rle(s, flush)
  78094. deflate_state *s;
  78095. int flush;
  78096. {
  78097. int bflush; /* set if current block must be flushed */
  78098. uInt run; /* length of run */
  78099. uInt max; /* maximum length of run */
  78100. uInt prev; /* byte at distance one to match */
  78101. Bytef *scan; /* scan for end of run */
  78102. for (;;) {
  78103. /* Make sure that we always have enough lookahead, except
  78104. * at the end of the input file. We need MAX_MATCH bytes
  78105. * for the longest encodable run.
  78106. */
  78107. if (s->lookahead < MAX_MATCH) {
  78108. fill_window(s);
  78109. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  78110. return need_more;
  78111. }
  78112. if (s->lookahead == 0) break; /* flush the current block */
  78113. }
  78114. /* See how many times the previous byte repeats */
  78115. run = 0;
  78116. if (s->strstart > 0) { /* if there is a previous byte, that is */
  78117. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  78118. scan = s->window + s->strstart - 1;
  78119. prev = *scan++;
  78120. do {
  78121. if (*scan++ != prev)
  78122. break;
  78123. } while (++run < max);
  78124. }
  78125. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  78126. if (run >= MIN_MATCH) {
  78127. check_match(s, s->strstart, s->strstart - 1, run);
  78128. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  78129. s->lookahead -= run;
  78130. s->strstart += run;
  78131. } else {
  78132. /* No match, output a literal byte */
  78133. Tracevv((stderr,"%c", s->window[s->strstart]));
  78134. _tr_tally_lit (s, s->window[s->strstart], bflush);
  78135. s->lookahead--;
  78136. s->strstart++;
  78137. }
  78138. if (bflush) FLUSH_BLOCK(s, 0);
  78139. }
  78140. FLUSH_BLOCK(s, flush == Z_FINISH);
  78141. return flush == Z_FINISH ? finish_done : block_done;
  78142. }
  78143. #endif
  78144. /********* End of inlined file: deflate.c *********/
  78145. /********* Start of inlined file: inffast.c *********/
  78146. /********* Start of inlined file: inftrees.h *********/
  78147. /* WARNING: this file should *not* be used by applications. It is
  78148. part of the implementation of the compression library and is
  78149. subject to change. Applications should only use zlib.h.
  78150. */
  78151. #ifndef _INFTREES_H_
  78152. #define _INFTREES_H_
  78153. /* Structure for decoding tables. Each entry provides either the
  78154. information needed to do the operation requested by the code that
  78155. indexed that table entry, or it provides a pointer to another
  78156. table that indexes more bits of the code. op indicates whether
  78157. the entry is a pointer to another table, a literal, a length or
  78158. distance, an end-of-block, or an invalid code. For a table
  78159. pointer, the low four bits of op is the number of index bits of
  78160. that table. For a length or distance, the low four bits of op
  78161. is the number of extra bits to get after the code. bits is
  78162. the number of bits in this code or part of the code to drop off
  78163. of the bit buffer. val is the actual byte to output in the case
  78164. of a literal, the base length or distance, or the offset from
  78165. the current table to the next table. Each entry is four bytes. */
  78166. typedef struct {
  78167. unsigned char op; /* operation, extra bits, table bits */
  78168. unsigned char bits; /* bits in this part of the code */
  78169. unsigned short val; /* offset in table or code value */
  78170. } code;
  78171. /* op values as set by inflate_table():
  78172. 00000000 - literal
  78173. 0000tttt - table link, tttt != 0 is the number of table index bits
  78174. 0001eeee - length or distance, eeee is the number of extra bits
  78175. 01100000 - end of block
  78176. 01000000 - invalid code
  78177. */
  78178. /* Maximum size of dynamic tree. The maximum found in a long but non-
  78179. exhaustive search was 1444 code structures (852 for length/literals
  78180. and 592 for distances, the latter actually the result of an
  78181. exhaustive search). The true maximum is not known, but the value
  78182. below is more than safe. */
  78183. #define ENOUGH 2048
  78184. #define MAXD 592
  78185. /* Type of code to build for inftable() */
  78186. typedef enum {
  78187. CODES,
  78188. LENS,
  78189. DISTS
  78190. } codetype;
  78191. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  78192. unsigned codes, code FAR * FAR *table,
  78193. unsigned FAR *bits, unsigned short FAR *work));
  78194. #endif
  78195. /********* End of inlined file: inftrees.h *********/
  78196. /********* Start of inlined file: inflate.h *********/
  78197. /* WARNING: this file should *not* be used by applications. It is
  78198. part of the implementation of the compression library and is
  78199. subject to change. Applications should only use zlib.h.
  78200. */
  78201. #ifndef _INFLATE_H_
  78202. #define _INFLATE_H_
  78203. /* define NO_GZIP when compiling if you want to disable gzip header and
  78204. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  78205. the crc code when it is not needed. For shared libraries, gzip decoding
  78206. should be left enabled. */
  78207. #ifndef NO_GZIP
  78208. # define GUNZIP
  78209. #endif
  78210. /* Possible inflate modes between inflate() calls */
  78211. typedef enum {
  78212. HEAD, /* i: waiting for magic header */
  78213. FLAGS, /* i: waiting for method and flags (gzip) */
  78214. TIME, /* i: waiting for modification time (gzip) */
  78215. OS, /* i: waiting for extra flags and operating system (gzip) */
  78216. EXLEN, /* i: waiting for extra length (gzip) */
  78217. EXTRA, /* i: waiting for extra bytes (gzip) */
  78218. NAME, /* i: waiting for end of file name (gzip) */
  78219. COMMENT, /* i: waiting for end of comment (gzip) */
  78220. HCRC, /* i: waiting for header crc (gzip) */
  78221. DICTID, /* i: waiting for dictionary check value */
  78222. DICT, /* waiting for inflateSetDictionary() call */
  78223. TYPE, /* i: waiting for type bits, including last-flag bit */
  78224. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  78225. STORED, /* i: waiting for stored size (length and complement) */
  78226. COPY, /* i/o: waiting for input or output to copy stored block */
  78227. TABLE, /* i: waiting for dynamic block table lengths */
  78228. LENLENS, /* i: waiting for code length code lengths */
  78229. CODELENS, /* i: waiting for length/lit and distance code lengths */
  78230. LEN, /* i: waiting for length/lit code */
  78231. LENEXT, /* i: waiting for length extra bits */
  78232. DIST, /* i: waiting for distance code */
  78233. DISTEXT, /* i: waiting for distance extra bits */
  78234. MATCH, /* o: waiting for output space to copy string */
  78235. LIT, /* o: waiting for output space to write literal */
  78236. CHECK, /* i: waiting for 32-bit check value */
  78237. LENGTH, /* i: waiting for 32-bit length (gzip) */
  78238. DONE, /* finished check, done -- remain here until reset */
  78239. BAD, /* got a data error -- remain here until reset */
  78240. MEM, /* got an inflate() memory error -- remain here until reset */
  78241. SYNC /* looking for synchronization bytes to restart inflate() */
  78242. } inflate_mode;
  78243. /*
  78244. State transitions between above modes -
  78245. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  78246. Process header:
  78247. HEAD -> (gzip) or (zlib)
  78248. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  78249. NAME -> COMMENT -> HCRC -> TYPE
  78250. (zlib) -> DICTID or TYPE
  78251. DICTID -> DICT -> TYPE
  78252. Read deflate blocks:
  78253. TYPE -> STORED or TABLE or LEN or CHECK
  78254. STORED -> COPY -> TYPE
  78255. TABLE -> LENLENS -> CODELENS -> LEN
  78256. Read deflate codes:
  78257. LEN -> LENEXT or LIT or TYPE
  78258. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  78259. LIT -> LEN
  78260. Process trailer:
  78261. CHECK -> LENGTH -> DONE
  78262. */
  78263. /* state maintained between inflate() calls. Approximately 7K bytes. */
  78264. struct inflate_state {
  78265. inflate_mode mode; /* current inflate mode */
  78266. int last; /* true if processing last block */
  78267. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  78268. int havedict; /* true if dictionary provided */
  78269. int flags; /* gzip header method and flags (0 if zlib) */
  78270. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  78271. unsigned long check; /* protected copy of check value */
  78272. unsigned long total; /* protected copy of output count */
  78273. gz_headerp head; /* where to save gzip header information */
  78274. /* sliding window */
  78275. unsigned wbits; /* log base 2 of requested window size */
  78276. unsigned wsize; /* window size or zero if not using window */
  78277. unsigned whave; /* valid bytes in the window */
  78278. unsigned write; /* window write index */
  78279. unsigned char FAR *window; /* allocated sliding window, if needed */
  78280. /* bit accumulator */
  78281. unsigned long hold; /* input bit accumulator */
  78282. unsigned bits; /* number of bits in "in" */
  78283. /* for string and stored block copying */
  78284. unsigned length; /* literal or length of data to copy */
  78285. unsigned offset; /* distance back to copy string from */
  78286. /* for table and code decoding */
  78287. unsigned extra; /* extra bits needed */
  78288. /* fixed and dynamic code tables */
  78289. code const FAR *lencode; /* starting table for length/literal codes */
  78290. code const FAR *distcode; /* starting table for distance codes */
  78291. unsigned lenbits; /* index bits for lencode */
  78292. unsigned distbits; /* index bits for distcode */
  78293. /* dynamic table building */
  78294. unsigned ncode; /* number of code length code lengths */
  78295. unsigned nlen; /* number of length code lengths */
  78296. unsigned ndist; /* number of distance code lengths */
  78297. unsigned have; /* number of code lengths in lens[] */
  78298. code FAR *next; /* next available space in codes[] */
  78299. unsigned short lens[320]; /* temporary storage for code lengths */
  78300. unsigned short work[288]; /* work area for code table building */
  78301. code codes[ENOUGH]; /* space for code tables */
  78302. };
  78303. #endif
  78304. /********* End of inlined file: inflate.h *********/
  78305. /********* Start of inlined file: inffast.h *********/
  78306. /* WARNING: this file should *not* be used by applications. It is
  78307. part of the implementation of the compression library and is
  78308. subject to change. Applications should only use zlib.h.
  78309. */
  78310. void inflate_fast OF((z_streamp strm, unsigned start));
  78311. /********* End of inlined file: inffast.h *********/
  78312. #ifndef ASMINF
  78313. /* Allow machine dependent optimization for post-increment or pre-increment.
  78314. Based on testing to date,
  78315. Pre-increment preferred for:
  78316. - PowerPC G3 (Adler)
  78317. - MIPS R5000 (Randers-Pehrson)
  78318. Post-increment preferred for:
  78319. - none
  78320. No measurable difference:
  78321. - Pentium III (Anderson)
  78322. - M68060 (Nikl)
  78323. */
  78324. #ifdef POSTINC
  78325. # define OFF 0
  78326. # define PUP(a) *(a)++
  78327. #else
  78328. # define OFF 1
  78329. # define PUP(a) *++(a)
  78330. #endif
  78331. /*
  78332. Decode literal, length, and distance codes and write out the resulting
  78333. literal and match bytes until either not enough input or output is
  78334. available, an end-of-block is encountered, or a data error is encountered.
  78335. When large enough input and output buffers are supplied to inflate(), for
  78336. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  78337. inflate execution time is spent in this routine.
  78338. Entry assumptions:
  78339. state->mode == LEN
  78340. strm->avail_in >= 6
  78341. strm->avail_out >= 258
  78342. start >= strm->avail_out
  78343. state->bits < 8
  78344. On return, state->mode is one of:
  78345. LEN -- ran out of enough output space or enough available input
  78346. TYPE -- reached end of block code, inflate() to interpret next block
  78347. BAD -- error in block data
  78348. Notes:
  78349. - The maximum input bits used by a length/distance pair is 15 bits for the
  78350. length code, 5 bits for the length extra, 15 bits for the distance code,
  78351. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  78352. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  78353. checking for available input while decoding.
  78354. - The maximum bytes that a single length/distance pair can output is 258
  78355. bytes, which is the maximum length that can be coded. inflate_fast()
  78356. requires strm->avail_out >= 258 for each loop to avoid checking for
  78357. output space.
  78358. */
  78359. void inflate_fast (z_streamp strm, unsigned start)
  78360. {
  78361. struct inflate_state FAR *state;
  78362. unsigned char FAR *in; /* local strm->next_in */
  78363. unsigned char FAR *last; /* while in < last, enough input available */
  78364. unsigned char FAR *out; /* local strm->next_out */
  78365. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  78366. unsigned char FAR *end; /* while out < end, enough space available */
  78367. #ifdef INFLATE_STRICT
  78368. unsigned dmax; /* maximum distance from zlib header */
  78369. #endif
  78370. unsigned wsize; /* window size or zero if not using window */
  78371. unsigned whave; /* valid bytes in the window */
  78372. unsigned write; /* window write index */
  78373. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  78374. unsigned long hold; /* local strm->hold */
  78375. unsigned bits; /* local strm->bits */
  78376. code const FAR *lcode; /* local strm->lencode */
  78377. code const FAR *dcode; /* local strm->distcode */
  78378. unsigned lmask; /* mask for first level of length codes */
  78379. unsigned dmask; /* mask for first level of distance codes */
  78380. code thisx; /* retrieved table entry */
  78381. unsigned op; /* code bits, operation, extra bits, or */
  78382. /* window position, window bytes to copy */
  78383. unsigned len; /* match length, unused bytes */
  78384. unsigned dist; /* match distance */
  78385. unsigned char FAR *from; /* where to copy match from */
  78386. /* copy state to local variables */
  78387. state = (struct inflate_state FAR *)strm->state;
  78388. in = strm->next_in - OFF;
  78389. last = in + (strm->avail_in - 5);
  78390. out = strm->next_out - OFF;
  78391. beg = out - (start - strm->avail_out);
  78392. end = out + (strm->avail_out - 257);
  78393. #ifdef INFLATE_STRICT
  78394. dmax = state->dmax;
  78395. #endif
  78396. wsize = state->wsize;
  78397. whave = state->whave;
  78398. write = state->write;
  78399. window = state->window;
  78400. hold = state->hold;
  78401. bits = state->bits;
  78402. lcode = state->lencode;
  78403. dcode = state->distcode;
  78404. lmask = (1U << state->lenbits) - 1;
  78405. dmask = (1U << state->distbits) - 1;
  78406. /* decode literals and length/distances until end-of-block or not enough
  78407. input data or output space */
  78408. do {
  78409. if (bits < 15) {
  78410. hold += (unsigned long)(PUP(in)) << bits;
  78411. bits += 8;
  78412. hold += (unsigned long)(PUP(in)) << bits;
  78413. bits += 8;
  78414. }
  78415. thisx = lcode[hold & lmask];
  78416. dolen:
  78417. op = (unsigned)(thisx.bits);
  78418. hold >>= op;
  78419. bits -= op;
  78420. op = (unsigned)(thisx.op);
  78421. if (op == 0) { /* literal */
  78422. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78423. "inflate: literal '%c'\n" :
  78424. "inflate: literal 0x%02x\n", thisx.val));
  78425. PUP(out) = (unsigned char)(thisx.val);
  78426. }
  78427. else if (op & 16) { /* length base */
  78428. len = (unsigned)(thisx.val);
  78429. op &= 15; /* number of extra bits */
  78430. if (op) {
  78431. if (bits < op) {
  78432. hold += (unsigned long)(PUP(in)) << bits;
  78433. bits += 8;
  78434. }
  78435. len += (unsigned)hold & ((1U << op) - 1);
  78436. hold >>= op;
  78437. bits -= op;
  78438. }
  78439. Tracevv((stderr, "inflate: length %u\n", len));
  78440. if (bits < 15) {
  78441. hold += (unsigned long)(PUP(in)) << bits;
  78442. bits += 8;
  78443. hold += (unsigned long)(PUP(in)) << bits;
  78444. bits += 8;
  78445. }
  78446. thisx = dcode[hold & dmask];
  78447. dodist:
  78448. op = (unsigned)(thisx.bits);
  78449. hold >>= op;
  78450. bits -= op;
  78451. op = (unsigned)(thisx.op);
  78452. if (op & 16) { /* distance base */
  78453. dist = (unsigned)(thisx.val);
  78454. op &= 15; /* number of extra bits */
  78455. if (bits < op) {
  78456. hold += (unsigned long)(PUP(in)) << bits;
  78457. bits += 8;
  78458. if (bits < op) {
  78459. hold += (unsigned long)(PUP(in)) << bits;
  78460. bits += 8;
  78461. }
  78462. }
  78463. dist += (unsigned)hold & ((1U << op) - 1);
  78464. #ifdef INFLATE_STRICT
  78465. if (dist > dmax) {
  78466. strm->msg = (char *)"invalid distance too far back";
  78467. state->mode = BAD;
  78468. break;
  78469. }
  78470. #endif
  78471. hold >>= op;
  78472. bits -= op;
  78473. Tracevv((stderr, "inflate: distance %u\n", dist));
  78474. op = (unsigned)(out - beg); /* max distance in output */
  78475. if (dist > op) { /* see if copy from window */
  78476. op = dist - op; /* distance back in window */
  78477. if (op > whave) {
  78478. strm->msg = (char *)"invalid distance too far back";
  78479. state->mode = BAD;
  78480. break;
  78481. }
  78482. from = window - OFF;
  78483. if (write == 0) { /* very common case */
  78484. from += wsize - op;
  78485. if (op < len) { /* some from window */
  78486. len -= op;
  78487. do {
  78488. PUP(out) = PUP(from);
  78489. } while (--op);
  78490. from = out - dist; /* rest from output */
  78491. }
  78492. }
  78493. else if (write < op) { /* wrap around window */
  78494. from += wsize + write - op;
  78495. op -= write;
  78496. if (op < len) { /* some from end of window */
  78497. len -= op;
  78498. do {
  78499. PUP(out) = PUP(from);
  78500. } while (--op);
  78501. from = window - OFF;
  78502. if (write < len) { /* some from start of window */
  78503. op = write;
  78504. len -= op;
  78505. do {
  78506. PUP(out) = PUP(from);
  78507. } while (--op);
  78508. from = out - dist; /* rest from output */
  78509. }
  78510. }
  78511. }
  78512. else { /* contiguous in window */
  78513. from += write - op;
  78514. if (op < len) { /* some from window */
  78515. len -= op;
  78516. do {
  78517. PUP(out) = PUP(from);
  78518. } while (--op);
  78519. from = out - dist; /* rest from output */
  78520. }
  78521. }
  78522. while (len > 2) {
  78523. PUP(out) = PUP(from);
  78524. PUP(out) = PUP(from);
  78525. PUP(out) = PUP(from);
  78526. len -= 3;
  78527. }
  78528. if (len) {
  78529. PUP(out) = PUP(from);
  78530. if (len > 1)
  78531. PUP(out) = PUP(from);
  78532. }
  78533. }
  78534. else {
  78535. from = out - dist; /* copy direct from output */
  78536. do { /* minimum length is three */
  78537. PUP(out) = PUP(from);
  78538. PUP(out) = PUP(from);
  78539. PUP(out) = PUP(from);
  78540. len -= 3;
  78541. } while (len > 2);
  78542. if (len) {
  78543. PUP(out) = PUP(from);
  78544. if (len > 1)
  78545. PUP(out) = PUP(from);
  78546. }
  78547. }
  78548. }
  78549. else if ((op & 64) == 0) { /* 2nd level distance code */
  78550. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  78551. goto dodist;
  78552. }
  78553. else {
  78554. strm->msg = (char *)"invalid distance code";
  78555. state->mode = BAD;
  78556. break;
  78557. }
  78558. }
  78559. else if ((op & 64) == 0) { /* 2nd level length code */
  78560. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  78561. goto dolen;
  78562. }
  78563. else if (op & 32) { /* end-of-block */
  78564. Tracevv((stderr, "inflate: end of block\n"));
  78565. state->mode = TYPE;
  78566. break;
  78567. }
  78568. else {
  78569. strm->msg = (char *)"invalid literal/length code";
  78570. state->mode = BAD;
  78571. break;
  78572. }
  78573. } while (in < last && out < end);
  78574. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  78575. len = bits >> 3;
  78576. in -= len;
  78577. bits -= len << 3;
  78578. hold &= (1U << bits) - 1;
  78579. /* update state and return */
  78580. strm->next_in = in + OFF;
  78581. strm->next_out = out + OFF;
  78582. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  78583. strm->avail_out = (unsigned)(out < end ?
  78584. 257 + (end - out) : 257 - (out - end));
  78585. state->hold = hold;
  78586. state->bits = bits;
  78587. return;
  78588. }
  78589. /*
  78590. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  78591. - Using bit fields for code structure
  78592. - Different op definition to avoid & for extra bits (do & for table bits)
  78593. - Three separate decoding do-loops for direct, window, and write == 0
  78594. - Special case for distance > 1 copies to do overlapped load and store copy
  78595. - Explicit branch predictions (based on measured branch probabilities)
  78596. - Deferring match copy and interspersed it with decoding subsequent codes
  78597. - Swapping literal/length else
  78598. - Swapping window/direct else
  78599. - Larger unrolled copy loops (three is about right)
  78600. - Moving len -= 3 statement into middle of loop
  78601. */
  78602. #endif /* !ASMINF */
  78603. /********* End of inlined file: inffast.c *********/
  78604. #undef PULLBYTE
  78605. #undef LOAD
  78606. #undef RESTORE
  78607. #undef INITBITS
  78608. #undef NEEDBITS
  78609. #undef DROPBITS
  78610. #undef BYTEBITS
  78611. /********* Start of inlined file: inflate.c *********/
  78612. /*
  78613. * Change history:
  78614. *
  78615. * 1.2.beta0 24 Nov 2002
  78616. * - First version -- complete rewrite of inflate to simplify code, avoid
  78617. * creation of window when not needed, minimize use of window when it is
  78618. * needed, make inffast.c even faster, implement gzip decoding, and to
  78619. * improve code readability and style over the previous zlib inflate code
  78620. *
  78621. * 1.2.beta1 25 Nov 2002
  78622. * - Use pointers for available input and output checking in inffast.c
  78623. * - Remove input and output counters in inffast.c
  78624. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  78625. * - Remove unnecessary second byte pull from length extra in inffast.c
  78626. * - Unroll direct copy to three copies per loop in inffast.c
  78627. *
  78628. * 1.2.beta2 4 Dec 2002
  78629. * - Change external routine names to reduce potential conflicts
  78630. * - Correct filename to inffixed.h for fixed tables in inflate.c
  78631. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  78632. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  78633. * to avoid negation problem on Alphas (64 bit) in inflate.c
  78634. *
  78635. * 1.2.beta3 22 Dec 2002
  78636. * - Add comments on state->bits assertion in inffast.c
  78637. * - Add comments on op field in inftrees.h
  78638. * - Fix bug in reuse of allocated window after inflateReset()
  78639. * - Remove bit fields--back to byte structure for speed
  78640. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  78641. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  78642. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  78643. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  78644. * - Use local copies of stream next and avail values, as well as local bit
  78645. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  78646. *
  78647. * 1.2.beta4 1 Jan 2003
  78648. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  78649. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  78650. * - Add comments in inffast.c to introduce the inflate_fast() routine
  78651. * - Rearrange window copies in inflate_fast() for speed and simplification
  78652. * - Unroll last copy for window match in inflate_fast()
  78653. * - Use local copies of window variables in inflate_fast() for speed
  78654. * - Pull out common write == 0 case for speed in inflate_fast()
  78655. * - Make op and len in inflate_fast() unsigned for consistency
  78656. * - Add FAR to lcode and dcode declarations in inflate_fast()
  78657. * - Simplified bad distance check in inflate_fast()
  78658. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  78659. * source file infback.c to provide a call-back interface to inflate for
  78660. * programs like gzip and unzip -- uses window as output buffer to avoid
  78661. * window copying
  78662. *
  78663. * 1.2.beta5 1 Jan 2003
  78664. * - Improved inflateBack() interface to allow the caller to provide initial
  78665. * input in strm.
  78666. * - Fixed stored blocks bug in inflateBack()
  78667. *
  78668. * 1.2.beta6 4 Jan 2003
  78669. * - Added comments in inffast.c on effectiveness of POSTINC
  78670. * - Typecasting all around to reduce compiler warnings
  78671. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  78672. * make compilers happy
  78673. * - Changed type of window in inflateBackInit() to unsigned char *
  78674. *
  78675. * 1.2.beta7 27 Jan 2003
  78676. * - Changed many types to unsigned or unsigned short to avoid warnings
  78677. * - Added inflateCopy() function
  78678. *
  78679. * 1.2.0 9 Mar 2003
  78680. * - Changed inflateBack() interface to provide separate opaque descriptors
  78681. * for the in() and out() functions
  78682. * - Changed inflateBack() argument and in_func typedef to swap the length
  78683. * and buffer address return values for the input function
  78684. * - Check next_in and next_out for Z_NULL on entry to inflate()
  78685. *
  78686. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  78687. */
  78688. /********* Start of inlined file: inffast.h *********/
  78689. /* WARNING: this file should *not* be used by applications. It is
  78690. part of the implementation of the compression library and is
  78691. subject to change. Applications should only use zlib.h.
  78692. */
  78693. void inflate_fast OF((z_streamp strm, unsigned start));
  78694. /********* End of inlined file: inffast.h *********/
  78695. #ifdef MAKEFIXED
  78696. # ifndef BUILDFIXED
  78697. # define BUILDFIXED
  78698. # endif
  78699. #endif
  78700. /* function prototypes */
  78701. local void fixedtables OF((struct inflate_state FAR *state));
  78702. local int updatewindow OF((z_streamp strm, unsigned out));
  78703. #ifdef BUILDFIXED
  78704. void makefixed OF((void));
  78705. #endif
  78706. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  78707. unsigned len));
  78708. int ZEXPORT inflateReset (z_streamp strm)
  78709. {
  78710. struct inflate_state FAR *state;
  78711. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78712. state = (struct inflate_state FAR *)strm->state;
  78713. strm->total_in = strm->total_out = state->total = 0;
  78714. strm->msg = Z_NULL;
  78715. strm->adler = 1; /* to support ill-conceived Java test suite */
  78716. state->mode = HEAD;
  78717. state->last = 0;
  78718. state->havedict = 0;
  78719. state->dmax = 32768U;
  78720. state->head = Z_NULL;
  78721. state->wsize = 0;
  78722. state->whave = 0;
  78723. state->write = 0;
  78724. state->hold = 0;
  78725. state->bits = 0;
  78726. state->lencode = state->distcode = state->next = state->codes;
  78727. Tracev((stderr, "inflate: reset\n"));
  78728. return Z_OK;
  78729. }
  78730. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  78731. {
  78732. struct inflate_state FAR *state;
  78733. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78734. state = (struct inflate_state FAR *)strm->state;
  78735. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  78736. value &= (1L << bits) - 1;
  78737. state->hold += value << state->bits;
  78738. state->bits += bits;
  78739. return Z_OK;
  78740. }
  78741. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  78742. {
  78743. struct inflate_state FAR *state;
  78744. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  78745. stream_size != (int)(sizeof(z_stream)))
  78746. return Z_VERSION_ERROR;
  78747. if (strm == Z_NULL) return Z_STREAM_ERROR;
  78748. strm->msg = Z_NULL; /* in case we return an error */
  78749. if (strm->zalloc == (alloc_func)0) {
  78750. strm->zalloc = zcalloc;
  78751. strm->opaque = (voidpf)0;
  78752. }
  78753. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  78754. state = (struct inflate_state FAR *)
  78755. ZALLOC(strm, 1, sizeof(struct inflate_state));
  78756. if (state == Z_NULL) return Z_MEM_ERROR;
  78757. Tracev((stderr, "inflate: allocated\n"));
  78758. strm->state = (struct internal_state FAR *)state;
  78759. if (windowBits < 0) {
  78760. state->wrap = 0;
  78761. windowBits = -windowBits;
  78762. }
  78763. else {
  78764. state->wrap = (windowBits >> 4) + 1;
  78765. #ifdef GUNZIP
  78766. if (windowBits < 48) windowBits &= 15;
  78767. #endif
  78768. }
  78769. if (windowBits < 8 || windowBits > 15) {
  78770. ZFREE(strm, state);
  78771. strm->state = Z_NULL;
  78772. return Z_STREAM_ERROR;
  78773. }
  78774. state->wbits = (unsigned)windowBits;
  78775. state->window = Z_NULL;
  78776. return inflateReset(strm);
  78777. }
  78778. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  78779. {
  78780. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  78781. }
  78782. /*
  78783. Return state with length and distance decoding tables and index sizes set to
  78784. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  78785. If BUILDFIXED is defined, then instead this routine builds the tables the
  78786. first time it's called, and returns those tables the first time and
  78787. thereafter. This reduces the size of the code by about 2K bytes, in
  78788. exchange for a little execution time. However, BUILDFIXED should not be
  78789. used for threaded applications, since the rewriting of the tables and virgin
  78790. may not be thread-safe.
  78791. */
  78792. local void fixedtables (struct inflate_state FAR *state)
  78793. {
  78794. #ifdef BUILDFIXED
  78795. static int virgin = 1;
  78796. static code *lenfix, *distfix;
  78797. static code fixed[544];
  78798. /* build fixed huffman tables if first call (may not be thread safe) */
  78799. if (virgin) {
  78800. unsigned sym, bits;
  78801. static code *next;
  78802. /* literal/length table */
  78803. sym = 0;
  78804. while (sym < 144) state->lens[sym++] = 8;
  78805. while (sym < 256) state->lens[sym++] = 9;
  78806. while (sym < 280) state->lens[sym++] = 7;
  78807. while (sym < 288) state->lens[sym++] = 8;
  78808. next = fixed;
  78809. lenfix = next;
  78810. bits = 9;
  78811. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  78812. /* distance table */
  78813. sym = 0;
  78814. while (sym < 32) state->lens[sym++] = 5;
  78815. distfix = next;
  78816. bits = 5;
  78817. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  78818. /* do this just once */
  78819. virgin = 0;
  78820. }
  78821. #else /* !BUILDFIXED */
  78822. /********* Start of inlined file: inffixed.h *********/
  78823. /* inffixed.h -- table for decoding fixed codes
  78824. * Generated automatically by makefixed().
  78825. */
  78826. /* WARNING: this file should *not* be used by applications. It
  78827. is part of the implementation of the compression library and
  78828. is subject to change. Applications should only use zlib.h.
  78829. */
  78830. static const code lenfix[512] = {
  78831. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  78832. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  78833. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  78834. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  78835. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  78836. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  78837. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  78838. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  78839. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  78840. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  78841. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  78842. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  78843. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  78844. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  78845. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  78846. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  78847. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  78848. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  78849. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  78850. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  78851. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  78852. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  78853. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  78854. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  78855. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  78856. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  78857. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  78858. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  78859. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  78860. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  78861. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  78862. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  78863. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  78864. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  78865. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  78866. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  78867. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  78868. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  78869. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  78870. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  78871. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  78872. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  78873. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  78874. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  78875. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  78876. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  78877. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  78878. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  78879. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  78880. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  78881. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  78882. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  78883. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  78884. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  78885. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  78886. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  78887. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  78888. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  78889. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  78890. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  78891. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  78892. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  78893. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  78894. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  78895. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  78896. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  78897. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  78898. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  78899. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  78900. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  78901. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  78902. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  78903. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  78904. {0,9,255}
  78905. };
  78906. static const code distfix[32] = {
  78907. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  78908. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  78909. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  78910. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  78911. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  78912. {22,5,193},{64,5,0}
  78913. };
  78914. /********* End of inlined file: inffixed.h *********/
  78915. #endif /* BUILDFIXED */
  78916. state->lencode = lenfix;
  78917. state->lenbits = 9;
  78918. state->distcode = distfix;
  78919. state->distbits = 5;
  78920. }
  78921. #ifdef MAKEFIXED
  78922. #include <stdio.h>
  78923. /*
  78924. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  78925. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  78926. those tables to stdout, which would be piped to inffixed.h. A small program
  78927. can simply call makefixed to do this:
  78928. void makefixed(void);
  78929. int main(void)
  78930. {
  78931. makefixed();
  78932. return 0;
  78933. }
  78934. Then that can be linked with zlib built with MAKEFIXED defined and run:
  78935. a.out > inffixed.h
  78936. */
  78937. void makefixed()
  78938. {
  78939. unsigned low, size;
  78940. struct inflate_state state;
  78941. fixedtables(&state);
  78942. puts(" /* inffixed.h -- table for decoding fixed codes");
  78943. puts(" * Generated automatically by makefixed().");
  78944. puts(" */");
  78945. puts("");
  78946. puts(" /* WARNING: this file should *not* be used by applications.");
  78947. puts(" It is part of the implementation of this library and is");
  78948. puts(" subject to change. Applications should only use zlib.h.");
  78949. puts(" */");
  78950. puts("");
  78951. size = 1U << 9;
  78952. printf(" static const code lenfix[%u] = {", size);
  78953. low = 0;
  78954. for (;;) {
  78955. if ((low % 7) == 0) printf("\n ");
  78956. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  78957. state.lencode[low].val);
  78958. if (++low == size) break;
  78959. putchar(',');
  78960. }
  78961. puts("\n };");
  78962. size = 1U << 5;
  78963. printf("\n static const code distfix[%u] = {", size);
  78964. low = 0;
  78965. for (;;) {
  78966. if ((low % 6) == 0) printf("\n ");
  78967. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  78968. state.distcode[low].val);
  78969. if (++low == size) break;
  78970. putchar(',');
  78971. }
  78972. puts("\n };");
  78973. }
  78974. #endif /* MAKEFIXED */
  78975. /*
  78976. Update the window with the last wsize (normally 32K) bytes written before
  78977. returning. If window does not exist yet, create it. This is only called
  78978. when a window is already in use, or when output has been written during this
  78979. inflate call, but the end of the deflate stream has not been reached yet.
  78980. It is also called to create a window for dictionary data when a dictionary
  78981. is loaded.
  78982. Providing output buffers larger than 32K to inflate() should provide a speed
  78983. advantage, since only the last 32K of output is copied to the sliding window
  78984. upon return from inflate(), and since all distances after the first 32K of
  78985. output will fall in the output data, making match copies simpler and faster.
  78986. The advantage may be dependent on the size of the processor's data caches.
  78987. */
  78988. local int updatewindow (z_streamp strm, unsigned out)
  78989. {
  78990. struct inflate_state FAR *state;
  78991. unsigned copy, dist;
  78992. state = (struct inflate_state FAR *)strm->state;
  78993. /* if it hasn't been done already, allocate space for the window */
  78994. if (state->window == Z_NULL) {
  78995. state->window = (unsigned char FAR *)
  78996. ZALLOC(strm, 1U << state->wbits,
  78997. sizeof(unsigned char));
  78998. if (state->window == Z_NULL) return 1;
  78999. }
  79000. /* if window not in use yet, initialize */
  79001. if (state->wsize == 0) {
  79002. state->wsize = 1U << state->wbits;
  79003. state->write = 0;
  79004. state->whave = 0;
  79005. }
  79006. /* copy state->wsize or less output bytes into the circular window */
  79007. copy = out - strm->avail_out;
  79008. if (copy >= state->wsize) {
  79009. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  79010. state->write = 0;
  79011. state->whave = state->wsize;
  79012. }
  79013. else {
  79014. dist = state->wsize - state->write;
  79015. if (dist > copy) dist = copy;
  79016. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  79017. copy -= dist;
  79018. if (copy) {
  79019. zmemcpy(state->window, strm->next_out - copy, copy);
  79020. state->write = copy;
  79021. state->whave = state->wsize;
  79022. }
  79023. else {
  79024. state->write += dist;
  79025. if (state->write == state->wsize) state->write = 0;
  79026. if (state->whave < state->wsize) state->whave += dist;
  79027. }
  79028. }
  79029. return 0;
  79030. }
  79031. /* Macros for inflate(): */
  79032. /* check function to use adler32() for zlib or crc32() for gzip */
  79033. #ifdef GUNZIP
  79034. # define UPDATE(check, buf, len) \
  79035. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  79036. #else
  79037. # define UPDATE(check, buf, len) adler32(check, buf, len)
  79038. #endif
  79039. /* check macros for header crc */
  79040. #ifdef GUNZIP
  79041. # define CRC2(check, word) \
  79042. do { \
  79043. hbuf[0] = (unsigned char)(word); \
  79044. hbuf[1] = (unsigned char)((word) >> 8); \
  79045. check = crc32(check, hbuf, 2); \
  79046. } while (0)
  79047. # define CRC4(check, word) \
  79048. do { \
  79049. hbuf[0] = (unsigned char)(word); \
  79050. hbuf[1] = (unsigned char)((word) >> 8); \
  79051. hbuf[2] = (unsigned char)((word) >> 16); \
  79052. hbuf[3] = (unsigned char)((word) >> 24); \
  79053. check = crc32(check, hbuf, 4); \
  79054. } while (0)
  79055. #endif
  79056. /* Load registers with state in inflate() for speed */
  79057. #define LOAD() \
  79058. do { \
  79059. put = strm->next_out; \
  79060. left = strm->avail_out; \
  79061. next = strm->next_in; \
  79062. have = strm->avail_in; \
  79063. hold = state->hold; \
  79064. bits = state->bits; \
  79065. } while (0)
  79066. /* Restore state from registers in inflate() */
  79067. #define RESTORE() \
  79068. do { \
  79069. strm->next_out = put; \
  79070. strm->avail_out = left; \
  79071. strm->next_in = next; \
  79072. strm->avail_in = have; \
  79073. state->hold = hold; \
  79074. state->bits = bits; \
  79075. } while (0)
  79076. /* Clear the input bit accumulator */
  79077. #define INITBITS() \
  79078. do { \
  79079. hold = 0; \
  79080. bits = 0; \
  79081. } while (0)
  79082. /* Get a byte of input into the bit accumulator, or return from inflate()
  79083. if there is no input available. */
  79084. #define PULLBYTE() \
  79085. do { \
  79086. if (have == 0) goto inf_leave; \
  79087. have--; \
  79088. hold += (unsigned long)(*next++) << bits; \
  79089. bits += 8; \
  79090. } while (0)
  79091. /* Assure that there are at least n bits in the bit accumulator. If there is
  79092. not enough available input to do that, then return from inflate(). */
  79093. #define NEEDBITS(n) \
  79094. do { \
  79095. while (bits < (unsigned)(n)) \
  79096. PULLBYTE(); \
  79097. } while (0)
  79098. /* Return the low n bits of the bit accumulator (n < 16) */
  79099. #define BITS(n) \
  79100. ((unsigned)hold & ((1U << (n)) - 1))
  79101. /* Remove n bits from the bit accumulator */
  79102. #define DROPBITS(n) \
  79103. do { \
  79104. hold >>= (n); \
  79105. bits -= (unsigned)(n); \
  79106. } while (0)
  79107. /* Remove zero to seven bits as needed to go to a byte boundary */
  79108. #define BYTEBITS() \
  79109. do { \
  79110. hold >>= bits & 7; \
  79111. bits -= bits & 7; \
  79112. } while (0)
  79113. /* Reverse the bytes in a 32-bit value */
  79114. #define REVERSE(q) \
  79115. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  79116. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  79117. /*
  79118. inflate() uses a state machine to process as much input data and generate as
  79119. much output data as possible before returning. The state machine is
  79120. structured roughly as follows:
  79121. for (;;) switch (state) {
  79122. ...
  79123. case STATEn:
  79124. if (not enough input data or output space to make progress)
  79125. return;
  79126. ... make progress ...
  79127. state = STATEm;
  79128. break;
  79129. ...
  79130. }
  79131. so when inflate() is called again, the same case is attempted again, and
  79132. if the appropriate resources are provided, the machine proceeds to the
  79133. next state. The NEEDBITS() macro is usually the way the state evaluates
  79134. whether it can proceed or should return. NEEDBITS() does the return if
  79135. the requested bits are not available. The typical use of the BITS macros
  79136. is:
  79137. NEEDBITS(n);
  79138. ... do something with BITS(n) ...
  79139. DROPBITS(n);
  79140. where NEEDBITS(n) either returns from inflate() if there isn't enough
  79141. input left to load n bits into the accumulator, or it continues. BITS(n)
  79142. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  79143. the low n bits off the accumulator. INITBITS() clears the accumulator
  79144. and sets the number of available bits to zero. BYTEBITS() discards just
  79145. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  79146. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  79147. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  79148. if there is no input available. The decoding of variable length codes uses
  79149. PULLBYTE() directly in order to pull just enough bytes to decode the next
  79150. code, and no more.
  79151. Some states loop until they get enough input, making sure that enough
  79152. state information is maintained to continue the loop where it left off
  79153. if NEEDBITS() returns in the loop. For example, want, need, and keep
  79154. would all have to actually be part of the saved state in case NEEDBITS()
  79155. returns:
  79156. case STATEw:
  79157. while (want < need) {
  79158. NEEDBITS(n);
  79159. keep[want++] = BITS(n);
  79160. DROPBITS(n);
  79161. }
  79162. state = STATEx;
  79163. case STATEx:
  79164. As shown above, if the next state is also the next case, then the break
  79165. is omitted.
  79166. A state may also return if there is not enough output space available to
  79167. complete that state. Those states are copying stored data, writing a
  79168. literal byte, and copying a matching string.
  79169. When returning, a "goto inf_leave" is used to update the total counters,
  79170. update the check value, and determine whether any progress has been made
  79171. during that inflate() call in order to return the proper return code.
  79172. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  79173. When there is a window, goto inf_leave will update the window with the last
  79174. output written. If a goto inf_leave occurs in the middle of decompression
  79175. and there is no window currently, goto inf_leave will create one and copy
  79176. output to the window for the next call of inflate().
  79177. In this implementation, the flush parameter of inflate() only affects the
  79178. return code (per zlib.h). inflate() always writes as much as possible to
  79179. strm->next_out, given the space available and the provided input--the effect
  79180. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  79181. the allocation of and copying into a sliding window until necessary, which
  79182. provides the effect documented in zlib.h for Z_FINISH when the entire input
  79183. stream available. So the only thing the flush parameter actually does is:
  79184. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  79185. will return Z_BUF_ERROR if it has not reached the end of the stream.
  79186. */
  79187. int ZEXPORT inflate (z_streamp strm, int flush)
  79188. {
  79189. struct inflate_state FAR *state;
  79190. unsigned char FAR *next; /* next input */
  79191. unsigned char FAR *put; /* next output */
  79192. unsigned have, left; /* available input and output */
  79193. unsigned long hold; /* bit buffer */
  79194. unsigned bits; /* bits in bit buffer */
  79195. unsigned in, out; /* save starting available input and output */
  79196. unsigned copy; /* number of stored or match bytes to copy */
  79197. unsigned char FAR *from; /* where to copy match bytes from */
  79198. code thisx; /* current decoding table entry */
  79199. code last; /* parent table entry */
  79200. unsigned len; /* length to copy for repeats, bits to drop */
  79201. int ret; /* return code */
  79202. #ifdef GUNZIP
  79203. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  79204. #endif
  79205. static const unsigned short order[19] = /* permutation of code lengths */
  79206. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  79207. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  79208. (strm->next_in == Z_NULL && strm->avail_in != 0))
  79209. return Z_STREAM_ERROR;
  79210. state = (struct inflate_state FAR *)strm->state;
  79211. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  79212. LOAD();
  79213. in = have;
  79214. out = left;
  79215. ret = Z_OK;
  79216. for (;;)
  79217. switch (state->mode) {
  79218. case HEAD:
  79219. if (state->wrap == 0) {
  79220. state->mode = TYPEDO;
  79221. break;
  79222. }
  79223. NEEDBITS(16);
  79224. #ifdef GUNZIP
  79225. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  79226. state->check = crc32(0L, Z_NULL, 0);
  79227. CRC2(state->check, hold);
  79228. INITBITS();
  79229. state->mode = FLAGS;
  79230. break;
  79231. }
  79232. state->flags = 0; /* expect zlib header */
  79233. if (state->head != Z_NULL)
  79234. state->head->done = -1;
  79235. if (!(state->wrap & 1) || /* check if zlib header allowed */
  79236. #else
  79237. if (
  79238. #endif
  79239. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  79240. strm->msg = (char *)"incorrect header check";
  79241. state->mode = BAD;
  79242. break;
  79243. }
  79244. if (BITS(4) != Z_DEFLATED) {
  79245. strm->msg = (char *)"unknown compression method";
  79246. state->mode = BAD;
  79247. break;
  79248. }
  79249. DROPBITS(4);
  79250. len = BITS(4) + 8;
  79251. if (len > state->wbits) {
  79252. strm->msg = (char *)"invalid window size";
  79253. state->mode = BAD;
  79254. break;
  79255. }
  79256. state->dmax = 1U << len;
  79257. Tracev((stderr, "inflate: zlib header ok\n"));
  79258. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79259. state->mode = hold & 0x200 ? DICTID : TYPE;
  79260. INITBITS();
  79261. break;
  79262. #ifdef GUNZIP
  79263. case FLAGS:
  79264. NEEDBITS(16);
  79265. state->flags = (int)(hold);
  79266. if ((state->flags & 0xff) != Z_DEFLATED) {
  79267. strm->msg = (char *)"unknown compression method";
  79268. state->mode = BAD;
  79269. break;
  79270. }
  79271. if (state->flags & 0xe000) {
  79272. strm->msg = (char *)"unknown header flags set";
  79273. state->mode = BAD;
  79274. break;
  79275. }
  79276. if (state->head != Z_NULL)
  79277. state->head->text = (int)((hold >> 8) & 1);
  79278. if (state->flags & 0x0200) CRC2(state->check, hold);
  79279. INITBITS();
  79280. state->mode = TIME;
  79281. case TIME:
  79282. NEEDBITS(32);
  79283. if (state->head != Z_NULL)
  79284. state->head->time = hold;
  79285. if (state->flags & 0x0200) CRC4(state->check, hold);
  79286. INITBITS();
  79287. state->mode = OS;
  79288. case OS:
  79289. NEEDBITS(16);
  79290. if (state->head != Z_NULL) {
  79291. state->head->xflags = (int)(hold & 0xff);
  79292. state->head->os = (int)(hold >> 8);
  79293. }
  79294. if (state->flags & 0x0200) CRC2(state->check, hold);
  79295. INITBITS();
  79296. state->mode = EXLEN;
  79297. case EXLEN:
  79298. if (state->flags & 0x0400) {
  79299. NEEDBITS(16);
  79300. state->length = (unsigned)(hold);
  79301. if (state->head != Z_NULL)
  79302. state->head->extra_len = (unsigned)hold;
  79303. if (state->flags & 0x0200) CRC2(state->check, hold);
  79304. INITBITS();
  79305. }
  79306. else if (state->head != Z_NULL)
  79307. state->head->extra = Z_NULL;
  79308. state->mode = EXTRA;
  79309. case EXTRA:
  79310. if (state->flags & 0x0400) {
  79311. copy = state->length;
  79312. if (copy > have) copy = have;
  79313. if (copy) {
  79314. if (state->head != Z_NULL &&
  79315. state->head->extra != Z_NULL) {
  79316. len = state->head->extra_len - state->length;
  79317. zmemcpy(state->head->extra + len, next,
  79318. len + copy > state->head->extra_max ?
  79319. state->head->extra_max - len : copy);
  79320. }
  79321. if (state->flags & 0x0200)
  79322. state->check = crc32(state->check, next, copy);
  79323. have -= copy;
  79324. next += copy;
  79325. state->length -= copy;
  79326. }
  79327. if (state->length) goto inf_leave;
  79328. }
  79329. state->length = 0;
  79330. state->mode = NAME;
  79331. case NAME:
  79332. if (state->flags & 0x0800) {
  79333. if (have == 0) goto inf_leave;
  79334. copy = 0;
  79335. do {
  79336. len = (unsigned)(next[copy++]);
  79337. if (state->head != Z_NULL &&
  79338. state->head->name != Z_NULL &&
  79339. state->length < state->head->name_max)
  79340. state->head->name[state->length++] = len;
  79341. } while (len && copy < have);
  79342. if (state->flags & 0x0200)
  79343. state->check = crc32(state->check, next, copy);
  79344. have -= copy;
  79345. next += copy;
  79346. if (len) goto inf_leave;
  79347. }
  79348. else if (state->head != Z_NULL)
  79349. state->head->name = Z_NULL;
  79350. state->length = 0;
  79351. state->mode = COMMENT;
  79352. case COMMENT:
  79353. if (state->flags & 0x1000) {
  79354. if (have == 0) goto inf_leave;
  79355. copy = 0;
  79356. do {
  79357. len = (unsigned)(next[copy++]);
  79358. if (state->head != Z_NULL &&
  79359. state->head->comment != Z_NULL &&
  79360. state->length < state->head->comm_max)
  79361. state->head->comment[state->length++] = len;
  79362. } while (len && copy < have);
  79363. if (state->flags & 0x0200)
  79364. state->check = crc32(state->check, next, copy);
  79365. have -= copy;
  79366. next += copy;
  79367. if (len) goto inf_leave;
  79368. }
  79369. else if (state->head != Z_NULL)
  79370. state->head->comment = Z_NULL;
  79371. state->mode = HCRC;
  79372. case HCRC:
  79373. if (state->flags & 0x0200) {
  79374. NEEDBITS(16);
  79375. if (hold != (state->check & 0xffff)) {
  79376. strm->msg = (char *)"header crc mismatch";
  79377. state->mode = BAD;
  79378. break;
  79379. }
  79380. INITBITS();
  79381. }
  79382. if (state->head != Z_NULL) {
  79383. state->head->hcrc = (int)((state->flags >> 9) & 1);
  79384. state->head->done = 1;
  79385. }
  79386. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  79387. state->mode = TYPE;
  79388. break;
  79389. #endif
  79390. case DICTID:
  79391. NEEDBITS(32);
  79392. strm->adler = state->check = REVERSE(hold);
  79393. INITBITS();
  79394. state->mode = DICT;
  79395. case DICT:
  79396. if (state->havedict == 0) {
  79397. RESTORE();
  79398. return Z_NEED_DICT;
  79399. }
  79400. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  79401. state->mode = TYPE;
  79402. case TYPE:
  79403. if (flush == Z_BLOCK) goto inf_leave;
  79404. case TYPEDO:
  79405. if (state->last) {
  79406. BYTEBITS();
  79407. state->mode = CHECK;
  79408. break;
  79409. }
  79410. NEEDBITS(3);
  79411. state->last = BITS(1);
  79412. DROPBITS(1);
  79413. switch (BITS(2)) {
  79414. case 0: /* stored block */
  79415. Tracev((stderr, "inflate: stored block%s\n",
  79416. state->last ? " (last)" : ""));
  79417. state->mode = STORED;
  79418. break;
  79419. case 1: /* fixed block */
  79420. fixedtables(state);
  79421. Tracev((stderr, "inflate: fixed codes block%s\n",
  79422. state->last ? " (last)" : ""));
  79423. state->mode = LEN; /* decode codes */
  79424. break;
  79425. case 2: /* dynamic block */
  79426. Tracev((stderr, "inflate: dynamic codes block%s\n",
  79427. state->last ? " (last)" : ""));
  79428. state->mode = TABLE;
  79429. break;
  79430. case 3:
  79431. strm->msg = (char *)"invalid block type";
  79432. state->mode = BAD;
  79433. }
  79434. DROPBITS(2);
  79435. break;
  79436. case STORED:
  79437. BYTEBITS(); /* go to byte boundary */
  79438. NEEDBITS(32);
  79439. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  79440. strm->msg = (char *)"invalid stored block lengths";
  79441. state->mode = BAD;
  79442. break;
  79443. }
  79444. state->length = (unsigned)hold & 0xffff;
  79445. Tracev((stderr, "inflate: stored length %u\n",
  79446. state->length));
  79447. INITBITS();
  79448. state->mode = COPY;
  79449. case COPY:
  79450. copy = state->length;
  79451. if (copy) {
  79452. if (copy > have) copy = have;
  79453. if (copy > left) copy = left;
  79454. if (copy == 0) goto inf_leave;
  79455. zmemcpy(put, next, copy);
  79456. have -= copy;
  79457. next += copy;
  79458. left -= copy;
  79459. put += copy;
  79460. state->length -= copy;
  79461. break;
  79462. }
  79463. Tracev((stderr, "inflate: stored end\n"));
  79464. state->mode = TYPE;
  79465. break;
  79466. case TABLE:
  79467. NEEDBITS(14);
  79468. state->nlen = BITS(5) + 257;
  79469. DROPBITS(5);
  79470. state->ndist = BITS(5) + 1;
  79471. DROPBITS(5);
  79472. state->ncode = BITS(4) + 4;
  79473. DROPBITS(4);
  79474. #ifndef PKZIP_BUG_WORKAROUND
  79475. if (state->nlen > 286 || state->ndist > 30) {
  79476. strm->msg = (char *)"too many length or distance symbols";
  79477. state->mode = BAD;
  79478. break;
  79479. }
  79480. #endif
  79481. Tracev((stderr, "inflate: table sizes ok\n"));
  79482. state->have = 0;
  79483. state->mode = LENLENS;
  79484. case LENLENS:
  79485. while (state->have < state->ncode) {
  79486. NEEDBITS(3);
  79487. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  79488. DROPBITS(3);
  79489. }
  79490. while (state->have < 19)
  79491. state->lens[order[state->have++]] = 0;
  79492. state->next = state->codes;
  79493. state->lencode = (code const FAR *)(state->next);
  79494. state->lenbits = 7;
  79495. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  79496. &(state->lenbits), state->work);
  79497. if (ret) {
  79498. strm->msg = (char *)"invalid code lengths set";
  79499. state->mode = BAD;
  79500. break;
  79501. }
  79502. Tracev((stderr, "inflate: code lengths ok\n"));
  79503. state->have = 0;
  79504. state->mode = CODELENS;
  79505. case CODELENS:
  79506. while (state->have < state->nlen + state->ndist) {
  79507. for (;;) {
  79508. thisx = state->lencode[BITS(state->lenbits)];
  79509. if ((unsigned)(thisx.bits) <= bits) break;
  79510. PULLBYTE();
  79511. }
  79512. if (thisx.val < 16) {
  79513. NEEDBITS(thisx.bits);
  79514. DROPBITS(thisx.bits);
  79515. state->lens[state->have++] = thisx.val;
  79516. }
  79517. else {
  79518. if (thisx.val == 16) {
  79519. NEEDBITS(thisx.bits + 2);
  79520. DROPBITS(thisx.bits);
  79521. if (state->have == 0) {
  79522. strm->msg = (char *)"invalid bit length repeat";
  79523. state->mode = BAD;
  79524. break;
  79525. }
  79526. len = state->lens[state->have - 1];
  79527. copy = 3 + BITS(2);
  79528. DROPBITS(2);
  79529. }
  79530. else if (thisx.val == 17) {
  79531. NEEDBITS(thisx.bits + 3);
  79532. DROPBITS(thisx.bits);
  79533. len = 0;
  79534. copy = 3 + BITS(3);
  79535. DROPBITS(3);
  79536. }
  79537. else {
  79538. NEEDBITS(thisx.bits + 7);
  79539. DROPBITS(thisx.bits);
  79540. len = 0;
  79541. copy = 11 + BITS(7);
  79542. DROPBITS(7);
  79543. }
  79544. if (state->have + copy > state->nlen + state->ndist) {
  79545. strm->msg = (char *)"invalid bit length repeat";
  79546. state->mode = BAD;
  79547. break;
  79548. }
  79549. while (copy--)
  79550. state->lens[state->have++] = (unsigned short)len;
  79551. }
  79552. }
  79553. /* handle error breaks in while */
  79554. if (state->mode == BAD) break;
  79555. /* build code tables */
  79556. state->next = state->codes;
  79557. state->lencode = (code const FAR *)(state->next);
  79558. state->lenbits = 9;
  79559. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  79560. &(state->lenbits), state->work);
  79561. if (ret) {
  79562. strm->msg = (char *)"invalid literal/lengths set";
  79563. state->mode = BAD;
  79564. break;
  79565. }
  79566. state->distcode = (code const FAR *)(state->next);
  79567. state->distbits = 6;
  79568. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  79569. &(state->next), &(state->distbits), state->work);
  79570. if (ret) {
  79571. strm->msg = (char *)"invalid distances set";
  79572. state->mode = BAD;
  79573. break;
  79574. }
  79575. Tracev((stderr, "inflate: codes ok\n"));
  79576. state->mode = LEN;
  79577. case LEN:
  79578. if (have >= 6 && left >= 258) {
  79579. RESTORE();
  79580. inflate_fast(strm, out);
  79581. LOAD();
  79582. break;
  79583. }
  79584. for (;;) {
  79585. thisx = state->lencode[BITS(state->lenbits)];
  79586. if ((unsigned)(thisx.bits) <= bits) break;
  79587. PULLBYTE();
  79588. }
  79589. if (thisx.op && (thisx.op & 0xf0) == 0) {
  79590. last = thisx;
  79591. for (;;) {
  79592. thisx = state->lencode[last.val +
  79593. (BITS(last.bits + last.op) >> last.bits)];
  79594. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79595. PULLBYTE();
  79596. }
  79597. DROPBITS(last.bits);
  79598. }
  79599. DROPBITS(thisx.bits);
  79600. state->length = (unsigned)thisx.val;
  79601. if ((int)(thisx.op) == 0) {
  79602. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  79603. "inflate: literal '%c'\n" :
  79604. "inflate: literal 0x%02x\n", thisx.val));
  79605. state->mode = LIT;
  79606. break;
  79607. }
  79608. if (thisx.op & 32) {
  79609. Tracevv((stderr, "inflate: end of block\n"));
  79610. state->mode = TYPE;
  79611. break;
  79612. }
  79613. if (thisx.op & 64) {
  79614. strm->msg = (char *)"invalid literal/length code";
  79615. state->mode = BAD;
  79616. break;
  79617. }
  79618. state->extra = (unsigned)(thisx.op) & 15;
  79619. state->mode = LENEXT;
  79620. case LENEXT:
  79621. if (state->extra) {
  79622. NEEDBITS(state->extra);
  79623. state->length += BITS(state->extra);
  79624. DROPBITS(state->extra);
  79625. }
  79626. Tracevv((stderr, "inflate: length %u\n", state->length));
  79627. state->mode = DIST;
  79628. case DIST:
  79629. for (;;) {
  79630. thisx = state->distcode[BITS(state->distbits)];
  79631. if ((unsigned)(thisx.bits) <= bits) break;
  79632. PULLBYTE();
  79633. }
  79634. if ((thisx.op & 0xf0) == 0) {
  79635. last = thisx;
  79636. for (;;) {
  79637. thisx = state->distcode[last.val +
  79638. (BITS(last.bits + last.op) >> last.bits)];
  79639. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  79640. PULLBYTE();
  79641. }
  79642. DROPBITS(last.bits);
  79643. }
  79644. DROPBITS(thisx.bits);
  79645. if (thisx.op & 64) {
  79646. strm->msg = (char *)"invalid distance code";
  79647. state->mode = BAD;
  79648. break;
  79649. }
  79650. state->offset = (unsigned)thisx.val;
  79651. state->extra = (unsigned)(thisx.op) & 15;
  79652. state->mode = DISTEXT;
  79653. case DISTEXT:
  79654. if (state->extra) {
  79655. NEEDBITS(state->extra);
  79656. state->offset += BITS(state->extra);
  79657. DROPBITS(state->extra);
  79658. }
  79659. #ifdef INFLATE_STRICT
  79660. if (state->offset > state->dmax) {
  79661. strm->msg = (char *)"invalid distance too far back";
  79662. state->mode = BAD;
  79663. break;
  79664. }
  79665. #endif
  79666. if (state->offset > state->whave + out - left) {
  79667. strm->msg = (char *)"invalid distance too far back";
  79668. state->mode = BAD;
  79669. break;
  79670. }
  79671. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  79672. state->mode = MATCH;
  79673. case MATCH:
  79674. if (left == 0) goto inf_leave;
  79675. copy = out - left;
  79676. if (state->offset > copy) { /* copy from window */
  79677. copy = state->offset - copy;
  79678. if (copy > state->write) {
  79679. copy -= state->write;
  79680. from = state->window + (state->wsize - copy);
  79681. }
  79682. else
  79683. from = state->window + (state->write - copy);
  79684. if (copy > state->length) copy = state->length;
  79685. }
  79686. else { /* copy from output */
  79687. from = put - state->offset;
  79688. copy = state->length;
  79689. }
  79690. if (copy > left) copy = left;
  79691. left -= copy;
  79692. state->length -= copy;
  79693. do {
  79694. *put++ = *from++;
  79695. } while (--copy);
  79696. if (state->length == 0) state->mode = LEN;
  79697. break;
  79698. case LIT:
  79699. if (left == 0) goto inf_leave;
  79700. *put++ = (unsigned char)(state->length);
  79701. left--;
  79702. state->mode = LEN;
  79703. break;
  79704. case CHECK:
  79705. if (state->wrap) {
  79706. NEEDBITS(32);
  79707. out -= left;
  79708. strm->total_out += out;
  79709. state->total += out;
  79710. if (out)
  79711. strm->adler = state->check =
  79712. UPDATE(state->check, put - out, out);
  79713. out = left;
  79714. if ((
  79715. #ifdef GUNZIP
  79716. state->flags ? hold :
  79717. #endif
  79718. REVERSE(hold)) != state->check) {
  79719. strm->msg = (char *)"incorrect data check";
  79720. state->mode = BAD;
  79721. break;
  79722. }
  79723. INITBITS();
  79724. Tracev((stderr, "inflate: check matches trailer\n"));
  79725. }
  79726. #ifdef GUNZIP
  79727. state->mode = LENGTH;
  79728. case LENGTH:
  79729. if (state->wrap && state->flags) {
  79730. NEEDBITS(32);
  79731. if (hold != (state->total & 0xffffffffUL)) {
  79732. strm->msg = (char *)"incorrect length check";
  79733. state->mode = BAD;
  79734. break;
  79735. }
  79736. INITBITS();
  79737. Tracev((stderr, "inflate: length matches trailer\n"));
  79738. }
  79739. #endif
  79740. state->mode = DONE;
  79741. case DONE:
  79742. ret = Z_STREAM_END;
  79743. goto inf_leave;
  79744. case BAD:
  79745. ret = Z_DATA_ERROR;
  79746. goto inf_leave;
  79747. case MEM:
  79748. return Z_MEM_ERROR;
  79749. case SYNC:
  79750. default:
  79751. return Z_STREAM_ERROR;
  79752. }
  79753. /*
  79754. Return from inflate(), updating the total counts and the check value.
  79755. If there was no progress during the inflate() call, return a buffer
  79756. error. Call updatewindow() to create and/or update the window state.
  79757. Note: a memory error from inflate() is non-recoverable.
  79758. */
  79759. inf_leave:
  79760. RESTORE();
  79761. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  79762. if (updatewindow(strm, out)) {
  79763. state->mode = MEM;
  79764. return Z_MEM_ERROR;
  79765. }
  79766. in -= strm->avail_in;
  79767. out -= strm->avail_out;
  79768. strm->total_in += in;
  79769. strm->total_out += out;
  79770. state->total += out;
  79771. if (state->wrap && out)
  79772. strm->adler = state->check =
  79773. UPDATE(state->check, strm->next_out - out, out);
  79774. strm->data_type = state->bits + (state->last ? 64 : 0) +
  79775. (state->mode == TYPE ? 128 : 0);
  79776. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  79777. ret = Z_BUF_ERROR;
  79778. return ret;
  79779. }
  79780. int ZEXPORT inflateEnd (z_streamp strm)
  79781. {
  79782. struct inflate_state FAR *state;
  79783. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  79784. return Z_STREAM_ERROR;
  79785. state = (struct inflate_state FAR *)strm->state;
  79786. if (state->window != Z_NULL) ZFREE(strm, state->window);
  79787. ZFREE(strm, strm->state);
  79788. strm->state = Z_NULL;
  79789. Tracev((stderr, "inflate: end\n"));
  79790. return Z_OK;
  79791. }
  79792. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  79793. {
  79794. struct inflate_state FAR *state;
  79795. unsigned long id_;
  79796. /* check state */
  79797. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79798. state = (struct inflate_state FAR *)strm->state;
  79799. if (state->wrap != 0 && state->mode != DICT)
  79800. return Z_STREAM_ERROR;
  79801. /* check for correct dictionary id */
  79802. if (state->mode == DICT) {
  79803. id_ = adler32(0L, Z_NULL, 0);
  79804. id_ = adler32(id_, dictionary, dictLength);
  79805. if (id_ != state->check)
  79806. return Z_DATA_ERROR;
  79807. }
  79808. /* copy dictionary to window */
  79809. if (updatewindow(strm, strm->avail_out)) {
  79810. state->mode = MEM;
  79811. return Z_MEM_ERROR;
  79812. }
  79813. if (dictLength > state->wsize) {
  79814. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  79815. state->wsize);
  79816. state->whave = state->wsize;
  79817. }
  79818. else {
  79819. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  79820. dictLength);
  79821. state->whave = dictLength;
  79822. }
  79823. state->havedict = 1;
  79824. Tracev((stderr, "inflate: dictionary set\n"));
  79825. return Z_OK;
  79826. }
  79827. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  79828. {
  79829. struct inflate_state FAR *state;
  79830. /* check state */
  79831. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79832. state = (struct inflate_state FAR *)strm->state;
  79833. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  79834. /* save header structure */
  79835. state->head = head;
  79836. head->done = 0;
  79837. return Z_OK;
  79838. }
  79839. /*
  79840. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  79841. or when out of input. When called, *have is the number of pattern bytes
  79842. found in order so far, in 0..3. On return *have is updated to the new
  79843. state. If on return *have equals four, then the pattern was found and the
  79844. return value is how many bytes were read including the last byte of the
  79845. pattern. If *have is less than four, then the pattern has not been found
  79846. yet and the return value is len. In the latter case, syncsearch() can be
  79847. called again with more data and the *have state. *have is initialized to
  79848. zero for the first call.
  79849. */
  79850. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  79851. {
  79852. unsigned got;
  79853. unsigned next;
  79854. got = *have;
  79855. next = 0;
  79856. while (next < len && got < 4) {
  79857. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  79858. got++;
  79859. else if (buf[next])
  79860. got = 0;
  79861. else
  79862. got = 4 - got;
  79863. next++;
  79864. }
  79865. *have = got;
  79866. return next;
  79867. }
  79868. int ZEXPORT inflateSync (z_streamp strm)
  79869. {
  79870. unsigned len; /* number of bytes to look at or looked at */
  79871. unsigned long in, out; /* temporary to save total_in and total_out */
  79872. unsigned char buf[4]; /* to restore bit buffer to byte string */
  79873. struct inflate_state FAR *state;
  79874. /* check parameters */
  79875. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79876. state = (struct inflate_state FAR *)strm->state;
  79877. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  79878. /* if first time, start search in bit buffer */
  79879. if (state->mode != SYNC) {
  79880. state->mode = SYNC;
  79881. state->hold <<= state->bits & 7;
  79882. state->bits -= state->bits & 7;
  79883. len = 0;
  79884. while (state->bits >= 8) {
  79885. buf[len++] = (unsigned char)(state->hold);
  79886. state->hold >>= 8;
  79887. state->bits -= 8;
  79888. }
  79889. state->have = 0;
  79890. syncsearch(&(state->have), buf, len);
  79891. }
  79892. /* search available input */
  79893. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  79894. strm->avail_in -= len;
  79895. strm->next_in += len;
  79896. strm->total_in += len;
  79897. /* return no joy or set up to restart inflate() on a new block */
  79898. if (state->have != 4) return Z_DATA_ERROR;
  79899. in = strm->total_in; out = strm->total_out;
  79900. inflateReset(strm);
  79901. strm->total_in = in; strm->total_out = out;
  79902. state->mode = TYPE;
  79903. return Z_OK;
  79904. }
  79905. /*
  79906. Returns true if inflate is currently at the end of a block generated by
  79907. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  79908. implementation to provide an additional safety check. PPP uses
  79909. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  79910. block. When decompressing, PPP checks that at the end of input packet,
  79911. inflate is waiting for these length bytes.
  79912. */
  79913. int ZEXPORT inflateSyncPoint (z_streamp strm)
  79914. {
  79915. struct inflate_state FAR *state;
  79916. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  79917. state = (struct inflate_state FAR *)strm->state;
  79918. return state->mode == STORED && state->bits == 0;
  79919. }
  79920. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  79921. {
  79922. struct inflate_state FAR *state;
  79923. struct inflate_state FAR *copy;
  79924. unsigned char FAR *window;
  79925. unsigned wsize;
  79926. /* check input */
  79927. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  79928. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  79929. return Z_STREAM_ERROR;
  79930. state = (struct inflate_state FAR *)source->state;
  79931. /* allocate space */
  79932. copy = (struct inflate_state FAR *)
  79933. ZALLOC(source, 1, sizeof(struct inflate_state));
  79934. if (copy == Z_NULL) return Z_MEM_ERROR;
  79935. window = Z_NULL;
  79936. if (state->window != Z_NULL) {
  79937. window = (unsigned char FAR *)
  79938. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  79939. if (window == Z_NULL) {
  79940. ZFREE(source, copy);
  79941. return Z_MEM_ERROR;
  79942. }
  79943. }
  79944. /* copy state */
  79945. zmemcpy(dest, source, sizeof(z_stream));
  79946. zmemcpy(copy, state, sizeof(struct inflate_state));
  79947. if (state->lencode >= state->codes &&
  79948. state->lencode <= state->codes + ENOUGH - 1) {
  79949. copy->lencode = copy->codes + (state->lencode - state->codes);
  79950. copy->distcode = copy->codes + (state->distcode - state->codes);
  79951. }
  79952. copy->next = copy->codes + (state->next - state->codes);
  79953. if (window != Z_NULL) {
  79954. wsize = 1U << state->wbits;
  79955. zmemcpy(window, state->window, wsize);
  79956. }
  79957. copy->window = window;
  79958. dest->state = (struct internal_state FAR *)copy;
  79959. return Z_OK;
  79960. }
  79961. /********* End of inlined file: inflate.c *********/
  79962. /********* Start of inlined file: inftrees.c *********/
  79963. #define MAXBITS 15
  79964. const char inflate_copyright[] =
  79965. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  79966. /*
  79967. If you use the zlib library in a product, an acknowledgment is welcome
  79968. in the documentation of your product. If for some reason you cannot
  79969. include such an acknowledgment, I would appreciate that you keep this
  79970. copyright string in the executable of your product.
  79971. */
  79972. /*
  79973. Build a set of tables to decode the provided canonical Huffman code.
  79974. The code lengths are lens[0..codes-1]. The result starts at *table,
  79975. whose indices are 0..2^bits-1. work is a writable array of at least
  79976. lens shorts, which is used as a work area. type is the type of code
  79977. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  79978. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  79979. on return points to the next available entry's address. bits is the
  79980. requested root table index bits, and on return it is the actual root
  79981. table index bits. It will differ if the request is greater than the
  79982. longest code or if it is less than the shortest code.
  79983. */
  79984. int inflate_table (codetype type,
  79985. unsigned short FAR *lens,
  79986. unsigned codes,
  79987. code FAR * FAR *table,
  79988. unsigned FAR *bits,
  79989. unsigned short FAR *work)
  79990. {
  79991. unsigned len; /* a code's length in bits */
  79992. unsigned sym; /* index of code symbols */
  79993. unsigned min, max; /* minimum and maximum code lengths */
  79994. unsigned root; /* number of index bits for root table */
  79995. unsigned curr; /* number of index bits for current table */
  79996. unsigned drop; /* code bits to drop for sub-table */
  79997. int left; /* number of prefix codes available */
  79998. unsigned used; /* code entries in table used */
  79999. unsigned huff; /* Huffman code */
  80000. unsigned incr; /* for incrementing code, index */
  80001. unsigned fill; /* index for replicating entries */
  80002. unsigned low; /* low bits for current root entry */
  80003. unsigned mask; /* mask for low root bits */
  80004. code thisx; /* table entry for duplication */
  80005. code FAR *next; /* next available space in table */
  80006. const unsigned short FAR *base; /* base value table to use */
  80007. const unsigned short FAR *extra; /* extra bits table to use */
  80008. int end; /* use base and extra for symbol > end */
  80009. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  80010. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  80011. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  80012. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  80013. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  80014. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  80015. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  80016. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  80017. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  80018. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  80019. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  80020. 8193, 12289, 16385, 24577, 0, 0};
  80021. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  80022. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  80023. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  80024. 28, 28, 29, 29, 64, 64};
  80025. /*
  80026. Process a set of code lengths to create a canonical Huffman code. The
  80027. code lengths are lens[0..codes-1]. Each length corresponds to the
  80028. symbols 0..codes-1. The Huffman code is generated by first sorting the
  80029. symbols by length from short to long, and retaining the symbol order
  80030. for codes with equal lengths. Then the code starts with all zero bits
  80031. for the first code of the shortest length, and the codes are integer
  80032. increments for the same length, and zeros are appended as the length
  80033. increases. For the deflate format, these bits are stored backwards
  80034. from their more natural integer increment ordering, and so when the
  80035. decoding tables are built in the large loop below, the integer codes
  80036. are incremented backwards.
  80037. This routine assumes, but does not check, that all of the entries in
  80038. lens[] are in the range 0..MAXBITS. The caller must assure this.
  80039. 1..MAXBITS is interpreted as that code length. zero means that that
  80040. symbol does not occur in this code.
  80041. The codes are sorted by computing a count of codes for each length,
  80042. creating from that a table of starting indices for each length in the
  80043. sorted table, and then entering the symbols in order in the sorted
  80044. table. The sorted table is work[], with that space being provided by
  80045. the caller.
  80046. The length counts are used for other purposes as well, i.e. finding
  80047. the minimum and maximum length codes, determining if there are any
  80048. codes at all, checking for a valid set of lengths, and looking ahead
  80049. at length counts to determine sub-table sizes when building the
  80050. decoding tables.
  80051. */
  80052. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  80053. for (len = 0; len <= MAXBITS; len++)
  80054. count[len] = 0;
  80055. for (sym = 0; sym < codes; sym++)
  80056. count[lens[sym]]++;
  80057. /* bound code lengths, force root to be within code lengths */
  80058. root = *bits;
  80059. for (max = MAXBITS; max >= 1; max--)
  80060. if (count[max] != 0) break;
  80061. if (root > max) root = max;
  80062. if (max == 0) { /* no symbols to code at all */
  80063. thisx.op = (unsigned char)64; /* invalid code marker */
  80064. thisx.bits = (unsigned char)1;
  80065. thisx.val = (unsigned short)0;
  80066. *(*table)++ = thisx; /* make a table to force an error */
  80067. *(*table)++ = thisx;
  80068. *bits = 1;
  80069. return 0; /* no symbols, but wait for decoding to report error */
  80070. }
  80071. for (min = 1; min <= MAXBITS; min++)
  80072. if (count[min] != 0) break;
  80073. if (root < min) root = min;
  80074. /* check for an over-subscribed or incomplete set of lengths */
  80075. left = 1;
  80076. for (len = 1; len <= MAXBITS; len++) {
  80077. left <<= 1;
  80078. left -= count[len];
  80079. if (left < 0) return -1; /* over-subscribed */
  80080. }
  80081. if (left > 0 && (type == CODES || max != 1))
  80082. return -1; /* incomplete set */
  80083. /* generate offsets into symbol table for each length for sorting */
  80084. offs[1] = 0;
  80085. for (len = 1; len < MAXBITS; len++)
  80086. offs[len + 1] = offs[len] + count[len];
  80087. /* sort symbols by length, by symbol order within each length */
  80088. for (sym = 0; sym < codes; sym++)
  80089. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  80090. /*
  80091. Create and fill in decoding tables. In this loop, the table being
  80092. filled is at next and has curr index bits. The code being used is huff
  80093. with length len. That code is converted to an index by dropping drop
  80094. bits off of the bottom. For codes where len is less than drop + curr,
  80095. those top drop + curr - len bits are incremented through all values to
  80096. fill the table with replicated entries.
  80097. root is the number of index bits for the root table. When len exceeds
  80098. root, sub-tables are created pointed to by the root entry with an index
  80099. of the low root bits of huff. This is saved in low to check for when a
  80100. new sub-table should be started. drop is zero when the root table is
  80101. being filled, and drop is root when sub-tables are being filled.
  80102. When a new sub-table is needed, it is necessary to look ahead in the
  80103. code lengths to determine what size sub-table is needed. The length
  80104. counts are used for this, and so count[] is decremented as codes are
  80105. entered in the tables.
  80106. used keeps track of how many table entries have been allocated from the
  80107. provided *table space. It is checked when a LENS table is being made
  80108. against the space in *table, ENOUGH, minus the maximum space needed by
  80109. the worst case distance code, MAXD. This should never happen, but the
  80110. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  80111. This assumes that when type == LENS, bits == 9.
  80112. sym increments through all symbols, and the loop terminates when
  80113. all codes of length max, i.e. all codes, have been processed. This
  80114. routine permits incomplete codes, so another loop after this one fills
  80115. in the rest of the decoding tables with invalid code markers.
  80116. */
  80117. /* set up for code type */
  80118. switch (type) {
  80119. case CODES:
  80120. base = extra = work; /* dummy value--not used */
  80121. end = 19;
  80122. break;
  80123. case LENS:
  80124. base = lbase;
  80125. base -= 257;
  80126. extra = lext;
  80127. extra -= 257;
  80128. end = 256;
  80129. break;
  80130. default: /* DISTS */
  80131. base = dbase;
  80132. extra = dext;
  80133. end = -1;
  80134. }
  80135. /* initialize state for loop */
  80136. huff = 0; /* starting code */
  80137. sym = 0; /* starting code symbol */
  80138. len = min; /* starting code length */
  80139. next = *table; /* current table to fill in */
  80140. curr = root; /* current table index bits */
  80141. drop = 0; /* current bits to drop from code for index */
  80142. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  80143. used = 1U << root; /* use root table entries */
  80144. mask = used - 1; /* mask for comparing low */
  80145. /* check available table space */
  80146. if (type == LENS && used >= ENOUGH - MAXD)
  80147. return 1;
  80148. /* process all codes and make table entries */
  80149. for (;;) {
  80150. /* create table entry */
  80151. thisx.bits = (unsigned char)(len - drop);
  80152. if ((int)(work[sym]) < end) {
  80153. thisx.op = (unsigned char)0;
  80154. thisx.val = work[sym];
  80155. }
  80156. else if ((int)(work[sym]) > end) {
  80157. thisx.op = (unsigned char)(extra[work[sym]]);
  80158. thisx.val = base[work[sym]];
  80159. }
  80160. else {
  80161. thisx.op = (unsigned char)(32 + 64); /* end of block */
  80162. thisx.val = 0;
  80163. }
  80164. /* replicate for those indices with low len bits equal to huff */
  80165. incr = 1U << (len - drop);
  80166. fill = 1U << curr;
  80167. min = fill; /* save offset to next table */
  80168. do {
  80169. fill -= incr;
  80170. next[(huff >> drop) + fill] = thisx;
  80171. } while (fill != 0);
  80172. /* backwards increment the len-bit code huff */
  80173. incr = 1U << (len - 1);
  80174. while (huff & incr)
  80175. incr >>= 1;
  80176. if (incr != 0) {
  80177. huff &= incr - 1;
  80178. huff += incr;
  80179. }
  80180. else
  80181. huff = 0;
  80182. /* go to next symbol, update count, len */
  80183. sym++;
  80184. if (--(count[len]) == 0) {
  80185. if (len == max) break;
  80186. len = lens[work[sym]];
  80187. }
  80188. /* create new sub-table if needed */
  80189. if (len > root && (huff & mask) != low) {
  80190. /* if first time, transition to sub-tables */
  80191. if (drop == 0)
  80192. drop = root;
  80193. /* increment past last table */
  80194. next += min; /* here min is 1 << curr */
  80195. /* determine length of next table */
  80196. curr = len - drop;
  80197. left = (int)(1 << curr);
  80198. while (curr + drop < max) {
  80199. left -= count[curr + drop];
  80200. if (left <= 0) break;
  80201. curr++;
  80202. left <<= 1;
  80203. }
  80204. /* check for enough space */
  80205. used += 1U << curr;
  80206. if (type == LENS && used >= ENOUGH - MAXD)
  80207. return 1;
  80208. /* point entry in root table to sub-table */
  80209. low = huff & mask;
  80210. (*table)[low].op = (unsigned char)curr;
  80211. (*table)[low].bits = (unsigned char)root;
  80212. (*table)[low].val = (unsigned short)(next - *table);
  80213. }
  80214. }
  80215. /*
  80216. Fill in rest of table for incomplete codes. This loop is similar to the
  80217. loop above in incrementing huff for table indices. It is assumed that
  80218. len is equal to curr + drop, so there is no loop needed to increment
  80219. through high index bits. When the current sub-table is filled, the loop
  80220. drops back to the root table to fill in any remaining entries there.
  80221. */
  80222. thisx.op = (unsigned char)64; /* invalid code marker */
  80223. thisx.bits = (unsigned char)(len - drop);
  80224. thisx.val = (unsigned short)0;
  80225. while (huff != 0) {
  80226. /* when done with sub-table, drop back to root table */
  80227. if (drop != 0 && (huff & mask) != low) {
  80228. drop = 0;
  80229. len = root;
  80230. next = *table;
  80231. thisx.bits = (unsigned char)len;
  80232. }
  80233. /* put invalid code marker in table */
  80234. next[huff >> drop] = thisx;
  80235. /* backwards increment the len-bit code huff */
  80236. incr = 1U << (len - 1);
  80237. while (huff & incr)
  80238. incr >>= 1;
  80239. if (incr != 0) {
  80240. huff &= incr - 1;
  80241. huff += incr;
  80242. }
  80243. else
  80244. huff = 0;
  80245. }
  80246. /* set return parameters */
  80247. *table += used;
  80248. *bits = root;
  80249. return 0;
  80250. }
  80251. /********* End of inlined file: inftrees.c *********/
  80252. /********* Start of inlined file: trees.c *********/
  80253. /*
  80254. * ALGORITHM
  80255. *
  80256. * The "deflation" process uses several Huffman trees. The more
  80257. * common source values are represented by shorter bit sequences.
  80258. *
  80259. * Each code tree is stored in a compressed form which is itself
  80260. * a Huffman encoding of the lengths of all the code strings (in
  80261. * ascending order by source values). The actual code strings are
  80262. * reconstructed from the lengths in the inflate process, as described
  80263. * in the deflate specification.
  80264. *
  80265. * REFERENCES
  80266. *
  80267. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  80268. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  80269. *
  80270. * Storer, James A.
  80271. * Data Compression: Methods and Theory, pp. 49-50.
  80272. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  80273. *
  80274. * Sedgewick, R.
  80275. * Algorithms, p290.
  80276. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  80277. */
  80278. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80279. /* #define GEN_TREES_H */
  80280. #ifdef DEBUG
  80281. # include <ctype.h>
  80282. #endif
  80283. /* ===========================================================================
  80284. * Constants
  80285. */
  80286. #define MAX_BL_BITS 7
  80287. /* Bit length codes must not exceed MAX_BL_BITS bits */
  80288. #define END_BLOCK 256
  80289. /* end of block literal code */
  80290. #define REP_3_6 16
  80291. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  80292. #define REPZ_3_10 17
  80293. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  80294. #define REPZ_11_138 18
  80295. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  80296. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  80297. = {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};
  80298. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  80299. = {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};
  80300. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  80301. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  80302. local const uch bl_order[BL_CODES]
  80303. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  80304. /* The lengths of the bit length codes are sent in order of decreasing
  80305. * probability, to avoid transmitting the lengths for unused bit length codes.
  80306. */
  80307. #define Buf_size (8 * 2*sizeof(char))
  80308. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  80309. * more than 16 bits on some systems.)
  80310. */
  80311. /* ===========================================================================
  80312. * Local data. These are initialized only once.
  80313. */
  80314. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  80315. #if defined(GEN_TREES_H) || !defined(STDC)
  80316. /* non ANSI compilers may not accept trees.h */
  80317. local ct_data static_ltree[L_CODES+2];
  80318. /* The static literal tree. Since the bit lengths are imposed, there is no
  80319. * need for the L_CODES extra codes used during heap construction. However
  80320. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  80321. * below).
  80322. */
  80323. local ct_data static_dtree[D_CODES];
  80324. /* The static distance tree. (Actually a trivial tree since all codes use
  80325. * 5 bits.)
  80326. */
  80327. uch _dist_code[DIST_CODE_LEN];
  80328. /* Distance codes. The first 256 values correspond to the distances
  80329. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  80330. * the 15 bit distances.
  80331. */
  80332. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  80333. /* length code for each normalized match length (0 == MIN_MATCH) */
  80334. local int base_length[LENGTH_CODES];
  80335. /* First normalized length for each code (0 = MIN_MATCH) */
  80336. local int base_dist[D_CODES];
  80337. /* First normalized distance for each code (0 = distance of 1) */
  80338. #else
  80339. /********* Start of inlined file: trees.h *********/
  80340. local const ct_data static_ltree[L_CODES+2] = {
  80341. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  80342. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  80343. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  80344. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  80345. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  80346. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  80347. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  80348. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  80349. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  80350. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  80351. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  80352. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  80353. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  80354. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  80355. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  80356. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  80357. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  80358. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  80359. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  80360. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  80361. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  80362. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  80363. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  80364. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  80365. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  80366. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  80367. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  80368. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  80369. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  80370. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  80371. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  80372. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  80373. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  80374. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  80375. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  80376. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  80377. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  80378. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  80379. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  80380. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  80381. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  80382. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  80383. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  80384. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  80385. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  80386. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  80387. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  80388. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  80389. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  80390. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  80391. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  80392. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  80393. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  80394. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  80395. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  80396. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  80397. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  80398. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  80399. };
  80400. local const ct_data static_dtree[D_CODES] = {
  80401. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  80402. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  80403. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  80404. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  80405. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  80406. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  80407. };
  80408. const uch _dist_code[DIST_CODE_LEN] = {
  80409. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  80410. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  80411. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  80412. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  80413. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  80414. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  80415. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80416. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80417. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  80418. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  80419. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80420. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  80421. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  80422. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  80423. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80424. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80425. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80426. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  80427. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80428. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80429. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80430. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  80431. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80432. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80433. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  80434. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  80435. };
  80436. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  80437. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  80438. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  80439. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  80440. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  80441. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  80442. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  80443. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80444. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  80445. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  80446. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  80447. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  80448. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  80449. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  80450. };
  80451. local const int base_length[LENGTH_CODES] = {
  80452. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  80453. 64, 80, 96, 112, 128, 160, 192, 224, 0
  80454. };
  80455. local const int base_dist[D_CODES] = {
  80456. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  80457. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  80458. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  80459. };
  80460. /********* End of inlined file: trees.h *********/
  80461. #endif /* GEN_TREES_H */
  80462. struct static_tree_desc_s {
  80463. const ct_data *static_tree; /* static tree or NULL */
  80464. const intf *extra_bits; /* extra bits for each code or NULL */
  80465. int extra_base; /* base index for extra_bits */
  80466. int elems; /* max number of elements in the tree */
  80467. int max_length; /* max bit length for the codes */
  80468. };
  80469. local static_tree_desc static_l_desc =
  80470. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  80471. local static_tree_desc static_d_desc =
  80472. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  80473. local static_tree_desc static_bl_desc =
  80474. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  80475. /* ===========================================================================
  80476. * Local (static) routines in this file.
  80477. */
  80478. local void tr_static_init OF((void));
  80479. local void init_block OF((deflate_state *s));
  80480. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  80481. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  80482. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  80483. local void build_tree OF((deflate_state *s, tree_desc *desc));
  80484. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80485. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  80486. local int build_bl_tree OF((deflate_state *s));
  80487. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  80488. int blcodes));
  80489. local void compress_block OF((deflate_state *s, ct_data *ltree,
  80490. ct_data *dtree));
  80491. local void set_data_type OF((deflate_state *s));
  80492. local unsigned bi_reverse OF((unsigned value, int length));
  80493. local void bi_windup OF((deflate_state *s));
  80494. local void bi_flush OF((deflate_state *s));
  80495. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  80496. int header));
  80497. #ifdef GEN_TREES_H
  80498. local void gen_trees_header OF((void));
  80499. #endif
  80500. #ifndef DEBUG
  80501. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  80502. /* Send a code of the given tree. c and tree must not have side effects */
  80503. #else /* DEBUG */
  80504. # define send_code(s, c, tree) \
  80505. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  80506. send_bits(s, tree[c].Code, tree[c].Len); }
  80507. #endif
  80508. /* ===========================================================================
  80509. * Output a short LSB first on the stream.
  80510. * IN assertion: there is enough room in pendingBuf.
  80511. */
  80512. #define put_short(s, w) { \
  80513. put_byte(s, (uch)((w) & 0xff)); \
  80514. put_byte(s, (uch)((ush)(w) >> 8)); \
  80515. }
  80516. /* ===========================================================================
  80517. * Send a value on a given number of bits.
  80518. * IN assertion: length <= 16 and value fits in length bits.
  80519. */
  80520. #ifdef DEBUG
  80521. local void send_bits OF((deflate_state *s, int value, int length));
  80522. local void send_bits (deflate_state *s, int value, int length)
  80523. {
  80524. Tracevv((stderr," l %2d v %4x ", length, value));
  80525. Assert(length > 0 && length <= 15, "invalid length");
  80526. s->bits_sent += (ulg)length;
  80527. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  80528. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  80529. * unused bits in value.
  80530. */
  80531. if (s->bi_valid > (int)Buf_size - length) {
  80532. s->bi_buf |= (value << s->bi_valid);
  80533. put_short(s, s->bi_buf);
  80534. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  80535. s->bi_valid += length - Buf_size;
  80536. } else {
  80537. s->bi_buf |= value << s->bi_valid;
  80538. s->bi_valid += length;
  80539. }
  80540. }
  80541. #else /* !DEBUG */
  80542. #define send_bits(s, value, length) \
  80543. { int len = length;\
  80544. if (s->bi_valid > (int)Buf_size - len) {\
  80545. int val = value;\
  80546. s->bi_buf |= (val << s->bi_valid);\
  80547. put_short(s, s->bi_buf);\
  80548. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  80549. s->bi_valid += len - Buf_size;\
  80550. } else {\
  80551. s->bi_buf |= (value) << s->bi_valid;\
  80552. s->bi_valid += len;\
  80553. }\
  80554. }
  80555. #endif /* DEBUG */
  80556. /* the arguments must not have side effects */
  80557. /* ===========================================================================
  80558. * Initialize the various 'constant' tables.
  80559. */
  80560. local void tr_static_init()
  80561. {
  80562. #if defined(GEN_TREES_H) || !defined(STDC)
  80563. static int static_init_done = 0;
  80564. int n; /* iterates over tree elements */
  80565. int bits; /* bit counter */
  80566. int length; /* length value */
  80567. int code; /* code value */
  80568. int dist; /* distance index */
  80569. ush bl_count[MAX_BITS+1];
  80570. /* number of codes at each bit length for an optimal tree */
  80571. if (static_init_done) return;
  80572. /* For some embedded targets, global variables are not initialized: */
  80573. static_l_desc.static_tree = static_ltree;
  80574. static_l_desc.extra_bits = extra_lbits;
  80575. static_d_desc.static_tree = static_dtree;
  80576. static_d_desc.extra_bits = extra_dbits;
  80577. static_bl_desc.extra_bits = extra_blbits;
  80578. /* Initialize the mapping length (0..255) -> length code (0..28) */
  80579. length = 0;
  80580. for (code = 0; code < LENGTH_CODES-1; code++) {
  80581. base_length[code] = length;
  80582. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  80583. _length_code[length++] = (uch)code;
  80584. }
  80585. }
  80586. Assert (length == 256, "tr_static_init: length != 256");
  80587. /* Note that the length 255 (match length 258) can be represented
  80588. * in two different ways: code 284 + 5 bits or code 285, so we
  80589. * overwrite length_code[255] to use the best encoding:
  80590. */
  80591. _length_code[length-1] = (uch)code;
  80592. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  80593. dist = 0;
  80594. for (code = 0 ; code < 16; code++) {
  80595. base_dist[code] = dist;
  80596. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  80597. _dist_code[dist++] = (uch)code;
  80598. }
  80599. }
  80600. Assert (dist == 256, "tr_static_init: dist != 256");
  80601. dist >>= 7; /* from now on, all distances are divided by 128 */
  80602. for ( ; code < D_CODES; code++) {
  80603. base_dist[code] = dist << 7;
  80604. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  80605. _dist_code[256 + dist++] = (uch)code;
  80606. }
  80607. }
  80608. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  80609. /* Construct the codes of the static literal tree */
  80610. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  80611. n = 0;
  80612. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  80613. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  80614. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  80615. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  80616. /* Codes 286 and 287 do not exist, but we must include them in the
  80617. * tree construction to get a canonical Huffman tree (longest code
  80618. * all ones)
  80619. */
  80620. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  80621. /* The static distance tree is trivial: */
  80622. for (n = 0; n < D_CODES; n++) {
  80623. static_dtree[n].Len = 5;
  80624. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  80625. }
  80626. static_init_done = 1;
  80627. # ifdef GEN_TREES_H
  80628. gen_trees_header();
  80629. # endif
  80630. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  80631. }
  80632. /* ===========================================================================
  80633. * Genererate the file trees.h describing the static trees.
  80634. */
  80635. #ifdef GEN_TREES_H
  80636. # ifndef DEBUG
  80637. # include <stdio.h>
  80638. # endif
  80639. # define SEPARATOR(i, last, width) \
  80640. ((i) == (last)? "\n};\n\n" : \
  80641. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  80642. void gen_trees_header()
  80643. {
  80644. FILE *header = fopen("trees.h", "w");
  80645. int i;
  80646. Assert (header != NULL, "Can't open trees.h");
  80647. fprintf(header,
  80648. "/* header created automatically with -DGEN_TREES_H */\n\n");
  80649. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  80650. for (i = 0; i < L_CODES+2; i++) {
  80651. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  80652. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  80653. }
  80654. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  80655. for (i = 0; i < D_CODES; i++) {
  80656. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  80657. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  80658. }
  80659. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  80660. for (i = 0; i < DIST_CODE_LEN; i++) {
  80661. fprintf(header, "%2u%s", _dist_code[i],
  80662. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  80663. }
  80664. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  80665. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  80666. fprintf(header, "%2u%s", _length_code[i],
  80667. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  80668. }
  80669. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  80670. for (i = 0; i < LENGTH_CODES; i++) {
  80671. fprintf(header, "%1u%s", base_length[i],
  80672. SEPARATOR(i, LENGTH_CODES-1, 20));
  80673. }
  80674. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  80675. for (i = 0; i < D_CODES; i++) {
  80676. fprintf(header, "%5u%s", base_dist[i],
  80677. SEPARATOR(i, D_CODES-1, 10));
  80678. }
  80679. fclose(header);
  80680. }
  80681. #endif /* GEN_TREES_H */
  80682. /* ===========================================================================
  80683. * Initialize the tree data structures for a new zlib stream.
  80684. */
  80685. void _tr_init(deflate_state *s)
  80686. {
  80687. tr_static_init();
  80688. s->l_desc.dyn_tree = s->dyn_ltree;
  80689. s->l_desc.stat_desc = &static_l_desc;
  80690. s->d_desc.dyn_tree = s->dyn_dtree;
  80691. s->d_desc.stat_desc = &static_d_desc;
  80692. s->bl_desc.dyn_tree = s->bl_tree;
  80693. s->bl_desc.stat_desc = &static_bl_desc;
  80694. s->bi_buf = 0;
  80695. s->bi_valid = 0;
  80696. s->last_eob_len = 8; /* enough lookahead for inflate */
  80697. #ifdef DEBUG
  80698. s->compressed_len = 0L;
  80699. s->bits_sent = 0L;
  80700. #endif
  80701. /* Initialize the first block of the first file: */
  80702. init_block(s);
  80703. }
  80704. /* ===========================================================================
  80705. * Initialize a new block.
  80706. */
  80707. local void init_block (deflate_state *s)
  80708. {
  80709. int n; /* iterates over tree elements */
  80710. /* Initialize the trees. */
  80711. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  80712. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  80713. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  80714. s->dyn_ltree[END_BLOCK].Freq = 1;
  80715. s->opt_len = s->static_len = 0L;
  80716. s->last_lit = s->matches = 0;
  80717. }
  80718. #define SMALLEST 1
  80719. /* Index within the heap array of least frequent node in the Huffman tree */
  80720. /* ===========================================================================
  80721. * Remove the smallest element from the heap and recreate the heap with
  80722. * one less element. Updates heap and heap_len.
  80723. */
  80724. #define pqremove(s, tree, top) \
  80725. {\
  80726. top = s->heap[SMALLEST]; \
  80727. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  80728. pqdownheap(s, tree, SMALLEST); \
  80729. }
  80730. /* ===========================================================================
  80731. * Compares to subtrees, using the tree depth as tie breaker when
  80732. * the subtrees have equal frequency. This minimizes the worst case length.
  80733. */
  80734. #define smaller(tree, n, m, depth) \
  80735. (tree[n].Freq < tree[m].Freq || \
  80736. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  80737. /* ===========================================================================
  80738. * Restore the heap property by moving down the tree starting at node k,
  80739. * exchanging a node with the smallest of its two sons if necessary, stopping
  80740. * when the heap property is re-established (each father smaller than its
  80741. * two sons).
  80742. */
  80743. local void pqdownheap (deflate_state *s,
  80744. ct_data *tree, /* the tree to restore */
  80745. int k) /* node to move down */
  80746. {
  80747. int v = s->heap[k];
  80748. int j = k << 1; /* left son of k */
  80749. while (j <= s->heap_len) {
  80750. /* Set j to the smallest of the two sons: */
  80751. if (j < s->heap_len &&
  80752. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  80753. j++;
  80754. }
  80755. /* Exit if v is smaller than both sons */
  80756. if (smaller(tree, v, s->heap[j], s->depth)) break;
  80757. /* Exchange v with the smallest son */
  80758. s->heap[k] = s->heap[j]; k = j;
  80759. /* And continue down the tree, setting j to the left son of k */
  80760. j <<= 1;
  80761. }
  80762. s->heap[k] = v;
  80763. }
  80764. /* ===========================================================================
  80765. * Compute the optimal bit lengths for a tree and update the total bit length
  80766. * for the current block.
  80767. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  80768. * above are the tree nodes sorted by increasing frequency.
  80769. * OUT assertions: the field len is set to the optimal bit length, the
  80770. * array bl_count contains the frequencies for each bit length.
  80771. * The length opt_len is updated; static_len is also updated if stree is
  80772. * not null.
  80773. */
  80774. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  80775. {
  80776. ct_data *tree = desc->dyn_tree;
  80777. int max_code = desc->max_code;
  80778. const ct_data *stree = desc->stat_desc->static_tree;
  80779. const intf *extra = desc->stat_desc->extra_bits;
  80780. int base = desc->stat_desc->extra_base;
  80781. int max_length = desc->stat_desc->max_length;
  80782. int h; /* heap index */
  80783. int n, m; /* iterate over the tree elements */
  80784. int bits; /* bit length */
  80785. int xbits; /* extra bits */
  80786. ush f; /* frequency */
  80787. int overflow = 0; /* number of elements with bit length too large */
  80788. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  80789. /* In a first pass, compute the optimal bit lengths (which may
  80790. * overflow in the case of the bit length tree).
  80791. */
  80792. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  80793. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  80794. n = s->heap[h];
  80795. bits = tree[tree[n].Dad].Len + 1;
  80796. if (bits > max_length) bits = max_length, overflow++;
  80797. tree[n].Len = (ush)bits;
  80798. /* We overwrite tree[n].Dad which is no longer needed */
  80799. if (n > max_code) continue; /* not a leaf node */
  80800. s->bl_count[bits]++;
  80801. xbits = 0;
  80802. if (n >= base) xbits = extra[n-base];
  80803. f = tree[n].Freq;
  80804. s->opt_len += (ulg)f * (bits + xbits);
  80805. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  80806. }
  80807. if (overflow == 0) return;
  80808. Trace((stderr,"\nbit length overflow\n"));
  80809. /* This happens for example on obj2 and pic of the Calgary corpus */
  80810. /* Find the first bit length which could increase: */
  80811. do {
  80812. bits = max_length-1;
  80813. while (s->bl_count[bits] == 0) bits--;
  80814. s->bl_count[bits]--; /* move one leaf down the tree */
  80815. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  80816. s->bl_count[max_length]--;
  80817. /* The brother of the overflow item also moves one step up,
  80818. * but this does not affect bl_count[max_length]
  80819. */
  80820. overflow -= 2;
  80821. } while (overflow > 0);
  80822. /* Now recompute all bit lengths, scanning in increasing frequency.
  80823. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  80824. * lengths instead of fixing only the wrong ones. This idea is taken
  80825. * from 'ar' written by Haruhiko Okumura.)
  80826. */
  80827. for (bits = max_length; bits != 0; bits--) {
  80828. n = s->bl_count[bits];
  80829. while (n != 0) {
  80830. m = s->heap[--h];
  80831. if (m > max_code) continue;
  80832. if ((unsigned) tree[m].Len != (unsigned) bits) {
  80833. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  80834. s->opt_len += ((long)bits - (long)tree[m].Len)
  80835. *(long)tree[m].Freq;
  80836. tree[m].Len = (ush)bits;
  80837. }
  80838. n--;
  80839. }
  80840. }
  80841. }
  80842. /* ===========================================================================
  80843. * Generate the codes for a given tree and bit counts (which need not be
  80844. * optimal).
  80845. * IN assertion: the array bl_count contains the bit length statistics for
  80846. * the given tree and the field len is set for all tree elements.
  80847. * OUT assertion: the field code is set for all tree elements of non
  80848. * zero code length.
  80849. */
  80850. local void gen_codes (ct_data *tree, /* the tree to decorate */
  80851. int max_code, /* largest code with non zero frequency */
  80852. ushf *bl_count) /* number of codes at each bit length */
  80853. {
  80854. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  80855. ush code = 0; /* running code value */
  80856. int bits; /* bit index */
  80857. int n; /* code index */
  80858. /* The distribution counts are first used to generate the code values
  80859. * without bit reversal.
  80860. */
  80861. for (bits = 1; bits <= MAX_BITS; bits++) {
  80862. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  80863. }
  80864. /* Check that the bit counts in bl_count are consistent. The last code
  80865. * must be all ones.
  80866. */
  80867. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  80868. "inconsistent bit counts");
  80869. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  80870. for (n = 0; n <= max_code; n++) {
  80871. int len = tree[n].Len;
  80872. if (len == 0) continue;
  80873. /* Now reverse the bits */
  80874. tree[n].Code = bi_reverse(next_code[len]++, len);
  80875. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  80876. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  80877. }
  80878. }
  80879. /* ===========================================================================
  80880. * Construct one Huffman tree and assigns the code bit strings and lengths.
  80881. * Update the total bit length for the current block.
  80882. * IN assertion: the field freq is set for all tree elements.
  80883. * OUT assertions: the fields len and code are set to the optimal bit length
  80884. * and corresponding code. The length opt_len is updated; static_len is
  80885. * also updated if stree is not null. The field max_code is set.
  80886. */
  80887. local void build_tree (deflate_state *s,
  80888. tree_desc *desc) /* the tree descriptor */
  80889. {
  80890. ct_data *tree = desc->dyn_tree;
  80891. const ct_data *stree = desc->stat_desc->static_tree;
  80892. int elems = desc->stat_desc->elems;
  80893. int n, m; /* iterate over heap elements */
  80894. int max_code = -1; /* largest code with non zero frequency */
  80895. int node; /* new node being created */
  80896. /* Construct the initial heap, with least frequent element in
  80897. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  80898. * heap[0] is not used.
  80899. */
  80900. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  80901. for (n = 0; n < elems; n++) {
  80902. if (tree[n].Freq != 0) {
  80903. s->heap[++(s->heap_len)] = max_code = n;
  80904. s->depth[n] = 0;
  80905. } else {
  80906. tree[n].Len = 0;
  80907. }
  80908. }
  80909. /* The pkzip format requires that at least one distance code exists,
  80910. * and that at least one bit should be sent even if there is only one
  80911. * possible code. So to avoid special checks later on we force at least
  80912. * two codes of non zero frequency.
  80913. */
  80914. while (s->heap_len < 2) {
  80915. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  80916. tree[node].Freq = 1;
  80917. s->depth[node] = 0;
  80918. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  80919. /* node is 0 or 1 so it does not have extra bits */
  80920. }
  80921. desc->max_code = max_code;
  80922. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  80923. * establish sub-heaps of increasing lengths:
  80924. */
  80925. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  80926. /* Construct the Huffman tree by repeatedly combining the least two
  80927. * frequent nodes.
  80928. */
  80929. node = elems; /* next internal node of the tree */
  80930. do {
  80931. pqremove(s, tree, n); /* n = node of least frequency */
  80932. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  80933. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  80934. s->heap[--(s->heap_max)] = m;
  80935. /* Create a new node father of n and m */
  80936. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  80937. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  80938. s->depth[n] : s->depth[m]) + 1);
  80939. tree[n].Dad = tree[m].Dad = (ush)node;
  80940. #ifdef DUMP_BL_TREE
  80941. if (tree == s->bl_tree) {
  80942. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  80943. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  80944. }
  80945. #endif
  80946. /* and insert the new node in the heap */
  80947. s->heap[SMALLEST] = node++;
  80948. pqdownheap(s, tree, SMALLEST);
  80949. } while (s->heap_len >= 2);
  80950. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  80951. /* At this point, the fields freq and dad are set. We can now
  80952. * generate the bit lengths.
  80953. */
  80954. gen_bitlen(s, (tree_desc *)desc);
  80955. /* The field len is now set, we can generate the bit codes */
  80956. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  80957. }
  80958. /* ===========================================================================
  80959. * Scan a literal or distance tree to determine the frequencies of the codes
  80960. * in the bit length tree.
  80961. */
  80962. local void scan_tree (deflate_state *s,
  80963. ct_data *tree, /* the tree to be scanned */
  80964. int max_code) /* and its largest code of non zero frequency */
  80965. {
  80966. int n; /* iterates over all tree elements */
  80967. int prevlen = -1; /* last emitted length */
  80968. int curlen; /* length of current code */
  80969. int nextlen = tree[0].Len; /* length of next code */
  80970. int count = 0; /* repeat count of the current code */
  80971. int max_count = 7; /* max repeat count */
  80972. int min_count = 4; /* min repeat count */
  80973. if (nextlen == 0) max_count = 138, min_count = 3;
  80974. tree[max_code+1].Len = (ush)0xffff; /* guard */
  80975. for (n = 0; n <= max_code; n++) {
  80976. curlen = nextlen; nextlen = tree[n+1].Len;
  80977. if (++count < max_count && curlen == nextlen) {
  80978. continue;
  80979. } else if (count < min_count) {
  80980. s->bl_tree[curlen].Freq += count;
  80981. } else if (curlen != 0) {
  80982. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  80983. s->bl_tree[REP_3_6].Freq++;
  80984. } else if (count <= 10) {
  80985. s->bl_tree[REPZ_3_10].Freq++;
  80986. } else {
  80987. s->bl_tree[REPZ_11_138].Freq++;
  80988. }
  80989. count = 0; prevlen = curlen;
  80990. if (nextlen == 0) {
  80991. max_count = 138, min_count = 3;
  80992. } else if (curlen == nextlen) {
  80993. max_count = 6, min_count = 3;
  80994. } else {
  80995. max_count = 7, min_count = 4;
  80996. }
  80997. }
  80998. }
  80999. /* ===========================================================================
  81000. * Send a literal or distance tree in compressed form, using the codes in
  81001. * bl_tree.
  81002. */
  81003. local void send_tree (deflate_state *s,
  81004. ct_data *tree, /* the tree to be scanned */
  81005. int max_code) /* and its largest code of non zero frequency */
  81006. {
  81007. int n; /* iterates over all tree elements */
  81008. int prevlen = -1; /* last emitted length */
  81009. int curlen; /* length of current code */
  81010. int nextlen = tree[0].Len; /* length of next code */
  81011. int count = 0; /* repeat count of the current code */
  81012. int max_count = 7; /* max repeat count */
  81013. int min_count = 4; /* min repeat count */
  81014. /* tree[max_code+1].Len = -1; */ /* guard already set */
  81015. if (nextlen == 0) max_count = 138, min_count = 3;
  81016. for (n = 0; n <= max_code; n++) {
  81017. curlen = nextlen; nextlen = tree[n+1].Len;
  81018. if (++count < max_count && curlen == nextlen) {
  81019. continue;
  81020. } else if (count < min_count) {
  81021. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  81022. } else if (curlen != 0) {
  81023. if (curlen != prevlen) {
  81024. send_code(s, curlen, s->bl_tree); count--;
  81025. }
  81026. Assert(count >= 3 && count <= 6, " 3_6?");
  81027. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  81028. } else if (count <= 10) {
  81029. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  81030. } else {
  81031. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  81032. }
  81033. count = 0; prevlen = curlen;
  81034. if (nextlen == 0) {
  81035. max_count = 138, min_count = 3;
  81036. } else if (curlen == nextlen) {
  81037. max_count = 6, min_count = 3;
  81038. } else {
  81039. max_count = 7, min_count = 4;
  81040. }
  81041. }
  81042. }
  81043. /* ===========================================================================
  81044. * Construct the Huffman tree for the bit lengths and return the index in
  81045. * bl_order of the last bit length code to send.
  81046. */
  81047. local int build_bl_tree (deflate_state *s)
  81048. {
  81049. int max_blindex; /* index of last bit length code of non zero freq */
  81050. /* Determine the bit length frequencies for literal and distance trees */
  81051. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  81052. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  81053. /* Build the bit length tree: */
  81054. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  81055. /* opt_len now includes the length of the tree representations, except
  81056. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  81057. */
  81058. /* Determine the number of bit length codes to send. The pkzip format
  81059. * requires that at least 4 bit length codes be sent. (appnote.txt says
  81060. * 3 but the actual value used is 4.)
  81061. */
  81062. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  81063. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  81064. }
  81065. /* Update opt_len to include the bit length tree and counts */
  81066. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  81067. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  81068. s->opt_len, s->static_len));
  81069. return max_blindex;
  81070. }
  81071. /* ===========================================================================
  81072. * Send the header for a block using dynamic Huffman trees: the counts, the
  81073. * lengths of the bit length codes, the literal tree and the distance tree.
  81074. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  81075. */
  81076. local void send_all_trees (deflate_state *s,
  81077. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  81078. {
  81079. int rank; /* index in bl_order */
  81080. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  81081. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  81082. "too many codes");
  81083. Tracev((stderr, "\nbl counts: "));
  81084. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  81085. send_bits(s, dcodes-1, 5);
  81086. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  81087. for (rank = 0; rank < blcodes; rank++) {
  81088. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  81089. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  81090. }
  81091. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  81092. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  81093. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  81094. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  81095. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  81096. }
  81097. /* ===========================================================================
  81098. * Send a stored block
  81099. */
  81100. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  81101. {
  81102. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  81103. #ifdef DEBUG
  81104. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  81105. s->compressed_len += (stored_len + 4) << 3;
  81106. #endif
  81107. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  81108. }
  81109. /* ===========================================================================
  81110. * Send one empty static block to give enough lookahead for inflate.
  81111. * This takes 10 bits, of which 7 may remain in the bit buffer.
  81112. * The current inflate code requires 9 bits of lookahead. If the
  81113. * last two codes for the previous block (real code plus EOB) were coded
  81114. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  81115. * the last real code. In this case we send two empty static blocks instead
  81116. * of one. (There are no problems if the previous block is stored or fixed.)
  81117. * To simplify the code, we assume the worst case of last real code encoded
  81118. * on one bit only.
  81119. */
  81120. void _tr_align (deflate_state *s)
  81121. {
  81122. send_bits(s, STATIC_TREES<<1, 3);
  81123. send_code(s, END_BLOCK, static_ltree);
  81124. #ifdef DEBUG
  81125. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  81126. #endif
  81127. bi_flush(s);
  81128. /* Of the 10 bits for the empty block, we have already sent
  81129. * (10 - bi_valid) bits. The lookahead for the last real code (before
  81130. * the EOB of the previous block) was thus at least one plus the length
  81131. * of the EOB plus what we have just sent of the empty static block.
  81132. */
  81133. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  81134. send_bits(s, STATIC_TREES<<1, 3);
  81135. send_code(s, END_BLOCK, static_ltree);
  81136. #ifdef DEBUG
  81137. s->compressed_len += 10L;
  81138. #endif
  81139. bi_flush(s);
  81140. }
  81141. s->last_eob_len = 7;
  81142. }
  81143. /* ===========================================================================
  81144. * Determine the best encoding for the current block: dynamic trees, static
  81145. * trees or store, and output the encoded block to the zip file.
  81146. */
  81147. void _tr_flush_block (deflate_state *s,
  81148. charf *buf, /* input block, or NULL if too old */
  81149. ulg stored_len, /* length of input block */
  81150. int eof) /* true if this is the last block for a file */
  81151. {
  81152. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  81153. int max_blindex = 0; /* index of last bit length code of non zero freq */
  81154. /* Build the Huffman trees unless a stored block is forced */
  81155. if (s->level > 0) {
  81156. /* Check if the file is binary or text */
  81157. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  81158. set_data_type(s);
  81159. /* Construct the literal and distance trees */
  81160. build_tree(s, (tree_desc *)(&(s->l_desc)));
  81161. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  81162. s->static_len));
  81163. build_tree(s, (tree_desc *)(&(s->d_desc)));
  81164. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  81165. s->static_len));
  81166. /* At this point, opt_len and static_len are the total bit lengths of
  81167. * the compressed block data, excluding the tree representations.
  81168. */
  81169. /* Build the bit length tree for the above two trees, and get the index
  81170. * in bl_order of the last bit length code to send.
  81171. */
  81172. max_blindex = build_bl_tree(s);
  81173. /* Determine the best encoding. Compute the block lengths in bytes. */
  81174. opt_lenb = (s->opt_len+3+7)>>3;
  81175. static_lenb = (s->static_len+3+7)>>3;
  81176. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  81177. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  81178. s->last_lit));
  81179. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  81180. } else {
  81181. Assert(buf != (char*)0, "lost buf");
  81182. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  81183. }
  81184. #ifdef FORCE_STORED
  81185. if (buf != (char*)0) { /* force stored block */
  81186. #else
  81187. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  81188. /* 4: two words for the lengths */
  81189. #endif
  81190. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  81191. * Otherwise we can't have processed more than WSIZE input bytes since
  81192. * the last block flush, because compression would have been
  81193. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  81194. * transform a block into a stored block.
  81195. */
  81196. _tr_stored_block(s, buf, stored_len, eof);
  81197. #ifdef FORCE_STATIC
  81198. } else if (static_lenb >= 0) { /* force static trees */
  81199. #else
  81200. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  81201. #endif
  81202. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  81203. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  81204. #ifdef DEBUG
  81205. s->compressed_len += 3 + s->static_len;
  81206. #endif
  81207. } else {
  81208. send_bits(s, (DYN_TREES<<1)+eof, 3);
  81209. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  81210. max_blindex+1);
  81211. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  81212. #ifdef DEBUG
  81213. s->compressed_len += 3 + s->opt_len;
  81214. #endif
  81215. }
  81216. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  81217. /* The above check is made mod 2^32, for files larger than 512 MB
  81218. * and uLong implemented on 32 bits.
  81219. */
  81220. init_block(s);
  81221. if (eof) {
  81222. bi_windup(s);
  81223. #ifdef DEBUG
  81224. s->compressed_len += 7; /* align on byte boundary */
  81225. #endif
  81226. }
  81227. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  81228. s->compressed_len-7*eof));
  81229. }
  81230. /* ===========================================================================
  81231. * Save the match info and tally the frequency counts. Return true if
  81232. * the current block must be flushed.
  81233. */
  81234. int _tr_tally (deflate_state *s,
  81235. unsigned dist, /* distance of matched string */
  81236. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  81237. {
  81238. s->d_buf[s->last_lit] = (ush)dist;
  81239. s->l_buf[s->last_lit++] = (uch)lc;
  81240. if (dist == 0) {
  81241. /* lc is the unmatched char */
  81242. s->dyn_ltree[lc].Freq++;
  81243. } else {
  81244. s->matches++;
  81245. /* Here, lc is the match length - MIN_MATCH */
  81246. dist--; /* dist = match distance - 1 */
  81247. Assert((ush)dist < (ush)MAX_DIST(s) &&
  81248. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  81249. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  81250. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  81251. s->dyn_dtree[d_code(dist)].Freq++;
  81252. }
  81253. #ifdef TRUNCATE_BLOCK
  81254. /* Try to guess if it is profitable to stop the current block here */
  81255. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  81256. /* Compute an upper bound for the compressed length */
  81257. ulg out_length = (ulg)s->last_lit*8L;
  81258. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  81259. int dcode;
  81260. for (dcode = 0; dcode < D_CODES; dcode++) {
  81261. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  81262. (5L+extra_dbits[dcode]);
  81263. }
  81264. out_length >>= 3;
  81265. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  81266. s->last_lit, in_length, out_length,
  81267. 100L - out_length*100L/in_length));
  81268. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  81269. }
  81270. #endif
  81271. return (s->last_lit == s->lit_bufsize-1);
  81272. /* We avoid equality with lit_bufsize because of wraparound at 64K
  81273. * on 16 bit machines and because stored blocks are restricted to
  81274. * 64K-1 bytes.
  81275. */
  81276. }
  81277. /* ===========================================================================
  81278. * Send the block data compressed using the given Huffman trees
  81279. */
  81280. local void compress_block (deflate_state *s,
  81281. ct_data *ltree, /* literal tree */
  81282. ct_data *dtree) /* distance tree */
  81283. {
  81284. unsigned dist; /* distance of matched string */
  81285. int lc; /* match length or unmatched char (if dist == 0) */
  81286. unsigned lx = 0; /* running index in l_buf */
  81287. unsigned code; /* the code to send */
  81288. int extra; /* number of extra bits to send */
  81289. if (s->last_lit != 0) do {
  81290. dist = s->d_buf[lx];
  81291. lc = s->l_buf[lx++];
  81292. if (dist == 0) {
  81293. send_code(s, lc, ltree); /* send a literal byte */
  81294. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  81295. } else {
  81296. /* Here, lc is the match length - MIN_MATCH */
  81297. code = _length_code[lc];
  81298. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  81299. extra = extra_lbits[code];
  81300. if (extra != 0) {
  81301. lc -= base_length[code];
  81302. send_bits(s, lc, extra); /* send the extra length bits */
  81303. }
  81304. dist--; /* dist is now the match distance - 1 */
  81305. code = d_code(dist);
  81306. Assert (code < D_CODES, "bad d_code");
  81307. send_code(s, code, dtree); /* send the distance code */
  81308. extra = extra_dbits[code];
  81309. if (extra != 0) {
  81310. dist -= base_dist[code];
  81311. send_bits(s, dist, extra); /* send the extra distance bits */
  81312. }
  81313. } /* literal or match pair ? */
  81314. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  81315. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  81316. "pendingBuf overflow");
  81317. } while (lx < s->last_lit);
  81318. send_code(s, END_BLOCK, ltree);
  81319. s->last_eob_len = ltree[END_BLOCK].Len;
  81320. }
  81321. /* ===========================================================================
  81322. * Set the data type to BINARY or TEXT, using a crude approximation:
  81323. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  81324. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  81325. * IN assertion: the fields Freq of dyn_ltree are set.
  81326. */
  81327. local void set_data_type (deflate_state *s)
  81328. {
  81329. int n;
  81330. for (n = 0; n < 9; n++)
  81331. if (s->dyn_ltree[n].Freq != 0)
  81332. break;
  81333. if (n == 9)
  81334. for (n = 14; n < 32; n++)
  81335. if (s->dyn_ltree[n].Freq != 0)
  81336. break;
  81337. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  81338. }
  81339. /* ===========================================================================
  81340. * Reverse the first len bits of a code, using straightforward code (a faster
  81341. * method would use a table)
  81342. * IN assertion: 1 <= len <= 15
  81343. */
  81344. local unsigned bi_reverse (unsigned code, int len)
  81345. {
  81346. register unsigned res = 0;
  81347. do {
  81348. res |= code & 1;
  81349. code >>= 1, res <<= 1;
  81350. } while (--len > 0);
  81351. return res >> 1;
  81352. }
  81353. /* ===========================================================================
  81354. * Flush the bit buffer, keeping at most 7 bits in it.
  81355. */
  81356. local void bi_flush (deflate_state *s)
  81357. {
  81358. if (s->bi_valid == 16) {
  81359. put_short(s, s->bi_buf);
  81360. s->bi_buf = 0;
  81361. s->bi_valid = 0;
  81362. } else if (s->bi_valid >= 8) {
  81363. put_byte(s, (Byte)s->bi_buf);
  81364. s->bi_buf >>= 8;
  81365. s->bi_valid -= 8;
  81366. }
  81367. }
  81368. /* ===========================================================================
  81369. * Flush the bit buffer and align the output on a byte boundary
  81370. */
  81371. local void bi_windup (deflate_state *s)
  81372. {
  81373. if (s->bi_valid > 8) {
  81374. put_short(s, s->bi_buf);
  81375. } else if (s->bi_valid > 0) {
  81376. put_byte(s, (Byte)s->bi_buf);
  81377. }
  81378. s->bi_buf = 0;
  81379. s->bi_valid = 0;
  81380. #ifdef DEBUG
  81381. s->bits_sent = (s->bits_sent+7) & ~7;
  81382. #endif
  81383. }
  81384. /* ===========================================================================
  81385. * Copy a stored block, storing first the length and its
  81386. * one's complement if requested.
  81387. */
  81388. local void copy_block(deflate_state *s,
  81389. charf *buf, /* the input data */
  81390. unsigned len, /* its length */
  81391. int header) /* true if block header must be written */
  81392. {
  81393. bi_windup(s); /* align on byte boundary */
  81394. s->last_eob_len = 8; /* enough lookahead for inflate */
  81395. if (header) {
  81396. put_short(s, (ush)len);
  81397. put_short(s, (ush)~len);
  81398. #ifdef DEBUG
  81399. s->bits_sent += 2*16;
  81400. #endif
  81401. }
  81402. #ifdef DEBUG
  81403. s->bits_sent += (ulg)len<<3;
  81404. #endif
  81405. while (len--) {
  81406. put_byte(s, *buf++);
  81407. }
  81408. }
  81409. /********* End of inlined file: trees.c *********/
  81410. /********* Start of inlined file: zutil.c *********/
  81411. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81412. #ifndef NO_DUMMY_DECL
  81413. struct internal_state {int dummy;}; /* for buggy compilers */
  81414. #endif
  81415. const char * const z_errmsg[10] = {
  81416. "need dictionary", /* Z_NEED_DICT 2 */
  81417. "stream end", /* Z_STREAM_END 1 */
  81418. "", /* Z_OK 0 */
  81419. "file error", /* Z_ERRNO (-1) */
  81420. "stream error", /* Z_STREAM_ERROR (-2) */
  81421. "data error", /* Z_DATA_ERROR (-3) */
  81422. "insufficient memory", /* Z_MEM_ERROR (-4) */
  81423. "buffer error", /* Z_BUF_ERROR (-5) */
  81424. "incompatible version",/* Z_VERSION_ERROR (-6) */
  81425. ""};
  81426. /*const char * ZEXPORT zlibVersion()
  81427. {
  81428. return ZLIB_VERSION;
  81429. }
  81430. uLong ZEXPORT zlibCompileFlags()
  81431. {
  81432. uLong flags;
  81433. flags = 0;
  81434. switch (sizeof(uInt)) {
  81435. case 2: break;
  81436. case 4: flags += 1; break;
  81437. case 8: flags += 2; break;
  81438. default: flags += 3;
  81439. }
  81440. switch (sizeof(uLong)) {
  81441. case 2: break;
  81442. case 4: flags += 1 << 2; break;
  81443. case 8: flags += 2 << 2; break;
  81444. default: flags += 3 << 2;
  81445. }
  81446. switch (sizeof(voidpf)) {
  81447. case 2: break;
  81448. case 4: flags += 1 << 4; break;
  81449. case 8: flags += 2 << 4; break;
  81450. default: flags += 3 << 4;
  81451. }
  81452. switch (sizeof(z_off_t)) {
  81453. case 2: break;
  81454. case 4: flags += 1 << 6; break;
  81455. case 8: flags += 2 << 6; break;
  81456. default: flags += 3 << 6;
  81457. }
  81458. #ifdef DEBUG
  81459. flags += 1 << 8;
  81460. #endif
  81461. #if defined(ASMV) || defined(ASMINF)
  81462. flags += 1 << 9;
  81463. #endif
  81464. #ifdef ZLIB_WINAPI
  81465. flags += 1 << 10;
  81466. #endif
  81467. #ifdef BUILDFIXED
  81468. flags += 1 << 12;
  81469. #endif
  81470. #ifdef DYNAMIC_CRC_TABLE
  81471. flags += 1 << 13;
  81472. #endif
  81473. #ifdef NO_GZCOMPRESS
  81474. flags += 1L << 16;
  81475. #endif
  81476. #ifdef NO_GZIP
  81477. flags += 1L << 17;
  81478. #endif
  81479. #ifdef PKZIP_BUG_WORKAROUND
  81480. flags += 1L << 20;
  81481. #endif
  81482. #ifdef FASTEST
  81483. flags += 1L << 21;
  81484. #endif
  81485. #ifdef STDC
  81486. # ifdef NO_vsnprintf
  81487. flags += 1L << 25;
  81488. # ifdef HAS_vsprintf_void
  81489. flags += 1L << 26;
  81490. # endif
  81491. # else
  81492. # ifdef HAS_vsnprintf_void
  81493. flags += 1L << 26;
  81494. # endif
  81495. # endif
  81496. #else
  81497. flags += 1L << 24;
  81498. # ifdef NO_snprintf
  81499. flags += 1L << 25;
  81500. # ifdef HAS_sprintf_void
  81501. flags += 1L << 26;
  81502. # endif
  81503. # else
  81504. # ifdef HAS_snprintf_void
  81505. flags += 1L << 26;
  81506. # endif
  81507. # endif
  81508. #endif
  81509. return flags;
  81510. }*/
  81511. #ifdef DEBUG
  81512. # ifndef verbose
  81513. # define verbose 0
  81514. # endif
  81515. int z_verbose = verbose;
  81516. void z_error (const char *m)
  81517. {
  81518. fprintf(stderr, "%s\n", m);
  81519. exit(1);
  81520. }
  81521. #endif
  81522. /* exported to allow conversion of error code to string for compress() and
  81523. * uncompress()
  81524. */
  81525. const char * ZEXPORT zError(int err)
  81526. {
  81527. return ERR_MSG(err);
  81528. }
  81529. #if defined(_WIN32_WCE)
  81530. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  81531. * errno. We define it as a global variable to simplify porting.
  81532. * Its value is always 0 and should not be used.
  81533. */
  81534. int errno = 0;
  81535. #endif
  81536. #ifndef HAVE_MEMCPY
  81537. void zmemcpy(dest, source, len)
  81538. Bytef* dest;
  81539. const Bytef* source;
  81540. uInt len;
  81541. {
  81542. if (len == 0) return;
  81543. do {
  81544. *dest++ = *source++; /* ??? to be unrolled */
  81545. } while (--len != 0);
  81546. }
  81547. int zmemcmp(s1, s2, len)
  81548. const Bytef* s1;
  81549. const Bytef* s2;
  81550. uInt len;
  81551. {
  81552. uInt j;
  81553. for (j = 0; j < len; j++) {
  81554. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  81555. }
  81556. return 0;
  81557. }
  81558. void zmemzero(dest, len)
  81559. Bytef* dest;
  81560. uInt len;
  81561. {
  81562. if (len == 0) return;
  81563. do {
  81564. *dest++ = 0; /* ??? to be unrolled */
  81565. } while (--len != 0);
  81566. }
  81567. #endif
  81568. #ifdef SYS16BIT
  81569. #ifdef __TURBOC__
  81570. /* Turbo C in 16-bit mode */
  81571. # define MY_ZCALLOC
  81572. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  81573. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  81574. * must fix the pointer. Warning: the pointer must be put back to its
  81575. * original form in order to free it, use zcfree().
  81576. */
  81577. #define MAX_PTR 10
  81578. /* 10*64K = 640K */
  81579. local int next_ptr = 0;
  81580. typedef struct ptr_table_s {
  81581. voidpf org_ptr;
  81582. voidpf new_ptr;
  81583. } ptr_table;
  81584. local ptr_table table[MAX_PTR];
  81585. /* This table is used to remember the original form of pointers
  81586. * to large buffers (64K). Such pointers are normalized with a zero offset.
  81587. * Since MSDOS is not a preemptive multitasking OS, this table is not
  81588. * protected from concurrent access. This hack doesn't work anyway on
  81589. * a protected system like OS/2. Use Microsoft C instead.
  81590. */
  81591. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81592. {
  81593. voidpf buf = opaque; /* just to make some compilers happy */
  81594. ulg bsize = (ulg)items*size;
  81595. /* If we allocate less than 65520 bytes, we assume that farmalloc
  81596. * will return a usable pointer which doesn't have to be normalized.
  81597. */
  81598. if (bsize < 65520L) {
  81599. buf = farmalloc(bsize);
  81600. if (*(ush*)&buf != 0) return buf;
  81601. } else {
  81602. buf = farmalloc(bsize + 16L);
  81603. }
  81604. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  81605. table[next_ptr].org_ptr = buf;
  81606. /* Normalize the pointer to seg:0 */
  81607. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  81608. *(ush*)&buf = 0;
  81609. table[next_ptr++].new_ptr = buf;
  81610. return buf;
  81611. }
  81612. void zcfree (voidpf opaque, voidpf ptr)
  81613. {
  81614. int n;
  81615. if (*(ush*)&ptr != 0) { /* object < 64K */
  81616. farfree(ptr);
  81617. return;
  81618. }
  81619. /* Find the original pointer */
  81620. for (n = 0; n < next_ptr; n++) {
  81621. if (ptr != table[n].new_ptr) continue;
  81622. farfree(table[n].org_ptr);
  81623. while (++n < next_ptr) {
  81624. table[n-1] = table[n];
  81625. }
  81626. next_ptr--;
  81627. return;
  81628. }
  81629. ptr = opaque; /* just to make some compilers happy */
  81630. Assert(0, "zcfree: ptr not found");
  81631. }
  81632. #endif /* __TURBOC__ */
  81633. #ifdef M_I86
  81634. /* Microsoft C in 16-bit mode */
  81635. # define MY_ZCALLOC
  81636. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  81637. # define _halloc halloc
  81638. # define _hfree hfree
  81639. #endif
  81640. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81641. {
  81642. if (opaque) opaque = 0; /* to make compiler happy */
  81643. return _halloc((long)items, size);
  81644. }
  81645. void zcfree (voidpf opaque, voidpf ptr)
  81646. {
  81647. if (opaque) opaque = 0; /* to make compiler happy */
  81648. _hfree(ptr);
  81649. }
  81650. #endif /* M_I86 */
  81651. #endif /* SYS16BIT */
  81652. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  81653. #ifndef STDC
  81654. extern voidp malloc OF((uInt size));
  81655. extern voidp calloc OF((uInt items, uInt size));
  81656. extern void free OF((voidpf ptr));
  81657. #endif
  81658. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  81659. {
  81660. if (opaque) items += size - size; /* make compiler happy */
  81661. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  81662. (voidpf)calloc(items, size);
  81663. }
  81664. void zcfree (voidpf opaque, voidpf ptr)
  81665. {
  81666. free(ptr);
  81667. if (opaque) return; /* make compiler happy */
  81668. }
  81669. #endif /* MY_ZCALLOC */
  81670. /********* End of inlined file: zutil.c *********/
  81671. #undef Byte
  81672. }
  81673. #else
  81674. #include <zlib.h>
  81675. #endif
  81676. }
  81677. #if JUCE_MSVC
  81678. #pragma warning (pop)
  81679. #endif
  81680. BEGIN_JUCE_NAMESPACE
  81681. using namespace zlibNamespace;
  81682. // internal helper object that holds the zlib structures so they don't have to be
  81683. // included publicly.
  81684. class GZIPDecompressHelper
  81685. {
  81686. private:
  81687. z_stream* stream;
  81688. uint8* data;
  81689. int dataSize;
  81690. public:
  81691. bool finished, needsDictionary, error;
  81692. GZIPDecompressHelper (const bool noWrap) throw()
  81693. : data (0),
  81694. dataSize (0),
  81695. finished (false),
  81696. needsDictionary (false),
  81697. error (false)
  81698. {
  81699. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  81700. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  81701. : MAX_WBITS) != Z_OK)
  81702. {
  81703. juce_free (stream);
  81704. stream = 0;
  81705. error = true;
  81706. finished = true;
  81707. }
  81708. }
  81709. ~GZIPDecompressHelper() throw()
  81710. {
  81711. if (stream != 0)
  81712. {
  81713. inflateEnd (stream);
  81714. juce_free (stream);
  81715. }
  81716. }
  81717. bool needsInput() const throw() { return dataSize <= 0; }
  81718. void setInput (uint8* const data_, const int size) throw()
  81719. {
  81720. data = data_;
  81721. dataSize = size;
  81722. }
  81723. int doNextBlock (uint8* const dest, const int destSize) throw()
  81724. {
  81725. if (stream != 0 && data != 0 && ! finished)
  81726. {
  81727. stream->next_in = data;
  81728. stream->next_out = dest;
  81729. stream->avail_in = dataSize;
  81730. stream->avail_out = destSize;
  81731. switch (inflate (stream, Z_PARTIAL_FLUSH))
  81732. {
  81733. case Z_STREAM_END:
  81734. finished = true;
  81735. // deliberate fall-through
  81736. case Z_OK:
  81737. data += dataSize - stream->avail_in;
  81738. dataSize = stream->avail_in;
  81739. return destSize - stream->avail_out;
  81740. case Z_NEED_DICT:
  81741. needsDictionary = true;
  81742. data += dataSize - stream->avail_in;
  81743. dataSize = stream->avail_in;
  81744. break;
  81745. case Z_DATA_ERROR:
  81746. case Z_MEM_ERROR:
  81747. error = true;
  81748. default:
  81749. break;
  81750. }
  81751. }
  81752. return 0;
  81753. }
  81754. };
  81755. const int gzipDecompBufferSize = 32768;
  81756. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  81757. const bool deleteSourceWhenDestroyed_,
  81758. const bool noWrap_,
  81759. const int64 uncompressedStreamLength_)
  81760. : sourceStream (sourceStream_),
  81761. uncompressedStreamLength (uncompressedStreamLength_),
  81762. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  81763. noWrap (noWrap_),
  81764. isEof (false),
  81765. activeBufferSize (0),
  81766. originalSourcePos (sourceStream_->getPosition()),
  81767. currentPos (0)
  81768. {
  81769. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  81770. helper = new GZIPDecompressHelper (noWrap_);
  81771. }
  81772. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  81773. {
  81774. juce_free (buffer);
  81775. if (deleteSourceWhenDestroyed)
  81776. delete sourceStream;
  81777. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81778. delete h;
  81779. }
  81780. int64 GZIPDecompressorInputStream::getTotalLength()
  81781. {
  81782. return uncompressedStreamLength;
  81783. }
  81784. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  81785. {
  81786. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81787. if ((howMany > 0) && ! isEof)
  81788. {
  81789. jassert (destBuffer != 0);
  81790. if (destBuffer != 0)
  81791. {
  81792. int numRead = 0;
  81793. uint8* d = (uint8*) destBuffer;
  81794. while (! h->error)
  81795. {
  81796. const int n = h->doNextBlock (d, howMany);
  81797. currentPos += n;
  81798. if (n == 0)
  81799. {
  81800. if (h->finished || h->needsDictionary)
  81801. {
  81802. isEof = true;
  81803. return numRead;
  81804. }
  81805. if (h->needsInput())
  81806. {
  81807. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  81808. if (activeBufferSize > 0)
  81809. {
  81810. h->setInput ((uint8*) buffer, activeBufferSize);
  81811. }
  81812. else
  81813. {
  81814. isEof = true;
  81815. return numRead;
  81816. }
  81817. }
  81818. }
  81819. else
  81820. {
  81821. numRead += n;
  81822. howMany -= n;
  81823. d += n;
  81824. if (howMany <= 0)
  81825. return numRead;
  81826. }
  81827. }
  81828. }
  81829. }
  81830. return 0;
  81831. }
  81832. bool GZIPDecompressorInputStream::isExhausted()
  81833. {
  81834. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81835. return h->error || isEof;
  81836. }
  81837. int64 GZIPDecompressorInputStream::getPosition()
  81838. {
  81839. return currentPos;
  81840. }
  81841. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  81842. {
  81843. if (newPos != currentPos)
  81844. {
  81845. if (newPos > currentPos)
  81846. {
  81847. skipNextBytes (newPos - currentPos);
  81848. }
  81849. else
  81850. {
  81851. // reset the stream and start again..
  81852. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  81853. delete h;
  81854. isEof = false;
  81855. activeBufferSize = 0;
  81856. currentPos = 0;
  81857. helper = new GZIPDecompressHelper (noWrap);
  81858. sourceStream->setPosition (originalSourcePos);
  81859. skipNextBytes (newPos);
  81860. }
  81861. }
  81862. return true;
  81863. }
  81864. END_JUCE_NAMESPACE
  81865. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  81866. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  81867. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  81868. #ifdef _MSC_VER
  81869. #include <windows.h>
  81870. #endif
  81871. #if JUCE_USE_FLAC
  81872. #ifdef _MSC_VER
  81873. #pragma warning (disable : 4505)
  81874. #pragma warning (push)
  81875. #endif
  81876. namespace FlacNamespace
  81877. {
  81878. #if JUCE_INCLUDE_FLAC_CODE
  81879. #define FLAC__NO_DLL 1
  81880. #if ! defined (SIZE_MAX)
  81881. #define SIZE_MAX 0xffffffff
  81882. #endif
  81883. #define __STDC_LIMIT_MACROS 1
  81884. /********* Start of inlined file: all.h *********/
  81885. #ifndef FLAC__ALL_H
  81886. #define FLAC__ALL_H
  81887. /********* Start of inlined file: export.h *********/
  81888. #ifndef FLAC__EXPORT_H
  81889. #define FLAC__EXPORT_H
  81890. /** \file include/FLAC/export.h
  81891. *
  81892. * \brief
  81893. * This module contains #defines and symbols for exporting function
  81894. * calls, and providing version information and compiled-in features.
  81895. *
  81896. * See the \link flac_export export \endlink module.
  81897. */
  81898. /** \defgroup flac_export FLAC/export.h: export symbols
  81899. * \ingroup flac
  81900. *
  81901. * \brief
  81902. * This module contains #defines and symbols for exporting function
  81903. * calls, and providing version information and compiled-in features.
  81904. *
  81905. * If you are compiling with MSVC and will link to the static library
  81906. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  81907. * make sure the symbols are exported properly.
  81908. *
  81909. * \{
  81910. */
  81911. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  81912. #define FLAC_API
  81913. #else
  81914. #ifdef FLAC_API_EXPORTS
  81915. #define FLAC_API _declspec(dllexport)
  81916. #else
  81917. #define FLAC_API _declspec(dllimport)
  81918. #endif
  81919. #endif
  81920. /** These #defines will mirror the libtool-based library version number, see
  81921. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  81922. */
  81923. #define FLAC_API_VERSION_CURRENT 10
  81924. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  81925. #define FLAC_API_VERSION_AGE 2 /**< see above */
  81926. #ifdef __cplusplus
  81927. extern "C" {
  81928. #endif
  81929. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  81930. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  81931. #ifdef __cplusplus
  81932. }
  81933. #endif
  81934. /* \} */
  81935. #endif
  81936. /********* End of inlined file: export.h *********/
  81937. /********* Start of inlined file: assert.h *********/
  81938. #ifndef FLAC__ASSERT_H
  81939. #define FLAC__ASSERT_H
  81940. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  81941. #ifdef DEBUG
  81942. #include <assert.h>
  81943. #define FLAC__ASSERT(x) assert(x)
  81944. #define FLAC__ASSERT_DECLARATION(x) x
  81945. #else
  81946. #define FLAC__ASSERT(x)
  81947. #define FLAC__ASSERT_DECLARATION(x)
  81948. #endif
  81949. #endif
  81950. /********* End of inlined file: assert.h *********/
  81951. /********* Start of inlined file: callback.h *********/
  81952. #ifndef FLAC__CALLBACK_H
  81953. #define FLAC__CALLBACK_H
  81954. /********* Start of inlined file: ordinals.h *********/
  81955. #ifndef FLAC__ORDINALS_H
  81956. #define FLAC__ORDINALS_H
  81957. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  81958. #include <inttypes.h>
  81959. #endif
  81960. typedef signed char FLAC__int8;
  81961. typedef unsigned char FLAC__uint8;
  81962. #if defined(_MSC_VER) || defined(__BORLANDC__)
  81963. typedef __int16 FLAC__int16;
  81964. typedef __int32 FLAC__int32;
  81965. typedef __int64 FLAC__int64;
  81966. typedef unsigned __int16 FLAC__uint16;
  81967. typedef unsigned __int32 FLAC__uint32;
  81968. typedef unsigned __int64 FLAC__uint64;
  81969. #elif defined(__EMX__)
  81970. typedef short FLAC__int16;
  81971. typedef long FLAC__int32;
  81972. typedef long long FLAC__int64;
  81973. typedef unsigned short FLAC__uint16;
  81974. typedef unsigned long FLAC__uint32;
  81975. typedef unsigned long long FLAC__uint64;
  81976. #else
  81977. typedef int16_t FLAC__int16;
  81978. typedef int32_t FLAC__int32;
  81979. typedef int64_t FLAC__int64;
  81980. typedef uint16_t FLAC__uint16;
  81981. typedef uint32_t FLAC__uint32;
  81982. typedef uint64_t FLAC__uint64;
  81983. #endif
  81984. typedef int FLAC__bool;
  81985. typedef FLAC__uint8 FLAC__byte;
  81986. #ifdef true
  81987. #undef true
  81988. #endif
  81989. #ifdef false
  81990. #undef false
  81991. #endif
  81992. #ifndef __cplusplus
  81993. #define true 1
  81994. #define false 0
  81995. #endif
  81996. #endif
  81997. /********* End of inlined file: ordinals.h *********/
  81998. #include <stdlib.h> /* for size_t */
  81999. /** \file include/FLAC/callback.h
  82000. *
  82001. * \brief
  82002. * This module defines the structures for describing I/O callbacks
  82003. * to the other FLAC interfaces.
  82004. *
  82005. * See the detailed documentation for callbacks in the
  82006. * \link flac_callbacks callbacks \endlink module.
  82007. */
  82008. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  82009. * \ingroup flac
  82010. *
  82011. * \brief
  82012. * This module defines the structures for describing I/O callbacks
  82013. * to the other FLAC interfaces.
  82014. *
  82015. * The purpose of the I/O callback functions is to create a common way
  82016. * for the metadata interfaces to handle I/O.
  82017. *
  82018. * Originally the metadata interfaces required filenames as the way of
  82019. * specifying FLAC files to operate on. This is problematic in some
  82020. * environments so there is an additional option to specify a set of
  82021. * callbacks for doing I/O on the FLAC file, instead of the filename.
  82022. *
  82023. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  82024. * opaque structure for a data source.
  82025. *
  82026. * The callback function prototypes are similar (but not identical) to the
  82027. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  82028. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  82029. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  82030. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  82031. * is required. \warning You generally CANNOT directly use fseek or ftell
  82032. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  82033. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  82034. * large files. You will have to find an equivalent function (e.g. ftello),
  82035. * or write a wrapper. The same is true for feof() since this is usually
  82036. * implemented as a macro, not as a function whose address can be taken.
  82037. *
  82038. * \{
  82039. */
  82040. #ifdef __cplusplus
  82041. extern "C" {
  82042. #endif
  82043. /** This is the opaque handle type used by the callbacks. Typically
  82044. * this is a \c FILE* or address of a file descriptor.
  82045. */
  82046. typedef void* FLAC__IOHandle;
  82047. /** Signature for the read callback.
  82048. * The signature and semantics match POSIX fread() implementations
  82049. * and can generally be used interchangeably.
  82050. *
  82051. * \param ptr The address of the read buffer.
  82052. * \param size The size of the records to be read.
  82053. * \param nmemb The number of records to be read.
  82054. * \param handle The handle to the data source.
  82055. * \retval size_t
  82056. * The number of records read.
  82057. */
  82058. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82059. /** Signature for the write callback.
  82060. * The signature and semantics match POSIX fwrite() implementations
  82061. * and can generally be used interchangeably.
  82062. *
  82063. * \param ptr The address of the write buffer.
  82064. * \param size The size of the records to be written.
  82065. * \param nmemb The number of records to be written.
  82066. * \param handle The handle to the data source.
  82067. * \retval size_t
  82068. * The number of records written.
  82069. */
  82070. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  82071. /** Signature for the seek callback.
  82072. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  82073. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  82074. * and 32-bits wide.
  82075. *
  82076. * \param handle The handle to the data source.
  82077. * \param offset The new position, relative to \a whence
  82078. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  82079. * \retval int
  82080. * \c 0 on success, \c -1 on error.
  82081. */
  82082. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  82083. /** Signature for the tell callback.
  82084. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  82085. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  82086. * and 32-bits wide.
  82087. *
  82088. * \param handle The handle to the data source.
  82089. * \retval FLAC__int64
  82090. * The current position on success, \c -1 on error.
  82091. */
  82092. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  82093. /** Signature for the EOF callback.
  82094. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  82095. * on many systems, feof() is a macro, so in this case a wrapper function
  82096. * must be provided instead.
  82097. *
  82098. * \param handle The handle to the data source.
  82099. * \retval int
  82100. * \c 0 if not at end of file, nonzero if at end of file.
  82101. */
  82102. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  82103. /** Signature for the close callback.
  82104. * The signature and semantics match POSIX fclose() implementations
  82105. * and can generally be used interchangeably.
  82106. *
  82107. * \param handle The handle to the data source.
  82108. * \retval int
  82109. * \c 0 on success, \c EOF on error.
  82110. */
  82111. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  82112. /** A structure for holding a set of callbacks.
  82113. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  82114. * describe which of the callbacks are required. The ones that are not
  82115. * required may be set to NULL.
  82116. *
  82117. * If the seek requirement for an interface is optional, you can signify that
  82118. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  82119. */
  82120. typedef struct {
  82121. FLAC__IOCallback_Read read;
  82122. FLAC__IOCallback_Write write;
  82123. FLAC__IOCallback_Seek seek;
  82124. FLAC__IOCallback_Tell tell;
  82125. FLAC__IOCallback_Eof eof;
  82126. FLAC__IOCallback_Close close;
  82127. } FLAC__IOCallbacks;
  82128. /* \} */
  82129. #ifdef __cplusplus
  82130. }
  82131. #endif
  82132. #endif
  82133. /********* End of inlined file: callback.h *********/
  82134. /********* Start of inlined file: format.h *********/
  82135. #ifndef FLAC__FORMAT_H
  82136. #define FLAC__FORMAT_H
  82137. #ifdef __cplusplus
  82138. extern "C" {
  82139. #endif
  82140. /** \file include/FLAC/format.h
  82141. *
  82142. * \brief
  82143. * This module contains structure definitions for the representation
  82144. * of FLAC format components in memory. These are the basic
  82145. * structures used by the rest of the interfaces.
  82146. *
  82147. * See the detailed documentation in the
  82148. * \link flac_format format \endlink module.
  82149. */
  82150. /** \defgroup flac_format FLAC/format.h: format components
  82151. * \ingroup flac
  82152. *
  82153. * \brief
  82154. * This module contains structure definitions for the representation
  82155. * of FLAC format components in memory. These are the basic
  82156. * structures used by the rest of the interfaces.
  82157. *
  82158. * First, you should be familiar with the
  82159. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  82160. * follow directly from the specification. As a user of libFLAC, the
  82161. * interesting parts really are the structures that describe the frame
  82162. * header and metadata blocks.
  82163. *
  82164. * The format structures here are very primitive, designed to store
  82165. * information in an efficient way. Reading information from the
  82166. * structures is easy but creating or modifying them directly is
  82167. * more complex. For the most part, as a user of a library, editing
  82168. * is not necessary; however, for metadata blocks it is, so there are
  82169. * convenience functions provided in the \link flac_metadata metadata
  82170. * module \endlink to simplify the manipulation of metadata blocks.
  82171. *
  82172. * \note
  82173. * It's not the best convention, but symbols ending in _LEN are in bits
  82174. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  82175. * global variables because they are usually used when declaring byte
  82176. * arrays and some compilers require compile-time knowledge of array
  82177. * sizes when declared on the stack.
  82178. *
  82179. * \{
  82180. */
  82181. /*
  82182. Most of the values described in this file are defined by the FLAC
  82183. format specification. There is nothing to tune here.
  82184. */
  82185. /** The largest legal metadata type code. */
  82186. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  82187. /** The minimum block size, in samples, permitted by the format. */
  82188. #define FLAC__MIN_BLOCK_SIZE (16u)
  82189. /** The maximum block size, in samples, permitted by the format. */
  82190. #define FLAC__MAX_BLOCK_SIZE (65535u)
  82191. /** The maximum block size, in samples, permitted by the FLAC subset for
  82192. * sample rates up to 48kHz. */
  82193. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  82194. /** The maximum number of channels permitted by the format. */
  82195. #define FLAC__MAX_CHANNELS (8u)
  82196. /** The minimum sample resolution permitted by the format. */
  82197. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  82198. /** The maximum sample resolution permitted by the format. */
  82199. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  82200. /** The maximum sample resolution permitted by libFLAC.
  82201. *
  82202. * \warning
  82203. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  82204. * the reference encoder/decoder is currently limited to 24 bits because
  82205. * of prevalent 32-bit math, so make sure and use this value when
  82206. * appropriate.
  82207. */
  82208. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  82209. /** The maximum sample rate permitted by the format. The value is
  82210. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  82211. * as to why.
  82212. */
  82213. #define FLAC__MAX_SAMPLE_RATE (655350u)
  82214. /** The maximum LPC order permitted by the format. */
  82215. #define FLAC__MAX_LPC_ORDER (32u)
  82216. /** The maximum LPC order permitted by the FLAC subset for sample rates
  82217. * up to 48kHz. */
  82218. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  82219. /** The minimum quantized linear predictor coefficient precision
  82220. * permitted by the format.
  82221. */
  82222. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  82223. /** The maximum quantized linear predictor coefficient precision
  82224. * permitted by the format.
  82225. */
  82226. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  82227. /** The maximum order of the fixed predictors permitted by the format. */
  82228. #define FLAC__MAX_FIXED_ORDER (4u)
  82229. /** The maximum Rice partition order permitted by the format. */
  82230. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  82231. /** The maximum Rice partition order permitted by the FLAC Subset. */
  82232. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  82233. /** The version string of the release, stamped onto the libraries and binaries.
  82234. *
  82235. * \note
  82236. * This does not correspond to the shared library version number, which
  82237. * is used to determine binary compatibility.
  82238. */
  82239. extern FLAC_API const char *FLAC__VERSION_STRING;
  82240. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  82241. * This is a NUL-terminated ASCII string; when inserted into the
  82242. * VORBIS_COMMENT the trailing null is stripped.
  82243. */
  82244. extern FLAC_API const char *FLAC__VENDOR_STRING;
  82245. /** The byte string representation of the beginning of a FLAC stream. */
  82246. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  82247. /** The 32-bit integer big-endian representation of the beginning of
  82248. * a FLAC stream.
  82249. */
  82250. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  82251. /** The length of the FLAC signature in bits. */
  82252. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  82253. /** The length of the FLAC signature in bytes. */
  82254. #define FLAC__STREAM_SYNC_LENGTH (4u)
  82255. /*****************************************************************************
  82256. *
  82257. * Subframe structures
  82258. *
  82259. *****************************************************************************/
  82260. /*****************************************************************************/
  82261. /** An enumeration of the available entropy coding methods. */
  82262. typedef enum {
  82263. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  82264. /**< Residual is coded by partitioning into contexts, each with it's own
  82265. * 4-bit Rice parameter. */
  82266. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  82267. /**< Residual is coded by partitioning into contexts, each with it's own
  82268. * 5-bit Rice parameter. */
  82269. } FLAC__EntropyCodingMethodType;
  82270. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  82271. *
  82272. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  82273. * give the string equivalent. The contents should not be modified.
  82274. */
  82275. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  82276. /** Contents of a Rice partitioned residual
  82277. */
  82278. typedef struct {
  82279. unsigned *parameters;
  82280. /**< The Rice parameters for each context. */
  82281. unsigned *raw_bits;
  82282. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  82283. * partitions and zero for unescaped partitions.
  82284. */
  82285. unsigned capacity_by_order;
  82286. /**< The capacity of the \a parameters and \a raw_bits arrays
  82287. * specified as an order, i.e. the number of array elements
  82288. * allocated is 2 ^ \a capacity_by_order.
  82289. */
  82290. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  82291. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  82292. */
  82293. typedef struct {
  82294. unsigned order;
  82295. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  82296. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  82297. /**< The context's Rice parameters and/or raw bits. */
  82298. } FLAC__EntropyCodingMethod_PartitionedRice;
  82299. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  82300. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  82301. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  82302. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  82303. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  82304. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  82305. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  82306. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  82307. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  82308. */
  82309. typedef struct {
  82310. FLAC__EntropyCodingMethodType type;
  82311. union {
  82312. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  82313. } data;
  82314. } FLAC__EntropyCodingMethod;
  82315. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  82316. /*****************************************************************************/
  82317. /** An enumeration of the available subframe types. */
  82318. typedef enum {
  82319. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  82320. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  82321. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  82322. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  82323. } FLAC__SubframeType;
  82324. /** Maps a FLAC__SubframeType to a C string.
  82325. *
  82326. * Using a FLAC__SubframeType as the index to this array will
  82327. * give the string equivalent. The contents should not be modified.
  82328. */
  82329. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  82330. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  82331. */
  82332. typedef struct {
  82333. FLAC__int32 value; /**< The constant signal value. */
  82334. } FLAC__Subframe_Constant;
  82335. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  82336. */
  82337. typedef struct {
  82338. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  82339. } FLAC__Subframe_Verbatim;
  82340. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  82341. */
  82342. typedef struct {
  82343. FLAC__EntropyCodingMethod entropy_coding_method;
  82344. /**< The residual coding method. */
  82345. unsigned order;
  82346. /**< The polynomial order. */
  82347. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  82348. /**< Warmup samples to prime the predictor, length == order. */
  82349. const FLAC__int32 *residual;
  82350. /**< The residual signal, length == (blocksize minus order) samples. */
  82351. } FLAC__Subframe_Fixed;
  82352. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  82353. */
  82354. typedef struct {
  82355. FLAC__EntropyCodingMethod entropy_coding_method;
  82356. /**< The residual coding method. */
  82357. unsigned order;
  82358. /**< The FIR order. */
  82359. unsigned qlp_coeff_precision;
  82360. /**< Quantized FIR filter coefficient precision in bits. */
  82361. int quantization_level;
  82362. /**< The qlp coeff shift needed. */
  82363. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  82364. /**< FIR filter coefficients. */
  82365. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  82366. /**< Warmup samples to prime the predictor, length == order. */
  82367. const FLAC__int32 *residual;
  82368. /**< The residual signal, length == (blocksize minus order) samples. */
  82369. } FLAC__Subframe_LPC;
  82370. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  82371. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  82372. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  82373. */
  82374. typedef struct {
  82375. FLAC__SubframeType type;
  82376. union {
  82377. FLAC__Subframe_Constant constant;
  82378. FLAC__Subframe_Fixed fixed;
  82379. FLAC__Subframe_LPC lpc;
  82380. FLAC__Subframe_Verbatim verbatim;
  82381. } data;
  82382. unsigned wasted_bits;
  82383. } FLAC__Subframe;
  82384. /** == 1 (bit)
  82385. *
  82386. * This used to be a zero-padding bit (hence the name
  82387. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  82388. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  82389. * to mean something else.
  82390. */
  82391. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  82392. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  82393. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  82394. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  82395. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  82396. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  82397. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  82398. /*****************************************************************************/
  82399. /*****************************************************************************
  82400. *
  82401. * Frame structures
  82402. *
  82403. *****************************************************************************/
  82404. /** An enumeration of the available channel assignments. */
  82405. typedef enum {
  82406. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  82407. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  82408. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  82409. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  82410. } FLAC__ChannelAssignment;
  82411. /** Maps a FLAC__ChannelAssignment to a C string.
  82412. *
  82413. * Using a FLAC__ChannelAssignment as the index to this array will
  82414. * give the string equivalent. The contents should not be modified.
  82415. */
  82416. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  82417. /** An enumeration of the possible frame numbering methods. */
  82418. typedef enum {
  82419. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  82420. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  82421. } FLAC__FrameNumberType;
  82422. /** Maps a FLAC__FrameNumberType to a C string.
  82423. *
  82424. * Using a FLAC__FrameNumberType as the index to this array will
  82425. * give the string equivalent. The contents should not be modified.
  82426. */
  82427. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  82428. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  82429. */
  82430. typedef struct {
  82431. unsigned blocksize;
  82432. /**< The number of samples per subframe. */
  82433. unsigned sample_rate;
  82434. /**< The sample rate in Hz. */
  82435. unsigned channels;
  82436. /**< The number of channels (== number of subframes). */
  82437. FLAC__ChannelAssignment channel_assignment;
  82438. /**< The channel assignment for the frame. */
  82439. unsigned bits_per_sample;
  82440. /**< The sample resolution. */
  82441. FLAC__FrameNumberType number_type;
  82442. /**< The numbering scheme used for the frame. As a convenience, the
  82443. * decoder will always convert a frame number to a sample number because
  82444. * the rules are complex. */
  82445. union {
  82446. FLAC__uint32 frame_number;
  82447. FLAC__uint64 sample_number;
  82448. } number;
  82449. /**< The frame number or sample number of first sample in frame;
  82450. * use the \a number_type value to determine which to use. */
  82451. FLAC__uint8 crc;
  82452. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  82453. * of the raw frame header bytes, meaning everything before the CRC byte
  82454. * including the sync code.
  82455. */
  82456. } FLAC__FrameHeader;
  82457. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  82458. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  82459. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  82460. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  82461. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  82462. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  82463. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  82464. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  82465. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  82466. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  82467. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  82468. */
  82469. typedef struct {
  82470. FLAC__uint16 crc;
  82471. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  82472. * 0) of the bytes before the crc, back to and including the frame header
  82473. * sync code.
  82474. */
  82475. } FLAC__FrameFooter;
  82476. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  82477. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  82478. */
  82479. typedef struct {
  82480. FLAC__FrameHeader header;
  82481. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  82482. FLAC__FrameFooter footer;
  82483. } FLAC__Frame;
  82484. /*****************************************************************************/
  82485. /*****************************************************************************
  82486. *
  82487. * Meta-data structures
  82488. *
  82489. *****************************************************************************/
  82490. /** An enumeration of the available metadata block types. */
  82491. typedef enum {
  82492. FLAC__METADATA_TYPE_STREAMINFO = 0,
  82493. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  82494. FLAC__METADATA_TYPE_PADDING = 1,
  82495. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  82496. FLAC__METADATA_TYPE_APPLICATION = 2,
  82497. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  82498. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  82499. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  82500. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  82501. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  82502. FLAC__METADATA_TYPE_CUESHEET = 5,
  82503. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  82504. FLAC__METADATA_TYPE_PICTURE = 6,
  82505. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  82506. FLAC__METADATA_TYPE_UNDEFINED = 7
  82507. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  82508. } FLAC__MetadataType;
  82509. /** Maps a FLAC__MetadataType to a C string.
  82510. *
  82511. * Using a FLAC__MetadataType as the index to this array will
  82512. * give the string equivalent. The contents should not be modified.
  82513. */
  82514. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  82515. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  82516. */
  82517. typedef struct {
  82518. unsigned min_blocksize, max_blocksize;
  82519. unsigned min_framesize, max_framesize;
  82520. unsigned sample_rate;
  82521. unsigned channels;
  82522. unsigned bits_per_sample;
  82523. FLAC__uint64 total_samples;
  82524. FLAC__byte md5sum[16];
  82525. } FLAC__StreamMetadata_StreamInfo;
  82526. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82527. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  82528. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82529. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  82530. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  82531. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  82532. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  82533. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  82534. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  82535. /** The total stream length of the STREAMINFO block in bytes. */
  82536. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  82537. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  82538. */
  82539. typedef struct {
  82540. int dummy;
  82541. /**< Conceptually this is an empty struct since we don't store the
  82542. * padding bytes. Empty structs are not allowed by some C compilers,
  82543. * hence the dummy.
  82544. */
  82545. } FLAC__StreamMetadata_Padding;
  82546. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  82547. */
  82548. typedef struct {
  82549. FLAC__byte id[4];
  82550. FLAC__byte *data;
  82551. } FLAC__StreamMetadata_Application;
  82552. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  82553. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  82554. */
  82555. typedef struct {
  82556. FLAC__uint64 sample_number;
  82557. /**< The sample number of the target frame. */
  82558. FLAC__uint64 stream_offset;
  82559. /**< The offset, in bytes, of the target frame with respect to
  82560. * beginning of the first frame. */
  82561. unsigned frame_samples;
  82562. /**< The number of samples in the target frame. */
  82563. } FLAC__StreamMetadata_SeekPoint;
  82564. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  82565. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  82566. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  82567. /** The total stream length of a seek point in bytes. */
  82568. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  82569. /** The value used in the \a sample_number field of
  82570. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  82571. * point (== 0xffffffffffffffff).
  82572. */
  82573. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  82574. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  82575. *
  82576. * \note From the format specification:
  82577. * - The seek points must be sorted by ascending sample number.
  82578. * - Each seek point's sample number must be the first sample of the
  82579. * target frame.
  82580. * - Each seek point's sample number must be unique within the table.
  82581. * - Existence of a SEEKTABLE block implies a correct setting of
  82582. * total_samples in the stream_info block.
  82583. * - Behavior is undefined when more than one SEEKTABLE block is
  82584. * present in a stream.
  82585. */
  82586. typedef struct {
  82587. unsigned num_points;
  82588. FLAC__StreamMetadata_SeekPoint *points;
  82589. } FLAC__StreamMetadata_SeekTable;
  82590. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82591. *
  82592. * For convenience, the APIs maintain a trailing NUL character at the end of
  82593. * \a entry which is not counted toward \a length, i.e.
  82594. * \code strlen(entry) == length \endcode
  82595. */
  82596. typedef struct {
  82597. FLAC__uint32 length;
  82598. FLAC__byte *entry;
  82599. } FLAC__StreamMetadata_VorbisComment_Entry;
  82600. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  82601. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  82602. */
  82603. typedef struct {
  82604. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  82605. FLAC__uint32 num_comments;
  82606. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  82607. } FLAC__StreamMetadata_VorbisComment;
  82608. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  82609. /** FLAC CUESHEET track index structure. (See the
  82610. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  82611. * the full description of each field.)
  82612. */
  82613. typedef struct {
  82614. FLAC__uint64 offset;
  82615. /**< Offset in samples, relative to the track offset, of the index
  82616. * point.
  82617. */
  82618. FLAC__byte number;
  82619. /**< The index point number. */
  82620. } FLAC__StreamMetadata_CueSheet_Index;
  82621. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  82622. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  82623. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  82624. /** FLAC CUESHEET track structure. (See the
  82625. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  82626. * the full description of each field.)
  82627. */
  82628. typedef struct {
  82629. FLAC__uint64 offset;
  82630. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  82631. FLAC__byte number;
  82632. /**< The track number. */
  82633. char isrc[13];
  82634. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  82635. unsigned type:1;
  82636. /**< The track type: 0 for audio, 1 for non-audio. */
  82637. unsigned pre_emphasis:1;
  82638. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  82639. FLAC__byte num_indices;
  82640. /**< The number of track index points. */
  82641. FLAC__StreamMetadata_CueSheet_Index *indices;
  82642. /**< NULL if num_indices == 0, else pointer to array of index points. */
  82643. } FLAC__StreamMetadata_CueSheet_Track;
  82644. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  82645. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  82646. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  82647. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  82648. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  82649. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  82650. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  82651. /** FLAC CUESHEET structure. (See the
  82652. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  82653. * for the full description of each field.)
  82654. */
  82655. typedef struct {
  82656. char media_catalog_number[129];
  82657. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  82658. * general, the media catalog number may be 0 to 128 bytes long; any
  82659. * unused characters should be right-padded with NUL characters.
  82660. */
  82661. FLAC__uint64 lead_in;
  82662. /**< The number of lead-in samples. */
  82663. FLAC__bool is_cd;
  82664. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  82665. unsigned num_tracks;
  82666. /**< The number of tracks. */
  82667. FLAC__StreamMetadata_CueSheet_Track *tracks;
  82668. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  82669. } FLAC__StreamMetadata_CueSheet;
  82670. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  82671. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  82672. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  82673. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  82674. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  82675. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  82676. typedef enum {
  82677. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  82678. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  82679. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  82680. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  82681. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  82682. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  82683. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  82684. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  82685. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  82686. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  82687. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  82688. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  82689. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  82690. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  82691. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  82692. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  82693. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  82694. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  82695. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  82696. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  82697. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  82698. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  82699. } FLAC__StreamMetadata_Picture_Type;
  82700. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  82701. *
  82702. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  82703. * will give the string equivalent. The contents should not be
  82704. * modified.
  82705. */
  82706. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  82707. /** FLAC PICTURE structure. (See the
  82708. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  82709. * for the full description of each field.)
  82710. */
  82711. typedef struct {
  82712. FLAC__StreamMetadata_Picture_Type type;
  82713. /**< The kind of picture stored. */
  82714. char *mime_type;
  82715. /**< Picture data's MIME type, in ASCII printable characters
  82716. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  82717. * use picture data of MIME type \c image/jpeg or \c image/png. A
  82718. * MIME type of '-->' is also allowed, in which case the picture
  82719. * data should be a complete URL. In file storage, the MIME type is
  82720. * stored as a 32-bit length followed by the ASCII string with no NUL
  82721. * terminator, but is converted to a plain C string in this structure
  82722. * for convenience.
  82723. */
  82724. FLAC__byte *description;
  82725. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  82726. * the description is stored as a 32-bit length followed by the UTF-8
  82727. * string with no NUL terminator, but is converted to a plain C string
  82728. * in this structure for convenience.
  82729. */
  82730. FLAC__uint32 width;
  82731. /**< Picture's width in pixels. */
  82732. FLAC__uint32 height;
  82733. /**< Picture's height in pixels. */
  82734. FLAC__uint32 depth;
  82735. /**< Picture's color depth in bits-per-pixel. */
  82736. FLAC__uint32 colors;
  82737. /**< For indexed palettes (like GIF), picture's number of colors (the
  82738. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  82739. */
  82740. FLAC__uint32 data_length;
  82741. /**< Length of binary picture data in bytes. */
  82742. FLAC__byte *data;
  82743. /**< Binary picture data. */
  82744. } FLAC__StreamMetadata_Picture;
  82745. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  82746. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  82747. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  82748. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  82749. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  82750. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  82751. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  82752. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  82753. /** Structure that is used when a metadata block of unknown type is loaded.
  82754. * The contents are opaque. The structure is used only internally to
  82755. * correctly handle unknown metadata.
  82756. */
  82757. typedef struct {
  82758. FLAC__byte *data;
  82759. } FLAC__StreamMetadata_Unknown;
  82760. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  82761. */
  82762. typedef struct {
  82763. FLAC__MetadataType type;
  82764. /**< The type of the metadata block; used determine which member of the
  82765. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  82766. * then \a data.unknown must be used. */
  82767. FLAC__bool is_last;
  82768. /**< \c true if this metadata block is the last, else \a false */
  82769. unsigned length;
  82770. /**< Length, in bytes, of the block data as it appears in the stream. */
  82771. union {
  82772. FLAC__StreamMetadata_StreamInfo stream_info;
  82773. FLAC__StreamMetadata_Padding padding;
  82774. FLAC__StreamMetadata_Application application;
  82775. FLAC__StreamMetadata_SeekTable seek_table;
  82776. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  82777. FLAC__StreamMetadata_CueSheet cue_sheet;
  82778. FLAC__StreamMetadata_Picture picture;
  82779. FLAC__StreamMetadata_Unknown unknown;
  82780. } data;
  82781. /**< Polymorphic block data; use the \a type value to determine which
  82782. * to use. */
  82783. } FLAC__StreamMetadata;
  82784. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  82785. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  82786. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  82787. /** The total stream length of a metadata block header in bytes. */
  82788. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  82789. /*****************************************************************************/
  82790. /*****************************************************************************
  82791. *
  82792. * Utility functions
  82793. *
  82794. *****************************************************************************/
  82795. /** Tests that a sample rate is valid for FLAC.
  82796. *
  82797. * \param sample_rate The sample rate to test for compliance.
  82798. * \retval FLAC__bool
  82799. * \c true if the given sample rate conforms to the specification, else
  82800. * \c false.
  82801. */
  82802. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  82803. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  82804. * for valid sample rates are slightly more complex since the rate has to
  82805. * be expressible completely in the frame header.
  82806. *
  82807. * \param sample_rate The sample rate to test for compliance.
  82808. * \retval FLAC__bool
  82809. * \c true if the given sample rate conforms to the specification for the
  82810. * subset, else \c false.
  82811. */
  82812. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  82813. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  82814. * comment specification.
  82815. *
  82816. * Vorbis comment names must be composed only of characters from
  82817. * [0x20-0x3C,0x3E-0x7D].
  82818. *
  82819. * \param name A NUL-terminated string to be checked.
  82820. * \assert
  82821. * \code name != NULL \endcode
  82822. * \retval FLAC__bool
  82823. * \c false if entry name is illegal, else \c true.
  82824. */
  82825. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  82826. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  82827. * comment specification.
  82828. *
  82829. * Vorbis comment values must be valid UTF-8 sequences.
  82830. *
  82831. * \param value A string to be checked.
  82832. * \param length A the length of \a value in bytes. May be
  82833. * \c (unsigned)(-1) to indicate that \a value is a plain
  82834. * UTF-8 NUL-terminated string.
  82835. * \assert
  82836. * \code value != NULL \endcode
  82837. * \retval FLAC__bool
  82838. * \c false if entry name is illegal, else \c true.
  82839. */
  82840. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  82841. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  82842. * comment specification.
  82843. *
  82844. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  82845. * 'value' must be legal according to
  82846. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  82847. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  82848. *
  82849. * \param entry An entry to be checked.
  82850. * \param length The length of \a entry in bytes.
  82851. * \assert
  82852. * \code value != NULL \endcode
  82853. * \retval FLAC__bool
  82854. * \c false if entry name is illegal, else \c true.
  82855. */
  82856. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  82857. /** Check a seek table to see if it conforms to the FLAC specification.
  82858. * See the format specification for limits on the contents of the
  82859. * seek table.
  82860. *
  82861. * \param seek_table A pointer to a seek table to be checked.
  82862. * \assert
  82863. * \code seek_table != NULL \endcode
  82864. * \retval FLAC__bool
  82865. * \c false if seek table is illegal, else \c true.
  82866. */
  82867. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  82868. /** Sort a seek table's seek points according to the format specification.
  82869. * This includes a "unique-ification" step to remove duplicates, i.e.
  82870. * seek points with identical \a sample_number values. Duplicate seek
  82871. * points are converted into placeholder points and sorted to the end of
  82872. * the table.
  82873. *
  82874. * \param seek_table A pointer to a seek table to be sorted.
  82875. * \assert
  82876. * \code seek_table != NULL \endcode
  82877. * \retval unsigned
  82878. * The number of duplicate seek points converted into placeholders.
  82879. */
  82880. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  82881. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82882. * See the format specification for limits on the contents of the
  82883. * cue sheet.
  82884. *
  82885. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  82886. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82887. * stringent requirements for a CD-DA (audio) disc.
  82888. * \param violation Address of a pointer to a string. If there is a
  82889. * violation, a pointer to a string explanation of the
  82890. * violation will be returned here. \a violation may be
  82891. * \c NULL if you don't need the returned string. Do not
  82892. * free the returned string; it will always point to static
  82893. * data.
  82894. * \assert
  82895. * \code cue_sheet != NULL \endcode
  82896. * \retval FLAC__bool
  82897. * \c false if cue sheet is illegal, else \c true.
  82898. */
  82899. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  82900. /** Check picture data to see if it conforms to the FLAC specification.
  82901. * See the format specification for limits on the contents of the
  82902. * PICTURE block.
  82903. *
  82904. * \param picture A pointer to existing picture data to be checked.
  82905. * \param violation Address of a pointer to a string. If there is a
  82906. * violation, a pointer to a string explanation of the
  82907. * violation will be returned here. \a violation may be
  82908. * \c NULL if you don't need the returned string. Do not
  82909. * free the returned string; it will always point to static
  82910. * data.
  82911. * \assert
  82912. * \code picture != NULL \endcode
  82913. * \retval FLAC__bool
  82914. * \c false if picture data is illegal, else \c true.
  82915. */
  82916. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  82917. /* \} */
  82918. #ifdef __cplusplus
  82919. }
  82920. #endif
  82921. #endif
  82922. /********* End of inlined file: format.h *********/
  82923. /********* Start of inlined file: metadata.h *********/
  82924. #ifndef FLAC__METADATA_H
  82925. #define FLAC__METADATA_H
  82926. #include <sys/types.h> /* for off_t */
  82927. /* --------------------------------------------------------------------
  82928. (For an example of how all these routines are used, see the source
  82929. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  82930. metaflac in src/metaflac/)
  82931. ------------------------------------------------------------------*/
  82932. /** \file include/FLAC/metadata.h
  82933. *
  82934. * \brief
  82935. * This module provides functions for creating and manipulating FLAC
  82936. * metadata blocks in memory, and three progressively more powerful
  82937. * interfaces for traversing and editing metadata in FLAC files.
  82938. *
  82939. * See the detailed documentation for each interface in the
  82940. * \link flac_metadata metadata \endlink module.
  82941. */
  82942. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  82943. * \ingroup flac
  82944. *
  82945. * \brief
  82946. * This module provides functions for creating and manipulating FLAC
  82947. * metadata blocks in memory, and three progressively more powerful
  82948. * interfaces for traversing and editing metadata in native FLAC files.
  82949. * Note that currently only the Chain interface (level 2) supports Ogg
  82950. * FLAC files, and it is read-only i.e. no writing back changed
  82951. * metadata to file.
  82952. *
  82953. * There are three metadata interfaces of increasing complexity:
  82954. *
  82955. * Level 0:
  82956. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  82957. * PICTURE blocks.
  82958. *
  82959. * Level 1:
  82960. * Read-write access to all metadata blocks. This level is write-
  82961. * efficient in most cases (more on this below), and uses less memory
  82962. * than level 2.
  82963. *
  82964. * Level 2:
  82965. * Read-write access to all metadata blocks. This level is write-
  82966. * efficient in all cases, but uses more memory since all metadata for
  82967. * the whole file is read into memory and manipulated before writing
  82968. * out again.
  82969. *
  82970. * What do we mean by efficient? Since FLAC metadata appears at the
  82971. * beginning of the file, when writing metadata back to a FLAC file
  82972. * it is possible to grow or shrink the metadata such that the entire
  82973. * file must be rewritten. However, if the size remains the same during
  82974. * changes or PADDING blocks are utilized, only the metadata needs to be
  82975. * overwritten, which is much faster.
  82976. *
  82977. * Efficient means the whole file is rewritten at most one time, and only
  82978. * when necessary. Level 1 is not efficient only in the case that you
  82979. * cause more than one metadata block to grow or shrink beyond what can
  82980. * be accomodated by padding. In this case you should probably use level
  82981. * 2, which allows you to edit all the metadata for a file in memory and
  82982. * write it out all at once.
  82983. *
  82984. * All levels know how to skip over and not disturb an ID3v2 tag at the
  82985. * front of the file.
  82986. *
  82987. * All levels access files via their filenames. In addition, level 2
  82988. * has additional alternative read and write functions that take an I/O
  82989. * handle and callbacks, for situations where access by filename is not
  82990. * possible.
  82991. *
  82992. * In addition to the three interfaces, this module defines functions for
  82993. * creating and manipulating various metadata objects in memory. As we see
  82994. * from the Format module, FLAC metadata blocks in memory are very primitive
  82995. * structures for storing information in an efficient way. Reading
  82996. * information from the structures is easy but creating or modifying them
  82997. * directly is more complex. The metadata object routines here facilitate
  82998. * this by taking care of the consistency and memory management drudgery.
  82999. *
  83000. * Unless you will be using the level 1 or 2 interfaces to modify existing
  83001. * metadata however, you will not probably not need these.
  83002. *
  83003. * From a dependency standpoint, none of the encoders or decoders require
  83004. * the metadata module. This is so that embedded users can strip out the
  83005. * metadata module from libFLAC to reduce the size and complexity.
  83006. */
  83007. #ifdef __cplusplus
  83008. extern "C" {
  83009. #endif
  83010. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  83011. * \ingroup flac_metadata
  83012. *
  83013. * \brief
  83014. * The level 0 interface consists of individual routines to read the
  83015. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  83016. * only a filename.
  83017. *
  83018. * They try to skip any ID3v2 tag at the head of the file.
  83019. *
  83020. * \{
  83021. */
  83022. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  83023. * will try to skip any ID3v2 tag at the head of the file.
  83024. *
  83025. * \param filename The path to the FLAC file to read.
  83026. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  83027. * FLAC__StreamMetadata is a simple structure with no
  83028. * memory allocation involved, you pass the address of
  83029. * an existing structure. It need not be initialized.
  83030. * \assert
  83031. * \code filename != NULL \endcode
  83032. * \code streaminfo != NULL \endcode
  83033. * \retval FLAC__bool
  83034. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  83035. * \c false if there was a memory allocation error, a file decoder error,
  83036. * or the file contained no STREAMINFO block. (A memory allocation error
  83037. * is possible because this function must set up a file decoder.)
  83038. */
  83039. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  83040. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  83041. * function will try to skip any ID3v2 tag at the head of the file.
  83042. *
  83043. * \param filename The path to the FLAC file to read.
  83044. * \param tags The address where the returned pointer will be
  83045. * stored. The \a tags object must be deleted by
  83046. * the caller using FLAC__metadata_object_delete().
  83047. * \assert
  83048. * \code filename != NULL \endcode
  83049. * \code tags != NULL \endcode
  83050. * \retval FLAC__bool
  83051. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  83052. * and \a *tags will be set to the address of the metadata structure.
  83053. * Returns \c false if there was a memory allocation error, a file
  83054. * decoder error, or the file contained no VORBIS_COMMENT block, and
  83055. * \a *tags will be set to \c NULL.
  83056. */
  83057. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  83058. /** Read the CUESHEET metadata block of the given FLAC file. This
  83059. * function will try to skip any ID3v2 tag at the head of the file.
  83060. *
  83061. * \param filename The path to the FLAC file to read.
  83062. * \param cuesheet The address where the returned pointer will be
  83063. * stored. The \a cuesheet object must be deleted by
  83064. * the caller using FLAC__metadata_object_delete().
  83065. * \assert
  83066. * \code filename != NULL \endcode
  83067. * \code cuesheet != NULL \endcode
  83068. * \retval FLAC__bool
  83069. * \c true if a valid CUESHEET block was read from \a filename,
  83070. * and \a *cuesheet will be set to the address of the metadata
  83071. * structure. Returns \c false if there was a memory allocation
  83072. * error, a file decoder error, or the file contained no CUESHEET
  83073. * block, and \a *cuesheet will be set to \c NULL.
  83074. */
  83075. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  83076. /** Read a PICTURE metadata block of the given FLAC file. This
  83077. * function will try to skip any ID3v2 tag at the head of the file.
  83078. * Since there can be more than one PICTURE block in a file, this
  83079. * function takes a number of parameters that act as constraints to
  83080. * the search. The PICTURE block with the largest area matching all
  83081. * the constraints will be returned, or \a *picture will be set to
  83082. * \c NULL if there was no such block.
  83083. *
  83084. * \param filename The path to the FLAC file to read.
  83085. * \param picture The address where the returned pointer will be
  83086. * stored. The \a picture object must be deleted by
  83087. * the caller using FLAC__metadata_object_delete().
  83088. * \param type The desired picture type. Use \c -1 to mean
  83089. * "any type".
  83090. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  83091. * string will be matched exactly. Use \c NULL to
  83092. * mean "any MIME type".
  83093. * \param description The desired description. The string will be
  83094. * matched exactly. Use \c NULL to mean "any
  83095. * description".
  83096. * \param max_width The maximum width in pixels desired. Use
  83097. * \c (unsigned)(-1) to mean "any width".
  83098. * \param max_height The maximum height in pixels desired. Use
  83099. * \c (unsigned)(-1) to mean "any height".
  83100. * \param max_depth The maximum color depth in bits-per-pixel desired.
  83101. * Use \c (unsigned)(-1) to mean "any depth".
  83102. * \param max_colors The maximum number of colors desired. Use
  83103. * \c (unsigned)(-1) to mean "any number of colors".
  83104. * \assert
  83105. * \code filename != NULL \endcode
  83106. * \code picture != NULL \endcode
  83107. * \retval FLAC__bool
  83108. * \c true if a valid PICTURE block was read from \a filename,
  83109. * and \a *picture will be set to the address of the metadata
  83110. * structure. Returns \c false if there was a memory allocation
  83111. * error, a file decoder error, or the file contained no PICTURE
  83112. * block, and \a *picture will be set to \c NULL.
  83113. */
  83114. 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);
  83115. /* \} */
  83116. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  83117. * \ingroup flac_metadata
  83118. *
  83119. * \brief
  83120. * The level 1 interface provides read-write access to FLAC file metadata and
  83121. * operates directly on the FLAC file.
  83122. *
  83123. * The general usage of this interface is:
  83124. *
  83125. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  83126. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  83127. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  83128. * see if the file is writable, or only read access is allowed.
  83129. * - Use FLAC__metadata_simple_iterator_next() and
  83130. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  83131. * This is does not read the actual blocks themselves.
  83132. * FLAC__metadata_simple_iterator_next() is relatively fast.
  83133. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  83134. * forward from the front of the file.
  83135. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  83136. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  83137. * the current iterator position. The returned object is yours to modify
  83138. * and free.
  83139. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  83140. * back. You must have write permission to the original file. Make sure to
  83141. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  83142. * below.
  83143. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  83144. * Use the object creation functions from
  83145. * \link flac_metadata_object here \endlink to generate new objects.
  83146. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  83147. * currently referred to by the iterator, or replace it with padding.
  83148. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  83149. * finished.
  83150. *
  83151. * \note
  83152. * The FLAC file remains open the whole time between
  83153. * FLAC__metadata_simple_iterator_init() and
  83154. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  83155. * the file during this time.
  83156. *
  83157. * \note
  83158. * Do not modify the \a is_last, \a length, or \a type fields of returned
  83159. * FLAC__StreamMetadata objects. These are managed automatically.
  83160. *
  83161. * \note
  83162. * If any of the modification functions
  83163. * (FLAC__metadata_simple_iterator_set_block(),
  83164. * FLAC__metadata_simple_iterator_delete_block(),
  83165. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  83166. * you should delete the iterator as it may no longer be valid.
  83167. *
  83168. * \{
  83169. */
  83170. struct FLAC__Metadata_SimpleIterator;
  83171. /** The opaque structure definition for the level 1 iterator type.
  83172. * See the
  83173. * \link flac_metadata_level1 metadata level 1 module \endlink
  83174. * for a detailed description.
  83175. */
  83176. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  83177. /** Status type for FLAC__Metadata_SimpleIterator.
  83178. *
  83179. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  83180. */
  83181. typedef enum {
  83182. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  83183. /**< The iterator is in the normal OK state */
  83184. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  83185. /**< The data passed into a function violated the function's usage criteria */
  83186. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  83187. /**< The iterator could not open the target file */
  83188. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  83189. /**< The iterator could not find the FLAC signature at the start of the file */
  83190. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  83191. /**< The iterator tried to write to a file that was not writable */
  83192. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  83193. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  83194. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  83195. /**< The iterator encountered an error while reading the FLAC file */
  83196. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  83197. /**< The iterator encountered an error while seeking in the FLAC file */
  83198. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  83199. /**< The iterator encountered an error while writing the FLAC file */
  83200. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  83201. /**< The iterator encountered an error renaming the FLAC file */
  83202. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  83203. /**< The iterator encountered an error removing the temporary file */
  83204. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  83205. /**< Memory allocation failed */
  83206. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  83207. /**< The caller violated an assertion or an unexpected error occurred */
  83208. } FLAC__Metadata_SimpleIteratorStatus;
  83209. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  83210. *
  83211. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  83212. * will give the string equivalent. The contents should not be modified.
  83213. */
  83214. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  83215. /** Create a new iterator instance.
  83216. *
  83217. * \retval FLAC__Metadata_SimpleIterator*
  83218. * \c NULL if there was an error allocating memory, else the new instance.
  83219. */
  83220. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  83221. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83222. *
  83223. * \param iterator A pointer to an existing iterator.
  83224. * \assert
  83225. * \code iterator != NULL \endcode
  83226. */
  83227. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  83228. /** Get the current status of the iterator. Call this after a function
  83229. * returns \c false to get the reason for the error. Also resets the status
  83230. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  83231. *
  83232. * \param iterator A pointer to an existing iterator.
  83233. * \assert
  83234. * \code iterator != NULL \endcode
  83235. * \retval FLAC__Metadata_SimpleIteratorStatus
  83236. * The current status of the iterator.
  83237. */
  83238. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  83239. /** Initialize the iterator to point to the first metadata block in the
  83240. * given FLAC file.
  83241. *
  83242. * \param iterator A pointer to an existing iterator.
  83243. * \param filename The path to the FLAC file.
  83244. * \param read_only If \c true, the FLAC file will be opened
  83245. * in read-only mode; if \c false, the FLAC
  83246. * file will be opened for edit even if no
  83247. * edits are performed.
  83248. * \param preserve_file_stats If \c true, the owner and modification
  83249. * time will be preserved even if the FLAC
  83250. * file is written to.
  83251. * \assert
  83252. * \code iterator != NULL \endcode
  83253. * \code filename != NULL \endcode
  83254. * \retval FLAC__bool
  83255. * \c false if a memory allocation error occurs, the file can't be
  83256. * opened, or another error occurs, else \c true.
  83257. */
  83258. 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);
  83259. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  83260. * FLAC__metadata_simple_iterator_set_block() and
  83261. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  83262. *
  83263. * \param iterator A pointer to an existing iterator.
  83264. * \assert
  83265. * \code iterator != NULL \endcode
  83266. * \retval FLAC__bool
  83267. * See above.
  83268. */
  83269. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  83270. /** Moves the iterator forward one metadata block, returning \c false if
  83271. * already at the end.
  83272. *
  83273. * \param iterator A pointer to an existing initialized iterator.
  83274. * \assert
  83275. * \code iterator != NULL \endcode
  83276. * \a iterator has been successfully initialized with
  83277. * FLAC__metadata_simple_iterator_init()
  83278. * \retval FLAC__bool
  83279. * \c false if already at the last metadata block of the chain, else
  83280. * \c true.
  83281. */
  83282. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  83283. /** Moves the iterator backward one metadata block, returning \c false if
  83284. * already at the beginning.
  83285. *
  83286. * \param iterator A pointer to an existing initialized iterator.
  83287. * \assert
  83288. * \code iterator != NULL \endcode
  83289. * \a iterator has been successfully initialized with
  83290. * FLAC__metadata_simple_iterator_init()
  83291. * \retval FLAC__bool
  83292. * \c false if already at the first metadata block of the chain, else
  83293. * \c true.
  83294. */
  83295. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  83296. /** Returns a flag telling if the current metadata block is the last.
  83297. *
  83298. * \param iterator A pointer to an existing initialized iterator.
  83299. * \assert
  83300. * \code iterator != NULL \endcode
  83301. * \a iterator has been successfully initialized with
  83302. * FLAC__metadata_simple_iterator_init()
  83303. * \retval FLAC__bool
  83304. * \c true if the current metadata block is the last in the file,
  83305. * else \c false.
  83306. */
  83307. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  83308. /** Get the offset of the metadata block at the current position. This
  83309. * avoids reading the actual block data which can save time for large
  83310. * blocks.
  83311. *
  83312. * \param iterator A pointer to an existing initialized iterator.
  83313. * \assert
  83314. * \code iterator != NULL \endcode
  83315. * \a iterator has been successfully initialized with
  83316. * FLAC__metadata_simple_iterator_init()
  83317. * \retval off_t
  83318. * The offset of the metadata block at the current iterator position.
  83319. * This is the byte offset relative to the beginning of the file of
  83320. * the current metadata block's header.
  83321. */
  83322. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  83323. /** Get the type of the metadata block at the current position. This
  83324. * avoids reading the actual block data which can save time for large
  83325. * blocks.
  83326. *
  83327. * \param iterator A pointer to an existing initialized iterator.
  83328. * \assert
  83329. * \code iterator != NULL \endcode
  83330. * \a iterator has been successfully initialized with
  83331. * FLAC__metadata_simple_iterator_init()
  83332. * \retval FLAC__MetadataType
  83333. * The type of the metadata block at the current iterator position.
  83334. */
  83335. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  83336. /** Get the length of the metadata block at the current position. This
  83337. * avoids reading the actual block data which can save time for large
  83338. * blocks.
  83339. *
  83340. * \param iterator A pointer to an existing initialized iterator.
  83341. * \assert
  83342. * \code iterator != NULL \endcode
  83343. * \a iterator has been successfully initialized with
  83344. * FLAC__metadata_simple_iterator_init()
  83345. * \retval unsigned
  83346. * The length of the metadata block at the current iterator position.
  83347. * The is same length as that in the
  83348. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  83349. * i.e. the length of the metadata body that follows the header.
  83350. */
  83351. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  83352. /** Get the application ID of the \c APPLICATION block at the current
  83353. * position. This avoids reading the actual block data which can save
  83354. * time for large blocks.
  83355. *
  83356. * \param iterator A pointer to an existing initialized iterator.
  83357. * \param id A pointer to a buffer of at least \c 4 bytes where
  83358. * the ID will be stored.
  83359. * \assert
  83360. * \code iterator != NULL \endcode
  83361. * \code id != NULL \endcode
  83362. * \a iterator has been successfully initialized with
  83363. * FLAC__metadata_simple_iterator_init()
  83364. * \retval FLAC__bool
  83365. * \c true if the ID was successfully read, else \c false, in which
  83366. * case you should check FLAC__metadata_simple_iterator_status() to
  83367. * find out why. If the status is
  83368. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  83369. * current metadata block is not an \c APPLICATION block. Otherwise
  83370. * if the status is
  83371. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  83372. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  83373. * occurred and the iterator can no longer be used.
  83374. */
  83375. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  83376. /** Get the metadata block at the current position. You can modify the
  83377. * block but must use FLAC__metadata_simple_iterator_set_block() to
  83378. * write it back to the FLAC file.
  83379. *
  83380. * You must call FLAC__metadata_object_delete() on the returned object
  83381. * when you are finished with it.
  83382. *
  83383. * \param iterator A pointer to an existing initialized iterator.
  83384. * \assert
  83385. * \code iterator != NULL \endcode
  83386. * \a iterator has been successfully initialized with
  83387. * FLAC__metadata_simple_iterator_init()
  83388. * \retval FLAC__StreamMetadata*
  83389. * The current metadata block, or \c NULL if there was a memory
  83390. * allocation error.
  83391. */
  83392. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  83393. /** Write a block back to the FLAC file. This function tries to be
  83394. * as efficient as possible; how the block is actually written is
  83395. * shown by the following:
  83396. *
  83397. * Existing block is a STREAMINFO block and the new block is a
  83398. * STREAMINFO block: the new block is written in place. Make sure
  83399. * you know what you're doing when changing the values of a
  83400. * STREAMINFO block.
  83401. *
  83402. * Existing block is a STREAMINFO block and the new block is a
  83403. * not a STREAMINFO block: this is an error since the first block
  83404. * must be a STREAMINFO block. Returns \c false without altering the
  83405. * file.
  83406. *
  83407. * Existing block is not a STREAMINFO block and the new block is a
  83408. * STREAMINFO block: this is an error since there may be only one
  83409. * STREAMINFO block. Returns \c false without altering the file.
  83410. *
  83411. * Existing block and new block are the same length: the existing
  83412. * block will be replaced by the new block, written in place.
  83413. *
  83414. * Existing block is longer than new block: if use_padding is \c true,
  83415. * the existing block will be overwritten in place with the new
  83416. * block followed by a PADDING block, if possible, to make the total
  83417. * size the same as the existing block. Remember that a padding
  83418. * block requires at least four bytes so if the difference in size
  83419. * between the new block and existing block is less than that, the
  83420. * entire file will have to be rewritten, using the new block's
  83421. * exact size. If use_padding is \c false, the entire file will be
  83422. * rewritten, replacing the existing block by the new block.
  83423. *
  83424. * Existing block is shorter than new block: if use_padding is \c true,
  83425. * the function will try and expand the new block into the following
  83426. * PADDING block, if it exists and doing so won't shrink the PADDING
  83427. * block to less than 4 bytes. If there is no following PADDING
  83428. * block, or it will shrink to less than 4 bytes, or use_padding is
  83429. * \c false, the entire file is rewritten, replacing the existing block
  83430. * with the new block. Note that in this case any following PADDING
  83431. * block is preserved as is.
  83432. *
  83433. * After writing the block, the iterator will remain in the same
  83434. * place, i.e. pointing to the new block.
  83435. *
  83436. * \param iterator A pointer to an existing initialized iterator.
  83437. * \param block The block to set.
  83438. * \param use_padding See above.
  83439. * \assert
  83440. * \code iterator != NULL \endcode
  83441. * \a iterator has been successfully initialized with
  83442. * FLAC__metadata_simple_iterator_init()
  83443. * \code block != NULL \endcode
  83444. * \retval FLAC__bool
  83445. * \c true if successful, else \c false.
  83446. */
  83447. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83448. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  83449. * except that instead of writing over an existing block, it appends
  83450. * a block after the existing block. \a use_padding is again used to
  83451. * tell the function to try an expand into following padding in an
  83452. * attempt to avoid rewriting the entire file.
  83453. *
  83454. * This function will fail and return \c false if given a STREAMINFO
  83455. * block.
  83456. *
  83457. * After writing the block, the iterator will be pointing to the
  83458. * 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_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  83472. /** Deletes the block at the current position. This will cause the
  83473. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  83474. * in which case the block will be replaced by an equal-sized PADDING
  83475. * block. The iterator will be left pointing to the block before the
  83476. * one just deleted.
  83477. *
  83478. * You may not delete the STREAMINFO block.
  83479. *
  83480. * \param iterator A pointer to an existing initialized iterator.
  83481. * \param use_padding See above.
  83482. * \assert
  83483. * \code iterator != NULL \endcode
  83484. * \a iterator has been successfully initialized with
  83485. * FLAC__metadata_simple_iterator_init()
  83486. * \retval FLAC__bool
  83487. * \c true if successful, else \c false.
  83488. */
  83489. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  83490. /* \} */
  83491. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  83492. * \ingroup flac_metadata
  83493. *
  83494. * \brief
  83495. * The level 2 interface provides read-write access to FLAC file metadata;
  83496. * all metadata is read into memory, operated on in memory, and then written
  83497. * to file, which is more efficient than level 1 when editing multiple blocks.
  83498. *
  83499. * Currently Ogg FLAC is supported for read only, via
  83500. * FLAC__metadata_chain_read_ogg() but a subsequent
  83501. * FLAC__metadata_chain_write() will fail.
  83502. *
  83503. * The general usage of this interface is:
  83504. *
  83505. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  83506. * linked list of FLAC metadata blocks.
  83507. * - Read all metadata into the the chain from a FLAC file using
  83508. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  83509. * check the status.
  83510. * - Optionally, consolidate the padding using
  83511. * FLAC__metadata_chain_merge_padding() or
  83512. * FLAC__metadata_chain_sort_padding().
  83513. * - Create a new iterator using FLAC__metadata_iterator_new()
  83514. * - Initialize the iterator to point to the first element in the chain
  83515. * using FLAC__metadata_iterator_init()
  83516. * - Traverse the chain using FLAC__metadata_iterator_next and
  83517. * FLAC__metadata_iterator_prev().
  83518. * - Get a block for reading or modification using
  83519. * FLAC__metadata_iterator_get_block(). The pointer to the object
  83520. * inside the chain is returned, so the block is yours to modify.
  83521. * Changes will be reflected in the FLAC file when you write the
  83522. * chain. You can also add and delete blocks (see functions below).
  83523. * - When done, write out the chain using FLAC__metadata_chain_write().
  83524. * Make sure to read the whole comment to the function below.
  83525. * - Delete the chain using FLAC__metadata_chain_delete().
  83526. *
  83527. * \note
  83528. * Even though the FLAC file is not open while the chain is being
  83529. * manipulated, you must not alter the file externally during
  83530. * this time. The chain assumes the FLAC file will not change
  83531. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  83532. * and FLAC__metadata_chain_write().
  83533. *
  83534. * \note
  83535. * Do not modify the is_last, length, or type fields of returned
  83536. * FLAC__StreamMetadata objects. These are managed automatically.
  83537. *
  83538. * \note
  83539. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  83540. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  83541. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  83542. * become owned by the chain and they will be deleted when the chain is
  83543. * deleted.
  83544. *
  83545. * \{
  83546. */
  83547. struct FLAC__Metadata_Chain;
  83548. /** The opaque structure definition for the level 2 chain type.
  83549. */
  83550. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  83551. struct FLAC__Metadata_Iterator;
  83552. /** The opaque structure definition for the level 2 iterator type.
  83553. */
  83554. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  83555. typedef enum {
  83556. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  83557. /**< The chain is in the normal OK state */
  83558. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  83559. /**< The data passed into a function violated the function's usage criteria */
  83560. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  83561. /**< The chain could not open the target file */
  83562. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  83563. /**< The chain could not find the FLAC signature at the start of the file */
  83564. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  83565. /**< The chain tried to write to a file that was not writable */
  83566. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  83567. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  83568. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  83569. /**< The chain encountered an error while reading the FLAC file */
  83570. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  83571. /**< The chain encountered an error while seeking in the FLAC file */
  83572. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  83573. /**< The chain encountered an error while writing the FLAC file */
  83574. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  83575. /**< The chain encountered an error renaming the FLAC file */
  83576. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  83577. /**< The chain encountered an error removing the temporary file */
  83578. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  83579. /**< Memory allocation failed */
  83580. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  83581. /**< The caller violated an assertion or an unexpected error occurred */
  83582. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  83583. /**< One or more of the required callbacks was NULL */
  83584. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  83585. /**< FLAC__metadata_chain_write() was called on a chain read by
  83586. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83587. * or
  83588. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  83589. * was called on a chain read by
  83590. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83591. * Matching read/write methods must always be used. */
  83592. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  83593. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  83594. * chain write requires a tempfile; use
  83595. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  83596. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  83597. * called when the chain write does not require a tempfile; use
  83598. * FLAC__metadata_chain_write_with_callbacks() instead.
  83599. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  83600. * before writing via callbacks. */
  83601. } FLAC__Metadata_ChainStatus;
  83602. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  83603. *
  83604. * Using a FLAC__Metadata_ChainStatus as the index to this array
  83605. * will give the string equivalent. The contents should not be modified.
  83606. */
  83607. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  83608. /*********** FLAC__Metadata_Chain ***********/
  83609. /** Create a new chain instance.
  83610. *
  83611. * \retval FLAC__Metadata_Chain*
  83612. * \c NULL if there was an error allocating memory, else the new instance.
  83613. */
  83614. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  83615. /** Free a chain instance. Deletes the object pointed to by \a chain.
  83616. *
  83617. * \param chain A pointer to an existing chain.
  83618. * \assert
  83619. * \code chain != NULL \endcode
  83620. */
  83621. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  83622. /** Get the current status of the chain. Call this after a function
  83623. * returns \c false to get the reason for the error. Also resets the
  83624. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  83625. *
  83626. * \param chain A pointer to an existing chain.
  83627. * \assert
  83628. * \code chain != NULL \endcode
  83629. * \retval FLAC__Metadata_ChainStatus
  83630. * The current status of the chain.
  83631. */
  83632. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  83633. /** Read all metadata from a FLAC file into the chain.
  83634. *
  83635. * \param chain A pointer to an existing chain.
  83636. * \param filename The path to the FLAC file to read.
  83637. * \assert
  83638. * \code chain != NULL \endcode
  83639. * \code filename != NULL \endcode
  83640. * \retval FLAC__bool
  83641. * \c true if a valid list of metadata blocks was read from
  83642. * \a filename, else \c false. On failure, check the status with
  83643. * FLAC__metadata_chain_status().
  83644. */
  83645. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  83646. /** Read all metadata from an Ogg FLAC file into the chain.
  83647. *
  83648. * \note Ogg FLAC metadata data writing is not supported yet and
  83649. * FLAC__metadata_chain_write() will fail.
  83650. *
  83651. * \param chain A pointer to an existing chain.
  83652. * \param filename The path to the Ogg FLAC file to read.
  83653. * \assert
  83654. * \code chain != NULL \endcode
  83655. * \code filename != NULL \endcode
  83656. * \retval FLAC__bool
  83657. * \c true if a valid list of metadata blocks was read from
  83658. * \a filename, else \c false. On failure, check the status with
  83659. * FLAC__metadata_chain_status().
  83660. */
  83661. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  83662. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  83663. *
  83664. * The \a handle need only be open for reading, but must be seekable.
  83665. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83666. * for Windows).
  83667. *
  83668. * \param chain A pointer to an existing chain.
  83669. * \param handle The I/O handle of the FLAC stream to read. The
  83670. * handle will NOT be closed after the metadata is read;
  83671. * that is the duty of the caller.
  83672. * \param callbacks
  83673. * A set of callbacks to use for I/O. The mandatory
  83674. * callbacks are \a read, \a seek, and \a tell.
  83675. * \assert
  83676. * \code chain != NULL \endcode
  83677. * \retval FLAC__bool
  83678. * \c true if a valid list of metadata blocks was read from
  83679. * \a handle, else \c false. On failure, check the status with
  83680. * FLAC__metadata_chain_status().
  83681. */
  83682. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83683. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  83684. *
  83685. * The \a handle need only be open for reading, but must be seekable.
  83686. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83687. * for Windows).
  83688. *
  83689. * \note Ogg FLAC metadata data writing is not supported yet and
  83690. * FLAC__metadata_chain_write() will fail.
  83691. *
  83692. * \param chain A pointer to an existing chain.
  83693. * \param handle The I/O handle of the Ogg 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_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83707. /** Checks if writing the given chain would require the use of a
  83708. * temporary file, or if it could be written in place.
  83709. *
  83710. * Under certain conditions, padding can be utilized so that writing
  83711. * edited metadata back to the FLAC file does not require rewriting the
  83712. * entire file. If rewriting is required, then a temporary workfile is
  83713. * required. When writing metadata using callbacks, you must check
  83714. * this function to know whether to call
  83715. * FLAC__metadata_chain_write_with_callbacks() or
  83716. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  83717. * writing with FLAC__metadata_chain_write(), the temporary file is
  83718. * handled internally.
  83719. *
  83720. * \param chain A pointer to an existing chain.
  83721. * \param use_padding
  83722. * Whether or not padding will be allowed to be used
  83723. * during the write. The value of \a use_padding given
  83724. * here must match the value later passed to
  83725. * FLAC__metadata_chain_write_with_callbacks() or
  83726. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  83727. * \assert
  83728. * \code chain != NULL \endcode
  83729. * \retval FLAC__bool
  83730. * \c true if writing the current chain would require a tempfile, or
  83731. * \c false if metadata can be written in place.
  83732. */
  83733. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  83734. /** Write all metadata out to the FLAC file. This function tries to be as
  83735. * efficient as possible; how the metadata is actually written is shown by
  83736. * the following:
  83737. *
  83738. * If the current chain is the same size as the existing metadata, the new
  83739. * data is written in place.
  83740. *
  83741. * If the current chain is longer than the existing metadata, and
  83742. * \a use_padding is \c true, and the last block is a PADDING block of
  83743. * sufficient length, the function will truncate the final padding block
  83744. * so that the overall size of the metadata is the same as the existing
  83745. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  83746. * the above conditions are met, the entire FLAC file must be rewritten.
  83747. * If you want to use padding this way it is a good idea to call
  83748. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  83749. * amount of padding to work with, unless you need to preserve ordering
  83750. * of the PADDING blocks for some reason.
  83751. *
  83752. * If the current chain is shorter than the existing metadata, and
  83753. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  83754. * is extended to make the overall size the same as the existing data. If
  83755. * \a use_padding is \c true and the last block is not a PADDING block, a new
  83756. * PADDING block is added to the end of the new data to make it the same
  83757. * size as the existing data (if possible, see the note to
  83758. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  83759. * and the new data is written in place. If none of the above apply or
  83760. * \a use_padding is \c false, the entire FLAC file is rewritten.
  83761. *
  83762. * If \a preserve_file_stats is \c true, the owner and modification time will
  83763. * be preserved even if the FLAC file is written.
  83764. *
  83765. * For this write function to be used, the chain must have been read with
  83766. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  83767. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  83768. *
  83769. * \param chain A pointer to an existing chain.
  83770. * \param use_padding See above.
  83771. * \param preserve_file_stats See above.
  83772. * \assert
  83773. * \code chain != NULL \endcode
  83774. * \retval FLAC__bool
  83775. * \c true if the write succeeded, else \c false. On failure,
  83776. * check the status with FLAC__metadata_chain_status().
  83777. */
  83778. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  83779. /** Write all metadata out to a FLAC stream via callbacks.
  83780. *
  83781. * (See FLAC__metadata_chain_write() for the details on how padding is
  83782. * used to write metadata in place if possible.)
  83783. *
  83784. * The \a handle must be open for updating and be seekable. The
  83785. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  83786. * for Windows).
  83787. *
  83788. * For this write function to be used, the chain must have been read with
  83789. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83790. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83791. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83792. * \c false.
  83793. *
  83794. * \param chain A pointer to an existing chain.
  83795. * \param use_padding See FLAC__metadata_chain_write()
  83796. * \param handle The I/O handle of the FLAC stream to write. The
  83797. * handle will NOT be closed after the metadata is
  83798. * written; that is the duty of the caller.
  83799. * \param callbacks A set of callbacks to use for I/O. The mandatory
  83800. * callbacks are \a write and \a seek.
  83801. * \assert
  83802. * \code chain != NULL \endcode
  83803. * \retval FLAC__bool
  83804. * \c true if the write succeeded, else \c false. On failure,
  83805. * check the status with FLAC__metadata_chain_status().
  83806. */
  83807. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  83808. /** Write all metadata out to a FLAC stream via callbacks.
  83809. *
  83810. * (See FLAC__metadata_chain_write() for the details on how padding is
  83811. * used to write metadata in place if possible.)
  83812. *
  83813. * This version of the write-with-callbacks function must be used when
  83814. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  83815. * this function, you must supply an I/O handle corresponding to the
  83816. * FLAC file to edit, and a temporary handle to which the new FLAC
  83817. * file will be written. It is the caller's job to move this temporary
  83818. * FLAC file on top of the original FLAC file to complete the metadata
  83819. * edit.
  83820. *
  83821. * The \a handle must be open for reading and be seekable. The
  83822. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  83823. * for Windows).
  83824. *
  83825. * The \a temp_handle must be open for writing. The
  83826. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  83827. * for Windows). It should be an empty stream, or at least positioned
  83828. * at the start-of-file (in which case it is the caller's duty to
  83829. * truncate it on return).
  83830. *
  83831. * For this write function to be used, the chain must have been read with
  83832. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  83833. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  83834. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  83835. * \c true.
  83836. *
  83837. * \param chain A pointer to an existing chain.
  83838. * \param use_padding See FLAC__metadata_chain_write()
  83839. * \param handle The I/O handle of the original FLAC stream to read.
  83840. * The handle will NOT be closed after the metadata is
  83841. * written; that is the duty of the caller.
  83842. * \param callbacks A set of callbacks to use for I/O on \a handle.
  83843. * The mandatory callbacks are \a read, \a seek, and
  83844. * \a eof.
  83845. * \param temp_handle The I/O handle of the FLAC stream to write. The
  83846. * handle will NOT be closed after the metadata is
  83847. * written; that is the duty of the caller.
  83848. * \param temp_callbacks
  83849. * A set of callbacks to use for I/O on temp_handle.
  83850. * The only mandatory callback is \a write.
  83851. * \assert
  83852. * \code chain != NULL \endcode
  83853. * \retval FLAC__bool
  83854. * \c true if the write succeeded, else \c false. On failure,
  83855. * check the status with FLAC__metadata_chain_status().
  83856. */
  83857. 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);
  83858. /** Merge adjacent PADDING blocks into a single block.
  83859. *
  83860. * \note This function does not write to the FLAC file, it only
  83861. * modifies the chain.
  83862. *
  83863. * \warning Any iterator on the current chain will become invalid after this
  83864. * call. You should delete the iterator and get a new one.
  83865. *
  83866. * \param chain A pointer to an existing chain.
  83867. * \assert
  83868. * \code chain != NULL \endcode
  83869. */
  83870. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  83871. /** This function will move all PADDING blocks to the end on the metadata,
  83872. * then merge them into a single block.
  83873. *
  83874. * \note This function does not write to the FLAC file, it only
  83875. * modifies the chain.
  83876. *
  83877. * \warning Any iterator on the current chain will become invalid after this
  83878. * call. You should delete the iterator and get a new one.
  83879. *
  83880. * \param chain A pointer to an existing chain.
  83881. * \assert
  83882. * \code chain != NULL \endcode
  83883. */
  83884. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  83885. /*********** FLAC__Metadata_Iterator ***********/
  83886. /** Create a new iterator instance.
  83887. *
  83888. * \retval FLAC__Metadata_Iterator*
  83889. * \c NULL if there was an error allocating memory, else the new instance.
  83890. */
  83891. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  83892. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  83893. *
  83894. * \param iterator A pointer to an existing iterator.
  83895. * \assert
  83896. * \code iterator != NULL \endcode
  83897. */
  83898. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  83899. /** Initialize the iterator to point to the first metadata block in the
  83900. * given chain.
  83901. *
  83902. * \param iterator A pointer to an existing iterator.
  83903. * \param chain A pointer to an existing and initialized (read) chain.
  83904. * \assert
  83905. * \code iterator != NULL \endcode
  83906. * \code chain != NULL \endcode
  83907. */
  83908. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  83909. /** Moves the iterator forward one metadata block, returning \c false if
  83910. * already at the end.
  83911. *
  83912. * \param iterator A pointer to an existing initialized iterator.
  83913. * \assert
  83914. * \code iterator != NULL \endcode
  83915. * \a iterator has been successfully initialized with
  83916. * FLAC__metadata_iterator_init()
  83917. * \retval FLAC__bool
  83918. * \c false if already at the last metadata block of the chain, else
  83919. * \c true.
  83920. */
  83921. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  83922. /** Moves the iterator backward one metadata block, returning \c false if
  83923. * already at the beginning.
  83924. *
  83925. * \param iterator A pointer to an existing initialized iterator.
  83926. * \assert
  83927. * \code iterator != NULL \endcode
  83928. * \a iterator has been successfully initialized with
  83929. * FLAC__metadata_iterator_init()
  83930. * \retval FLAC__bool
  83931. * \c false if already at the first metadata block of the chain, else
  83932. * \c true.
  83933. */
  83934. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  83935. /** Get the type of the metadata block at the current position.
  83936. *
  83937. * \param iterator A pointer to an existing initialized iterator.
  83938. * \assert
  83939. * \code iterator != NULL \endcode
  83940. * \a iterator has been successfully initialized with
  83941. * FLAC__metadata_iterator_init()
  83942. * \retval FLAC__MetadataType
  83943. * The type of the metadata block at the current iterator position.
  83944. */
  83945. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  83946. /** Get the metadata block at the current position. You can modify
  83947. * the block in place but must write the chain before the changes
  83948. * are reflected to the FLAC file. You do not need to call
  83949. * FLAC__metadata_iterator_set_block() to reflect the changes;
  83950. * the pointer returned by FLAC__metadata_iterator_get_block()
  83951. * points directly into the chain.
  83952. *
  83953. * \warning
  83954. * Do not call FLAC__metadata_object_delete() on the returned object;
  83955. * to delete a block use FLAC__metadata_iterator_delete_block().
  83956. *
  83957. * \param iterator A pointer to an existing initialized iterator.
  83958. * \assert
  83959. * \code iterator != NULL \endcode
  83960. * \a iterator has been successfully initialized with
  83961. * FLAC__metadata_iterator_init()
  83962. * \retval FLAC__StreamMetadata*
  83963. * The current metadata block.
  83964. */
  83965. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  83966. /** Set the metadata block at the current position, replacing the existing
  83967. * block. The new block passed in becomes owned by the chain and it will be
  83968. * deleted when the chain is deleted.
  83969. *
  83970. * \param iterator A pointer to an existing initialized iterator.
  83971. * \param block A pointer to a metadata block.
  83972. * \assert
  83973. * \code iterator != NULL \endcode
  83974. * \a iterator has been successfully initialized with
  83975. * FLAC__metadata_iterator_init()
  83976. * \code block != NULL \endcode
  83977. * \retval FLAC__bool
  83978. * \c false if the conditions in the above description are not met, or
  83979. * a memory allocation error occurs, otherwise \c true.
  83980. */
  83981. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  83982. /** Removes the current block from the chain. If \a replace_with_padding is
  83983. * \c true, the block will instead be replaced with a padding block of equal
  83984. * size. You can not delete the STREAMINFO block. The iterator will be
  83985. * left pointing to the block before the one just "deleted", even if
  83986. * \a replace_with_padding is \c true.
  83987. *
  83988. * \param iterator A pointer to an existing initialized iterator.
  83989. * \param replace_with_padding See above.
  83990. * \assert
  83991. * \code iterator != NULL \endcode
  83992. * \a iterator has been successfully initialized with
  83993. * FLAC__metadata_iterator_init()
  83994. * \retval FLAC__bool
  83995. * \c false if the conditions in the above description are not met,
  83996. * otherwise \c true.
  83997. */
  83998. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  83999. /** Insert a new block before the current block. You cannot insert a block
  84000. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  84001. * as there can be only one, the one that already exists at the head when you
  84002. * read in a chain. The chain takes ownership of the new block and it will be
  84003. * deleted when the chain is deleted. The iterator will be left pointing to
  84004. * the new block.
  84005. *
  84006. * \param iterator A pointer to an existing initialized iterator.
  84007. * \param block A pointer to a metadata block to insert.
  84008. * \assert
  84009. * \code iterator != NULL \endcode
  84010. * \a iterator has been successfully initialized with
  84011. * FLAC__metadata_iterator_init()
  84012. * \retval FLAC__bool
  84013. * \c false if the conditions in the above description are not met, or
  84014. * a memory allocation error occurs, otherwise \c true.
  84015. */
  84016. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84017. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  84018. * block as there can be only one, the one that already exists at the head when
  84019. * you read in a chain. The chain takes ownership of the new block and it will
  84020. * be deleted when the chain is deleted. The iterator will be left pointing to
  84021. * the new block.
  84022. *
  84023. * \param iterator A pointer to an existing initialized iterator.
  84024. * \param block A pointer to a metadata block to insert.
  84025. * \assert
  84026. * \code iterator != NULL \endcode
  84027. * \a iterator has been successfully initialized with
  84028. * FLAC__metadata_iterator_init()
  84029. * \retval FLAC__bool
  84030. * \c false if the conditions in the above description are not met, or
  84031. * a memory allocation error occurs, otherwise \c true.
  84032. */
  84033. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  84034. /* \} */
  84035. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  84036. * \ingroup flac_metadata
  84037. *
  84038. * \brief
  84039. * This module contains methods for manipulating FLAC metadata objects.
  84040. *
  84041. * Since many are variable length we have to be careful about the memory
  84042. * management. We decree that all pointers to data in the object are
  84043. * owned by the object and memory-managed by the object.
  84044. *
  84045. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  84046. * functions to create all instances. When using the
  84047. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  84048. * \a copy to \c true to have the function make it's own copy of the data, or
  84049. * to \c false to give the object ownership of your data. In the latter case
  84050. * your pointer must be freeable by free() and will be free()d when the object
  84051. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  84052. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  84053. * the length argument is 0 and the \a copy argument is \c false.
  84054. *
  84055. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  84056. * will return \c NULL in the case of a memory allocation error, otherwise a new
  84057. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  84058. * case of a memory allocation error.
  84059. *
  84060. * We don't have the convenience of C++ here, so note that the library relies
  84061. * on you to keep the types straight. In other words, if you pass, for
  84062. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  84063. * FLAC__metadata_object_application_set_data(), you will get an assertion
  84064. * failure.
  84065. *
  84066. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  84067. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  84068. * toward the length or stored in the stream, but it can make working with plain
  84069. * comments (those that don't contain embedded-NULs in the value) easier.
  84070. * Entries passed into these functions have trailing NULs added if missing, and
  84071. * returned entries are guaranteed to have a trailing NUL.
  84072. *
  84073. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  84074. * comment entry/name/value will first validate that it complies with the Vorbis
  84075. * comment specification and return false if it does not.
  84076. *
  84077. * There is no need to recalculate the length field on metadata blocks you
  84078. * have modified. They will be calculated automatically before they are
  84079. * written back to a file.
  84080. *
  84081. * \{
  84082. */
  84083. /** Create a new metadata object instance of the given type.
  84084. *
  84085. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  84086. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  84087. * the vendor string set (but zero comments).
  84088. *
  84089. * Do not pass in a value greater than or equal to
  84090. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  84091. * doing.
  84092. *
  84093. * \param type Type of object to create
  84094. * \retval FLAC__StreamMetadata*
  84095. * \c NULL if there was an error allocating memory or the type code is
  84096. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  84097. */
  84098. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  84099. /** Create a copy of an existing metadata object.
  84100. *
  84101. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84102. * object is also copied. The caller takes ownership of the new block and
  84103. * is responsible for freeing it with FLAC__metadata_object_delete().
  84104. *
  84105. * \param object Pointer to object to copy.
  84106. * \assert
  84107. * \code object != NULL \endcode
  84108. * \retval FLAC__StreamMetadata*
  84109. * \c NULL if there was an error allocating memory, else the new instance.
  84110. */
  84111. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  84112. /** Free a metadata object. Deletes the object pointed to by \a object.
  84113. *
  84114. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  84115. * object is also deleted.
  84116. *
  84117. * \param object A pointer to an existing object.
  84118. * \assert
  84119. * \code object != NULL \endcode
  84120. */
  84121. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  84122. /** Compares two metadata objects.
  84123. *
  84124. * The compare is "deep", i.e. dynamically allocated data within the
  84125. * object is also compared.
  84126. *
  84127. * \param block1 A pointer to an existing object.
  84128. * \param block2 A pointer to an existing object.
  84129. * \assert
  84130. * \code block1 != NULL \endcode
  84131. * \code block2 != NULL \endcode
  84132. * \retval FLAC__bool
  84133. * \c true if objects are identical, else \c false.
  84134. */
  84135. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  84136. /** Sets the application data of an APPLICATION block.
  84137. *
  84138. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84139. * takes ownership of the pointer. The existing data will be freed if this
  84140. * function is successful, otherwise the original data will remain if \a copy
  84141. * is \c true and malloc() fails.
  84142. *
  84143. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84144. *
  84145. * \param object A pointer to an existing APPLICATION object.
  84146. * \param data A pointer to the data to set.
  84147. * \param length The length of \a data in bytes.
  84148. * \param copy See above.
  84149. * \assert
  84150. * \code object != NULL \endcode
  84151. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  84152. * \code (data != NULL && length > 0) ||
  84153. * (data == NULL && length == 0 && copy == false) \endcode
  84154. * \retval FLAC__bool
  84155. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84156. */
  84157. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  84158. /** Resize the seekpoint array.
  84159. *
  84160. * If the size shrinks, elements will truncated; if it grows, new placeholder
  84161. * points will be added to the end.
  84162. *
  84163. * \param object A pointer to an existing SEEKTABLE object.
  84164. * \param new_num_points The desired length of the array; may be \c 0.
  84165. * \assert
  84166. * \code object != NULL \endcode
  84167. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84168. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  84169. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  84170. * \retval FLAC__bool
  84171. * \c false if memory allocation error, else \c true.
  84172. */
  84173. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  84174. /** Set a seekpoint in a seektable.
  84175. *
  84176. * \param object A pointer to an existing SEEKTABLE object.
  84177. * \param point_num Index into seekpoint array to set.
  84178. * \param point The point to set.
  84179. * \assert
  84180. * \code object != NULL \endcode
  84181. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84182. * \code object->data.seek_table.num_points > point_num \endcode
  84183. */
  84184. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84185. /** Insert a seekpoint into a seektable.
  84186. *
  84187. * \param object A pointer to an existing SEEKTABLE object.
  84188. * \param point_num Index into seekpoint array to set.
  84189. * \param point The point to set.
  84190. * \assert
  84191. * \code object != NULL \endcode
  84192. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84193. * \code object->data.seek_table.num_points >= point_num \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_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  84198. /** Delete a seekpoint from a seektable.
  84199. *
  84200. * \param object A pointer to an existing SEEKTABLE object.
  84201. * \param point_num Index into seekpoint array to set.
  84202. * \assert
  84203. * \code object != NULL \endcode
  84204. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84205. * \code object->data.seek_table.num_points > point_num \endcode
  84206. * \retval FLAC__bool
  84207. * \c false if memory allocation error, else \c true.
  84208. */
  84209. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  84210. /** Check a seektable to see if it conforms to the FLAC specification.
  84211. * See the format specification for limits on the contents of the
  84212. * seektable.
  84213. *
  84214. * \param object A pointer to an existing SEEKTABLE object.
  84215. * \assert
  84216. * \code object != NULL \endcode
  84217. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84218. * \retval FLAC__bool
  84219. * \c false if seek table is illegal, else \c true.
  84220. */
  84221. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  84222. /** Append a number of placeholder points to the end of a seek table.
  84223. *
  84224. * \note
  84225. * As with the other ..._seektable_template_... functions, you should
  84226. * call FLAC__metadata_object_seektable_template_sort() when finished
  84227. * to make the seek table legal.
  84228. *
  84229. * \param object A pointer to an existing SEEKTABLE object.
  84230. * \param num The number of placeholder points to append.
  84231. * \assert
  84232. * \code object != NULL \endcode
  84233. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84234. * \retval FLAC__bool
  84235. * \c false if memory allocation fails, else \c true.
  84236. */
  84237. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  84238. /** Append a specific seek point template to the end of a seek table.
  84239. *
  84240. * \note
  84241. * As with the other ..._seektable_template_... functions, you should
  84242. * call FLAC__metadata_object_seektable_template_sort() when finished
  84243. * to make the seek table legal.
  84244. *
  84245. * \param object A pointer to an existing SEEKTABLE object.
  84246. * \param sample_number The sample number of the seek point template.
  84247. * \assert
  84248. * \code object != NULL \endcode
  84249. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84250. * \retval FLAC__bool
  84251. * \c false if memory allocation fails, else \c true.
  84252. */
  84253. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  84254. /** Append specific seek point templates to the end of a seek table.
  84255. *
  84256. * \note
  84257. * As with the other ..._seektable_template_... functions, you should
  84258. * call FLAC__metadata_object_seektable_template_sort() when finished
  84259. * to make the seek table legal.
  84260. *
  84261. * \param object A pointer to an existing SEEKTABLE object.
  84262. * \param sample_numbers An array of sample numbers for the seek points.
  84263. * \param num The number of seek point templates to append.
  84264. * \assert
  84265. * \code object != NULL \endcode
  84266. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84267. * \retval FLAC__bool
  84268. * \c false if memory allocation fails, else \c true.
  84269. */
  84270. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  84271. /** Append a set of evenly-spaced seek point templates to the end of a
  84272. * seek table.
  84273. *
  84274. * \note
  84275. * As with the other ..._seektable_template_... functions, you should
  84276. * call FLAC__metadata_object_seektable_template_sort() when finished
  84277. * to make the seek table legal.
  84278. *
  84279. * \param object A pointer to an existing SEEKTABLE object.
  84280. * \param num The number of placeholder points to append.
  84281. * \param total_samples The total number of samples to be encoded;
  84282. * the seekpoints will be spaced approximately
  84283. * \a total_samples / \a num samples apart.
  84284. * \assert
  84285. * \code object != NULL \endcode
  84286. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84287. * \code total_samples > 0 \endcode
  84288. * \retval FLAC__bool
  84289. * \c false if memory allocation fails, else \c true.
  84290. */
  84291. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  84292. /** Append a set of evenly-spaced seek point templates to the end of a
  84293. * seek table.
  84294. *
  84295. * \note
  84296. * As with the other ..._seektable_template_... functions, you should
  84297. * call FLAC__metadata_object_seektable_template_sort() when finished
  84298. * to make the seek table legal.
  84299. *
  84300. * \param object A pointer to an existing SEEKTABLE object.
  84301. * \param samples The number of samples apart to space the placeholder
  84302. * points. The first point will be at sample \c 0, the
  84303. * second at sample \a samples, then 2*\a samples, and
  84304. * so on. As long as \a samples and \a total_samples
  84305. * are greater than \c 0, there will always be at least
  84306. * one seekpoint at sample \c 0.
  84307. * \param total_samples The total number of samples to be encoded;
  84308. * the seekpoints will be spaced
  84309. * \a samples samples apart.
  84310. * \assert
  84311. * \code object != NULL \endcode
  84312. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84313. * \code samples > 0 \endcode
  84314. * \code total_samples > 0 \endcode
  84315. * \retval FLAC__bool
  84316. * \c false if memory allocation fails, else \c true.
  84317. */
  84318. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  84319. /** Sort a seek table's seek points according to the format specification,
  84320. * removing duplicates.
  84321. *
  84322. * \param object A pointer to a seek table to be sorted.
  84323. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  84324. * If \c true, duplicates are deleted and the seek table is
  84325. * shrunk appropriately; the number of placeholder points
  84326. * present in the seek table will be the same after the call
  84327. * as before.
  84328. * \assert
  84329. * \code object != NULL \endcode
  84330. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  84331. * \retval FLAC__bool
  84332. * \c false if realloc() fails, else \c true.
  84333. */
  84334. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  84335. /** Sets the vendor string in a VORBIS_COMMENT block.
  84336. *
  84337. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84338. * one already.
  84339. *
  84340. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84341. * takes ownership of the \c entry.entry pointer.
  84342. *
  84343. * \note If this function returns \c false, the caller still owns the
  84344. * pointer.
  84345. *
  84346. * \param object A pointer to an existing VORBIS_COMMENT object.
  84347. * \param entry The entry to set the vendor string to.
  84348. * \param copy See above.
  84349. * \assert
  84350. * \code object != NULL \endcode
  84351. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84352. * \code (entry.entry != NULL && entry.length > 0) ||
  84353. * (entry.entry == NULL && entry.length == 0) \endcode
  84354. * \retval FLAC__bool
  84355. * \c false if memory allocation fails or \a entry does not comply with the
  84356. * Vorbis comment specification, else \c true.
  84357. */
  84358. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84359. /** Resize the comment array.
  84360. *
  84361. * If the size shrinks, elements will truncated; if it grows, new empty
  84362. * fields will be added to the end.
  84363. *
  84364. * \param object A pointer to an existing VORBIS_COMMENT object.
  84365. * \param new_num_comments The desired length of the array; may be \c 0.
  84366. * \assert
  84367. * \code object != NULL \endcode
  84368. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84369. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  84370. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  84371. * \retval FLAC__bool
  84372. * \c false if memory allocation fails, else \c true.
  84373. */
  84374. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  84375. /** Sets a comment in a VORBIS_COMMENT block.
  84376. *
  84377. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84378. * one already.
  84379. *
  84380. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84381. * takes ownership of the \c entry.entry pointer.
  84382. *
  84383. * \note If this function returns \c false, the caller still owns the
  84384. * pointer.
  84385. *
  84386. * \param object A pointer to an existing VORBIS_COMMENT object.
  84387. * \param comment_num Index into comment array to set.
  84388. * \param entry The entry to set the comment to.
  84389. * \param copy See above.
  84390. * \assert
  84391. * \code object != NULL \endcode
  84392. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84393. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  84394. * \code (entry.entry != NULL && entry.length > 0) ||
  84395. * (entry.entry == NULL && entry.length == 0) \endcode
  84396. * \retval FLAC__bool
  84397. * \c false if memory allocation fails or \a entry does not comply with the
  84398. * Vorbis comment specification, else \c true.
  84399. */
  84400. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84401. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  84402. *
  84403. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84404. * one already.
  84405. *
  84406. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84407. * takes ownership of the \c entry.entry pointer.
  84408. *
  84409. * \note If this function returns \c false, the caller still owns the
  84410. * pointer.
  84411. *
  84412. * \param object A pointer to an existing VORBIS_COMMENT object.
  84413. * \param comment_num The index at which to insert the comment. The comments
  84414. * at and after \a comment_num move right one position.
  84415. * To append a comment to the end, set \a comment_num to
  84416. * \c object->data.vorbis_comment.num_comments .
  84417. * \param entry The comment to insert.
  84418. * \param copy See above.
  84419. * \assert
  84420. * \code object != NULL \endcode
  84421. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84422. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  84423. * \code (entry.entry != NULL && entry.length > 0) ||
  84424. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84425. * \retval FLAC__bool
  84426. * \c false if memory allocation fails or \a entry does not comply with the
  84427. * Vorbis comment specification, else \c true.
  84428. */
  84429. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84430. /** Appends a comment to a VORBIS_COMMENT block.
  84431. *
  84432. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84433. * one already.
  84434. *
  84435. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84436. * takes ownership of the \c entry.entry pointer.
  84437. *
  84438. * \note If this function returns \c false, the caller still owns the
  84439. * pointer.
  84440. *
  84441. * \param object A pointer to an existing VORBIS_COMMENT object.
  84442. * \param entry The comment to insert.
  84443. * \param copy See above.
  84444. * \assert
  84445. * \code object != NULL \endcode
  84446. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \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_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  84454. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  84455. *
  84456. * For convenience, a trailing NUL is added to the entry if it doesn't have
  84457. * one already.
  84458. *
  84459. * Depending on the the value of \a all, either all or just the first comment
  84460. * whose field name(s) match the given entry's name will be replaced by the
  84461. * given entry. If no comments match, \a entry will simply be appended.
  84462. *
  84463. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  84464. * takes ownership of the \c entry.entry pointer.
  84465. *
  84466. * \note If this function returns \c false, the caller still owns the
  84467. * pointer.
  84468. *
  84469. * \param object A pointer to an existing VORBIS_COMMENT object.
  84470. * \param entry The comment to insert.
  84471. * \param all If \c true, all comments whose field name matches
  84472. * \a entry's field name will be removed, and \a entry will
  84473. * be inserted at the position of the first matching
  84474. * comment. If \c false, only the first comment whose
  84475. * field name matches \a entry's field name will be
  84476. * replaced with \a entry.
  84477. * \param copy See above.
  84478. * \assert
  84479. * \code object != NULL \endcode
  84480. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84481. * \code (entry.entry != NULL && entry.length > 0) ||
  84482. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  84483. * \retval FLAC__bool
  84484. * \c false if memory allocation fails or \a entry does not comply with the
  84485. * Vorbis comment specification, else \c true.
  84486. */
  84487. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  84488. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  84489. *
  84490. * \param object A pointer to an existing VORBIS_COMMENT object.
  84491. * \param comment_num The index of the comment to delete.
  84492. * \assert
  84493. * \code object != NULL \endcode
  84494. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84495. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  84496. * \retval FLAC__bool
  84497. * \c false if realloc() fails, else \c true.
  84498. */
  84499. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  84500. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  84501. *
  84502. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  84503. * memory and shall be owned by the caller. For convenience the entry will
  84504. * have a terminating NUL.
  84505. *
  84506. * \param entry A pointer to a Vorbis comment entry. The entry's
  84507. * \c entry pointer should not point to allocated
  84508. * memory as it will be overwritten.
  84509. * \param field_name The field name in ASCII, \c NUL terminated.
  84510. * \param field_value The field value in UTF-8, \c NUL terminated.
  84511. * \assert
  84512. * \code entry != NULL \endcode
  84513. * \code field_name != NULL \endcode
  84514. * \code field_value != NULL \endcode
  84515. * \retval FLAC__bool
  84516. * \c false if malloc() fails, or if \a field_name or \a field_value does
  84517. * not comply with the Vorbis comment specification, else \c true.
  84518. */
  84519. 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);
  84520. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  84521. *
  84522. * The returned pointers to name and value will be allocated by malloc()
  84523. * and shall be owned by the caller.
  84524. *
  84525. * \param entry An existing Vorbis comment entry.
  84526. * \param field_name The address of where the returned pointer to the
  84527. * field name will be stored.
  84528. * \param field_value The address of where the returned pointer to the
  84529. * field value will be stored.
  84530. * \assert
  84531. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84532. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  84533. * \code field_name != NULL \endcode
  84534. * \code field_value != NULL \endcode
  84535. * \retval FLAC__bool
  84536. * \c false if memory allocation fails or \a entry does not comply with the
  84537. * Vorbis comment specification, else \c true.
  84538. */
  84539. 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);
  84540. /** Check if the given Vorbis comment entry's field name matches the given
  84541. * field name.
  84542. *
  84543. * \param entry An existing Vorbis comment entry.
  84544. * \param field_name The field name to check.
  84545. * \param field_name_length The length of \a field_name, not including the
  84546. * terminating \c NUL.
  84547. * \assert
  84548. * \code (entry.entry != NULL && entry.length > 0) \endcode
  84549. * \retval FLAC__bool
  84550. * \c true if the field names match, else \c false
  84551. */
  84552. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  84553. /** Find a Vorbis comment with the given field name.
  84554. *
  84555. * The search begins at entry number \a offset; use an offset of 0 to
  84556. * search from the beginning of the comment array.
  84557. *
  84558. * \param object A pointer to an existing VORBIS_COMMENT object.
  84559. * \param offset The offset into the comment array from where to start
  84560. * the search.
  84561. * \param field_name The field name of the comment to find.
  84562. * \assert
  84563. * \code object != NULL \endcode
  84564. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84565. * \code field_name != NULL \endcode
  84566. * \retval int
  84567. * The offset in the comment array of the first comment whose field
  84568. * name matches \a field_name, or \c -1 if no match was found.
  84569. */
  84570. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  84571. /** Remove first Vorbis comment matching the given field name.
  84572. *
  84573. * \param object A pointer to an existing VORBIS_COMMENT object.
  84574. * \param field_name The field name of comment to delete.
  84575. * \assert
  84576. * \code object != NULL \endcode
  84577. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84578. * \retval int
  84579. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84580. * \c 1 for one matching entry deleted.
  84581. */
  84582. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  84583. /** Remove all Vorbis comments matching the given field name.
  84584. *
  84585. * \param object A pointer to an existing VORBIS_COMMENT object.
  84586. * \param field_name The field name of comments to delete.
  84587. * \assert
  84588. * \code object != NULL \endcode
  84589. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  84590. * \retval int
  84591. * \c -1 for memory allocation error, \c 0 for no matching entries,
  84592. * else the number of matching entries deleted.
  84593. */
  84594. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  84595. /** Create a new CUESHEET track instance.
  84596. *
  84597. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  84598. *
  84599. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84600. * \c NULL if there was an error allocating memory, else the new instance.
  84601. */
  84602. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  84603. /** Create a copy of an existing CUESHEET track object.
  84604. *
  84605. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  84606. * object is also copied. The caller takes ownership of the new object and
  84607. * is responsible for freeing it with
  84608. * FLAC__metadata_object_cuesheet_track_delete().
  84609. *
  84610. * \param object Pointer to object to copy.
  84611. * \assert
  84612. * \code object != NULL \endcode
  84613. * \retval FLAC__StreamMetadata_CueSheet_Track*
  84614. * \c NULL if there was an error allocating memory, else the new instance.
  84615. */
  84616. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  84617. /** Delete a CUESHEET track object
  84618. *
  84619. * \param object A pointer to an existing CUESHEET track object.
  84620. * \assert
  84621. * \code object != NULL \endcode
  84622. */
  84623. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  84624. /** Resize a track's index point array.
  84625. *
  84626. * If the size shrinks, elements will truncated; if it grows, new blank
  84627. * indices will be added to the end.
  84628. *
  84629. * \param object A pointer to an existing CUESHEET object.
  84630. * \param track_num The index of the track to modify. NOTE: this is not
  84631. * necessarily the same as the track's \a number field.
  84632. * \param new_num_indices The desired length of the array; may be \c 0.
  84633. * \assert
  84634. * \code object != NULL \endcode
  84635. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84636. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84637. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  84638. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  84639. * \retval FLAC__bool
  84640. * \c false if memory allocation error, else \c true.
  84641. */
  84642. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  84643. /** Insert an index point in a CUESHEET track at the given index.
  84644. *
  84645. * \param object A pointer to an existing CUESHEET object.
  84646. * \param track_num The index of the track to modify. NOTE: this is not
  84647. * necessarily the same as the track's \a number field.
  84648. * \param index_num The index into the track's index array at which to
  84649. * insert the index point. NOTE: this is not necessarily
  84650. * the same as the index point's \a number field. The
  84651. * indices at and after \a index_num move right one
  84652. * position. To append an index point to the end, set
  84653. * \a index_num to
  84654. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  84655. * \param index The index point to insert.
  84656. * \assert
  84657. * \code object != NULL \endcode
  84658. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84659. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84660. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84661. * \retval FLAC__bool
  84662. * \c false if realloc() fails, else \c true.
  84663. */
  84664. 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);
  84665. /** Insert a blank index point in a CUESHEET track at the given index.
  84666. *
  84667. * A blank index point is one in which all field values are zero.
  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. * \assert
  84680. * \code object != NULL \endcode
  84681. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84682. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84683. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  84684. * \retval FLAC__bool
  84685. * \c false if realloc() fails, else \c true.
  84686. */
  84687. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84688. /** Delete an index point in a CUESHEET track at the given index.
  84689. *
  84690. * \param object A pointer to an existing CUESHEET object.
  84691. * \param track_num The index into the track array of the track to
  84692. * modify. NOTE: this is not necessarily the same
  84693. * as the track's \a number field.
  84694. * \param index_num The index into the track's index array of the index
  84695. * to delete. NOTE: this is not necessarily the same
  84696. * as the index's \a number field.
  84697. * \assert
  84698. * \code object != NULL \endcode
  84699. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84700. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84701. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  84702. * \retval FLAC__bool
  84703. * \c false if realloc() fails, else \c true.
  84704. */
  84705. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  84706. /** Resize the track array.
  84707. *
  84708. * If the size shrinks, elements will truncated; if it grows, new blank
  84709. * tracks will be added to the end.
  84710. *
  84711. * \param object A pointer to an existing CUESHEET object.
  84712. * \param new_num_tracks The desired length of the array; may be \c 0.
  84713. * \assert
  84714. * \code object != NULL \endcode
  84715. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84716. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  84717. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  84718. * \retval FLAC__bool
  84719. * \c false if memory allocation error, else \c true.
  84720. */
  84721. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  84722. /** Sets a track in a CUESHEET block.
  84723. *
  84724. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84725. * takes ownership of the \a track pointer.
  84726. *
  84727. * \param object A pointer to an existing CUESHEET object.
  84728. * \param track_num Index into track array to set. NOTE: this is not
  84729. * necessarily the same as the track's \a number field.
  84730. * \param track The track to set the track to. You may safely pass in
  84731. * a const pointer if \a copy is \c true.
  84732. * \param copy See above.
  84733. * \assert
  84734. * \code object != NULL \endcode
  84735. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84736. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  84737. * \code (track->indices != NULL && track->num_indices > 0) ||
  84738. * (track->indices == NULL && track->num_indices == 0)
  84739. * \retval FLAC__bool
  84740. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84741. */
  84742. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84743. /** Insert a track in a CUESHEET block at the given index.
  84744. *
  84745. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  84746. * takes ownership of the \a track pointer.
  84747. *
  84748. * \param object A pointer to an existing CUESHEET object.
  84749. * \param track_num The index at which to insert the track. NOTE: this
  84750. * is not necessarily the same as the track's \a number
  84751. * field. The tracks at and after \a track_num move right
  84752. * one position. To append a track to the end, set
  84753. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84754. * \param track The track to insert. You may safely pass in a const
  84755. * 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 object->data.cue_sheet.num_tracks >= track_num \endcode
  84761. * \retval FLAC__bool
  84762. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84763. */
  84764. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  84765. /** Insert a blank track in a CUESHEET block at the given index.
  84766. *
  84767. * A blank track is one in which all field values are zero.
  84768. *
  84769. * \param object A pointer to an existing CUESHEET object.
  84770. * \param track_num The index at which to insert the track. NOTE: this
  84771. * is not necessarily the same as the track's \a number
  84772. * field. The tracks at and after \a track_num move right
  84773. * one position. To append a track to the end, set
  84774. * \a track_num to \c object->data.cue_sheet.num_tracks .
  84775. * \assert
  84776. * \code object != NULL \endcode
  84777. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84778. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  84779. * \retval FLAC__bool
  84780. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84781. */
  84782. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  84783. /** Delete a track in a CUESHEET block at the given index.
  84784. *
  84785. * \param object A pointer to an existing CUESHEET object.
  84786. * \param track_num The index into the track array of the track to
  84787. * delete. NOTE: this is not necessarily the same
  84788. * as the track's \a number field.
  84789. * \assert
  84790. * \code object != NULL \endcode
  84791. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84792. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  84793. * \retval FLAC__bool
  84794. * \c false if realloc() fails, else \c true.
  84795. */
  84796. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  84797. /** Check a cue sheet to see if it conforms to the FLAC specification.
  84798. * See the format specification for limits on the contents of the
  84799. * cue sheet.
  84800. *
  84801. * \param object A pointer to an existing CUESHEET object.
  84802. * \param check_cd_da_subset If \c true, check CUESHEET against more
  84803. * stringent requirements for a CD-DA (audio) disc.
  84804. * \param violation Address of a pointer to a string. If there is a
  84805. * violation, a pointer to a string explanation of the
  84806. * violation will be returned here. \a violation may be
  84807. * \c NULL if you don't need the returned string. Do not
  84808. * free the returned string; it will always point to static
  84809. * data.
  84810. * \assert
  84811. * \code object != NULL \endcode
  84812. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84813. * \retval FLAC__bool
  84814. * \c false if cue sheet is illegal, else \c true.
  84815. */
  84816. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  84817. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  84818. * assumes the cue sheet corresponds to a CD; the result is undefined
  84819. * if the cuesheet's is_cd bit is not set.
  84820. *
  84821. * \param object A pointer to an existing CUESHEET object.
  84822. * \assert
  84823. * \code object != NULL \endcode
  84824. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  84825. * \retval FLAC__uint32
  84826. * The unsigned integer representation of the CDDB/freedb ID
  84827. */
  84828. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  84829. /** Sets the MIME type of a PICTURE block.
  84830. *
  84831. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84832. * takes ownership of the pointer. The existing string will be freed if this
  84833. * function is successful, otherwise the original string will remain if \a copy
  84834. * is \c true and malloc() fails.
  84835. *
  84836. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  84837. *
  84838. * \param object A pointer to an existing PICTURE object.
  84839. * \param mime_type A pointer to the MIME type string. The string must be
  84840. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  84841. * is done.
  84842. * \param copy See above.
  84843. * \assert
  84844. * \code object != NULL \endcode
  84845. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84846. * \code (mime_type != NULL) \endcode
  84847. * \retval FLAC__bool
  84848. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84849. */
  84850. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  84851. /** Sets the description of a PICTURE block.
  84852. *
  84853. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  84854. * takes ownership of the pointer. The existing string will be freed if this
  84855. * function is successful, otherwise the original string will remain if \a copy
  84856. * is \c true and malloc() fails.
  84857. *
  84858. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  84859. *
  84860. * \param object A pointer to an existing PICTURE object.
  84861. * \param description A pointer to the description string. The string must be
  84862. * valid UTF-8, NUL-terminated. No validation is done.
  84863. * \param copy See above.
  84864. * \assert
  84865. * \code object != NULL \endcode
  84866. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84867. * \code (description != NULL) \endcode
  84868. * \retval FLAC__bool
  84869. * \c false if \a copy is \c true and malloc() fails, else \c true.
  84870. */
  84871. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  84872. /** Sets the picture data of a PICTURE block.
  84873. *
  84874. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  84875. * takes ownership of the pointer. Also sets the \a data_length field of the
  84876. * metadata object to what is passed in as the \a length parameter. The
  84877. * existing data will be freed if this function is successful, otherwise the
  84878. * original data and data_length will remain if \a copy is \c true and
  84879. * malloc() fails.
  84880. *
  84881. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  84882. *
  84883. * \param object A pointer to an existing PICTURE object.
  84884. * \param data A pointer to the data to set.
  84885. * \param length The length of \a data in bytes.
  84886. * \param copy See above.
  84887. * \assert
  84888. * \code object != NULL \endcode
  84889. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84890. * \code (data != NULL && length > 0) ||
  84891. * (data == NULL && length == 0 && copy == false) \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_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  84896. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  84897. * See the format specification for limits on the contents of the
  84898. * PICTURE block.
  84899. *
  84900. * \param object A pointer to existing PICTURE block to be checked.
  84901. * \param violation Address of a pointer to a string. If there is a
  84902. * violation, a pointer to a string explanation of the
  84903. * violation will be returned here. \a violation may be
  84904. * \c NULL if you don't need the returned string. Do not
  84905. * free the returned string; it will always point to static
  84906. * data.
  84907. * \assert
  84908. * \code object != NULL \endcode
  84909. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  84910. * \retval FLAC__bool
  84911. * \c false if PICTURE block is illegal, else \c true.
  84912. */
  84913. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  84914. /* \} */
  84915. #ifdef __cplusplus
  84916. }
  84917. #endif
  84918. #endif
  84919. /********* End of inlined file: metadata.h *********/
  84920. /********* Start of inlined file: stream_decoder.h *********/
  84921. #ifndef FLAC__STREAM_DECODER_H
  84922. #define FLAC__STREAM_DECODER_H
  84923. #include <stdio.h> /* for FILE */
  84924. #ifdef __cplusplus
  84925. extern "C" {
  84926. #endif
  84927. /** \file include/FLAC/stream_decoder.h
  84928. *
  84929. * \brief
  84930. * This module contains the functions which implement the stream
  84931. * decoder.
  84932. *
  84933. * See the detailed documentation in the
  84934. * \link flac_stream_decoder stream decoder \endlink module.
  84935. */
  84936. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  84937. * \ingroup flac
  84938. *
  84939. * \brief
  84940. * This module describes the decoder layers provided by libFLAC.
  84941. *
  84942. * The stream decoder can be used to decode complete streams either from
  84943. * the client via callbacks, or directly from a file, depending on how
  84944. * it is initialized. When decoding via callbacks, the client provides
  84945. * callbacks for reading FLAC data and writing decoded samples, and
  84946. * handling metadata and errors. If the client also supplies seek-related
  84947. * callback, the decoder function for sample-accurate seeking within the
  84948. * FLAC input is also available. When decoding from a file, the client
  84949. * needs only supply a filename or open \c FILE* and write/metadata/error
  84950. * callbacks; the rest of the callbacks are supplied internally. For more
  84951. * info see the \link flac_stream_decoder stream decoder \endlink module.
  84952. */
  84953. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  84954. * \ingroup flac_decoder
  84955. *
  84956. * \brief
  84957. * This module contains the functions which implement the stream
  84958. * decoder.
  84959. *
  84960. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  84961. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84962. *
  84963. * The basic usage of this decoder is as follows:
  84964. * - The program creates an instance of a decoder using
  84965. * FLAC__stream_decoder_new().
  84966. * - The program overrides the default settings using
  84967. * FLAC__stream_decoder_set_*() functions.
  84968. * - The program initializes the instance to validate the settings and
  84969. * prepare for decoding using
  84970. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  84971. * or FLAC__stream_decoder_init_file() for native FLAC,
  84972. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  84973. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  84974. * - The program calls the FLAC__stream_decoder_process_*() functions
  84975. * to decode data, which subsequently calls the callbacks.
  84976. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  84977. * which flushes the input and output and resets the decoder to the
  84978. * uninitialized state.
  84979. * - The instance may be used again or deleted with
  84980. * FLAC__stream_decoder_delete().
  84981. *
  84982. * In more detail, the program will create a new instance by calling
  84983. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  84984. * functions to override the default decoder options, and call
  84985. * one of the FLAC__stream_decoder_init_*() functions.
  84986. *
  84987. * There are three initialization functions for native FLAC, one for
  84988. * setting up the decoder to decode FLAC data from the client via
  84989. * callbacks, and two for decoding directly from a FLAC file.
  84990. *
  84991. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  84992. * You must also supply several callbacks for handling I/O. Some (like
  84993. * seeking) are optional, depending on the capabilities of the input.
  84994. *
  84995. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  84996. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  84997. * \c FILE* or filename and fewer callbacks; the decoder will handle
  84998. * the other callbacks internally.
  84999. *
  85000. * There are three similarly-named init functions for decoding from Ogg
  85001. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85002. * library has been built with Ogg support.
  85003. *
  85004. * Once the decoder is initialized, your program will call one of several
  85005. * functions to start the decoding process:
  85006. *
  85007. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  85008. * most one metadata block or audio frame and return, calling either the
  85009. * metadata callback or write callback, respectively, once. If the decoder
  85010. * loses sync it will return with only the error callback being called.
  85011. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  85012. * to process the stream from the current location and stop upon reaching
  85013. * the first audio frame. The client will get one metadata, write, or error
  85014. * callback per metadata block, audio frame, or sync error, respectively.
  85015. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  85016. * to process the stream from the current location until the read callback
  85017. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  85018. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  85019. * write, or error callback per metadata block, audio frame, or sync error,
  85020. * respectively.
  85021. *
  85022. * When the decoder has finished decoding (normally or through an abort),
  85023. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  85024. * ensures the decoder is in the correct state and frees memory. Then the
  85025. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  85026. * again to decode another stream.
  85027. *
  85028. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  85029. * At any point after the stream decoder has been initialized, the client can
  85030. * call this function to seek to an exact sample within the stream.
  85031. * Subsequently, the first time the write callback is called it will be
  85032. * passed a (possibly partial) block starting at that sample.
  85033. *
  85034. * If the client cannot seek via the callback interface provided, but still
  85035. * has another way of seeking, it can flush the decoder using
  85036. * FLAC__stream_decoder_flush() and start feeding data from the new position
  85037. * through the read callback.
  85038. *
  85039. * The stream decoder also provides MD5 signature checking. If this is
  85040. * turned on before initialization, FLAC__stream_decoder_finish() will
  85041. * report when the decoded MD5 signature does not match the one stored
  85042. * in the STREAMINFO block. MD5 checking is automatically turned off
  85043. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  85044. * in the STREAMINFO block or when a seek is attempted.
  85045. *
  85046. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  85047. * attention. By default, the decoder only calls the metadata_callback for
  85048. * the STREAMINFO block. These functions allow you to tell the decoder
  85049. * explicitly which blocks to parse and return via the metadata_callback
  85050. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  85051. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  85052. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  85053. * which blocks to return. Remember that metadata blocks can potentially
  85054. * be big (for example, cover art) so filtering out the ones you don't
  85055. * use can reduce the memory requirements of the decoder. Also note the
  85056. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  85057. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  85058. * filtering APPLICATION blocks based on the application ID.
  85059. *
  85060. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  85061. * they still can legally be filtered from the metadata_callback.
  85062. *
  85063. * \note
  85064. * The "set" functions may only be called when the decoder is in the
  85065. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  85066. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  85067. * before FLAC__stream_decoder_init_*(). If this is the case they will
  85068. * return \c true, otherwise \c false.
  85069. *
  85070. * \note
  85071. * FLAC__stream_decoder_finish() resets all settings to the constructor
  85072. * defaults, including the callbacks.
  85073. *
  85074. * \{
  85075. */
  85076. /** State values for a FLAC__StreamDecoder
  85077. *
  85078. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  85079. */
  85080. typedef enum {
  85081. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  85082. /**< The decoder is ready to search for metadata. */
  85083. FLAC__STREAM_DECODER_READ_METADATA,
  85084. /**< The decoder is ready to or is in the process of reading metadata. */
  85085. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  85086. /**< The decoder is ready to or is in the process of searching for the
  85087. * frame sync code.
  85088. */
  85089. FLAC__STREAM_DECODER_READ_FRAME,
  85090. /**< The decoder is ready to or is in the process of reading a frame. */
  85091. FLAC__STREAM_DECODER_END_OF_STREAM,
  85092. /**< The decoder has reached the end of the stream. */
  85093. FLAC__STREAM_DECODER_OGG_ERROR,
  85094. /**< An error occurred in the underlying Ogg layer. */
  85095. FLAC__STREAM_DECODER_SEEK_ERROR,
  85096. /**< An error occurred while seeking. The decoder must be flushed
  85097. * with FLAC__stream_decoder_flush() or reset with
  85098. * FLAC__stream_decoder_reset() before decoding can continue.
  85099. */
  85100. FLAC__STREAM_DECODER_ABORTED,
  85101. /**< The decoder was aborted by the read callback. */
  85102. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  85103. /**< An error occurred allocating memory. The decoder is in an invalid
  85104. * state and can no longer be used.
  85105. */
  85106. FLAC__STREAM_DECODER_UNINITIALIZED
  85107. /**< The decoder is in the uninitialized state; one of the
  85108. * FLAC__stream_decoder_init_*() functions must be called before samples
  85109. * can be processed.
  85110. */
  85111. } FLAC__StreamDecoderState;
  85112. /** Maps a FLAC__StreamDecoderState to a C string.
  85113. *
  85114. * Using a FLAC__StreamDecoderState as the index to this array
  85115. * will give the string equivalent. The contents should not be modified.
  85116. */
  85117. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  85118. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  85119. */
  85120. typedef enum {
  85121. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  85122. /**< Initialization was successful. */
  85123. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85124. /**< The library was not compiled with support for the given container
  85125. * format.
  85126. */
  85127. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  85128. /**< A required callback was not supplied. */
  85129. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  85130. /**< An error occurred allocating memory. */
  85131. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  85132. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  85133. * FLAC__stream_decoder_init_ogg_file(). */
  85134. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  85135. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  85136. * already initialized, usually because
  85137. * FLAC__stream_decoder_finish() was not called.
  85138. */
  85139. } FLAC__StreamDecoderInitStatus;
  85140. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  85141. *
  85142. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  85143. * will give the string equivalent. The contents should not be modified.
  85144. */
  85145. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  85146. /** Return values for the FLAC__StreamDecoder read callback.
  85147. */
  85148. typedef enum {
  85149. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  85150. /**< The read was OK and decoding can continue. */
  85151. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  85152. /**< The read was attempted while at the end of the stream. Note that
  85153. * the client must only return this value when the read callback was
  85154. * called when already at the end of the stream. Otherwise, if the read
  85155. * itself moves to the end of the stream, the client should still return
  85156. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  85157. * the next read callback it should return
  85158. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  85159. * of \c 0.
  85160. */
  85161. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  85162. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85163. } FLAC__StreamDecoderReadStatus;
  85164. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  85165. *
  85166. * Using a FLAC__StreamDecoderReadStatus 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__StreamDecoderReadStatusString[];
  85170. /** Return values for the FLAC__StreamDecoder seek callback.
  85171. */
  85172. typedef enum {
  85173. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  85174. /**< The seek was OK and decoding can continue. */
  85175. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  85176. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85177. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85178. /**< Client does not support seeking. */
  85179. } FLAC__StreamDecoderSeekStatus;
  85180. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  85181. *
  85182. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  85183. * will give the string equivalent. The contents should not be modified.
  85184. */
  85185. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  85186. /** Return values for the FLAC__StreamDecoder tell callback.
  85187. */
  85188. typedef enum {
  85189. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  85190. /**< The tell was OK and decoding can continue. */
  85191. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  85192. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85193. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85194. /**< Client does not support telling the position. */
  85195. } FLAC__StreamDecoderTellStatus;
  85196. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  85197. *
  85198. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  85199. * will give the string equivalent. The contents should not be modified.
  85200. */
  85201. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  85202. /** Return values for the FLAC__StreamDecoder length callback.
  85203. */
  85204. typedef enum {
  85205. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  85206. /**< The length call was OK and decoding can continue. */
  85207. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  85208. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85209. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85210. /**< Client does not support reporting the length. */
  85211. } FLAC__StreamDecoderLengthStatus;
  85212. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  85213. *
  85214. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  85215. * will give the string equivalent. The contents should not be modified.
  85216. */
  85217. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  85218. /** Return values for the FLAC__StreamDecoder write callback.
  85219. */
  85220. typedef enum {
  85221. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  85222. /**< The write was OK and decoding can continue. */
  85223. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  85224. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  85225. } FLAC__StreamDecoderWriteStatus;
  85226. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  85227. *
  85228. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  85229. * will give the string equivalent. The contents should not be modified.
  85230. */
  85231. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  85232. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  85233. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  85234. * all. The rest could be caused by bad sync (false synchronization on
  85235. * data that is not the start of a frame) or corrupted data. The error
  85236. * itself is the decoder's best guess at what happened assuming a correct
  85237. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  85238. * could be caused by a correct sync on the start of a frame, but some
  85239. * data in the frame header was corrupted. Or it could be the result of
  85240. * syncing on a point the stream that looked like the starting of a frame
  85241. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85242. * could be because the decoder encountered a valid frame made by a future
  85243. * version of the encoder which it cannot parse, or because of a false
  85244. * sync making it appear as though an encountered frame was generated by
  85245. * a future encoder.
  85246. */
  85247. typedef enum {
  85248. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  85249. /**< An error in the stream caused the decoder to lose synchronization. */
  85250. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  85251. /**< The decoder encountered a corrupted frame header. */
  85252. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  85253. /**< The frame's data did not match the CRC in the footer. */
  85254. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  85255. /**< The decoder encountered reserved fields in use in the stream. */
  85256. } FLAC__StreamDecoderErrorStatus;
  85257. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  85258. *
  85259. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  85260. * will give the string equivalent. The contents should not be modified.
  85261. */
  85262. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  85263. /***********************************************************************
  85264. *
  85265. * class FLAC__StreamDecoder
  85266. *
  85267. ***********************************************************************/
  85268. struct FLAC__StreamDecoderProtected;
  85269. struct FLAC__StreamDecoderPrivate;
  85270. /** The opaque structure definition for the stream decoder type.
  85271. * See the \link flac_stream_decoder stream decoder module \endlink
  85272. * for a detailed description.
  85273. */
  85274. typedef struct {
  85275. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85276. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85277. } FLAC__StreamDecoder;
  85278. /** Signature for the read callback.
  85279. *
  85280. * A function pointer matching this signature must be passed to
  85281. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85282. * called when the decoder needs more input data. The address of the
  85283. * buffer to be filled is supplied, along with the number of bytes the
  85284. * buffer can hold. The callback may choose to supply less data and
  85285. * modify the byte count but must be careful not to overflow the buffer.
  85286. * The callback then returns a status code chosen from
  85287. * FLAC__StreamDecoderReadStatus.
  85288. *
  85289. * Here is an example of a read callback for stdio streams:
  85290. * \code
  85291. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85292. * {
  85293. * FILE *file = ((MyClientData*)client_data)->file;
  85294. * if(*bytes > 0) {
  85295. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85296. * if(ferror(file))
  85297. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85298. * else if(*bytes == 0)
  85299. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  85300. * else
  85301. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  85302. * }
  85303. * else
  85304. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  85305. * }
  85306. * \endcode
  85307. *
  85308. * \note In general, FLAC__StreamDecoder functions which change the
  85309. * state should not be called on the \a decoder while in the callback.
  85310. *
  85311. * \param decoder The decoder instance calling the callback.
  85312. * \param buffer A pointer to a location for the callee to store
  85313. * data to be decoded.
  85314. * \param bytes A pointer to the size of the buffer. On entry
  85315. * to the callback, it contains the maximum number
  85316. * of bytes that may be stored in \a buffer. The
  85317. * callee must set it to the actual number of bytes
  85318. * stored (0 in case of error or end-of-stream) before
  85319. * returning.
  85320. * \param client_data The callee's client data set through
  85321. * FLAC__stream_decoder_init_*().
  85322. * \retval FLAC__StreamDecoderReadStatus
  85323. * The callee's return status. Note that the callback should return
  85324. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  85325. * zero bytes were read and there is no more data to be read.
  85326. */
  85327. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85328. /** Signature for the seek callback.
  85329. *
  85330. * A function pointer matching this signature may be passed to
  85331. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85332. * called when the decoder needs to seek the input stream. The decoder
  85333. * will pass the absolute byte offset to seek to, 0 meaning the
  85334. * beginning of the stream.
  85335. *
  85336. * Here is an example of a seek callback for stdio streams:
  85337. * \code
  85338. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85339. * {
  85340. * FILE *file = ((MyClientData*)client_data)->file;
  85341. * if(file == stdin)
  85342. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  85343. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85344. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  85345. * else
  85346. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  85347. * }
  85348. * \endcode
  85349. *
  85350. * \note In general, FLAC__StreamDecoder functions which change the
  85351. * state should not be called on the \a decoder while in the callback.
  85352. *
  85353. * \param decoder The decoder instance calling the callback.
  85354. * \param absolute_byte_offset The offset from the beginning of the stream
  85355. * to seek to.
  85356. * \param client_data The callee's client data set through
  85357. * FLAC__stream_decoder_init_*().
  85358. * \retval FLAC__StreamDecoderSeekStatus
  85359. * The callee's return status.
  85360. */
  85361. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85362. /** Signature for the tell callback.
  85363. *
  85364. * A function pointer matching this signature may be passed to
  85365. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85366. * called when the decoder wants to know the current position of the
  85367. * stream. The callback should return the byte offset from the
  85368. * beginning of the stream.
  85369. *
  85370. * Here is an example of a tell callback for stdio streams:
  85371. * \code
  85372. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85373. * {
  85374. * FILE *file = ((MyClientData*)client_data)->file;
  85375. * off_t pos;
  85376. * if(file == stdin)
  85377. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  85378. * else if((pos = ftello(file)) < 0)
  85379. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  85380. * else {
  85381. * *absolute_byte_offset = (FLAC__uint64)pos;
  85382. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  85383. * }
  85384. * }
  85385. * \endcode
  85386. *
  85387. * \note In general, FLAC__StreamDecoder functions which change the
  85388. * state should not be called on the \a decoder while in the callback.
  85389. *
  85390. * \param decoder The decoder instance calling the callback.
  85391. * \param absolute_byte_offset A pointer to storage for the current offset
  85392. * from the beginning of the stream.
  85393. * \param client_data The callee's client data set through
  85394. * FLAC__stream_decoder_init_*().
  85395. * \retval FLAC__StreamDecoderTellStatus
  85396. * The callee's return status.
  85397. */
  85398. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85399. /** Signature for the length callback.
  85400. *
  85401. * A function pointer matching this signature may be passed to
  85402. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85403. * called when the decoder wants to know the total length of the stream
  85404. * in bytes.
  85405. *
  85406. * Here is an example of a length callback for stdio streams:
  85407. * \code
  85408. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  85409. * {
  85410. * FILE *file = ((MyClientData*)client_data)->file;
  85411. * struct stat filestats;
  85412. *
  85413. * if(file == stdin)
  85414. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  85415. * else if(fstat(fileno(file), &filestats) != 0)
  85416. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  85417. * else {
  85418. * *stream_length = (FLAC__uint64)filestats.st_size;
  85419. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  85420. * }
  85421. * }
  85422. * \endcode
  85423. *
  85424. * \note In general, FLAC__StreamDecoder functions which change the
  85425. * state should not be called on the \a decoder while in the callback.
  85426. *
  85427. * \param decoder The decoder instance calling the callback.
  85428. * \param stream_length A pointer to storage for the length of the stream
  85429. * in bytes.
  85430. * \param client_data The callee's client data set through
  85431. * FLAC__stream_decoder_init_*().
  85432. * \retval FLAC__StreamDecoderLengthStatus
  85433. * The callee's return status.
  85434. */
  85435. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  85436. /** Signature for the EOF callback.
  85437. *
  85438. * A function pointer matching this signature may be passed to
  85439. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  85440. * called when the decoder needs to know if the end of the stream has
  85441. * been reached.
  85442. *
  85443. * Here is an example of a EOF callback for stdio streams:
  85444. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  85445. * \code
  85446. * {
  85447. * FILE *file = ((MyClientData*)client_data)->file;
  85448. * return feof(file)? true : false;
  85449. * }
  85450. * \endcode
  85451. *
  85452. * \note In general, FLAC__StreamDecoder functions which change the
  85453. * state should not be called on the \a decoder while in the callback.
  85454. *
  85455. * \param decoder The decoder instance calling the callback.
  85456. * \param client_data The callee's client data set through
  85457. * FLAC__stream_decoder_init_*().
  85458. * \retval FLAC__bool
  85459. * \c true if the currently at the end of the stream, else \c false.
  85460. */
  85461. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  85462. /** Signature for the write callback.
  85463. *
  85464. * A function pointer matching this signature must be passed to one of
  85465. * the FLAC__stream_decoder_init_*() functions.
  85466. * The supplied function will be called when the decoder has decoded a
  85467. * single audio frame. The decoder will pass the frame metadata as well
  85468. * as an array of pointers (one for each channel) pointing to the
  85469. * decoded audio.
  85470. *
  85471. * \note In general, FLAC__StreamDecoder functions which change the
  85472. * state should not be called on the \a decoder while in the callback.
  85473. *
  85474. * \param decoder The decoder instance calling the callback.
  85475. * \param frame The description of the decoded frame. See
  85476. * FLAC__Frame.
  85477. * \param buffer An array of pointers to decoded channels of data.
  85478. * Each pointer will point to an array of signed
  85479. * samples of length \a frame->header.blocksize.
  85480. * Channels will be ordered according to the FLAC
  85481. * specification; see the documentation for the
  85482. * <A HREF="../format.html#frame_header">frame header</A>.
  85483. * \param client_data The callee's client data set through
  85484. * FLAC__stream_decoder_init_*().
  85485. * \retval FLAC__StreamDecoderWriteStatus
  85486. * The callee's return status.
  85487. */
  85488. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  85489. /** Signature for the metadata callback.
  85490. *
  85491. * A function pointer matching this signature must be passed to one of
  85492. * the FLAC__stream_decoder_init_*() functions.
  85493. * The supplied function will be called when the decoder has decoded a
  85494. * metadata block. In a valid FLAC file there will always be one
  85495. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  85496. * These will be supplied by the decoder in the same order as they
  85497. * appear in the stream and always before the first audio frame (i.e.
  85498. * write callback). The metadata block that is passed in must not be
  85499. * modified, and it doesn't live beyond the callback, so you should make
  85500. * a copy of it with FLAC__metadata_object_clone() if you will need it
  85501. * elsewhere. Since metadata blocks can potentially be large, by
  85502. * default the decoder only calls the metadata callback for the
  85503. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  85504. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  85505. *
  85506. * \note In general, FLAC__StreamDecoder functions which change the
  85507. * state should not be called on the \a decoder while in the callback.
  85508. *
  85509. * \param decoder The decoder instance calling the callback.
  85510. * \param metadata The decoded metadata block.
  85511. * \param client_data The callee's client data set through
  85512. * FLAC__stream_decoder_init_*().
  85513. */
  85514. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85515. /** Signature for the error callback.
  85516. *
  85517. * A function pointer matching this signature must be passed to one of
  85518. * the FLAC__stream_decoder_init_*() functions.
  85519. * The supplied function will be called whenever an error occurs during
  85520. * decoding.
  85521. *
  85522. * \note In general, FLAC__StreamDecoder functions which change the
  85523. * state should not be called on the \a decoder while in the callback.
  85524. *
  85525. * \param decoder The decoder instance calling the callback.
  85526. * \param status The error encountered by the decoder.
  85527. * \param client_data The callee's client data set through
  85528. * FLAC__stream_decoder_init_*().
  85529. */
  85530. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  85531. /***********************************************************************
  85532. *
  85533. * Class constructor/destructor
  85534. *
  85535. ***********************************************************************/
  85536. /** Create a new stream decoder instance. The instance is created with
  85537. * default settings; see the individual FLAC__stream_decoder_set_*()
  85538. * functions for each setting's default.
  85539. *
  85540. * \retval FLAC__StreamDecoder*
  85541. * \c NULL if there was an error allocating memory, else the new instance.
  85542. */
  85543. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  85544. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  85545. *
  85546. * \param decoder A pointer to an existing decoder.
  85547. * \assert
  85548. * \code decoder != NULL \endcode
  85549. */
  85550. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  85551. /***********************************************************************
  85552. *
  85553. * Public class method prototypes
  85554. *
  85555. ***********************************************************************/
  85556. /** Set the serial number for the FLAC stream within the Ogg container.
  85557. * The default behavior is to use the serial number of the first Ogg
  85558. * page. Setting a serial number here will explicitly specify which
  85559. * stream is to be decoded.
  85560. *
  85561. * \note
  85562. * This does not need to be set for native FLAC decoding.
  85563. *
  85564. * \default \c use serial number of first page
  85565. * \param decoder A decoder instance to set.
  85566. * \param serial_number See above.
  85567. * \assert
  85568. * \code decoder != NULL \endcode
  85569. * \retval FLAC__bool
  85570. * \c false if the decoder is already initialized, else \c true.
  85571. */
  85572. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  85573. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  85574. * compute the MD5 signature of the unencoded audio data while decoding
  85575. * and compare it to the signature from the STREAMINFO block, if it
  85576. * exists, during FLAC__stream_decoder_finish().
  85577. *
  85578. * MD5 signature checking will be turned off (until the next
  85579. * FLAC__stream_decoder_reset()) if there is no signature in the
  85580. * STREAMINFO block or when a seek is attempted.
  85581. *
  85582. * Clients that do not use the MD5 check should leave this off to speed
  85583. * up decoding.
  85584. *
  85585. * \default \c false
  85586. * \param decoder A decoder instance to set.
  85587. * \param value Flag value (see above).
  85588. * \assert
  85589. * \code decoder != NULL \endcode
  85590. * \retval FLAC__bool
  85591. * \c false if the decoder is already initialized, else \c true.
  85592. */
  85593. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  85594. /** Direct the decoder to pass on all metadata blocks of type \a type.
  85595. *
  85596. * \default By default, only the \c STREAMINFO block is returned via the
  85597. * metadata callback.
  85598. * \param decoder A decoder instance to set.
  85599. * \param type See above.
  85600. * \assert
  85601. * \code decoder != NULL \endcode
  85602. * \a type is valid
  85603. * \retval FLAC__bool
  85604. * \c false if the decoder is already initialized, else \c true.
  85605. */
  85606. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85607. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  85608. * given \a id.
  85609. *
  85610. * \default By default, only the \c STREAMINFO block is returned via the
  85611. * metadata callback.
  85612. * \param decoder A decoder instance to set.
  85613. * \param id See above.
  85614. * \assert
  85615. * \code decoder != NULL \endcode
  85616. * \code id != NULL \endcode
  85617. * \retval FLAC__bool
  85618. * \c false if the decoder is already initialized, else \c true.
  85619. */
  85620. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85621. /** Direct the decoder to pass on all metadata blocks of any type.
  85622. *
  85623. * \default By default, only the \c STREAMINFO block is returned via the
  85624. * metadata callback.
  85625. * \param decoder A decoder instance to set.
  85626. * \assert
  85627. * \code decoder != NULL \endcode
  85628. * \retval FLAC__bool
  85629. * \c false if the decoder is already initialized, else \c true.
  85630. */
  85631. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  85632. /** Direct the decoder to filter out all metadata blocks of type \a type.
  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 type See above.
  85638. * \assert
  85639. * \code decoder != NULL \endcode
  85640. * \a type is valid
  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_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  85645. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  85646. * the given \a id.
  85647. *
  85648. * \default By default, only the \c STREAMINFO block is returned via the
  85649. * metadata callback.
  85650. * \param decoder A decoder instance to set.
  85651. * \param id See above.
  85652. * \assert
  85653. * \code decoder != NULL \endcode
  85654. * \code id != NULL \endcode
  85655. * \retval FLAC__bool
  85656. * \c false if the decoder is already initialized, else \c true.
  85657. */
  85658. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  85659. /** Direct the decoder to filter out all metadata blocks of any type.
  85660. *
  85661. * \default By default, only the \c STREAMINFO block is returned via the
  85662. * metadata callback.
  85663. * \param decoder A decoder instance to set.
  85664. * \assert
  85665. * \code decoder != NULL \endcode
  85666. * \retval FLAC__bool
  85667. * \c false if the decoder is already initialized, else \c true.
  85668. */
  85669. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  85670. /** Get the current decoder state.
  85671. *
  85672. * \param decoder A decoder instance to query.
  85673. * \assert
  85674. * \code decoder != NULL \endcode
  85675. * \retval FLAC__StreamDecoderState
  85676. * The current decoder state.
  85677. */
  85678. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  85679. /** Get the current decoder state as a C string.
  85680. *
  85681. * \param decoder A decoder instance to query.
  85682. * \assert
  85683. * \code decoder != NULL \endcode
  85684. * \retval const char *
  85685. * The decoder state as a C string. Do not modify the contents.
  85686. */
  85687. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  85688. /** Get the "MD5 signature checking" flag.
  85689. * This is the value of the setting, not whether or not the decoder is
  85690. * currently checking the MD5 (remember, it can be turned off automatically
  85691. * by a seek). When the decoder is reset the flag will be restored to the
  85692. * value returned by this function.
  85693. *
  85694. * \param decoder A decoder instance to query.
  85695. * \assert
  85696. * \code decoder != NULL \endcode
  85697. * \retval FLAC__bool
  85698. * See above.
  85699. */
  85700. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  85701. /** Get the total number of samples in the stream being decoded.
  85702. * Will only be valid after decoding has started and will contain the
  85703. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  85704. *
  85705. * \param decoder A decoder instance to query.
  85706. * \assert
  85707. * \code decoder != NULL \endcode
  85708. * \retval unsigned
  85709. * See above.
  85710. */
  85711. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  85712. /** Get the current number of channels in the stream being decoded.
  85713. * Will only be valid after decoding has started and will contain the
  85714. * value from the most recently decoded frame header.
  85715. *
  85716. * \param decoder A decoder instance to query.
  85717. * \assert
  85718. * \code decoder != NULL \endcode
  85719. * \retval unsigned
  85720. * See above.
  85721. */
  85722. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  85723. /** Get the current channel assignment in the stream being decoded.
  85724. * Will only be valid after decoding has started and will contain the
  85725. * value from the most recently decoded frame header.
  85726. *
  85727. * \param decoder A decoder instance to query.
  85728. * \assert
  85729. * \code decoder != NULL \endcode
  85730. * \retval FLAC__ChannelAssignment
  85731. * See above.
  85732. */
  85733. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  85734. /** Get the current sample resolution in the stream being decoded.
  85735. * Will only be valid after decoding has started and will contain the
  85736. * value from the most recently decoded frame header.
  85737. *
  85738. * \param decoder A decoder instance to query.
  85739. * \assert
  85740. * \code decoder != NULL \endcode
  85741. * \retval unsigned
  85742. * See above.
  85743. */
  85744. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  85745. /** Get the current sample rate in Hz of the stream being decoded.
  85746. * Will only be valid after decoding has started and will contain the
  85747. * value from the most recently decoded frame header.
  85748. *
  85749. * \param decoder A decoder instance to query.
  85750. * \assert
  85751. * \code decoder != NULL \endcode
  85752. * \retval unsigned
  85753. * See above.
  85754. */
  85755. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  85756. /** Get the current blocksize of the stream being decoded.
  85757. * Will only be valid after decoding has started and will contain the
  85758. * value from the most recently decoded frame header.
  85759. *
  85760. * \param decoder A decoder instance to query.
  85761. * \assert
  85762. * \code decoder != NULL \endcode
  85763. * \retval unsigned
  85764. * See above.
  85765. */
  85766. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  85767. /** Returns the decoder's current read position within the stream.
  85768. * The position is the byte offset from the start of the stream.
  85769. * Bytes before this position have been fully decoded. Note that
  85770. * there may still be undecoded bytes in the decoder's read FIFO.
  85771. * The returned position is correct even after a seek.
  85772. *
  85773. * \warning This function currently only works for native FLAC,
  85774. * not Ogg FLAC streams.
  85775. *
  85776. * \param decoder A decoder instance to query.
  85777. * \param position Address at which to return the desired position.
  85778. * \assert
  85779. * \code decoder != NULL \endcode
  85780. * \code position != NULL \endcode
  85781. * \retval FLAC__bool
  85782. * \c true if successful, \c false if the stream is not native FLAC,
  85783. * or there was an error from the 'tell' callback or it returned
  85784. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  85785. */
  85786. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  85787. /** Initialize the decoder instance to decode native FLAC streams.
  85788. *
  85789. * This flavor of initialization sets up the decoder to decode from a
  85790. * native FLAC stream. I/O is performed via callbacks to the client.
  85791. * For decoding from a plain file via filename or open FILE*,
  85792. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  85793. * provide a simpler interface.
  85794. *
  85795. * This function should be called after FLAC__stream_decoder_new() and
  85796. * FLAC__stream_decoder_set_*() but before any of the
  85797. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85798. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85799. * if initialization succeeded.
  85800. *
  85801. * \param decoder An uninitialized decoder instance.
  85802. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85803. * pointer must not be \c NULL.
  85804. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85805. * pointer may be \c NULL if seeking is not
  85806. * supported. If \a seek_callback is not \c NULL then a
  85807. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85808. * Alternatively, a dummy seek callback that just
  85809. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85810. * may also be supplied, all though this is slightly
  85811. * less efficient for the decoder.
  85812. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85813. * pointer may be \c NULL if not supported by the client. If
  85814. * \a seek_callback is not \c NULL then a
  85815. * \a tell_callback must also be supplied.
  85816. * Alternatively, a dummy tell callback that just
  85817. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85818. * may also be supplied, all though this is slightly
  85819. * less efficient for the decoder.
  85820. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85821. * pointer may be \c NULL if not supported by the client. If
  85822. * \a seek_callback is not \c NULL then a
  85823. * \a length_callback must also be supplied.
  85824. * Alternatively, a dummy length callback that just
  85825. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85826. * may also be supplied, all though this is slightly
  85827. * less efficient for the decoder.
  85828. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85829. * pointer may be \c NULL if not supported by the client. If
  85830. * \a seek_callback is not \c NULL then a
  85831. * \a eof_callback must also be supplied.
  85832. * Alternatively, a dummy length callback that just
  85833. * returns \c false
  85834. * may also be supplied, all though this is slightly
  85835. * less efficient for the decoder.
  85836. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85837. * pointer must not be \c NULL.
  85838. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85839. * pointer may be \c NULL if the callback is not
  85840. * desired.
  85841. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85842. * pointer must not be \c NULL.
  85843. * \param client_data This value will be supplied to callbacks in their
  85844. * \a client_data argument.
  85845. * \assert
  85846. * \code decoder != NULL \endcode
  85847. * \retval FLAC__StreamDecoderInitStatus
  85848. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85849. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85850. */
  85851. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  85852. FLAC__StreamDecoder *decoder,
  85853. FLAC__StreamDecoderReadCallback read_callback,
  85854. FLAC__StreamDecoderSeekCallback seek_callback,
  85855. FLAC__StreamDecoderTellCallback tell_callback,
  85856. FLAC__StreamDecoderLengthCallback length_callback,
  85857. FLAC__StreamDecoderEofCallback eof_callback,
  85858. FLAC__StreamDecoderWriteCallback write_callback,
  85859. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85860. FLAC__StreamDecoderErrorCallback error_callback,
  85861. void *client_data
  85862. );
  85863. /** Initialize the decoder instance to decode Ogg FLAC streams.
  85864. *
  85865. * This flavor of initialization sets up the decoder to decode from a
  85866. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  85867. * client. For decoding from a plain file via filename or open FILE*,
  85868. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  85869. * provide a simpler interface.
  85870. *
  85871. * This function should be called after FLAC__stream_decoder_new() and
  85872. * FLAC__stream_decoder_set_*() but before any of the
  85873. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85874. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85875. * if initialization succeeded.
  85876. *
  85877. * \note Support for Ogg FLAC in the library is optional. If this
  85878. * library has been built without support for Ogg FLAC, this function
  85879. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85880. *
  85881. * \param decoder An uninitialized decoder instance.
  85882. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  85883. * pointer must not be \c NULL.
  85884. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  85885. * pointer may be \c NULL if seeking is not
  85886. * supported. If \a seek_callback is not \c NULL then a
  85887. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  85888. * Alternatively, a dummy seek callback that just
  85889. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  85890. * may also be supplied, all though this is slightly
  85891. * less efficient for the decoder.
  85892. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  85893. * pointer may be \c NULL if not supported by the client. If
  85894. * \a seek_callback is not \c NULL then a
  85895. * \a tell_callback must also be supplied.
  85896. * Alternatively, a dummy tell callback that just
  85897. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  85898. * may also be supplied, all though this is slightly
  85899. * less efficient for the decoder.
  85900. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  85901. * pointer may be \c NULL if not supported by the client. If
  85902. * \a seek_callback is not \c NULL then a
  85903. * \a length_callback must also be supplied.
  85904. * Alternatively, a dummy length callback that just
  85905. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  85906. * may also be supplied, all though this is slightly
  85907. * less efficient for the decoder.
  85908. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  85909. * pointer may be \c NULL if not supported by the client. If
  85910. * \a seek_callback is not \c NULL then a
  85911. * \a eof_callback must also be supplied.
  85912. * Alternatively, a dummy length callback that just
  85913. * returns \c false
  85914. * may also be supplied, all though this is slightly
  85915. * less efficient for the decoder.
  85916. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85917. * pointer must not be \c NULL.
  85918. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85919. * pointer may be \c NULL if the callback is not
  85920. * desired.
  85921. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85922. * pointer must not be \c NULL.
  85923. * \param client_data This value will be supplied to callbacks in their
  85924. * \a client_data argument.
  85925. * \assert
  85926. * \code decoder != NULL \endcode
  85927. * \retval FLAC__StreamDecoderInitStatus
  85928. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85929. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85930. */
  85931. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  85932. FLAC__StreamDecoder *decoder,
  85933. FLAC__StreamDecoderReadCallback read_callback,
  85934. FLAC__StreamDecoderSeekCallback seek_callback,
  85935. FLAC__StreamDecoderTellCallback tell_callback,
  85936. FLAC__StreamDecoderLengthCallback length_callback,
  85937. FLAC__StreamDecoderEofCallback eof_callback,
  85938. FLAC__StreamDecoderWriteCallback write_callback,
  85939. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85940. FLAC__StreamDecoderErrorCallback error_callback,
  85941. void *client_data
  85942. );
  85943. /** Initialize the decoder instance to decode native FLAC files.
  85944. *
  85945. * This flavor of initialization sets up the decoder to decode from a
  85946. * plain native FLAC file. For non-stdio streams, you must use
  85947. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  85948. *
  85949. * This function should be called after FLAC__stream_decoder_new() and
  85950. * FLAC__stream_decoder_set_*() but before any of the
  85951. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85952. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85953. * if initialization succeeded.
  85954. *
  85955. * \param decoder An uninitialized decoder instance.
  85956. * \param file An open FLAC file. The file should have been
  85957. * opened with mode \c "rb" and rewound. The file
  85958. * becomes owned by the decoder and should not be
  85959. * manipulated by the client while decoding.
  85960. * Unless \a file is \c stdin, it will be closed
  85961. * when FLAC__stream_decoder_finish() is called.
  85962. * Note however that seeking will not work when
  85963. * decoding from \c stdout since it is not seekable.
  85964. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85965. * pointer must not be \c NULL.
  85966. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85967. * pointer may be \c NULL if the callback is not
  85968. * desired.
  85969. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85970. * pointer must not be \c NULL.
  85971. * \param client_data This value will be supplied to callbacks in their
  85972. * \a client_data argument.
  85973. * \assert
  85974. * \code decoder != NULL \endcode
  85975. * \code file != NULL \endcode
  85976. * \retval FLAC__StreamDecoderInitStatus
  85977. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85978. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85979. */
  85980. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  85981. FLAC__StreamDecoder *decoder,
  85982. FILE *file,
  85983. FLAC__StreamDecoderWriteCallback write_callback,
  85984. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85985. FLAC__StreamDecoderErrorCallback error_callback,
  85986. void *client_data
  85987. );
  85988. /** Initialize the decoder instance to decode Ogg FLAC files.
  85989. *
  85990. * This flavor of initialization sets up the decoder to decode from a
  85991. * plain Ogg FLAC file. For non-stdio streams, you must use
  85992. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  85993. *
  85994. * This function should be called after FLAC__stream_decoder_new() and
  85995. * FLAC__stream_decoder_set_*() but before any of the
  85996. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85997. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85998. * if initialization succeeded.
  85999. *
  86000. * \note Support for Ogg FLAC in the library is optional. If this
  86001. * library has been built without support for Ogg FLAC, this function
  86002. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86003. *
  86004. * \param decoder An uninitialized decoder instance.
  86005. * \param file An open FLAC file. The file should have been
  86006. * opened with mode \c "rb" and rewound. The file
  86007. * becomes owned by the decoder and should not be
  86008. * manipulated by the client while decoding.
  86009. * Unless \a file is \c stdin, it will be closed
  86010. * when FLAC__stream_decoder_finish() is called.
  86011. * Note however that seeking will not work when
  86012. * decoding from \c stdout since it is not seekable.
  86013. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86014. * pointer must not be \c NULL.
  86015. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86016. * pointer may be \c NULL if the callback is not
  86017. * desired.
  86018. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86019. * pointer must not be \c NULL.
  86020. * \param client_data This value will be supplied to callbacks in their
  86021. * \a client_data argument.
  86022. * \assert
  86023. * \code decoder != NULL \endcode
  86024. * \code file != NULL \endcode
  86025. * \retval FLAC__StreamDecoderInitStatus
  86026. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86027. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86028. */
  86029. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  86030. FLAC__StreamDecoder *decoder,
  86031. FILE *file,
  86032. FLAC__StreamDecoderWriteCallback write_callback,
  86033. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86034. FLAC__StreamDecoderErrorCallback error_callback,
  86035. void *client_data
  86036. );
  86037. /** Initialize the decoder instance to decode native FLAC files.
  86038. *
  86039. * This flavor of initialization sets up the decoder to decode from a plain
  86040. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86041. * example, with Unicode filenames on Windows), you must use
  86042. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  86043. * and provide callbacks for the I/O.
  86044. *
  86045. * This function should be called after FLAC__stream_decoder_new() and
  86046. * FLAC__stream_decoder_set_*() but before any of the
  86047. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86048. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86049. * if initialization succeeded.
  86050. *
  86051. * \param decoder An uninitialized decoder instance.
  86052. * \param filename The name of the file to decode from. The file will
  86053. * be opened with fopen(). Use \c NULL to decode from
  86054. * \c stdin. Note that \c stdin is not seekable.
  86055. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86056. * pointer must not be \c NULL.
  86057. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86058. * pointer may be \c NULL if the callback is not
  86059. * desired.
  86060. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86061. * pointer must not be \c NULL.
  86062. * \param client_data This value will be supplied to callbacks in their
  86063. * \a client_data argument.
  86064. * \assert
  86065. * \code decoder != NULL \endcode
  86066. * \retval FLAC__StreamDecoderInitStatus
  86067. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86068. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86069. */
  86070. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  86071. FLAC__StreamDecoder *decoder,
  86072. const char *filename,
  86073. FLAC__StreamDecoderWriteCallback write_callback,
  86074. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86075. FLAC__StreamDecoderErrorCallback error_callback,
  86076. void *client_data
  86077. );
  86078. /** Initialize the decoder instance to decode Ogg FLAC files.
  86079. *
  86080. * This flavor of initialization sets up the decoder to decode from a plain
  86081. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  86082. * example, with Unicode filenames on Windows), you must use
  86083. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  86084. * and provide callbacks for the I/O.
  86085. *
  86086. * This function should be called after FLAC__stream_decoder_new() and
  86087. * FLAC__stream_decoder_set_*() but before any of the
  86088. * FLAC__stream_decoder_process_*() functions. Will set and return the
  86089. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  86090. * if initialization succeeded.
  86091. *
  86092. * \note Support for Ogg FLAC in the library is optional. If this
  86093. * library has been built without support for Ogg FLAC, this function
  86094. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  86095. *
  86096. * \param decoder An uninitialized decoder instance.
  86097. * \param filename The name of the file to decode from. The file will
  86098. * be opened with fopen(). Use \c NULL to decode from
  86099. * \c stdin. Note that \c stdin is not seekable.
  86100. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  86101. * pointer must not be \c NULL.
  86102. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  86103. * pointer may be \c NULL if the callback is not
  86104. * desired.
  86105. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  86106. * pointer must not be \c NULL.
  86107. * \param client_data This value will be supplied to callbacks in their
  86108. * \a client_data argument.
  86109. * \assert
  86110. * \code decoder != NULL \endcode
  86111. * \retval FLAC__StreamDecoderInitStatus
  86112. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  86113. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  86114. */
  86115. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  86116. FLAC__StreamDecoder *decoder,
  86117. const char *filename,
  86118. FLAC__StreamDecoderWriteCallback write_callback,
  86119. FLAC__StreamDecoderMetadataCallback metadata_callback,
  86120. FLAC__StreamDecoderErrorCallback error_callback,
  86121. void *client_data
  86122. );
  86123. /** Finish the decoding process.
  86124. * Flushes the decoding buffer, releases resources, resets the decoder
  86125. * settings to their defaults, and returns the decoder state to
  86126. * FLAC__STREAM_DECODER_UNINITIALIZED.
  86127. *
  86128. * In the event of a prematurely-terminated decode, it is not strictly
  86129. * necessary to call this immediately before FLAC__stream_decoder_delete()
  86130. * but it is good practice to match every FLAC__stream_decoder_init_*()
  86131. * with a FLAC__stream_decoder_finish().
  86132. *
  86133. * \param decoder An uninitialized decoder instance.
  86134. * \assert
  86135. * \code decoder != NULL \endcode
  86136. * \retval FLAC__bool
  86137. * \c false if MD5 checking is on AND a STREAMINFO block was available
  86138. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  86139. * signature does not match the one computed by the decoder; else
  86140. * \c true.
  86141. */
  86142. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  86143. /** Flush the stream input.
  86144. * The decoder's input buffer will be cleared and the state set to
  86145. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  86146. * off MD5 checking.
  86147. *
  86148. * \param decoder A decoder instance.
  86149. * \assert
  86150. * \code decoder != NULL \endcode
  86151. * \retval FLAC__bool
  86152. * \c true if successful, else \c false if a memory allocation
  86153. * error occurs (in which case the state will be set to
  86154. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  86155. */
  86156. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  86157. /** Reset the decoding process.
  86158. * The decoder's input buffer will be cleared and the state set to
  86159. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  86160. * FLAC__stream_decoder_finish() except that the settings are
  86161. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  86162. * before decoding again. MD5 checking will be restored to its original
  86163. * setting.
  86164. *
  86165. * If the decoder is seekable, or was initialized with
  86166. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  86167. * the decoder will also attempt to seek to the beginning of the file.
  86168. * If this rewind fails, this function will return \c false. It follows
  86169. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  86170. * \c stdin.
  86171. *
  86172. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  86173. * and is not seekable (i.e. no seek callback was provided or the seek
  86174. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  86175. * is the duty of the client to start feeding data from the beginning of
  86176. * the stream on the next FLAC__stream_decoder_process() or
  86177. * FLAC__stream_decoder_process_interleaved() call.
  86178. *
  86179. * \param decoder A decoder instance.
  86180. * \assert
  86181. * \code decoder != NULL \endcode
  86182. * \retval FLAC__bool
  86183. * \c true if successful, else \c false if a memory allocation occurs
  86184. * (in which case the state will be set to
  86185. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  86186. * occurs (the state will be unchanged).
  86187. */
  86188. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  86189. /** Decode one metadata block or audio frame.
  86190. * This version instructs the decoder to decode a either a single metadata
  86191. * block or a single frame and stop, unless the callbacks return a fatal
  86192. * error or the read callback returns
  86193. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86194. *
  86195. * As the decoder needs more input it will call the read callback.
  86196. * Depending on what was decoded, the metadata or write callback will be
  86197. * called with the decoded metadata block or audio frame.
  86198. *
  86199. * Unless there is a fatal read error or end of stream, this function
  86200. * will return once one whole frame is decoded. In other words, if the
  86201. * stream is not synchronized or points to a corrupt frame header, the
  86202. * decoder will continue to try and resync until it gets to a valid
  86203. * frame, then decode one frame, then return. If the decoder points to
  86204. * a frame whose frame CRC in the frame footer does not match the
  86205. * computed frame CRC, this function will issue a
  86206. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  86207. * error callback, and return, having decoded one complete, although
  86208. * corrupt, frame. (Such corrupted frames are sent as silence of the
  86209. * correct length to the write callback.)
  86210. *
  86211. * \param decoder An initialized decoder instance.
  86212. * \assert
  86213. * \code decoder != NULL \endcode
  86214. * \retval FLAC__bool
  86215. * \c false if any fatal read, write, or memory allocation error
  86216. * occurred (meaning decoding must stop), else \c true; for more
  86217. * information about the decoder, check the decoder state with
  86218. * FLAC__stream_decoder_get_state().
  86219. */
  86220. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  86221. /** Decode until the end of the metadata.
  86222. * This version instructs the decoder to decode from the current position
  86223. * and continue until all the metadata has been read, or until the
  86224. * callbacks return a fatal error or the read callback returns
  86225. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86226. *
  86227. * As the decoder needs more input it will call the read callback.
  86228. * As each metadata block is decoded, the metadata callback will be called
  86229. * with the decoded metadata.
  86230. *
  86231. * \param decoder An initialized decoder instance.
  86232. * \assert
  86233. * \code decoder != NULL \endcode
  86234. * \retval FLAC__bool
  86235. * \c false if any fatal read, write, or memory allocation error
  86236. * occurred (meaning decoding must stop), else \c true; for more
  86237. * information about the decoder, check the decoder state with
  86238. * FLAC__stream_decoder_get_state().
  86239. */
  86240. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  86241. /** Decode until the end of the stream.
  86242. * This version instructs the decoder to decode from the current position
  86243. * and continue until the end of stream (the read callback returns
  86244. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  86245. * callbacks return a fatal error.
  86246. *
  86247. * As the decoder needs more input it will call the read callback.
  86248. * As each metadata block and frame is decoded, the metadata or write
  86249. * callback will be called with the decoded metadata or frame.
  86250. *
  86251. * \param decoder An initialized decoder instance.
  86252. * \assert
  86253. * \code decoder != NULL \endcode
  86254. * \retval FLAC__bool
  86255. * \c false if any fatal read, write, or memory allocation error
  86256. * occurred (meaning decoding must stop), else \c true; for more
  86257. * information about the decoder, check the decoder state with
  86258. * FLAC__stream_decoder_get_state().
  86259. */
  86260. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  86261. /** Skip one audio frame.
  86262. * This version instructs the decoder to 'skip' a single frame and stop,
  86263. * unless the callbacks return a fatal error or the read callback returns
  86264. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  86265. *
  86266. * The decoding flow is the same as what occurs when
  86267. * FLAC__stream_decoder_process_single() is called to process an audio
  86268. * frame, except that this function does not decode the parsed data into
  86269. * PCM or call the write callback. The integrity of the frame is still
  86270. * checked the same way as in the other process functions.
  86271. *
  86272. * This function will return once one whole frame is skipped, in the
  86273. * same way that FLAC__stream_decoder_process_single() will return once
  86274. * one whole frame is decoded.
  86275. *
  86276. * This function can be used in more quickly determining FLAC frame
  86277. * boundaries when decoding of the actual data is not needed, for
  86278. * example when an application is separating a FLAC stream into frames
  86279. * for editing or storing in a container. To do this, the application
  86280. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  86281. * to the next frame, then use
  86282. * FLAC__stream_decoder_get_decode_position() to find the new frame
  86283. * boundary.
  86284. *
  86285. * This function should only be called when the stream has advanced
  86286. * past all the metadata, otherwise it will return \c false.
  86287. *
  86288. * \param decoder An initialized decoder instance not in a metadata
  86289. * state.
  86290. * \assert
  86291. * \code decoder != NULL \endcode
  86292. * \retval FLAC__bool
  86293. * \c false if any fatal read, write, or memory allocation error
  86294. * occurred (meaning decoding must stop), or if the decoder
  86295. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  86296. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  86297. * information about the decoder, check the decoder state with
  86298. * FLAC__stream_decoder_get_state().
  86299. */
  86300. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  86301. /** Flush the input and seek to an absolute sample.
  86302. * Decoding will resume at the given sample. Note that because of
  86303. * this, the next write callback may contain a partial block. The
  86304. * client must support seeking the input or this function will fail
  86305. * and return \c false. Furthermore, if the decoder state is
  86306. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  86307. * with FLAC__stream_decoder_flush() or reset with
  86308. * FLAC__stream_decoder_reset() before decoding can continue.
  86309. *
  86310. * \param decoder A decoder instance.
  86311. * \param sample The target sample number to seek to.
  86312. * \assert
  86313. * \code decoder != NULL \endcode
  86314. * \retval FLAC__bool
  86315. * \c true if successful, else \c false.
  86316. */
  86317. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  86318. /* \} */
  86319. #ifdef __cplusplus
  86320. }
  86321. #endif
  86322. #endif
  86323. /********* End of inlined file: stream_decoder.h *********/
  86324. /********* Start of inlined file: stream_encoder.h *********/
  86325. #ifndef FLAC__STREAM_ENCODER_H
  86326. #define FLAC__STREAM_ENCODER_H
  86327. #include <stdio.h> /* for FILE */
  86328. #ifdef __cplusplus
  86329. extern "C" {
  86330. #endif
  86331. /** \file include/FLAC/stream_encoder.h
  86332. *
  86333. * \brief
  86334. * This module contains the functions which implement the stream
  86335. * encoder.
  86336. *
  86337. * See the detailed documentation in the
  86338. * \link flac_stream_encoder stream encoder \endlink module.
  86339. */
  86340. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  86341. * \ingroup flac
  86342. *
  86343. * \brief
  86344. * This module describes the encoder layers provided by libFLAC.
  86345. *
  86346. * The stream encoder can be used to encode complete streams either to the
  86347. * client via callbacks, or directly to a file, depending on how it is
  86348. * initialized. When encoding via callbacks, the client provides a write
  86349. * callback which will be called whenever FLAC data is ready to be written.
  86350. * If the client also supplies a seek callback, the encoder will also
  86351. * automatically handle the writing back of metadata discovered while
  86352. * encoding, like stream info, seek points offsets, etc. When encoding to
  86353. * a file, the client needs only supply a filename or open \c FILE* and an
  86354. * optional progress callback for periodic notification of progress; the
  86355. * write and seek callbacks are supplied internally. For more info see the
  86356. * \link flac_stream_encoder stream encoder \endlink module.
  86357. */
  86358. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  86359. * \ingroup flac_encoder
  86360. *
  86361. * \brief
  86362. * This module contains the functions which implement the stream
  86363. * encoder.
  86364. *
  86365. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  86366. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  86367. *
  86368. * The basic usage of this encoder is as follows:
  86369. * - The program creates an instance of an encoder using
  86370. * FLAC__stream_encoder_new().
  86371. * - The program overrides the default settings using
  86372. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  86373. * functions should be called:
  86374. * - FLAC__stream_encoder_set_channels()
  86375. * - FLAC__stream_encoder_set_bits_per_sample()
  86376. * - FLAC__stream_encoder_set_sample_rate()
  86377. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  86378. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  86379. * - If the application wants to control the compression level or set its own
  86380. * metadata, then the following should also be called:
  86381. * - FLAC__stream_encoder_set_compression_level()
  86382. * - FLAC__stream_encoder_set_verify()
  86383. * - FLAC__stream_encoder_set_metadata()
  86384. * - The rest of the set functions should only be called if the client needs
  86385. * exact control over how the audio is compressed; thorough understanding
  86386. * of the FLAC format is necessary to achieve good results.
  86387. * - The program initializes the instance to validate the settings and
  86388. * prepare for encoding using
  86389. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  86390. * or FLAC__stream_encoder_init_file() for native FLAC
  86391. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  86392. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  86393. * - The program calls FLAC__stream_encoder_process() or
  86394. * FLAC__stream_encoder_process_interleaved() to encode data, which
  86395. * subsequently calls the callbacks when there is encoder data ready
  86396. * to be written.
  86397. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  86398. * which causes the encoder to encode any data still in its input pipe,
  86399. * update the metadata with the final encoding statistics if output
  86400. * seeking is possible, and finally reset the encoder to the
  86401. * uninitialized state.
  86402. * - The instance may be used again or deleted with
  86403. * FLAC__stream_encoder_delete().
  86404. *
  86405. * In more detail, the stream encoder functions similarly to the
  86406. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  86407. * callbacks and more options. Typically the client will create a new
  86408. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  86409. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  86410. * calling one of the FLAC__stream_encoder_init_*() functions.
  86411. *
  86412. * Unlike the decoders, the stream encoder has many options that can
  86413. * affect the speed and compression ratio. When setting these parameters
  86414. * you should have some basic knowledge of the format (see the
  86415. * <A HREF="../documentation.html#format">user-level documentation</A>
  86416. * or the <A HREF="../format.html">formal description</A>). The
  86417. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  86418. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  86419. * functions will do this, so make sure to pay attention to the state
  86420. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  86421. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  86422. * before FLAC__stream_encoder_init_*() will take on the defaults from
  86423. * the constructor.
  86424. *
  86425. * There are three initialization functions for native FLAC, one for
  86426. * setting up the encoder to encode FLAC data to the client via
  86427. * callbacks, and two for encoding directly to a file.
  86428. *
  86429. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  86430. * You must also supply a write callback which will be called anytime
  86431. * there is raw encoded data to write. If the client can seek the output
  86432. * it is best to also supply seek and tell callbacks, as this allows the
  86433. * encoder to go back after encoding is finished to write back
  86434. * information that was collected while encoding, like seek point offsets,
  86435. * frame sizes, etc.
  86436. *
  86437. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  86438. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  86439. * filename or open \c FILE*; the encoder will handle all the callbacks
  86440. * internally. You may also supply a progress callback for periodic
  86441. * notification of the encoding progress.
  86442. *
  86443. * There are three similarly-named init functions for encoding to Ogg
  86444. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  86445. * library has been built with Ogg support.
  86446. *
  86447. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  86448. * call the write callback several times, once with the \c fLaC signature,
  86449. * and once for each encoded metadata block. Note that for Ogg FLAC
  86450. * encoding you will usually get at least twice the number of callbacks than
  86451. * with native FLAC, one for the Ogg page header and one for the page body.
  86452. *
  86453. * After initializing the instance, the client may feed audio data to the
  86454. * encoder in one of two ways:
  86455. *
  86456. * - Channel separate, through FLAC__stream_encoder_process() - The client
  86457. * will pass an array of pointers to buffers, one for each channel, to
  86458. * the encoder, each of the same length. The samples need not be
  86459. * block-aligned, but each channel should have the same number of samples.
  86460. * - Channel interleaved, through
  86461. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  86462. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  86463. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86464. * Again, the samples need not be block-aligned but they must be
  86465. * sample-aligned, i.e. the first value should be channel0_sample0 and
  86466. * the last value channelN_sampleM.
  86467. *
  86468. * Note that for either process call, each sample in the buffers should be a
  86469. * signed integer, right-justified to the resolution set by
  86470. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  86471. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  86472. *
  86473. * When the client is finished encoding data, it calls
  86474. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  86475. * data still in its input pipe, and call the metadata callback with the
  86476. * final encoding statistics. Then the instance may be deleted with
  86477. * FLAC__stream_encoder_delete() or initialized again to encode another
  86478. * stream.
  86479. *
  86480. * For programs that write their own metadata, but that do not know the
  86481. * actual metadata until after encoding, it is advantageous to instruct
  86482. * the encoder to write a PADDING block of the correct size, so that
  86483. * instead of rewriting the whole stream after encoding, the program can
  86484. * just overwrite the PADDING block. If only the maximum size of the
  86485. * metadata is known, the program can write a slightly larger padding
  86486. * block, then split it after encoding.
  86487. *
  86488. * Make sure you understand how lengths are calculated. All FLAC metadata
  86489. * blocks have a 4 byte header which contains the type and length. This
  86490. * length does not include the 4 bytes of the header. See the format page
  86491. * for the specification of metadata blocks and their lengths.
  86492. *
  86493. * \note
  86494. * If you are writing the FLAC data to a file via callbacks, make sure it
  86495. * is open for update (e.g. mode "w+" for stdio streams). This is because
  86496. * after the first encoding pass, the encoder will try to seek back to the
  86497. * beginning of the stream, to the STREAMINFO block, to write some data
  86498. * there. (If using FLAC__stream_encoder_init*_file() or
  86499. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  86500. *
  86501. * \note
  86502. * The "set" functions may only be called when the encoder is in the
  86503. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  86504. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  86505. * before FLAC__stream_encoder_init_*(). If this is the case they will
  86506. * return \c true, otherwise \c false.
  86507. *
  86508. * \note
  86509. * FLAC__stream_encoder_finish() resets all settings to the constructor
  86510. * defaults.
  86511. *
  86512. * \{
  86513. */
  86514. /** State values for a FLAC__StreamEncoder.
  86515. *
  86516. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  86517. *
  86518. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  86519. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  86520. * must be deleted with FLAC__stream_encoder_delete().
  86521. */
  86522. typedef enum {
  86523. FLAC__STREAM_ENCODER_OK = 0,
  86524. /**< The encoder is in the normal OK state and samples can be processed. */
  86525. FLAC__STREAM_ENCODER_UNINITIALIZED,
  86526. /**< The encoder is in the uninitialized state; one of the
  86527. * FLAC__stream_encoder_init_*() functions must be called before samples
  86528. * can be processed.
  86529. */
  86530. FLAC__STREAM_ENCODER_OGG_ERROR,
  86531. /**< An error occurred in the underlying Ogg layer. */
  86532. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  86533. /**< An error occurred in the underlying verify stream decoder;
  86534. * check FLAC__stream_encoder_get_verify_decoder_state().
  86535. */
  86536. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  86537. /**< The verify decoder detected a mismatch between the original
  86538. * audio signal and the decoded audio signal.
  86539. */
  86540. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  86541. /**< One of the callbacks returned a fatal error. */
  86542. FLAC__STREAM_ENCODER_IO_ERROR,
  86543. /**< An I/O error occurred while opening/reading/writing a file.
  86544. * Check \c errno.
  86545. */
  86546. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  86547. /**< An error occurred while writing the stream; usually, the
  86548. * write_callback returned an error.
  86549. */
  86550. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  86551. /**< Memory allocation failed. */
  86552. } FLAC__StreamEncoderState;
  86553. /** Maps a FLAC__StreamEncoderState to a C string.
  86554. *
  86555. * Using a FLAC__StreamEncoderState as the index to this array
  86556. * will give the string equivalent. The contents should not be modified.
  86557. */
  86558. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  86559. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  86560. */
  86561. typedef enum {
  86562. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  86563. /**< Initialization was successful. */
  86564. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  86565. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  86566. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  86567. /**< The library was not compiled with support for the given container
  86568. * format.
  86569. */
  86570. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  86571. /**< A required callback was not supplied. */
  86572. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  86573. /**< The encoder has an invalid setting for number of channels. */
  86574. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  86575. /**< The encoder has an invalid setting for bits-per-sample.
  86576. * FLAC supports 4-32 bps but the reference encoder currently supports
  86577. * only up to 24 bps.
  86578. */
  86579. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  86580. /**< The encoder has an invalid setting for the input sample rate. */
  86581. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  86582. /**< The encoder has an invalid setting for the block size. */
  86583. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  86584. /**< The encoder has an invalid setting for the maximum LPC order. */
  86585. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  86586. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  86587. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  86588. /**< The specified block size is less than the maximum LPC order. */
  86589. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  86590. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  86591. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  86592. /**< The metadata input to the encoder is invalid, in one of the following ways:
  86593. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  86594. * - One of the metadata blocks contains an undefined type
  86595. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  86596. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  86597. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  86598. */
  86599. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  86600. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  86601. * already initialized, usually because
  86602. * FLAC__stream_encoder_finish() was not called.
  86603. */
  86604. } FLAC__StreamEncoderInitStatus;
  86605. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  86606. *
  86607. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  86608. * will give the string equivalent. The contents should not be modified.
  86609. */
  86610. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  86611. /** Return values for the FLAC__StreamEncoder read callback.
  86612. */
  86613. typedef enum {
  86614. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  86615. /**< The read was OK and decoding can continue. */
  86616. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  86617. /**< The read was attempted at the end of the stream. */
  86618. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  86619. /**< An unrecoverable error occurred. */
  86620. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  86621. /**< Client does not support reading back from the output. */
  86622. } FLAC__StreamEncoderReadStatus;
  86623. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  86624. *
  86625. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  86626. * will give the string equivalent. The contents should not be modified.
  86627. */
  86628. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  86629. /** Return values for the FLAC__StreamEncoder write callback.
  86630. */
  86631. typedef enum {
  86632. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  86633. /**< The write was OK and encoding can continue. */
  86634. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  86635. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  86636. } FLAC__StreamEncoderWriteStatus;
  86637. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  86638. *
  86639. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  86640. * will give the string equivalent. The contents should not be modified.
  86641. */
  86642. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  86643. /** Return values for the FLAC__StreamEncoder seek callback.
  86644. */
  86645. typedef enum {
  86646. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  86647. /**< The seek was OK and encoding can continue. */
  86648. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  86649. /**< An unrecoverable error occurred. */
  86650. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86651. /**< Client does not support seeking. */
  86652. } FLAC__StreamEncoderSeekStatus;
  86653. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  86654. *
  86655. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  86656. * will give the string equivalent. The contents should not be modified.
  86657. */
  86658. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  86659. /** Return values for the FLAC__StreamEncoder tell callback.
  86660. */
  86661. typedef enum {
  86662. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  86663. /**< The tell was OK and encoding can continue. */
  86664. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  86665. /**< An unrecoverable error occurred. */
  86666. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86667. /**< Client does not support seeking. */
  86668. } FLAC__StreamEncoderTellStatus;
  86669. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  86670. *
  86671. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  86672. * will give the string equivalent. The contents should not be modified.
  86673. */
  86674. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  86675. /***********************************************************************
  86676. *
  86677. * class FLAC__StreamEncoder
  86678. *
  86679. ***********************************************************************/
  86680. struct FLAC__StreamEncoderProtected;
  86681. struct FLAC__StreamEncoderPrivate;
  86682. /** The opaque structure definition for the stream encoder type.
  86683. * See the \link flac_stream_encoder stream encoder module \endlink
  86684. * for a detailed description.
  86685. */
  86686. typedef struct {
  86687. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  86688. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  86689. } FLAC__StreamEncoder;
  86690. /** Signature for the read callback.
  86691. *
  86692. * A function pointer matching this signature must be passed to
  86693. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  86694. * The supplied function will be called when the encoder needs to read back
  86695. * encoded data. This happens during the metadata callback, when the encoder
  86696. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  86697. * while encoding. The address of the buffer to be filled is supplied, along
  86698. * with the number of bytes the buffer can hold. The callback may choose to
  86699. * supply less data and modify the byte count but must be careful not to
  86700. * overflow the buffer. The callback then returns a status code chosen from
  86701. * FLAC__StreamEncoderReadStatus.
  86702. *
  86703. * Here is an example of a read callback for stdio streams:
  86704. * \code
  86705. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  86706. * {
  86707. * FILE *file = ((MyClientData*)client_data)->file;
  86708. * if(*bytes > 0) {
  86709. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  86710. * if(ferror(file))
  86711. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86712. * else if(*bytes == 0)
  86713. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  86714. * else
  86715. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  86716. * }
  86717. * else
  86718. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  86719. * }
  86720. * \endcode
  86721. *
  86722. * \note In general, FLAC__StreamEncoder functions which change the
  86723. * state should not be called on the \a encoder while in the callback.
  86724. *
  86725. * \param encoder The encoder instance calling the callback.
  86726. * \param buffer A pointer to a location for the callee to store
  86727. * data to be encoded.
  86728. * \param bytes A pointer to the size of the buffer. On entry
  86729. * to the callback, it contains the maximum number
  86730. * of bytes that may be stored in \a buffer. The
  86731. * callee must set it to the actual number of bytes
  86732. * stored (0 in case of error or end-of-stream) before
  86733. * returning.
  86734. * \param client_data The callee's client data set through
  86735. * FLAC__stream_encoder_set_client_data().
  86736. * \retval FLAC__StreamEncoderReadStatus
  86737. * The callee's return status.
  86738. */
  86739. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  86740. /** Signature for the write callback.
  86741. *
  86742. * A function pointer matching this signature must be passed to
  86743. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86744. * by the encoder anytime there is raw encoded data ready to write. It may
  86745. * include metadata mixed with encoded audio frames and the data is not
  86746. * guaranteed to be aligned on frame or metadata block boundaries.
  86747. *
  86748. * The only duty of the callback is to write out the \a bytes worth of data
  86749. * in \a buffer to the current position in the output stream. The arguments
  86750. * \a samples and \a current_frame are purely informational. If \a samples
  86751. * is greater than \c 0, then \a current_frame will hold the current frame
  86752. * number that is being written; otherwise it indicates that the write
  86753. * callback is being called to write metadata.
  86754. *
  86755. * \note
  86756. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  86757. * write callback will be called twice when writing each audio
  86758. * frame; once for the page header, and once for the page body.
  86759. * When writing the page header, the \a samples argument to the
  86760. * write callback will be \c 0.
  86761. *
  86762. * \note In general, FLAC__StreamEncoder functions which change the
  86763. * state should not be called on the \a encoder while in the callback.
  86764. *
  86765. * \param encoder The encoder instance calling the callback.
  86766. * \param buffer An array of encoded data of length \a bytes.
  86767. * \param bytes The byte length of \a buffer.
  86768. * \param samples The number of samples encoded by \a buffer.
  86769. * \c 0 has a special meaning; see above.
  86770. * \param current_frame The number of the current frame being encoded.
  86771. * \param client_data The callee's client data set through
  86772. * FLAC__stream_encoder_init_*().
  86773. * \retval FLAC__StreamEncoderWriteStatus
  86774. * The callee's return status.
  86775. */
  86776. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  86777. /** Signature for the seek callback.
  86778. *
  86779. * A function pointer matching this signature may be passed to
  86780. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86781. * when the encoder needs to seek the output stream. The encoder will pass
  86782. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  86783. *
  86784. * Here is an example of a seek callback for stdio streams:
  86785. * \code
  86786. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  86787. * {
  86788. * FILE *file = ((MyClientData*)client_data)->file;
  86789. * if(file == stdin)
  86790. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  86791. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  86792. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  86793. * else
  86794. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  86795. * }
  86796. * \endcode
  86797. *
  86798. * \note In general, FLAC__StreamEncoder functions which change the
  86799. * state should not be called on the \a encoder while in the callback.
  86800. *
  86801. * \param encoder The encoder instance calling the callback.
  86802. * \param absolute_byte_offset The offset from the beginning of the stream
  86803. * to seek to.
  86804. * \param client_data The callee's client data set through
  86805. * FLAC__stream_encoder_init_*().
  86806. * \retval FLAC__StreamEncoderSeekStatus
  86807. * The callee's return status.
  86808. */
  86809. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  86810. /** Signature for the tell callback.
  86811. *
  86812. * A function pointer matching this signature may be passed to
  86813. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86814. * when the encoder needs to know the current position of the output stream.
  86815. *
  86816. * \warning
  86817. * The callback must return the true current byte offset of the output to
  86818. * which the encoder is writing. If you are buffering the output, make
  86819. * sure and take this into account. If you are writing directly to a
  86820. * FILE* from your write callback, ftell() is sufficient. If you are
  86821. * writing directly to a file descriptor from your write callback, you
  86822. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  86823. * these points to rewrite metadata after encoding.
  86824. *
  86825. * Here is an example of a tell callback for stdio streams:
  86826. * \code
  86827. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  86828. * {
  86829. * FILE *file = ((MyClientData*)client_data)->file;
  86830. * off_t pos;
  86831. * if(file == stdin)
  86832. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  86833. * else if((pos = ftello(file)) < 0)
  86834. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  86835. * else {
  86836. * *absolute_byte_offset = (FLAC__uint64)pos;
  86837. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  86838. * }
  86839. * }
  86840. * \endcode
  86841. *
  86842. * \note In general, FLAC__StreamEncoder functions which change the
  86843. * state should not be called on the \a encoder while in the callback.
  86844. *
  86845. * \param encoder The encoder instance calling the callback.
  86846. * \param absolute_byte_offset The address at which to store the current
  86847. * position of the output.
  86848. * \param client_data The callee's client data set through
  86849. * FLAC__stream_encoder_init_*().
  86850. * \retval FLAC__StreamEncoderTellStatus
  86851. * The callee's return status.
  86852. */
  86853. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  86854. /** Signature for the metadata callback.
  86855. *
  86856. * A function pointer matching this signature may be passed to
  86857. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  86858. * once at the end of encoding with the populated STREAMINFO structure. This
  86859. * is so the client can seek back to the beginning of the file and write the
  86860. * STREAMINFO block with the correct statistics after encoding (like
  86861. * minimum/maximum frame size and total samples).
  86862. *
  86863. * \note In general, FLAC__StreamEncoder functions which change the
  86864. * state should not be called on the \a encoder while in the callback.
  86865. *
  86866. * \param encoder The encoder instance calling the callback.
  86867. * \param metadata The final populated STREAMINFO block.
  86868. * \param client_data The callee's client data set through
  86869. * FLAC__stream_encoder_init_*().
  86870. */
  86871. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  86872. /** Signature for the progress callback.
  86873. *
  86874. * A function pointer matching this signature may be passed to
  86875. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  86876. * The supplied function will be called when the encoder has finished
  86877. * writing a frame. The \c total_frames_estimate argument to the
  86878. * callback will be based on the value from
  86879. * FLAC__stream_encoder_set_total_samples_estimate().
  86880. *
  86881. * \note In general, FLAC__StreamEncoder functions which change the
  86882. * state should not be called on the \a encoder while in the callback.
  86883. *
  86884. * \param encoder The encoder instance calling the callback.
  86885. * \param bytes_written Bytes written so far.
  86886. * \param samples_written Samples written so far.
  86887. * \param frames_written Frames written so far.
  86888. * \param total_frames_estimate The estimate of the total number of
  86889. * frames to be written.
  86890. * \param client_data The callee's client data set through
  86891. * FLAC__stream_encoder_init_*().
  86892. */
  86893. 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);
  86894. /***********************************************************************
  86895. *
  86896. * Class constructor/destructor
  86897. *
  86898. ***********************************************************************/
  86899. /** Create a new stream encoder instance. The instance is created with
  86900. * default settings; see the individual FLAC__stream_encoder_set_*()
  86901. * functions for each setting's default.
  86902. *
  86903. * \retval FLAC__StreamEncoder*
  86904. * \c NULL if there was an error allocating memory, else the new instance.
  86905. */
  86906. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  86907. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  86908. *
  86909. * \param encoder A pointer to an existing encoder.
  86910. * \assert
  86911. * \code encoder != NULL \endcode
  86912. */
  86913. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  86914. /***********************************************************************
  86915. *
  86916. * Public class method prototypes
  86917. *
  86918. ***********************************************************************/
  86919. /** Set the serial number for the FLAC stream to use in the Ogg container.
  86920. *
  86921. * \note
  86922. * This does not need to be set for native FLAC encoding.
  86923. *
  86924. * \note
  86925. * It is recommended to set a serial number explicitly as the default of '0'
  86926. * may collide with other streams.
  86927. *
  86928. * \default \c 0
  86929. * \param encoder An encoder instance to set.
  86930. * \param serial_number See above.
  86931. * \assert
  86932. * \code encoder != NULL \endcode
  86933. * \retval FLAC__bool
  86934. * \c false if the encoder is already initialized, else \c true.
  86935. */
  86936. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  86937. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  86938. * encoded output by feeding it through an internal decoder and comparing
  86939. * the original signal against the decoded signal. If a mismatch occurs,
  86940. * the process call will return \c false. Note that this will slow the
  86941. * encoding process by the extra time required for decoding and comparison.
  86942. *
  86943. * \default \c false
  86944. * \param encoder An encoder instance to set.
  86945. * \param value Flag value (see above).
  86946. * \assert
  86947. * \code encoder != NULL \endcode
  86948. * \retval FLAC__bool
  86949. * \c false if the encoder is already initialized, else \c true.
  86950. */
  86951. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86952. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  86953. * the encoder will comply with the Subset and will check the
  86954. * settings during FLAC__stream_encoder_init_*() to see if all settings
  86955. * comply. If \c false, the settings may take advantage of the full
  86956. * range that the format allows.
  86957. *
  86958. * Make sure you know what it entails before setting this to \c false.
  86959. *
  86960. * \default \c true
  86961. * \param encoder An encoder instance to set.
  86962. * \param value Flag value (see above).
  86963. * \assert
  86964. * \code encoder != NULL \endcode
  86965. * \retval FLAC__bool
  86966. * \c false if the encoder is already initialized, else \c true.
  86967. */
  86968. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86969. /** Set the number of channels to be encoded.
  86970. *
  86971. * \default \c 2
  86972. * \param encoder An encoder instance to set.
  86973. * \param value See above.
  86974. * \assert
  86975. * \code encoder != NULL \endcode
  86976. * \retval FLAC__bool
  86977. * \c false if the encoder is already initialized, else \c true.
  86978. */
  86979. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  86980. /** Set the sample resolution of the input to be encoded.
  86981. *
  86982. * \warning
  86983. * Do not feed the encoder data that is wider than the value you
  86984. * set here or you will generate an invalid stream.
  86985. *
  86986. * \default \c 16
  86987. * \param encoder An encoder instance to set.
  86988. * \param value See above.
  86989. * \assert
  86990. * \code encoder != NULL \endcode
  86991. * \retval FLAC__bool
  86992. * \c false if the encoder is already initialized, else \c true.
  86993. */
  86994. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  86995. /** Set the sample rate (in Hz) of the input to be encoded.
  86996. *
  86997. * \default \c 44100
  86998. * \param encoder An encoder instance to set.
  86999. * \param value See above.
  87000. * \assert
  87001. * \code encoder != NULL \endcode
  87002. * \retval FLAC__bool
  87003. * \c false if the encoder is already initialized, else \c true.
  87004. */
  87005. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  87006. /** Set the compression level
  87007. *
  87008. * The compression level is roughly proportional to the amount of effort
  87009. * the encoder expends to compress the file. A higher level usually
  87010. * means more computation but higher compression. The default level is
  87011. * suitable for most applications.
  87012. *
  87013. * Currently the levels range from \c 0 (fastest, least compression) to
  87014. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  87015. * treated as \c 8.
  87016. *
  87017. * This function automatically calls the following other \c _set_
  87018. * functions with appropriate values, so the client does not need to
  87019. * unless it specifically wants to override them:
  87020. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  87021. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  87022. * - FLAC__stream_encoder_set_apodization()
  87023. * - FLAC__stream_encoder_set_max_lpc_order()
  87024. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  87025. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  87026. * - FLAC__stream_encoder_set_do_escape_coding()
  87027. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  87028. * - FLAC__stream_encoder_set_min_residual_partition_order()
  87029. * - FLAC__stream_encoder_set_max_residual_partition_order()
  87030. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  87031. *
  87032. * The actual values set for each level are:
  87033. * <table>
  87034. * <tr>
  87035. * <td><b>level</b><td>
  87036. * <td>do mid-side stereo<td>
  87037. * <td>loose mid-side stereo<td>
  87038. * <td>apodization<td>
  87039. * <td>max lpc order<td>
  87040. * <td>qlp coeff precision<td>
  87041. * <td>qlp coeff prec search<td>
  87042. * <td>escape coding<td>
  87043. * <td>exhaustive model search<td>
  87044. * <td>min residual partition order<td>
  87045. * <td>max residual partition order<td>
  87046. * <td>rice parameter search dist<td>
  87047. * </tr>
  87048. * <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>
  87049. * <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>
  87050. * <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>
  87051. * <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>
  87052. * <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>
  87053. * <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>
  87054. * <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>
  87055. * <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>
  87056. * <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>
  87057. * </table>
  87058. *
  87059. * \default \c 5
  87060. * \param encoder An encoder instance to set.
  87061. * \param value See above.
  87062. * \assert
  87063. * \code encoder != NULL \endcode
  87064. * \retval FLAC__bool
  87065. * \c false if the encoder is already initialized, else \c true.
  87066. */
  87067. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  87068. /** Set the blocksize to use while encoding.
  87069. *
  87070. * The number of samples to use per frame. Use \c 0 to let the encoder
  87071. * estimate a blocksize; this is usually best.
  87072. *
  87073. * \default \c 0
  87074. * \param encoder An encoder instance to set.
  87075. * \param value See above.
  87076. * \assert
  87077. * \code encoder != NULL \endcode
  87078. * \retval FLAC__bool
  87079. * \c false if the encoder is already initialized, else \c true.
  87080. */
  87081. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  87082. /** Set to \c true to enable mid-side encoding on stereo input. The
  87083. * number of channels must be 2 for this to have any effect. Set to
  87084. * \c false to use only independent channel coding.
  87085. *
  87086. * \default \c false
  87087. * \param encoder An encoder instance to set.
  87088. * \param value Flag value (see above).
  87089. * \assert
  87090. * \code encoder != NULL \endcode
  87091. * \retval FLAC__bool
  87092. * \c false if the encoder is already initialized, else \c true.
  87093. */
  87094. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87095. /** Set to \c true to enable adaptive switching between mid-side and
  87096. * left-right encoding on stereo input. Set to \c false to use
  87097. * exhaustive searching. Setting this to \c true requires
  87098. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  87099. * \c true in order to have any effect.
  87100. *
  87101. * \default \c false
  87102. * \param encoder An encoder instance to set.
  87103. * \param value Flag value (see above).
  87104. * \assert
  87105. * \code encoder != NULL \endcode
  87106. * \retval FLAC__bool
  87107. * \c false if the encoder is already initialized, else \c true.
  87108. */
  87109. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87110. /** Sets the apodization function(s) the encoder will use when windowing
  87111. * audio data for LPC analysis.
  87112. *
  87113. * The \a specification is a plain ASCII string which specifies exactly
  87114. * which functions to use. There may be more than one (up to 32),
  87115. * separated by \c ';' characters. Some functions take one or more
  87116. * comma-separated arguments in parentheses.
  87117. *
  87118. * The available functions are \c bartlett, \c bartlett_hann,
  87119. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  87120. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  87121. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  87122. *
  87123. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  87124. * (0<STDDEV<=0.5).
  87125. *
  87126. * For \c tukey(P), P specifies the fraction of the window that is
  87127. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  87128. * corresponds to \c hann.
  87129. *
  87130. * Example specifications are \c "blackman" or
  87131. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  87132. *
  87133. * Any function that is specified erroneously is silently dropped. Up
  87134. * to 32 functions are kept, the rest are dropped. If the specification
  87135. * is empty the encoder defaults to \c "tukey(0.5)".
  87136. *
  87137. * When more than one function is specified, then for every subframe the
  87138. * encoder will try each of them separately and choose the window that
  87139. * results in the smallest compressed subframe.
  87140. *
  87141. * Note that each function specified causes the encoder to occupy a
  87142. * floating point array in which to store the window.
  87143. *
  87144. * \default \c "tukey(0.5)"
  87145. * \param encoder An encoder instance to set.
  87146. * \param specification See above.
  87147. * \assert
  87148. * \code encoder != NULL \endcode
  87149. * \code specification != NULL \endcode
  87150. * \retval FLAC__bool
  87151. * \c false if the encoder is already initialized, else \c true.
  87152. */
  87153. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  87154. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  87155. *
  87156. * \default \c 0
  87157. * \param encoder An encoder instance to set.
  87158. * \param value See above.
  87159. * \assert
  87160. * \code encoder != NULL \endcode
  87161. * \retval FLAC__bool
  87162. * \c false if the encoder is already initialized, else \c true.
  87163. */
  87164. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  87165. /** Set the precision, in bits, of the quantized linear predictor
  87166. * coefficients, or \c 0 to let the encoder select it based on the
  87167. * blocksize.
  87168. *
  87169. * \note
  87170. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  87171. * be less than 32.
  87172. *
  87173. * \default \c 0
  87174. * \param encoder An encoder instance to set.
  87175. * \param value See above.
  87176. * \assert
  87177. * \code encoder != NULL \endcode
  87178. * \retval FLAC__bool
  87179. * \c false if the encoder is already initialized, else \c true.
  87180. */
  87181. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  87182. /** Set to \c false to use only the specified quantized linear predictor
  87183. * coefficient precision, or \c true to search neighboring precision
  87184. * values and use the best one.
  87185. *
  87186. * \default \c false
  87187. * \param encoder An encoder instance to set.
  87188. * \param value See above.
  87189. * \assert
  87190. * \code encoder != NULL \endcode
  87191. * \retval FLAC__bool
  87192. * \c false if the encoder is already initialized, else \c true.
  87193. */
  87194. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87195. /** Deprecated. Setting this value has no effect.
  87196. *
  87197. * \default \c false
  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_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87206. /** Set to \c false to let the encoder estimate the best model order
  87207. * based on the residual signal energy, or \c true to force the
  87208. * encoder to evaluate all order models and select the best.
  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_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  87219. /** Set the minimum partition order to search when coding the residual.
  87220. * This is used in tandem with
  87221. * FLAC__stream_encoder_set_max_residual_partition_order().
  87222. *
  87223. * The partition order determines the context size in the residual.
  87224. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87225. *
  87226. * Set both min and max values to \c 0 to force a single context,
  87227. * whose Rice parameter is based on the residual signal variance.
  87228. * Otherwise, set a min and max order, and the encoder will search
  87229. * all orders, using the mean of each context for its Rice parameter,
  87230. * and use the best.
  87231. *
  87232. * \default \c 0
  87233. * \param encoder An encoder instance to set.
  87234. * \param value See above.
  87235. * \assert
  87236. * \code encoder != NULL \endcode
  87237. * \retval FLAC__bool
  87238. * \c false if the encoder is already initialized, else \c true.
  87239. */
  87240. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87241. /** Set the maximum partition order to search when coding the residual.
  87242. * This is used in tandem with
  87243. * FLAC__stream_encoder_set_min_residual_partition_order().
  87244. *
  87245. * The partition order determines the context size in the residual.
  87246. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  87247. *
  87248. * Set both min and max values to \c 0 to force a single context,
  87249. * whose Rice parameter is based on the residual signal variance.
  87250. * Otherwise, set a min and max order, and the encoder will search
  87251. * all orders, using the mean of each context for its Rice parameter,
  87252. * and use the best.
  87253. *
  87254. * \default \c 0
  87255. * \param encoder An encoder instance to set.
  87256. * \param value See above.
  87257. * \assert
  87258. * \code encoder != NULL \endcode
  87259. * \retval FLAC__bool
  87260. * \c false if the encoder is already initialized, else \c true.
  87261. */
  87262. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  87263. /** Deprecated. Setting this value has no effect.
  87264. *
  87265. * \default \c 0
  87266. * \param encoder An encoder instance to set.
  87267. * \param value See above.
  87268. * \assert
  87269. * \code encoder != NULL \endcode
  87270. * \retval FLAC__bool
  87271. * \c false if the encoder is already initialized, else \c true.
  87272. */
  87273. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  87274. /** Set an estimate of the total samples that will be encoded.
  87275. * This is merely an estimate and may be set to \c 0 if unknown.
  87276. * This value will be written to the STREAMINFO block before encoding,
  87277. * and can remove the need for the caller to rewrite the value later
  87278. * if the value is known before encoding.
  87279. *
  87280. * \default \c 0
  87281. * \param encoder An encoder instance to set.
  87282. * \param value See above.
  87283. * \assert
  87284. * \code encoder != NULL \endcode
  87285. * \retval FLAC__bool
  87286. * \c false if the encoder is already initialized, else \c true.
  87287. */
  87288. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  87289. /** Set the metadata blocks to be emitted to the stream before encoding.
  87290. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  87291. * array of pointers to metadata blocks. The array is non-const since
  87292. * the encoder may need to change the \a is_last flag inside them, and
  87293. * in some cases update seek point offsets. Otherwise, the encoder will
  87294. * not modify or free the blocks. It is up to the caller to free the
  87295. * metadata blocks after encoding finishes.
  87296. *
  87297. * \note
  87298. * The encoder stores only copies of the pointers in the \a metadata array;
  87299. * the metadata blocks themselves must survive at least until after
  87300. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  87301. *
  87302. * \note
  87303. * The STREAMINFO block is always written and no STREAMINFO block may
  87304. * occur in the supplied array.
  87305. *
  87306. * \note
  87307. * By default the encoder does not create a SEEKTABLE. If one is supplied
  87308. * in the \a metadata array, but the client has specified that it does not
  87309. * support seeking, then the SEEKTABLE will be written verbatim. However
  87310. * by itself this is not very useful as the client will not know the stream
  87311. * offsets for the seekpoints ahead of time. In order to get a proper
  87312. * seektable the client must support seeking. See next note.
  87313. *
  87314. * \note
  87315. * SEEKTABLE blocks are handled specially. Since you will not know
  87316. * the values for the seek point stream offsets, you should pass in
  87317. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  87318. * required sample numbers (or placeholder points), with \c 0 for the
  87319. * \a frame_samples and \a stream_offset fields for each point. If the
  87320. * client has specified that it supports seeking by providing a seek
  87321. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  87322. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  87323. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  87324. * then while it is encoding the encoder will fill the stream offsets in
  87325. * for you and when encoding is finished, it will seek back and write the
  87326. * real values into the SEEKTABLE block in the stream. There are helper
  87327. * routines for manipulating seektable template blocks; see metadata.h:
  87328. * FLAC__metadata_object_seektable_template_*(). If the client does
  87329. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  87330. * will slow down or remove the ability to seek in the FLAC stream.
  87331. *
  87332. * \note
  87333. * The encoder instance \b will modify the first \c SEEKTABLE block
  87334. * as it transforms the template to a valid seektable while encoding,
  87335. * but it is still up to the caller to free all metadata blocks after
  87336. * encoding.
  87337. *
  87338. * \note
  87339. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  87340. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  87341. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  87342. * will simply write it's own into the stream. If no VORBIS_COMMENT
  87343. * block is present in the \a metadata array, libFLAC will write an
  87344. * empty one, containing only the vendor string.
  87345. *
  87346. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  87347. * the second metadata block of the stream. The encoder already supplies
  87348. * the STREAMINFO block automatically. If \a metadata does not contain a
  87349. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  87350. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  87351. * first, the init function will reorder \a metadata by moving the
  87352. * VORBIS_COMMENT block to the front; the relative ordering of the other
  87353. * blocks will remain as they were.
  87354. *
  87355. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  87356. * stream to \c 65535. If \a num_blocks exceeds this the function will
  87357. * return \c false.
  87358. *
  87359. * \default \c NULL, 0
  87360. * \param encoder An encoder instance to set.
  87361. * \param metadata See above.
  87362. * \param num_blocks See above.
  87363. * \assert
  87364. * \code encoder != NULL \endcode
  87365. * \retval FLAC__bool
  87366. * \c false if the encoder is already initialized, else \c true.
  87367. * \c false if the encoder is already initialized, or if
  87368. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  87369. */
  87370. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  87371. /** Get the current encoder state.
  87372. *
  87373. * \param encoder An encoder instance to query.
  87374. * \assert
  87375. * \code encoder != NULL \endcode
  87376. * \retval FLAC__StreamEncoderState
  87377. * The current encoder state.
  87378. */
  87379. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  87380. /** Get the state of the verify stream decoder.
  87381. * Useful when the stream encoder state is
  87382. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  87383. *
  87384. * \param encoder An encoder instance to query.
  87385. * \assert
  87386. * \code encoder != NULL \endcode
  87387. * \retval FLAC__StreamDecoderState
  87388. * The verify stream decoder state.
  87389. */
  87390. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  87391. /** Get the current encoder state as a C string.
  87392. * This version automatically resolves
  87393. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  87394. * verify decoder's state.
  87395. *
  87396. * \param encoder A encoder instance to query.
  87397. * \assert
  87398. * \code encoder != NULL \endcode
  87399. * \retval const char *
  87400. * The encoder state as a C string. Do not modify the contents.
  87401. */
  87402. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  87403. /** Get relevant values about the nature of a verify decoder error.
  87404. * Useful when the stream encoder state is
  87405. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  87406. * be addresses in which the stats will be returned, or NULL if value
  87407. * is not desired.
  87408. *
  87409. * \param encoder An encoder instance to query.
  87410. * \param absolute_sample The absolute sample number of the mismatch.
  87411. * \param frame_number The number of the frame in which the mismatch occurred.
  87412. * \param channel The channel in which the mismatch occurred.
  87413. * \param sample The number of the sample (relative to the frame) in
  87414. * which the mismatch occurred.
  87415. * \param expected The expected value for the sample in question.
  87416. * \param got The actual value returned by the decoder.
  87417. * \assert
  87418. * \code encoder != NULL \endcode
  87419. */
  87420. 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);
  87421. /** Get the "verify" flag.
  87422. *
  87423. * \param encoder An encoder instance to query.
  87424. * \assert
  87425. * \code encoder != NULL \endcode
  87426. * \retval FLAC__bool
  87427. * See FLAC__stream_encoder_set_verify().
  87428. */
  87429. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  87430. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  87431. *
  87432. * \param encoder An encoder instance to query.
  87433. * \assert
  87434. * \code encoder != NULL \endcode
  87435. * \retval FLAC__bool
  87436. * See FLAC__stream_encoder_set_streamable_subset().
  87437. */
  87438. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  87439. /** Get the number of input channels being processed.
  87440. *
  87441. * \param encoder An encoder instance to query.
  87442. * \assert
  87443. * \code encoder != NULL \endcode
  87444. * \retval unsigned
  87445. * See FLAC__stream_encoder_set_channels().
  87446. */
  87447. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  87448. /** Get the input sample resolution setting.
  87449. *
  87450. * \param encoder An encoder instance to query.
  87451. * \assert
  87452. * \code encoder != NULL \endcode
  87453. * \retval unsigned
  87454. * See FLAC__stream_encoder_set_bits_per_sample().
  87455. */
  87456. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  87457. /** Get the input sample rate setting.
  87458. *
  87459. * \param encoder An encoder instance to query.
  87460. * \assert
  87461. * \code encoder != NULL \endcode
  87462. * \retval unsigned
  87463. * See FLAC__stream_encoder_set_sample_rate().
  87464. */
  87465. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  87466. /** Get the blocksize setting.
  87467. *
  87468. * \param encoder An encoder instance to query.
  87469. * \assert
  87470. * \code encoder != NULL \endcode
  87471. * \retval unsigned
  87472. * See FLAC__stream_encoder_set_blocksize().
  87473. */
  87474. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  87475. /** Get the "mid/side stereo coding" flag.
  87476. *
  87477. * \param encoder An encoder instance to query.
  87478. * \assert
  87479. * \code encoder != NULL \endcode
  87480. * \retval FLAC__bool
  87481. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  87482. */
  87483. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87484. /** Get the "adaptive mid/side switching" flag.
  87485. *
  87486. * \param encoder An encoder instance to query.
  87487. * \assert
  87488. * \code encoder != NULL \endcode
  87489. * \retval FLAC__bool
  87490. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  87491. */
  87492. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  87493. /** Get the maximum LPC order setting.
  87494. *
  87495. * \param encoder An encoder instance to query.
  87496. * \assert
  87497. * \code encoder != NULL \endcode
  87498. * \retval unsigned
  87499. * See FLAC__stream_encoder_set_max_lpc_order().
  87500. */
  87501. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  87502. /** Get the quantized linear predictor coefficient precision setting.
  87503. *
  87504. * \param encoder An encoder instance to query.
  87505. * \assert
  87506. * \code encoder != NULL \endcode
  87507. * \retval unsigned
  87508. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  87509. */
  87510. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  87511. /** Get the qlp coefficient precision search flag.
  87512. *
  87513. * \param encoder An encoder instance to query.
  87514. * \assert
  87515. * \code encoder != NULL \endcode
  87516. * \retval FLAC__bool
  87517. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  87518. */
  87519. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  87520. /** Get the "escape coding" flag.
  87521. *
  87522. * \param encoder An encoder instance to query.
  87523. * \assert
  87524. * \code encoder != NULL \endcode
  87525. * \retval FLAC__bool
  87526. * See FLAC__stream_encoder_set_do_escape_coding().
  87527. */
  87528. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  87529. /** Get the exhaustive model search flag.
  87530. *
  87531. * \param encoder An encoder instance to query.
  87532. * \assert
  87533. * \code encoder != NULL \endcode
  87534. * \retval FLAC__bool
  87535. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  87536. */
  87537. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  87538. /** Get the minimum residual partition order setting.
  87539. *
  87540. * \param encoder An encoder instance to query.
  87541. * \assert
  87542. * \code encoder != NULL \endcode
  87543. * \retval unsigned
  87544. * See FLAC__stream_encoder_set_min_residual_partition_order().
  87545. */
  87546. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87547. /** Get maximum residual partition order setting.
  87548. *
  87549. * \param encoder An encoder instance to query.
  87550. * \assert
  87551. * \code encoder != NULL \endcode
  87552. * \retval unsigned
  87553. * See FLAC__stream_encoder_set_max_residual_partition_order().
  87554. */
  87555. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  87556. /** Get the Rice parameter search distance setting.
  87557. *
  87558. * \param encoder An encoder instance to query.
  87559. * \assert
  87560. * \code encoder != NULL \endcode
  87561. * \retval unsigned
  87562. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  87563. */
  87564. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  87565. /** Get the previously set estimate of the total samples to be encoded.
  87566. * The encoder merely mimics back the value given to
  87567. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  87568. * other way of knowing how many samples the client will encode.
  87569. *
  87570. * \param encoder An encoder instance to set.
  87571. * \assert
  87572. * \code encoder != NULL \endcode
  87573. * \retval FLAC__uint64
  87574. * See FLAC__stream_encoder_get_total_samples_estimate().
  87575. */
  87576. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  87577. /** Initialize the encoder instance to encode native FLAC streams.
  87578. *
  87579. * This flavor of initialization sets up the encoder to encode to a
  87580. * native FLAC stream. I/O is performed via callbacks to the client.
  87581. * For encoding to a plain file via filename or open \c FILE*,
  87582. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  87583. * provide a simpler interface.
  87584. *
  87585. * This function should be called after FLAC__stream_encoder_new() and
  87586. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87587. * or FLAC__stream_encoder_process_interleaved().
  87588. * initialization succeeded.
  87589. *
  87590. * The call to FLAC__stream_encoder_init_stream() currently will also
  87591. * immediately call the write callback several times, once with the \c fLaC
  87592. * signature, and once for each encoded metadata block.
  87593. *
  87594. * \param encoder An uninitialized encoder instance.
  87595. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87596. * pointer must not be \c NULL.
  87597. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87598. * pointer may be \c NULL if seeking is not
  87599. * supported. The encoder uses seeking to go back
  87600. * and write some some stream statistics to the
  87601. * STREAMINFO block; this is recommended but not
  87602. * necessary to create a valid FLAC stream. If
  87603. * \a seek_callback is not \c NULL then a
  87604. * \a tell_callback must also be supplied.
  87605. * Alternatively, a dummy seek callback that just
  87606. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87607. * may also be supplied, all though this is slightly
  87608. * less efficient for the encoder.
  87609. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87610. * pointer may be \c NULL if seeking is not
  87611. * supported. If \a seek_callback is \c NULL then
  87612. * this argument will be ignored. If
  87613. * \a seek_callback is not \c NULL then a
  87614. * \a tell_callback must also be supplied.
  87615. * Alternatively, a dummy tell callback that just
  87616. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87617. * may also be supplied, all though this is slightly
  87618. * less efficient for the encoder.
  87619. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87620. * pointer may be \c NULL if the callback is not
  87621. * desired. If the client provides a seek callback,
  87622. * this function is not necessary as the encoder
  87623. * will automatically seek back and update the
  87624. * STREAMINFO block. It may also be \c NULL if the
  87625. * client does not support seeking, since it will
  87626. * have no way of going back to update the
  87627. * STREAMINFO. However the client can still supply
  87628. * a callback if it would like to know the details
  87629. * from the STREAMINFO.
  87630. * \param client_data This value will be supplied to callbacks in their
  87631. * \a client_data argument.
  87632. * \assert
  87633. * \code encoder != NULL \endcode
  87634. * \retval FLAC__StreamEncoderInitStatus
  87635. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87636. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87637. */
  87638. 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);
  87639. /** Initialize the encoder instance to encode Ogg FLAC streams.
  87640. *
  87641. * This flavor of initialization sets up the encoder to encode to a FLAC
  87642. * stream in an Ogg container. I/O is performed via callbacks to the
  87643. * client. For encoding to a plain file via filename or open \c FILE*,
  87644. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  87645. * provide a simpler interface.
  87646. *
  87647. * This function should be called after FLAC__stream_encoder_new() and
  87648. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87649. * or FLAC__stream_encoder_process_interleaved().
  87650. * initialization succeeded.
  87651. *
  87652. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  87653. * immediately call the write callback several times to write the metadata
  87654. * packets.
  87655. *
  87656. * \param encoder An uninitialized encoder instance.
  87657. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  87658. * pointer must not be \c NULL if \a seek_callback
  87659. * is non-NULL since they are both needed to be
  87660. * able to write data back to the Ogg FLAC stream
  87661. * in the post-encode phase.
  87662. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  87663. * pointer must not be \c NULL.
  87664. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  87665. * pointer may be \c NULL if seeking is not
  87666. * supported. The encoder uses seeking to go back
  87667. * and write some some stream statistics to the
  87668. * STREAMINFO block; this is recommended but not
  87669. * necessary to create a valid FLAC stream. If
  87670. * \a seek_callback is not \c NULL then a
  87671. * \a tell_callback must also be supplied.
  87672. * Alternatively, a dummy seek callback that just
  87673. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  87674. * may also be supplied, all though this is slightly
  87675. * less efficient for the encoder.
  87676. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  87677. * pointer may be \c NULL if seeking is not
  87678. * supported. If \a seek_callback is \c NULL then
  87679. * this argument will be ignored. If
  87680. * \a seek_callback is not \c NULL then a
  87681. * \a tell_callback must also be supplied.
  87682. * Alternatively, a dummy tell callback that just
  87683. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  87684. * may also be supplied, all though this is slightly
  87685. * less efficient for the encoder.
  87686. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  87687. * pointer may be \c NULL if the callback is not
  87688. * desired. If the client provides a seek callback,
  87689. * this function is not necessary as the encoder
  87690. * will automatically seek back and update the
  87691. * STREAMINFO block. It may also be \c NULL if the
  87692. * client does not support seeking, since it will
  87693. * have no way of going back to update the
  87694. * STREAMINFO. However the client can still supply
  87695. * a callback if it would like to know the details
  87696. * from the STREAMINFO.
  87697. * \param client_data This value will be supplied to callbacks in their
  87698. * \a client_data argument.
  87699. * \assert
  87700. * \code encoder != NULL \endcode
  87701. * \retval FLAC__StreamEncoderInitStatus
  87702. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87703. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87704. */
  87705. 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);
  87706. /** Initialize the encoder instance to encode native FLAC files.
  87707. *
  87708. * This flavor of initialization sets up the encoder to encode to a
  87709. * plain native FLAC file. For non-stdio streams, you must use
  87710. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  87711. *
  87712. * This function should be called after FLAC__stream_encoder_new() and
  87713. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87714. * or FLAC__stream_encoder_process_interleaved().
  87715. * initialization succeeded.
  87716. *
  87717. * \param encoder An uninitialized encoder instance.
  87718. * \param file An open file. The file should have been opened
  87719. * with mode \c "w+b" and rewound. The file
  87720. * becomes owned by the encoder and should not be
  87721. * manipulated by the client while encoding.
  87722. * Unless \a file is \c stdout, it will be closed
  87723. * when FLAC__stream_encoder_finish() is called.
  87724. * Note however that a proper SEEKTABLE cannot be
  87725. * created when encoding to \c stdout since it is
  87726. * not seekable.
  87727. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87728. * pointer may be \c NULL if the callback is not
  87729. * desired.
  87730. * \param client_data This value will be supplied to callbacks in their
  87731. * \a client_data argument.
  87732. * \assert
  87733. * \code encoder != NULL \endcode
  87734. * \code file != NULL \endcode
  87735. * \retval FLAC__StreamEncoderInitStatus
  87736. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87737. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87738. */
  87739. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87740. /** Initialize the encoder instance to encode Ogg FLAC files.
  87741. *
  87742. * This flavor of initialization sets up the encoder to encode to a
  87743. * plain Ogg FLAC file. For non-stdio streams, you must use
  87744. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  87745. *
  87746. * This function should be called after FLAC__stream_encoder_new() and
  87747. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87748. * or FLAC__stream_encoder_process_interleaved().
  87749. * initialization succeeded.
  87750. *
  87751. * \param encoder An uninitialized encoder instance.
  87752. * \param file An open file. The file should have been opened
  87753. * with mode \c "w+b" and rewound. The file
  87754. * becomes owned by the encoder and should not be
  87755. * manipulated by the client while encoding.
  87756. * Unless \a file is \c stdout, it will be closed
  87757. * when FLAC__stream_encoder_finish() is called.
  87758. * Note however that a proper SEEKTABLE cannot be
  87759. * created when encoding to \c stdout since it is
  87760. * not seekable.
  87761. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87762. * pointer may be \c NULL if the callback is not
  87763. * desired.
  87764. * \param client_data This value will be supplied to callbacks in their
  87765. * \a client_data argument.
  87766. * \assert
  87767. * \code encoder != NULL \endcode
  87768. * \code file != NULL \endcode
  87769. * \retval FLAC__StreamEncoderInitStatus
  87770. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87771. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87772. */
  87773. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87774. /** Initialize the encoder instance to encode native FLAC files.
  87775. *
  87776. * This flavor of initialization sets up the encoder to encode to a plain
  87777. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87778. * with Unicode filenames on Windows), you must use
  87779. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  87780. * and provide callbacks for the I/O.
  87781. *
  87782. * This function should be called after FLAC__stream_encoder_new() and
  87783. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87784. * or FLAC__stream_encoder_process_interleaved().
  87785. * initialization succeeded.
  87786. *
  87787. * \param encoder An uninitialized encoder instance.
  87788. * \param filename The name of the file to encode to. The file will
  87789. * be opened with fopen(). Use \c NULL to encode to
  87790. * \c stdout. Note however that a proper SEEKTABLE
  87791. * cannot be created when encoding to \c stdout since
  87792. * it is not seekable.
  87793. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87794. * pointer may be \c NULL if the callback is not
  87795. * desired.
  87796. * \param client_data This value will be supplied to callbacks in their
  87797. * \a client_data argument.
  87798. * \assert
  87799. * \code encoder != NULL \endcode
  87800. * \retval FLAC__StreamEncoderInitStatus
  87801. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87802. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87803. */
  87804. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87805. /** Initialize the encoder instance to encode Ogg FLAC files.
  87806. *
  87807. * This flavor of initialization sets up the encoder to encode to a plain
  87808. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  87809. * with Unicode filenames on Windows), you must use
  87810. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  87811. * and provide callbacks for the I/O.
  87812. *
  87813. * This function should be called after FLAC__stream_encoder_new() and
  87814. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  87815. * or FLAC__stream_encoder_process_interleaved().
  87816. * initialization succeeded.
  87817. *
  87818. * \param encoder An uninitialized encoder instance.
  87819. * \param filename The name of the file to encode to. The file will
  87820. * be opened with fopen(). Use \c NULL to encode to
  87821. * \c stdout. Note however that a proper SEEKTABLE
  87822. * cannot be created when encoding to \c stdout since
  87823. * it is not seekable.
  87824. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  87825. * pointer may be \c NULL if the callback is not
  87826. * desired.
  87827. * \param client_data This value will be supplied to callbacks in their
  87828. * \a client_data argument.
  87829. * \assert
  87830. * \code encoder != NULL \endcode
  87831. * \retval FLAC__StreamEncoderInitStatus
  87832. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  87833. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  87834. */
  87835. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  87836. /** Finish the encoding process.
  87837. * Flushes the encoding buffer, releases resources, resets the encoder
  87838. * settings to their defaults, and returns the encoder state to
  87839. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  87840. * one or more write callbacks before returning, and will generate
  87841. * a metadata callback.
  87842. *
  87843. * Note that in the course of processing the last frame, errors can
  87844. * occur, so the caller should be sure to check the return value to
  87845. * ensure the file was encoded properly.
  87846. *
  87847. * In the event of a prematurely-terminated encode, it is not strictly
  87848. * necessary to call this immediately before FLAC__stream_encoder_delete()
  87849. * but it is good practice to match every FLAC__stream_encoder_init_*()
  87850. * with a FLAC__stream_encoder_finish().
  87851. *
  87852. * \param encoder An uninitialized encoder instance.
  87853. * \assert
  87854. * \code encoder != NULL \endcode
  87855. * \retval FLAC__bool
  87856. * \c false if an error occurred processing the last frame; or if verify
  87857. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  87858. * verify mismatch; else \c true. If \c false, caller should check the
  87859. * state with FLAC__stream_encoder_get_state() for more information
  87860. * about the error.
  87861. */
  87862. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  87863. /** Submit data for encoding.
  87864. * This version allows you to supply the input data via an array of
  87865. * pointers, each pointer pointing to an array of \a samples samples
  87866. * representing one channel. The samples need not be block-aligned,
  87867. * but each channel should have the same number of samples. Each sample
  87868. * should be a signed integer, right-justified to the resolution set by
  87869. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87870. * resolution is 16 bits per sample, the samples should all be in the
  87871. * range [-32768,32767].
  87872. *
  87873. * For applications where channel order is important, channels must
  87874. * follow the order as described in the
  87875. * <A HREF="../format.html#frame_header">frame header</A>.
  87876. *
  87877. * \param encoder An initialized encoder instance in the OK state.
  87878. * \param buffer An array of pointers to each channel's signal.
  87879. * \param samples The number of samples in one channel.
  87880. * \assert
  87881. * \code encoder != NULL \endcode
  87882. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87883. * \retval FLAC__bool
  87884. * \c true if successful, else \c false; in this case, check the
  87885. * encoder state with FLAC__stream_encoder_get_state() to see what
  87886. * went wrong.
  87887. */
  87888. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  87889. /** Submit data for encoding.
  87890. * This version allows you to supply the input data where the channels
  87891. * are interleaved into a single array (i.e. channel0_sample0,
  87892. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  87893. * The samples need not be block-aligned but they must be
  87894. * sample-aligned, i.e. the first value should be channel0_sample0
  87895. * and the last value channelN_sampleM. Each sample should be a signed
  87896. * integer, right-justified to the resolution set by
  87897. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  87898. * resolution is 16 bits per sample, the samples should all be in the
  87899. * range [-32768,32767].
  87900. *
  87901. * For applications where channel order is important, channels must
  87902. * follow the order as described in the
  87903. * <A HREF="../format.html#frame_header">frame header</A>.
  87904. *
  87905. * \param encoder An initialized encoder instance in the OK state.
  87906. * \param buffer An array of channel-interleaved data (see above).
  87907. * \param samples The number of samples in one channel, the same as for
  87908. * FLAC__stream_encoder_process(). For example, if
  87909. * encoding two channels, \c 1000 \a samples corresponds
  87910. * to a \a buffer of 2000 values.
  87911. * \assert
  87912. * \code encoder != NULL \endcode
  87913. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  87914. * \retval FLAC__bool
  87915. * \c true if successful, else \c false; in this case, check the
  87916. * encoder state with FLAC__stream_encoder_get_state() to see what
  87917. * went wrong.
  87918. */
  87919. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  87920. /* \} */
  87921. #ifdef __cplusplus
  87922. }
  87923. #endif
  87924. #endif
  87925. /********* End of inlined file: stream_encoder.h *********/
  87926. #ifdef _MSC_VER
  87927. /* OPT: an MSVC built-in would be better */
  87928. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  87929. {
  87930. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  87931. return (x>>16) | (x<<16);
  87932. }
  87933. #endif
  87934. #if defined(_MSC_VER) && defined(_X86_)
  87935. /* OPT: an MSVC built-in would be better */
  87936. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  87937. {
  87938. __asm {
  87939. mov edx, start
  87940. mov ecx, len
  87941. test ecx, ecx
  87942. loop1:
  87943. jz done1
  87944. mov eax, [edx]
  87945. bswap eax
  87946. mov [edx], eax
  87947. add edx, 4
  87948. dec ecx
  87949. jmp short loop1
  87950. done1:
  87951. }
  87952. }
  87953. #endif
  87954. /** \mainpage
  87955. *
  87956. * \section intro Introduction
  87957. *
  87958. * This is the documentation for the FLAC C and C++ APIs. It is
  87959. * highly interconnected; this introduction should give you a top
  87960. * level idea of the structure and how to find the information you
  87961. * need. As a prerequisite you should have at least a basic
  87962. * knowledge of the FLAC format, documented
  87963. * <A HREF="../format.html">here</A>.
  87964. *
  87965. * \section c_api FLAC C API
  87966. *
  87967. * The FLAC C API is the interface to libFLAC, a set of structures
  87968. * describing the components of FLAC streams, and functions for
  87969. * encoding and decoding streams, as well as manipulating FLAC
  87970. * metadata in files. The public include files will be installed
  87971. * in your include area (for example /usr/include/FLAC/...).
  87972. *
  87973. * By writing a little code and linking against libFLAC, it is
  87974. * relatively easy to add FLAC support to another program. The
  87975. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  87976. * Complete source code of libFLAC as well as the command-line
  87977. * encoder and plugins is available and is a useful source of
  87978. * examples.
  87979. *
  87980. * Aside from encoders and decoders, libFLAC provides a powerful
  87981. * metadata interface for manipulating metadata in FLAC files. It
  87982. * allows the user to add, delete, and modify FLAC metadata blocks
  87983. * and it can automatically take advantage of PADDING blocks to avoid
  87984. * rewriting the entire FLAC file when changing the size of the
  87985. * metadata.
  87986. *
  87987. * libFLAC usually only requires the standard C library and C math
  87988. * library. In particular, threading is not used so there is no
  87989. * dependency on a thread library. However, libFLAC does not use
  87990. * global variables and should be thread-safe.
  87991. *
  87992. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  87993. * However the metadata editing interfaces currently have limited
  87994. * read-only support for Ogg FLAC files.
  87995. *
  87996. * \section cpp_api FLAC C++ API
  87997. *
  87998. * The FLAC C++ API is a set of classes that encapsulate the
  87999. * structures and functions in libFLAC. They provide slightly more
  88000. * functionality with respect to metadata but are otherwise
  88001. * equivalent. For the most part, they share the same usage as
  88002. * their counterparts in libFLAC, and the FLAC C API documentation
  88003. * can be used as a supplement. The public include files
  88004. * for the C++ API will be installed in your include area (for
  88005. * example /usr/include/FLAC++/...).
  88006. *
  88007. * libFLAC++ is also licensed under
  88008. * <A HREF="../license.html">Xiph's BSD license</A>.
  88009. *
  88010. * \section getting_started Getting Started
  88011. *
  88012. * A good starting point for learning the API is to browse through
  88013. * the <A HREF="modules.html">modules</A>. Modules are logical
  88014. * groupings of related functions or classes, which correspond roughly
  88015. * to header files or sections of header files. Each module includes a
  88016. * detailed description of the general usage of its functions or
  88017. * classes.
  88018. *
  88019. * From there you can go on to look at the documentation of
  88020. * individual functions. You can see different views of the individual
  88021. * functions through the links in top bar across this page.
  88022. *
  88023. * If you prefer a more hands-on approach, you can jump right to some
  88024. * <A HREF="../documentation_example_code.html">example code</A>.
  88025. *
  88026. * \section porting_guide Porting Guide
  88027. *
  88028. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  88029. * has been introduced which gives detailed instructions on how to
  88030. * port your code to newer versions of FLAC.
  88031. *
  88032. * \section embedded_developers Embedded Developers
  88033. *
  88034. * libFLAC has grown larger over time as more functionality has been
  88035. * included, but much of it may be unnecessary for a particular embedded
  88036. * implementation. Unused parts may be pruned by some simple editing of
  88037. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  88038. * metadata interface are all independent from each other.
  88039. *
  88040. * It is easiest to just describe the dependencies:
  88041. *
  88042. * - All modules depend on the \link flac_format Format \endlink module.
  88043. * - The decoders and encoders depend on the bitbuffer.
  88044. * - The decoder is independent of the encoder. The encoder uses the
  88045. * decoder because of the verify feature, but this can be removed if
  88046. * not needed.
  88047. * - Parts of the metadata interface require the stream decoder (but not
  88048. * the encoder).
  88049. * - Ogg support is selectable through the compile time macro
  88050. * \c FLAC__HAS_OGG.
  88051. *
  88052. * For example, if your application only requires the stream decoder, no
  88053. * encoder, and no metadata interface, you can remove the stream encoder
  88054. * and the metadata interface, which will greatly reduce the size of the
  88055. * library.
  88056. *
  88057. * Also, there are several places in the libFLAC code with comments marked
  88058. * with "OPT:" where a #define can be changed to enable code that might be
  88059. * faster on a specific platform. Experimenting with these can yield faster
  88060. * binaries.
  88061. */
  88062. /** \defgroup porting Porting Guide for New Versions
  88063. *
  88064. * This module describes differences in the library interfaces from
  88065. * version to version. It assists in the porting of code that uses
  88066. * the libraries to newer versions of FLAC.
  88067. *
  88068. * One simple facility for making porting easier that has been added
  88069. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  88070. * library's includes (e.g. \c include/FLAC/export.h). The
  88071. * \c #defines mirror the libraries'
  88072. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  88073. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  88074. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  88075. * These can be used to support multiple versions of an API during the
  88076. * transition phase, e.g.
  88077. *
  88078. * \code
  88079. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  88080. * legacy code
  88081. * #else
  88082. * new code
  88083. * #endif
  88084. * \endcode
  88085. *
  88086. * The the source will work for multiple versions and the legacy code can
  88087. * easily be removed when the transition is complete.
  88088. *
  88089. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  88090. * include/FLAC/export.h), which can be used to determine whether or not
  88091. * the library has been compiled with support for Ogg FLAC. This is
  88092. * simpler than trying to call an Ogg init function and catching the
  88093. * error.
  88094. */
  88095. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  88096. * \ingroup porting
  88097. *
  88098. * \brief
  88099. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  88100. *
  88101. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  88102. * been simplified. First, libOggFLAC has been merged into libFLAC and
  88103. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  88104. * decoding layers and three encoding layers have been merged into a
  88105. * single stream decoder and stream encoder. That is, the functionality
  88106. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  88107. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  88108. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  88109. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  88110. * is there is now a single API that can be used to encode or decode
  88111. * streams to/from native FLAC or Ogg FLAC and the single API can work
  88112. * on both seekable and non-seekable streams.
  88113. *
  88114. * Instead of creating an encoder or decoder of a certain layer, now the
  88115. * client will always create a FLAC__StreamEncoder or
  88116. * FLAC__StreamDecoder. The old layers are now differentiated by the
  88117. * initialization function. For example, for the decoder,
  88118. * FLAC__stream_decoder_init() has been replaced by
  88119. * FLAC__stream_decoder_init_stream(). This init function takes
  88120. * callbacks for the I/O, and the seeking callbacks are optional. This
  88121. * allows the client to use the same object for seekable and
  88122. * non-seekable streams. For decoding a FLAC file directly, the client
  88123. * can use FLAC__stream_decoder_init_file() and pass just a filename
  88124. * and fewer callbacks; most of the other callbacks are supplied
  88125. * internally. For situations where fopen()ing by filename is not
  88126. * possible (e.g. Unicode filenames on Windows) the client can instead
  88127. * open the file itself and supply the FILE* to
  88128. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  88129. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  88130. * Since the callbacks and client data are now passed to the init
  88131. * function, the FLAC__stream_decoder_set_*_callback() functions and
  88132. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  88133. * rest of the calls to the decoder are the same as before.
  88134. *
  88135. * There are counterpart init functions for Ogg FLAC, e.g.
  88136. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  88137. * and callbacks are the same as for native FLAC.
  88138. *
  88139. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  88140. * been set up like so:
  88141. *
  88142. * \code
  88143. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  88144. * if(decoder == NULL) do_something;
  88145. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  88146. * [... other settings ...]
  88147. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  88148. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  88149. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  88150. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  88151. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  88152. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  88153. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  88154. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  88155. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  88156. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  88157. * \endcode
  88158. *
  88159. * In FLAC 1.1.3 it is like this:
  88160. *
  88161. * \code
  88162. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  88163. * if(decoder == NULL) do_something;
  88164. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  88165. * [... other settings ...]
  88166. * if(FLAC__stream_decoder_init_stream(
  88167. * decoder,
  88168. * my_read_callback,
  88169. * my_seek_callback, // or NULL
  88170. * my_tell_callback, // or NULL
  88171. * my_length_callback, // or NULL
  88172. * my_eof_callback, // or NULL
  88173. * my_write_callback,
  88174. * my_metadata_callback, // or NULL
  88175. * my_error_callback,
  88176. * my_client_data
  88177. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88178. * \endcode
  88179. *
  88180. * or you could do;
  88181. *
  88182. * \code
  88183. * [...]
  88184. * FILE *file = fopen("somefile.flac","rb");
  88185. * if(file == NULL) do_somthing;
  88186. * if(FLAC__stream_decoder_init_FILE(
  88187. * decoder,
  88188. * file,
  88189. * my_write_callback,
  88190. * my_metadata_callback, // or NULL
  88191. * my_error_callback,
  88192. * my_client_data
  88193. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88194. * \endcode
  88195. *
  88196. * or just:
  88197. *
  88198. * \code
  88199. * [...]
  88200. * if(FLAC__stream_decoder_init_file(
  88201. * decoder,
  88202. * "somefile.flac",
  88203. * my_write_callback,
  88204. * my_metadata_callback, // or NULL
  88205. * my_error_callback,
  88206. * my_client_data
  88207. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  88208. * \endcode
  88209. *
  88210. * Another small change to the decoder is in how it handles unparseable
  88211. * streams. Before, when the decoder found an unparseable stream
  88212. * (reserved for when the decoder encounters a stream from a future
  88213. * encoder that it can't parse), it changed the state to
  88214. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  88215. * drops sync and calls the error callback with a new error code
  88216. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  88217. * more robust. If your error callback does not discriminate on the the
  88218. * error state, your code does not need to be changed.
  88219. *
  88220. * The encoder now has a new setting:
  88221. * FLAC__stream_encoder_set_apodization(). This is for setting the
  88222. * method used to window the data before LPC analysis. You only need to
  88223. * add a call to this function if the default is not suitable. There
  88224. * are also two new convenience functions that may be useful:
  88225. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  88226. * FLAC__metadata_get_cuesheet().
  88227. *
  88228. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  88229. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  88230. * is now \c size_t instead of \c unsigned.
  88231. */
  88232. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  88233. * \ingroup porting
  88234. *
  88235. * \brief
  88236. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  88237. *
  88238. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  88239. * There was a slight change in the implementation of
  88240. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  88241. * of the \a metadata array of pointers so the client no longer needs
  88242. * to maintain it after the call. The objects themselves that are
  88243. * pointed to by the array are still not copied though and must be
  88244. * maintained until the call to FLAC__stream_encoder_finish().
  88245. */
  88246. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  88247. * \ingroup porting
  88248. *
  88249. * \brief
  88250. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  88251. *
  88252. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  88253. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  88254. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  88255. *
  88256. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  88257. * has changed to reflect the conversion of one of the reserved bits
  88258. * into active use. It used to be \c 2 and now is \c 1. However the
  88259. * FLAC frame header length has not changed, so to skip the proper
  88260. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  88261. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  88262. */
  88263. /** \defgroup flac FLAC C API
  88264. *
  88265. * The FLAC C API is the interface to libFLAC, a set of structures
  88266. * describing the components of FLAC streams, and functions for
  88267. * encoding and decoding streams, as well as manipulating FLAC
  88268. * metadata in files.
  88269. *
  88270. * You should start with the format components as all other modules
  88271. * are dependent on it.
  88272. */
  88273. #endif
  88274. /********* End of inlined file: all.h *********/
  88275. /********* Start of inlined file: bitmath.c *********/
  88276. /********* Start of inlined file: juce_FlacHeader.h *********/
  88277. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88278. // tasks..
  88279. #define VERSION "1.2.1"
  88280. #define FLAC__NO_DLL 1
  88281. #ifdef _MSC_VER
  88282. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88283. #endif
  88284. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88285. #define FLAC__SYS_DARWIN 1
  88286. #endif
  88287. /********* End of inlined file: juce_FlacHeader.h *********/
  88288. #if JUCE_USE_FLAC
  88289. #if HAVE_CONFIG_H
  88290. # include <config.h>
  88291. #endif
  88292. /********* Start of inlined file: bitmath.h *********/
  88293. #ifndef FLAC__PRIVATE__BITMATH_H
  88294. #define FLAC__PRIVATE__BITMATH_H
  88295. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  88296. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  88297. unsigned FLAC__bitmath_silog2(int v);
  88298. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  88299. #endif
  88300. /********* End of inlined file: bitmath.h *********/
  88301. /* An example of what FLAC__bitmath_ilog2() computes:
  88302. *
  88303. * ilog2( 0) = assertion failure
  88304. * ilog2( 1) = 0
  88305. * ilog2( 2) = 1
  88306. * ilog2( 3) = 1
  88307. * ilog2( 4) = 2
  88308. * ilog2( 5) = 2
  88309. * ilog2( 6) = 2
  88310. * ilog2( 7) = 2
  88311. * ilog2( 8) = 3
  88312. * ilog2( 9) = 3
  88313. * ilog2(10) = 3
  88314. * ilog2(11) = 3
  88315. * ilog2(12) = 3
  88316. * ilog2(13) = 3
  88317. * ilog2(14) = 3
  88318. * ilog2(15) = 3
  88319. * ilog2(16) = 4
  88320. * ilog2(17) = 4
  88321. * ilog2(18) = 4
  88322. */
  88323. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  88324. {
  88325. unsigned l = 0;
  88326. FLAC__ASSERT(v > 0);
  88327. while(v >>= 1)
  88328. l++;
  88329. return l;
  88330. }
  88331. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  88332. {
  88333. unsigned l = 0;
  88334. FLAC__ASSERT(v > 0);
  88335. while(v >>= 1)
  88336. l++;
  88337. return l;
  88338. }
  88339. /* An example of what FLAC__bitmath_silog2() computes:
  88340. *
  88341. * silog2(-10) = 5
  88342. * silog2(- 9) = 5
  88343. * silog2(- 8) = 4
  88344. * silog2(- 7) = 4
  88345. * silog2(- 6) = 4
  88346. * silog2(- 5) = 4
  88347. * silog2(- 4) = 3
  88348. * silog2(- 3) = 3
  88349. * silog2(- 2) = 2
  88350. * silog2(- 1) = 2
  88351. * silog2( 0) = 0
  88352. * silog2( 1) = 2
  88353. * silog2( 2) = 3
  88354. * silog2( 3) = 3
  88355. * silog2( 4) = 4
  88356. * silog2( 5) = 4
  88357. * silog2( 6) = 4
  88358. * silog2( 7) = 4
  88359. * silog2( 8) = 5
  88360. * silog2( 9) = 5
  88361. * silog2( 10) = 5
  88362. */
  88363. unsigned FLAC__bitmath_silog2(int v)
  88364. {
  88365. while(1) {
  88366. if(v == 0) {
  88367. return 0;
  88368. }
  88369. else if(v > 0) {
  88370. unsigned l = 0;
  88371. while(v) {
  88372. l++;
  88373. v >>= 1;
  88374. }
  88375. return l+1;
  88376. }
  88377. else if(v == -1) {
  88378. return 2;
  88379. }
  88380. else {
  88381. v++;
  88382. v = -v;
  88383. }
  88384. }
  88385. }
  88386. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  88387. {
  88388. while(1) {
  88389. if(v == 0) {
  88390. return 0;
  88391. }
  88392. else if(v > 0) {
  88393. unsigned l = 0;
  88394. while(v) {
  88395. l++;
  88396. v >>= 1;
  88397. }
  88398. return l+1;
  88399. }
  88400. else if(v == -1) {
  88401. return 2;
  88402. }
  88403. else {
  88404. v++;
  88405. v = -v;
  88406. }
  88407. }
  88408. }
  88409. #endif
  88410. /********* End of inlined file: bitmath.c *********/
  88411. /********* Start of inlined file: bitreader.c *********/
  88412. /********* Start of inlined file: juce_FlacHeader.h *********/
  88413. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88414. // tasks..
  88415. #define VERSION "1.2.1"
  88416. #define FLAC__NO_DLL 1
  88417. #ifdef _MSC_VER
  88418. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88419. #endif
  88420. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88421. #define FLAC__SYS_DARWIN 1
  88422. #endif
  88423. /********* End of inlined file: juce_FlacHeader.h *********/
  88424. #if JUCE_USE_FLAC
  88425. #if HAVE_CONFIG_H
  88426. # include <config.h>
  88427. #endif
  88428. #include <stdlib.h> /* for malloc() */
  88429. #include <string.h> /* for memcpy(), memset() */
  88430. #ifdef _MSC_VER
  88431. #include <winsock.h> /* for ntohl() */
  88432. #elif defined FLAC__SYS_DARWIN
  88433. #include <machine/endian.h> /* for ntohl() */
  88434. #elif defined __MINGW32__
  88435. #include <winsock.h> /* for ntohl() */
  88436. #else
  88437. #include <netinet/in.h> /* for ntohl() */
  88438. #endif
  88439. /********* Start of inlined file: bitreader.h *********/
  88440. #ifndef FLAC__PRIVATE__BITREADER_H
  88441. #define FLAC__PRIVATE__BITREADER_H
  88442. #include <stdio.h> /* for FILE */
  88443. /********* Start of inlined file: cpu.h *********/
  88444. #ifndef FLAC__PRIVATE__CPU_H
  88445. #define FLAC__PRIVATE__CPU_H
  88446. #ifdef HAVE_CONFIG_H
  88447. #include <config.h>
  88448. #endif
  88449. typedef enum {
  88450. FLAC__CPUINFO_TYPE_IA32,
  88451. FLAC__CPUINFO_TYPE_PPC,
  88452. FLAC__CPUINFO_TYPE_UNKNOWN
  88453. } FLAC__CPUInfo_Type;
  88454. typedef struct {
  88455. FLAC__bool cpuid;
  88456. FLAC__bool bswap;
  88457. FLAC__bool cmov;
  88458. FLAC__bool mmx;
  88459. FLAC__bool fxsr;
  88460. FLAC__bool sse;
  88461. FLAC__bool sse2;
  88462. FLAC__bool sse3;
  88463. FLAC__bool ssse3;
  88464. FLAC__bool _3dnow;
  88465. FLAC__bool ext3dnow;
  88466. FLAC__bool extmmx;
  88467. } FLAC__CPUInfo_IA32;
  88468. typedef struct {
  88469. FLAC__bool altivec;
  88470. FLAC__bool ppc64;
  88471. } FLAC__CPUInfo_PPC;
  88472. typedef struct {
  88473. FLAC__bool use_asm;
  88474. FLAC__CPUInfo_Type type;
  88475. union {
  88476. FLAC__CPUInfo_IA32 ia32;
  88477. FLAC__CPUInfo_PPC ppc;
  88478. } data;
  88479. } FLAC__CPUInfo;
  88480. void FLAC__cpu_info(FLAC__CPUInfo *info);
  88481. #ifndef FLAC__NO_ASM
  88482. #ifdef FLAC__CPU_IA32
  88483. #ifdef FLAC__HAS_NASM
  88484. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  88485. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  88486. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  88487. #endif
  88488. #endif
  88489. #endif
  88490. #endif
  88491. /********* End of inlined file: cpu.h *********/
  88492. /*
  88493. * opaque structure definition
  88494. */
  88495. struct FLAC__BitReader;
  88496. typedef struct FLAC__BitReader FLAC__BitReader;
  88497. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  88498. /*
  88499. * construction, deletion, initialization, etc functions
  88500. */
  88501. FLAC__BitReader *FLAC__bitreader_new(void);
  88502. void FLAC__bitreader_delete(FLAC__BitReader *br);
  88503. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  88504. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  88505. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  88506. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  88507. /*
  88508. * CRC functions
  88509. */
  88510. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  88511. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  88512. /*
  88513. * info functions
  88514. */
  88515. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  88516. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  88517. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  88518. /*
  88519. * read functions
  88520. */
  88521. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  88522. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  88523. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  88524. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  88525. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  88526. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  88527. 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! */
  88528. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  88529. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88530. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88531. #ifndef FLAC__NO_ASM
  88532. # ifdef FLAC__CPU_IA32
  88533. # ifdef FLAC__HAS_NASM
  88534. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  88535. # endif
  88536. # endif
  88537. #endif
  88538. #if 0 /* UNUSED */
  88539. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  88540. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  88541. #endif
  88542. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  88543. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  88544. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  88545. #endif
  88546. /********* End of inlined file: bitreader.h *********/
  88547. /********* Start of inlined file: crc.h *********/
  88548. #ifndef FLAC__PRIVATE__CRC_H
  88549. #define FLAC__PRIVATE__CRC_H
  88550. /* 8 bit CRC generator, MSB shifted first
  88551. ** polynomial = x^8 + x^2 + x^1 + x^0
  88552. ** init = 0
  88553. */
  88554. extern FLAC__byte const FLAC__crc8_table[256];
  88555. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  88556. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  88557. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  88558. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  88559. /* 16 bit CRC generator, MSB shifted first
  88560. ** polynomial = x^16 + x^15 + x^2 + x^0
  88561. ** init = 0
  88562. */
  88563. extern unsigned FLAC__crc16_table[256];
  88564. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  88565. /* this alternate may be faster on some systems/compilers */
  88566. #if 0
  88567. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  88568. #endif
  88569. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  88570. #endif
  88571. /********* End of inlined file: crc.h *********/
  88572. /* Things should be fastest when this matches the machine word size */
  88573. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  88574. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  88575. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  88576. typedef FLAC__uint32 brword;
  88577. #define FLAC__BYTES_PER_WORD 4
  88578. #define FLAC__BITS_PER_WORD 32
  88579. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  88580. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  88581. #if WORDS_BIGENDIAN
  88582. #define SWAP_BE_WORD_TO_HOST(x) (x)
  88583. #else
  88584. #if defined (_MSC_VER) && defined (_X86_)
  88585. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  88586. #else
  88587. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  88588. #endif
  88589. #endif
  88590. /* counts the # of zero MSBs in a word */
  88591. #define COUNT_ZERO_MSBS(word) ( \
  88592. (word) <= 0xffff ? \
  88593. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  88594. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  88595. )
  88596. /* this alternate might be slightly faster on some systems/compilers: */
  88597. #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])) )
  88598. /*
  88599. * This should be at least twice as large as the largest number of words
  88600. * required to represent any 'number' (in any encoding) you are going to
  88601. * read. With FLAC this is on the order of maybe a few hundred bits.
  88602. * If the buffer is smaller than that, the decoder won't be able to read
  88603. * in a whole number that is in a variable length encoding (e.g. Rice).
  88604. * But to be practical it should be at least 1K bytes.
  88605. *
  88606. * Increase this number to decrease the number of read callbacks, at the
  88607. * expense of using more memory. Or decrease for the reverse effect,
  88608. * keeping in mind the limit from the first paragraph. The optimal size
  88609. * also depends on the CPU cache size and other factors; some twiddling
  88610. * may be necessary to squeeze out the best performance.
  88611. */
  88612. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  88613. static const unsigned char byte_to_unary_table[] = {
  88614. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  88615. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88616. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88617. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  88618. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88619. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88620. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88621. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  88622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  88629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  88630. };
  88631. #ifdef min
  88632. #undef min
  88633. #endif
  88634. #define min(x,y) ((x)<(y)?(x):(y))
  88635. #ifdef max
  88636. #undef max
  88637. #endif
  88638. #define max(x,y) ((x)>(y)?(x):(y))
  88639. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  88640. #ifdef _MSC_VER
  88641. #define FLAC__U64L(x) x
  88642. #else
  88643. #define FLAC__U64L(x) x##LLU
  88644. #endif
  88645. #ifndef FLaC__INLINE
  88646. #define FLaC__INLINE
  88647. #endif
  88648. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  88649. struct FLAC__BitReader {
  88650. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  88651. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  88652. brword *buffer;
  88653. unsigned capacity; /* in words */
  88654. unsigned words; /* # of completed words in buffer */
  88655. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  88656. unsigned consumed_words; /* #words ... */
  88657. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  88658. unsigned read_crc16; /* the running frame CRC */
  88659. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  88660. FLAC__BitReaderReadCallback read_callback;
  88661. void *client_data;
  88662. FLAC__CPUInfo cpu_info;
  88663. };
  88664. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  88665. {
  88666. register unsigned crc = br->read_crc16;
  88667. #if FLAC__BYTES_PER_WORD == 4
  88668. switch(br->crc16_align) {
  88669. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  88670. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88671. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88672. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88673. }
  88674. #elif FLAC__BYTES_PER_WORD == 8
  88675. switch(br->crc16_align) {
  88676. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  88677. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  88678. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  88679. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  88680. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  88681. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  88682. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  88683. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  88684. }
  88685. #else
  88686. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  88687. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  88688. br->read_crc16 = crc;
  88689. #endif
  88690. br->crc16_align = 0;
  88691. }
  88692. /* would be static except it needs to be called by asm routines */
  88693. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  88694. {
  88695. unsigned start, end;
  88696. size_t bytes;
  88697. FLAC__byte *target;
  88698. /* first shift the unconsumed buffer data toward the front as much as possible */
  88699. if(br->consumed_words > 0) {
  88700. start = br->consumed_words;
  88701. end = br->words + (br->bytes? 1:0);
  88702. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  88703. br->words -= start;
  88704. br->consumed_words = 0;
  88705. }
  88706. /*
  88707. * set the target for reading, taking into account word alignment and endianness
  88708. */
  88709. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  88710. if(bytes == 0)
  88711. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  88712. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  88713. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  88714. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  88715. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  88716. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  88717. * ^^-------target, bytes=3
  88718. * on LE machines, have to byteswap the odd tail word so nothing is
  88719. * overwritten:
  88720. */
  88721. #if WORDS_BIGENDIAN
  88722. #else
  88723. if(br->bytes)
  88724. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  88725. #endif
  88726. /* now it looks like:
  88727. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  88728. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  88729. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  88730. * ^^-------target, bytes=3
  88731. */
  88732. /* read in the data; note that the callback may return a smaller number of bytes */
  88733. if(!br->read_callback(target, &bytes, br->client_data))
  88734. return false;
  88735. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  88736. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88737. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88738. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  88739. * now have to byteswap on LE machines:
  88740. */
  88741. #if WORDS_BIGENDIAN
  88742. #else
  88743. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88744. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88745. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88746. start = br->words;
  88747. local_swap32_block_(br->buffer + start, end - start);
  88748. }
  88749. else
  88750. # endif
  88751. for(start = br->words; start < end; start++)
  88752. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88753. #endif
  88754. /* now it looks like:
  88755. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88756. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88757. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88758. * finally we'll update the reader values:
  88759. */
  88760. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88761. br->words = end / FLAC__BYTES_PER_WORD;
  88762. br->bytes = end % FLAC__BYTES_PER_WORD;
  88763. return true;
  88764. }
  88765. /***********************************************************************
  88766. *
  88767. * Class constructor/destructor
  88768. *
  88769. ***********************************************************************/
  88770. FLAC__BitReader *FLAC__bitreader_new(void)
  88771. {
  88772. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88773. /* calloc() implies:
  88774. memset(br, 0, sizeof(FLAC__BitReader));
  88775. br->buffer = 0;
  88776. br->capacity = 0;
  88777. br->words = br->bytes = 0;
  88778. br->consumed_words = br->consumed_bits = 0;
  88779. br->read_callback = 0;
  88780. br->client_data = 0;
  88781. */
  88782. return br;
  88783. }
  88784. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88785. {
  88786. FLAC__ASSERT(0 != br);
  88787. FLAC__bitreader_free(br);
  88788. free(br);
  88789. }
  88790. /***********************************************************************
  88791. *
  88792. * Public class methods
  88793. *
  88794. ***********************************************************************/
  88795. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88796. {
  88797. FLAC__ASSERT(0 != br);
  88798. br->words = br->bytes = 0;
  88799. br->consumed_words = br->consumed_bits = 0;
  88800. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88801. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88802. if(br->buffer == 0)
  88803. return false;
  88804. br->read_callback = rcb;
  88805. br->client_data = cd;
  88806. br->cpu_info = cpu;
  88807. return true;
  88808. }
  88809. void FLAC__bitreader_free(FLAC__BitReader *br)
  88810. {
  88811. FLAC__ASSERT(0 != br);
  88812. if(0 != br->buffer)
  88813. free(br->buffer);
  88814. br->buffer = 0;
  88815. br->capacity = 0;
  88816. br->words = br->bytes = 0;
  88817. br->consumed_words = br->consumed_bits = 0;
  88818. br->read_callback = 0;
  88819. br->client_data = 0;
  88820. }
  88821. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88822. {
  88823. br->words = br->bytes = 0;
  88824. br->consumed_words = br->consumed_bits = 0;
  88825. return true;
  88826. }
  88827. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88828. {
  88829. unsigned i, j;
  88830. if(br == 0) {
  88831. fprintf(out, "bitreader is NULL\n");
  88832. }
  88833. else {
  88834. 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);
  88835. for(i = 0; i < br->words; i++) {
  88836. fprintf(out, "%08X: ", i);
  88837. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88838. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88839. fprintf(out, ".");
  88840. else
  88841. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88842. fprintf(out, "\n");
  88843. }
  88844. if(br->bytes > 0) {
  88845. fprintf(out, "%08X: ", i);
  88846. for(j = 0; j < br->bytes*8; j++)
  88847. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88848. fprintf(out, ".");
  88849. else
  88850. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  88851. fprintf(out, "\n");
  88852. }
  88853. }
  88854. }
  88855. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  88856. {
  88857. FLAC__ASSERT(0 != br);
  88858. FLAC__ASSERT(0 != br->buffer);
  88859. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88860. br->read_crc16 = (unsigned)seed;
  88861. br->crc16_align = br->consumed_bits;
  88862. }
  88863. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  88864. {
  88865. FLAC__ASSERT(0 != br);
  88866. FLAC__ASSERT(0 != br->buffer);
  88867. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88868. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  88869. /* CRC any tail bytes in a partially-consumed word */
  88870. if(br->consumed_bits) {
  88871. const brword tail = br->buffer[br->consumed_words];
  88872. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  88873. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  88874. }
  88875. return br->read_crc16;
  88876. }
  88877. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  88878. {
  88879. return ((br->consumed_bits & 7) == 0);
  88880. }
  88881. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  88882. {
  88883. return 8 - (br->consumed_bits & 7);
  88884. }
  88885. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  88886. {
  88887. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  88888. }
  88889. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  88890. {
  88891. FLAC__ASSERT(0 != br);
  88892. FLAC__ASSERT(0 != br->buffer);
  88893. FLAC__ASSERT(bits <= 32);
  88894. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  88895. FLAC__ASSERT(br->consumed_words <= br->words);
  88896. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88897. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88898. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  88899. *val = 0;
  88900. return true;
  88901. }
  88902. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  88903. if(!bitreader_read_from_client_(br))
  88904. return false;
  88905. }
  88906. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88907. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88908. if(br->consumed_bits) {
  88909. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88910. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  88911. const brword word = br->buffer[br->consumed_words];
  88912. if(bits < n) {
  88913. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  88914. br->consumed_bits += bits;
  88915. return true;
  88916. }
  88917. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  88918. bits -= n;
  88919. crc16_update_word_(br, word);
  88920. br->consumed_words++;
  88921. br->consumed_bits = 0;
  88922. 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 */
  88923. *val <<= bits;
  88924. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  88925. br->consumed_bits = bits;
  88926. }
  88927. return true;
  88928. }
  88929. else {
  88930. const brword word = br->buffer[br->consumed_words];
  88931. if(bits < FLAC__BITS_PER_WORD) {
  88932. *val = word >> (FLAC__BITS_PER_WORD-bits);
  88933. br->consumed_bits = bits;
  88934. return true;
  88935. }
  88936. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  88937. *val = word;
  88938. crc16_update_word_(br, word);
  88939. br->consumed_words++;
  88940. return true;
  88941. }
  88942. }
  88943. else {
  88944. /* in this case we're starting our read at a partial tail word;
  88945. * the reader has guaranteed that we have at least 'bits' bits
  88946. * available to read, which makes this case simpler.
  88947. */
  88948. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88949. if(br->consumed_bits) {
  88950. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88951. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  88952. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  88953. br->consumed_bits += bits;
  88954. return true;
  88955. }
  88956. else {
  88957. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  88958. br->consumed_bits += bits;
  88959. return true;
  88960. }
  88961. }
  88962. }
  88963. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  88964. {
  88965. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  88966. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  88967. return false;
  88968. /* sign-extend: */
  88969. *val <<= (32-bits);
  88970. *val >>= (32-bits);
  88971. return true;
  88972. }
  88973. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  88974. {
  88975. FLAC__uint32 hi, lo;
  88976. if(bits > 32) {
  88977. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  88978. return false;
  88979. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  88980. return false;
  88981. *val = hi;
  88982. *val <<= 32;
  88983. *val |= lo;
  88984. }
  88985. else {
  88986. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  88987. return false;
  88988. *val = lo;
  88989. }
  88990. return true;
  88991. }
  88992. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  88993. {
  88994. FLAC__uint32 x8, x32 = 0;
  88995. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88996. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  88997. return false;
  88998. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88999. return false;
  89000. x32 |= (x8 << 8);
  89001. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89002. return false;
  89003. x32 |= (x8 << 16);
  89004. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  89005. return false;
  89006. x32 |= (x8 << 24);
  89007. *val = x32;
  89008. return true;
  89009. }
  89010. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  89011. {
  89012. /*
  89013. * OPT: a faster implementation is possible but probably not that useful
  89014. * since this is only called a couple of times in the metadata readers.
  89015. */
  89016. FLAC__ASSERT(0 != br);
  89017. FLAC__ASSERT(0 != br->buffer);
  89018. if(bits > 0) {
  89019. const unsigned n = br->consumed_bits & 7;
  89020. unsigned m;
  89021. FLAC__uint32 x;
  89022. if(n != 0) {
  89023. m = min(8-n, bits);
  89024. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  89025. return false;
  89026. bits -= m;
  89027. }
  89028. m = bits / 8;
  89029. if(m > 0) {
  89030. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  89031. return false;
  89032. bits %= 8;
  89033. }
  89034. if(bits > 0) {
  89035. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  89036. return false;
  89037. }
  89038. }
  89039. return true;
  89040. }
  89041. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  89042. {
  89043. FLAC__uint32 x;
  89044. FLAC__ASSERT(0 != br);
  89045. FLAC__ASSERT(0 != br->buffer);
  89046. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89047. /* step 1: skip over partial head word to get word aligned */
  89048. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89049. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89050. return false;
  89051. nvals--;
  89052. }
  89053. if(0 == nvals)
  89054. return true;
  89055. /* step 2: skip whole words in chunks */
  89056. while(nvals >= FLAC__BYTES_PER_WORD) {
  89057. if(br->consumed_words < br->words) {
  89058. br->consumed_words++;
  89059. nvals -= FLAC__BYTES_PER_WORD;
  89060. }
  89061. else if(!bitreader_read_from_client_(br))
  89062. return false;
  89063. }
  89064. /* step 3: skip any remainder from partial tail bytes */
  89065. while(nvals) {
  89066. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89067. return false;
  89068. nvals--;
  89069. }
  89070. return true;
  89071. }
  89072. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  89073. {
  89074. FLAC__uint32 x;
  89075. FLAC__ASSERT(0 != br);
  89076. FLAC__ASSERT(0 != br->buffer);
  89077. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  89078. /* step 1: read from partial head word to get word aligned */
  89079. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  89080. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89081. return false;
  89082. *val++ = (FLAC__byte)x;
  89083. nvals--;
  89084. }
  89085. if(0 == nvals)
  89086. return true;
  89087. /* step 2: read whole words in chunks */
  89088. while(nvals >= FLAC__BYTES_PER_WORD) {
  89089. if(br->consumed_words < br->words) {
  89090. const brword word = br->buffer[br->consumed_words++];
  89091. #if FLAC__BYTES_PER_WORD == 4
  89092. val[0] = (FLAC__byte)(word >> 24);
  89093. val[1] = (FLAC__byte)(word >> 16);
  89094. val[2] = (FLAC__byte)(word >> 8);
  89095. val[3] = (FLAC__byte)word;
  89096. #elif FLAC__BYTES_PER_WORD == 8
  89097. val[0] = (FLAC__byte)(word >> 56);
  89098. val[1] = (FLAC__byte)(word >> 48);
  89099. val[2] = (FLAC__byte)(word >> 40);
  89100. val[3] = (FLAC__byte)(word >> 32);
  89101. val[4] = (FLAC__byte)(word >> 24);
  89102. val[5] = (FLAC__byte)(word >> 16);
  89103. val[6] = (FLAC__byte)(word >> 8);
  89104. val[7] = (FLAC__byte)word;
  89105. #else
  89106. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  89107. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  89108. #endif
  89109. val += FLAC__BYTES_PER_WORD;
  89110. nvals -= FLAC__BYTES_PER_WORD;
  89111. }
  89112. else if(!bitreader_read_from_client_(br))
  89113. return false;
  89114. }
  89115. /* step 3: read any remainder from partial tail bytes */
  89116. while(nvals) {
  89117. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89118. return false;
  89119. *val++ = (FLAC__byte)x;
  89120. nvals--;
  89121. }
  89122. return true;
  89123. }
  89124. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  89125. #if 0 /* slow but readable version */
  89126. {
  89127. unsigned bit;
  89128. FLAC__ASSERT(0 != br);
  89129. FLAC__ASSERT(0 != br->buffer);
  89130. *val = 0;
  89131. while(1) {
  89132. if(!FLAC__bitreader_read_bit(br, &bit))
  89133. return false;
  89134. if(bit)
  89135. break;
  89136. else
  89137. *val++;
  89138. }
  89139. return true;
  89140. }
  89141. #else
  89142. {
  89143. unsigned i;
  89144. FLAC__ASSERT(0 != br);
  89145. FLAC__ASSERT(0 != br->buffer);
  89146. *val = 0;
  89147. while(1) {
  89148. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  89149. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  89150. if(b) {
  89151. i = COUNT_ZERO_MSBS(b);
  89152. *val += i;
  89153. i++;
  89154. br->consumed_bits += i;
  89155. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  89156. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89157. br->consumed_words++;
  89158. br->consumed_bits = 0;
  89159. }
  89160. return true;
  89161. }
  89162. else {
  89163. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  89164. crc16_update_word_(br, br->buffer[br->consumed_words]);
  89165. br->consumed_words++;
  89166. br->consumed_bits = 0;
  89167. /* didn't find stop bit yet, have to keep going... */
  89168. }
  89169. }
  89170. /* at this point we've eaten up all the whole words; have to try
  89171. * reading through any tail bytes before calling the read callback.
  89172. * this is a repeat of the above logic adjusted for the fact we
  89173. * don't have a whole word. note though if the client is feeding
  89174. * us data a byte at a time (unlikely), br->consumed_bits may not
  89175. * be zero.
  89176. */
  89177. if(br->bytes) {
  89178. const unsigned end = br->bytes * 8;
  89179. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  89180. if(b) {
  89181. i = COUNT_ZERO_MSBS(b);
  89182. *val += i;
  89183. i++;
  89184. br->consumed_bits += i;
  89185. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89186. return true;
  89187. }
  89188. else {
  89189. *val += end - br->consumed_bits;
  89190. br->consumed_bits += end;
  89191. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  89192. /* didn't find stop bit yet, have to keep going... */
  89193. }
  89194. }
  89195. if(!bitreader_read_from_client_(br))
  89196. return false;
  89197. }
  89198. }
  89199. #endif
  89200. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89201. {
  89202. FLAC__uint32 lsbs = 0, msbs = 0;
  89203. unsigned uval;
  89204. FLAC__ASSERT(0 != br);
  89205. FLAC__ASSERT(0 != br->buffer);
  89206. FLAC__ASSERT(parameter <= 31);
  89207. /* read the unary MSBs and end bit */
  89208. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  89209. return false;
  89210. /* read the binary LSBs */
  89211. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  89212. return false;
  89213. /* compose the value */
  89214. uval = (msbs << parameter) | lsbs;
  89215. if(uval & 1)
  89216. *val = -((int)(uval >> 1)) - 1;
  89217. else
  89218. *val = (int)(uval >> 1);
  89219. return true;
  89220. }
  89221. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  89222. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  89223. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  89224. /* OPT: possibly faster version for use with MSVC */
  89225. #ifdef _MSC_VER
  89226. {
  89227. unsigned i;
  89228. unsigned uval = 0;
  89229. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  89230. /* try and get br->consumed_words and br->consumed_bits into register;
  89231. * must remember to flush them back to *br before calling other
  89232. * bitwriter functions that use them, and before returning */
  89233. register unsigned cwords;
  89234. register unsigned cbits;
  89235. FLAC__ASSERT(0 != br);
  89236. FLAC__ASSERT(0 != br->buffer);
  89237. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89238. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89239. FLAC__ASSERT(parameter < 32);
  89240. /* 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 */
  89241. if(nvals == 0)
  89242. return true;
  89243. cbits = br->consumed_bits;
  89244. cwords = br->consumed_words;
  89245. while(1) {
  89246. /* read unary part */
  89247. while(1) {
  89248. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89249. brword b = br->buffer[cwords] << cbits;
  89250. if(b) {
  89251. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  89252. __asm {
  89253. bsr eax, b
  89254. not eax
  89255. and eax, 31
  89256. mov i, eax
  89257. }
  89258. #else
  89259. i = COUNT_ZERO_MSBS(b);
  89260. #endif
  89261. uval += i;
  89262. bits = parameter;
  89263. i++;
  89264. cbits += i;
  89265. if(cbits == FLAC__BITS_PER_WORD) {
  89266. crc16_update_word_(br, br->buffer[cwords]);
  89267. cwords++;
  89268. cbits = 0;
  89269. }
  89270. goto break1;
  89271. }
  89272. else {
  89273. uval += FLAC__BITS_PER_WORD - cbits;
  89274. crc16_update_word_(br, br->buffer[cwords]);
  89275. cwords++;
  89276. cbits = 0;
  89277. /* didn't find stop bit yet, have to keep going... */
  89278. }
  89279. }
  89280. /* at this point we've eaten up all the whole words; have to try
  89281. * reading through any tail bytes before calling the read callback.
  89282. * this is a repeat of the above logic adjusted for the fact we
  89283. * don't have a whole word. note though if the client is feeding
  89284. * us data a byte at a time (unlikely), br->consumed_bits may not
  89285. * be zero.
  89286. */
  89287. if(br->bytes) {
  89288. const unsigned end = br->bytes * 8;
  89289. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  89290. if(b) {
  89291. i = COUNT_ZERO_MSBS(b);
  89292. uval += i;
  89293. bits = parameter;
  89294. i++;
  89295. cbits += i;
  89296. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89297. goto break1;
  89298. }
  89299. else {
  89300. uval += end - cbits;
  89301. cbits += end;
  89302. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89303. /* didn't find stop bit yet, have to keep going... */
  89304. }
  89305. }
  89306. /* flush registers and read; bitreader_read_from_client_() does
  89307. * not touch br->consumed_bits at all but we still need to set
  89308. * it in case it fails and we have to return false.
  89309. */
  89310. br->consumed_bits = cbits;
  89311. br->consumed_words = cwords;
  89312. if(!bitreader_read_from_client_(br))
  89313. return false;
  89314. cwords = br->consumed_words;
  89315. }
  89316. break1:
  89317. /* read binary part */
  89318. FLAC__ASSERT(cwords <= br->words);
  89319. if(bits) {
  89320. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  89321. /* flush registers and read; bitreader_read_from_client_() does
  89322. * not touch br->consumed_bits at all but we still need to set
  89323. * it in case it fails and we have to return false.
  89324. */
  89325. br->consumed_bits = cbits;
  89326. br->consumed_words = cwords;
  89327. if(!bitreader_read_from_client_(br))
  89328. return false;
  89329. cwords = br->consumed_words;
  89330. }
  89331. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89332. if(cbits) {
  89333. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89334. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89335. const brword word = br->buffer[cwords];
  89336. if(bits < n) {
  89337. uval <<= bits;
  89338. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  89339. cbits += bits;
  89340. goto break2;
  89341. }
  89342. uval <<= n;
  89343. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89344. bits -= n;
  89345. crc16_update_word_(br, word);
  89346. cwords++;
  89347. cbits = 0;
  89348. 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 */
  89349. uval <<= bits;
  89350. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  89351. cbits = bits;
  89352. }
  89353. goto break2;
  89354. }
  89355. else {
  89356. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  89357. uval <<= bits;
  89358. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89359. cbits = bits;
  89360. goto break2;
  89361. }
  89362. }
  89363. else {
  89364. /* in this case we're starting our read at a partial tail word;
  89365. * the reader has guaranteed that we have at least 'bits' bits
  89366. * available to read, which makes this case simpler.
  89367. */
  89368. uval <<= bits;
  89369. if(cbits) {
  89370. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89371. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  89372. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  89373. cbits += bits;
  89374. goto break2;
  89375. }
  89376. else {
  89377. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  89378. cbits += bits;
  89379. goto break2;
  89380. }
  89381. }
  89382. }
  89383. break2:
  89384. /* compose the value */
  89385. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89386. /* are we done? */
  89387. --nvals;
  89388. if(nvals == 0) {
  89389. br->consumed_bits = cbits;
  89390. br->consumed_words = cwords;
  89391. return true;
  89392. }
  89393. uval = 0;
  89394. ++vals;
  89395. }
  89396. }
  89397. #else
  89398. {
  89399. unsigned i;
  89400. unsigned uval = 0;
  89401. /* try and get br->consumed_words and br->consumed_bits into register;
  89402. * must remember to flush them back to *br before calling other
  89403. * bitwriter functions that use them, and before returning */
  89404. register unsigned cwords;
  89405. register unsigned cbits;
  89406. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  89407. FLAC__ASSERT(0 != br);
  89408. FLAC__ASSERT(0 != br->buffer);
  89409. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89410. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89411. FLAC__ASSERT(parameter < 32);
  89412. /* 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 */
  89413. if(nvals == 0)
  89414. return true;
  89415. cbits = br->consumed_bits;
  89416. cwords = br->consumed_words;
  89417. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89418. while(1) {
  89419. /* read unary part */
  89420. while(1) {
  89421. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89422. brword b = br->buffer[cwords] << cbits;
  89423. if(b) {
  89424. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  89425. asm volatile (
  89426. "bsrl %1, %0;"
  89427. "notl %0;"
  89428. "andl $31, %0;"
  89429. : "=r"(i)
  89430. : "r"(b)
  89431. );
  89432. #else
  89433. i = COUNT_ZERO_MSBS(b);
  89434. #endif
  89435. uval += i;
  89436. cbits += i;
  89437. cbits++; /* skip over stop bit */
  89438. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  89439. crc16_update_word_(br, br->buffer[cwords]);
  89440. cwords++;
  89441. cbits = 0;
  89442. }
  89443. goto break1;
  89444. }
  89445. else {
  89446. uval += FLAC__BITS_PER_WORD - cbits;
  89447. crc16_update_word_(br, br->buffer[cwords]);
  89448. cwords++;
  89449. cbits = 0;
  89450. /* didn't find stop bit yet, have to keep going... */
  89451. }
  89452. }
  89453. /* at this point we've eaten up all the whole words; have to try
  89454. * reading through any tail bytes before calling the read callback.
  89455. * this is a repeat of the above logic adjusted for the fact we
  89456. * don't have a whole word. note though if the client is feeding
  89457. * us data a byte at a time (unlikely), br->consumed_bits may not
  89458. * be zero.
  89459. */
  89460. if(br->bytes) {
  89461. const unsigned end = br->bytes * 8;
  89462. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  89463. if(b) {
  89464. i = COUNT_ZERO_MSBS(b);
  89465. uval += i;
  89466. cbits += i;
  89467. cbits++; /* skip over stop bit */
  89468. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89469. goto break1;
  89470. }
  89471. else {
  89472. uval += end - cbits;
  89473. cbits += end;
  89474. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  89475. /* didn't find stop bit yet, have to keep going... */
  89476. }
  89477. }
  89478. /* flush registers and read; bitreader_read_from_client_() does
  89479. * not touch br->consumed_bits at all but we still need to set
  89480. * it in case it fails and we have to return false.
  89481. */
  89482. br->consumed_bits = cbits;
  89483. br->consumed_words = cwords;
  89484. if(!bitreader_read_from_client_(br))
  89485. return false;
  89486. cwords = br->consumed_words;
  89487. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  89488. /* + uval to offset our count by the # of unary bits already
  89489. * consumed before the read, because we will add these back
  89490. * in all at once at break1
  89491. */
  89492. }
  89493. break1:
  89494. ucbits -= uval;
  89495. ucbits--; /* account for stop bit */
  89496. /* read binary part */
  89497. FLAC__ASSERT(cwords <= br->words);
  89498. if(parameter) {
  89499. while(ucbits < parameter) {
  89500. /* flush registers and read; bitreader_read_from_client_() does
  89501. * not touch br->consumed_bits at all but we still need to set
  89502. * it in case it fails and we have to return false.
  89503. */
  89504. br->consumed_bits = cbits;
  89505. br->consumed_words = cwords;
  89506. if(!bitreader_read_from_client_(br))
  89507. return false;
  89508. cwords = br->consumed_words;
  89509. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  89510. }
  89511. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  89512. if(cbits) {
  89513. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  89514. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  89515. const brword word = br->buffer[cwords];
  89516. if(parameter < n) {
  89517. uval <<= parameter;
  89518. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  89519. cbits += parameter;
  89520. }
  89521. else {
  89522. uval <<= n;
  89523. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  89524. crc16_update_word_(br, word);
  89525. cwords++;
  89526. cbits = parameter - n;
  89527. 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 */
  89528. uval <<= cbits;
  89529. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  89530. }
  89531. }
  89532. }
  89533. else {
  89534. cbits = parameter;
  89535. uval <<= parameter;
  89536. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89537. }
  89538. }
  89539. else {
  89540. /* in this case we're starting our read at a partial tail word;
  89541. * the reader has guaranteed that we have at least 'parameter'
  89542. * bits available to read, which makes this case simpler.
  89543. */
  89544. uval <<= parameter;
  89545. if(cbits) {
  89546. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  89547. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  89548. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  89549. cbits += parameter;
  89550. }
  89551. else {
  89552. cbits = parameter;
  89553. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  89554. }
  89555. }
  89556. }
  89557. ucbits -= parameter;
  89558. /* compose the value */
  89559. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  89560. /* are we done? */
  89561. --nvals;
  89562. if(nvals == 0) {
  89563. br->consumed_bits = cbits;
  89564. br->consumed_words = cwords;
  89565. return true;
  89566. }
  89567. uval = 0;
  89568. ++vals;
  89569. }
  89570. }
  89571. #endif
  89572. #if 0 /* UNUSED */
  89573. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  89574. {
  89575. FLAC__uint32 lsbs = 0, msbs = 0;
  89576. unsigned bit, uval, k;
  89577. FLAC__ASSERT(0 != br);
  89578. FLAC__ASSERT(0 != br->buffer);
  89579. k = FLAC__bitmath_ilog2(parameter);
  89580. /* read the unary MSBs and end bit */
  89581. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89582. return false;
  89583. /* read the binary LSBs */
  89584. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89585. return false;
  89586. if(parameter == 1u<<k) {
  89587. /* compose the value */
  89588. uval = (msbs << k) | lsbs;
  89589. }
  89590. else {
  89591. unsigned d = (1 << (k+1)) - parameter;
  89592. if(lsbs >= d) {
  89593. if(!FLAC__bitreader_read_bit(br, &bit))
  89594. return false;
  89595. lsbs <<= 1;
  89596. lsbs |= bit;
  89597. lsbs -= d;
  89598. }
  89599. /* compose the value */
  89600. uval = msbs * parameter + lsbs;
  89601. }
  89602. /* unfold unsigned to signed */
  89603. if(uval & 1)
  89604. *val = -((int)(uval >> 1)) - 1;
  89605. else
  89606. *val = (int)(uval >> 1);
  89607. return true;
  89608. }
  89609. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  89610. {
  89611. FLAC__uint32 lsbs, msbs = 0;
  89612. unsigned bit, k;
  89613. FLAC__ASSERT(0 != br);
  89614. FLAC__ASSERT(0 != br->buffer);
  89615. k = FLAC__bitmath_ilog2(parameter);
  89616. /* read the unary MSBs and end bit */
  89617. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  89618. return false;
  89619. /* read the binary LSBs */
  89620. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  89621. return false;
  89622. if(parameter == 1u<<k) {
  89623. /* compose the value */
  89624. *val = (msbs << k) | lsbs;
  89625. }
  89626. else {
  89627. unsigned d = (1 << (k+1)) - parameter;
  89628. if(lsbs >= d) {
  89629. if(!FLAC__bitreader_read_bit(br, &bit))
  89630. return false;
  89631. lsbs <<= 1;
  89632. lsbs |= bit;
  89633. lsbs -= d;
  89634. }
  89635. /* compose the value */
  89636. *val = msbs * parameter + lsbs;
  89637. }
  89638. return true;
  89639. }
  89640. #endif /* UNUSED */
  89641. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89642. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  89643. {
  89644. FLAC__uint32 v = 0;
  89645. FLAC__uint32 x;
  89646. unsigned i;
  89647. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89648. return false;
  89649. if(raw)
  89650. raw[(*rawlen)++] = (FLAC__byte)x;
  89651. if(!(x & 0x80)) { /* 0xxxxxxx */
  89652. v = x;
  89653. i = 0;
  89654. }
  89655. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89656. v = x & 0x1F;
  89657. i = 1;
  89658. }
  89659. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89660. v = x & 0x0F;
  89661. i = 2;
  89662. }
  89663. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89664. v = x & 0x07;
  89665. i = 3;
  89666. }
  89667. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89668. v = x & 0x03;
  89669. i = 4;
  89670. }
  89671. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89672. v = x & 0x01;
  89673. i = 5;
  89674. }
  89675. else {
  89676. *val = 0xffffffff;
  89677. return true;
  89678. }
  89679. for( ; i; i--) {
  89680. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89681. return false;
  89682. if(raw)
  89683. raw[(*rawlen)++] = (FLAC__byte)x;
  89684. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89685. *val = 0xffffffff;
  89686. return true;
  89687. }
  89688. v <<= 6;
  89689. v |= (x & 0x3F);
  89690. }
  89691. *val = v;
  89692. return true;
  89693. }
  89694. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  89695. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  89696. {
  89697. FLAC__uint64 v = 0;
  89698. FLAC__uint32 x;
  89699. unsigned i;
  89700. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89701. return false;
  89702. if(raw)
  89703. raw[(*rawlen)++] = (FLAC__byte)x;
  89704. if(!(x & 0x80)) { /* 0xxxxxxx */
  89705. v = x;
  89706. i = 0;
  89707. }
  89708. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  89709. v = x & 0x1F;
  89710. i = 1;
  89711. }
  89712. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  89713. v = x & 0x0F;
  89714. i = 2;
  89715. }
  89716. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  89717. v = x & 0x07;
  89718. i = 3;
  89719. }
  89720. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  89721. v = x & 0x03;
  89722. i = 4;
  89723. }
  89724. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  89725. v = x & 0x01;
  89726. i = 5;
  89727. }
  89728. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  89729. v = 0;
  89730. i = 6;
  89731. }
  89732. else {
  89733. *val = FLAC__U64L(0xffffffffffffffff);
  89734. return true;
  89735. }
  89736. for( ; i; i--) {
  89737. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  89738. return false;
  89739. if(raw)
  89740. raw[(*rawlen)++] = (FLAC__byte)x;
  89741. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  89742. *val = FLAC__U64L(0xffffffffffffffff);
  89743. return true;
  89744. }
  89745. v <<= 6;
  89746. v |= (x & 0x3F);
  89747. }
  89748. *val = v;
  89749. return true;
  89750. }
  89751. #endif
  89752. /********* End of inlined file: bitreader.c *********/
  89753. /********* Start of inlined file: bitwriter.c *********/
  89754. /********* Start of inlined file: juce_FlacHeader.h *********/
  89755. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89756. // tasks..
  89757. #define VERSION "1.2.1"
  89758. #define FLAC__NO_DLL 1
  89759. #ifdef _MSC_VER
  89760. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89761. #endif
  89762. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89763. #define FLAC__SYS_DARWIN 1
  89764. #endif
  89765. /********* End of inlined file: juce_FlacHeader.h *********/
  89766. #if JUCE_USE_FLAC
  89767. #if HAVE_CONFIG_H
  89768. # include <config.h>
  89769. #endif
  89770. #include <stdlib.h> /* for malloc() */
  89771. #include <string.h> /* for memcpy(), memset() */
  89772. #ifdef _MSC_VER
  89773. #include <winsock.h> /* for ntohl() */
  89774. #elif defined FLAC__SYS_DARWIN
  89775. #include <machine/endian.h> /* for ntohl() */
  89776. #elif defined __MINGW32__
  89777. #include <winsock.h> /* for ntohl() */
  89778. #else
  89779. #include <netinet/in.h> /* for ntohl() */
  89780. #endif
  89781. #if 0 /* UNUSED */
  89782. #endif
  89783. /********* Start of inlined file: bitwriter.h *********/
  89784. #ifndef FLAC__PRIVATE__BITWRITER_H
  89785. #define FLAC__PRIVATE__BITWRITER_H
  89786. #include <stdio.h> /* for FILE */
  89787. /*
  89788. * opaque structure definition
  89789. */
  89790. struct FLAC__BitWriter;
  89791. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89792. /*
  89793. * construction, deletion, initialization, etc functions
  89794. */
  89795. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89796. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89797. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89798. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89799. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89800. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89801. /*
  89802. * CRC functions
  89803. *
  89804. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89805. */
  89806. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89807. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89808. /*
  89809. * info functions
  89810. */
  89811. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89812. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89813. /*
  89814. * direct buffer access
  89815. *
  89816. * there may be no calls on the bitwriter between get and release.
  89817. * the bitwriter continues to own the returned buffer.
  89818. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89819. */
  89820. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89821. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89822. /*
  89823. * write functions
  89824. */
  89825. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89826. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89827. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89828. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89829. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89830. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89831. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89832. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89833. #if 0 /* UNUSED */
  89834. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89835. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89836. #endif
  89837. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89838. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89839. #if 0 /* UNUSED */
  89840. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89841. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89842. #endif
  89843. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89844. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89845. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89846. #endif
  89847. /********* End of inlined file: bitwriter.h *********/
  89848. /********* Start of inlined file: alloc.h *********/
  89849. #ifndef FLAC__SHARE__ALLOC_H
  89850. #define FLAC__SHARE__ALLOC_H
  89851. #if HAVE_CONFIG_H
  89852. # include <config.h>
  89853. #endif
  89854. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  89855. * before #including this file, otherwise SIZE_MAX might not be defined
  89856. */
  89857. #include <limits.h> /* for SIZE_MAX */
  89858. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  89859. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  89860. #endif
  89861. #include <stdlib.h> /* for size_t, malloc(), etc */
  89862. #ifndef SIZE_MAX
  89863. # ifndef SIZE_T_MAX
  89864. # ifdef _MSC_VER
  89865. # define SIZE_T_MAX UINT_MAX
  89866. # else
  89867. # error
  89868. # endif
  89869. # endif
  89870. # define SIZE_MAX SIZE_T_MAX
  89871. #endif
  89872. #ifndef FLaC__INLINE
  89873. #define FLaC__INLINE
  89874. #endif
  89875. /* avoid malloc()ing 0 bytes, see:
  89876. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  89877. */
  89878. static FLaC__INLINE void *safe_malloc_(size_t size)
  89879. {
  89880. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89881. if(!size)
  89882. size++;
  89883. return malloc(size);
  89884. }
  89885. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  89886. {
  89887. if(!nmemb || !size)
  89888. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89889. return calloc(nmemb, size);
  89890. }
  89891. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  89892. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  89893. {
  89894. size2 += size1;
  89895. if(size2 < size1)
  89896. return 0;
  89897. return safe_malloc_(size2);
  89898. }
  89899. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  89900. {
  89901. size2 += size1;
  89902. if(size2 < size1)
  89903. return 0;
  89904. size3 += size2;
  89905. if(size3 < size2)
  89906. return 0;
  89907. return safe_malloc_(size3);
  89908. }
  89909. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  89910. {
  89911. size2 += size1;
  89912. if(size2 < size1)
  89913. return 0;
  89914. size3 += size2;
  89915. if(size3 < size2)
  89916. return 0;
  89917. size4 += size3;
  89918. if(size4 < size3)
  89919. return 0;
  89920. return safe_malloc_(size4);
  89921. }
  89922. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  89923. #if 0
  89924. needs support for cases where sizeof(size_t) != 4
  89925. {
  89926. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  89927. if(sizeof(size_t) == 4) {
  89928. if ((double)size1 * (double)size2 < 4294967296.0)
  89929. return malloc(size1*size2);
  89930. }
  89931. return 0;
  89932. }
  89933. #else
  89934. /* better? */
  89935. {
  89936. if(!size1 || !size2)
  89937. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89938. if(size1 > SIZE_MAX / size2)
  89939. return 0;
  89940. return malloc(size1*size2);
  89941. }
  89942. #endif
  89943. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  89944. {
  89945. if(!size1 || !size2 || !size3)
  89946. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89947. if(size1 > SIZE_MAX / size2)
  89948. return 0;
  89949. size1 *= size2;
  89950. if(size1 > SIZE_MAX / size3)
  89951. return 0;
  89952. return malloc(size1*size3);
  89953. }
  89954. /* size1*size2 + size3 */
  89955. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  89956. {
  89957. if(!size1 || !size2)
  89958. return safe_malloc_(size3);
  89959. if(size1 > SIZE_MAX / size2)
  89960. return 0;
  89961. return safe_malloc_add_2op_(size1*size2, size3);
  89962. }
  89963. /* size1 * (size2 + size3) */
  89964. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  89965. {
  89966. if(!size1 || (!size2 && !size3))
  89967. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89968. size2 += size3;
  89969. if(size2 < size3)
  89970. return 0;
  89971. return safe_malloc_mul_2op_(size1, size2);
  89972. }
  89973. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  89974. {
  89975. size2 += size1;
  89976. if(size2 < size1)
  89977. return 0;
  89978. return realloc(ptr, size2);
  89979. }
  89980. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  89981. {
  89982. size2 += size1;
  89983. if(size2 < size1)
  89984. return 0;
  89985. size3 += size2;
  89986. if(size3 < size2)
  89987. return 0;
  89988. return realloc(ptr, size3);
  89989. }
  89990. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  89991. {
  89992. size2 += size1;
  89993. if(size2 < size1)
  89994. return 0;
  89995. size3 += size2;
  89996. if(size3 < size2)
  89997. return 0;
  89998. size4 += size3;
  89999. if(size4 < size3)
  90000. return 0;
  90001. return realloc(ptr, size4);
  90002. }
  90003. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  90004. {
  90005. if(!size1 || !size2)
  90006. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90007. if(size1 > SIZE_MAX / size2)
  90008. return 0;
  90009. return realloc(ptr, size1*size2);
  90010. }
  90011. /* size1 * (size2 + size3) */
  90012. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  90013. {
  90014. if(!size1 || (!size2 && !size3))
  90015. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  90016. size2 += size3;
  90017. if(size2 < size3)
  90018. return 0;
  90019. return safe_realloc_mul_2op_(ptr, size1, size2);
  90020. }
  90021. #endif
  90022. /********* End of inlined file: alloc.h *********/
  90023. /* Things should be fastest when this matches the machine word size */
  90024. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  90025. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  90026. typedef FLAC__uint32 bwword;
  90027. #define FLAC__BYTES_PER_WORD 4
  90028. #define FLAC__BITS_PER_WORD 32
  90029. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  90030. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  90031. #if WORDS_BIGENDIAN
  90032. #define SWAP_BE_WORD_TO_HOST(x) (x)
  90033. #else
  90034. #ifdef _MSC_VER
  90035. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  90036. #else
  90037. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  90038. #endif
  90039. #endif
  90040. /*
  90041. * The default capacity here doesn't matter too much. The buffer always grows
  90042. * to hold whatever is written to it. Usually the encoder will stop adding at
  90043. * a frame or metadata block, then write that out and clear the buffer for the
  90044. * next one.
  90045. */
  90046. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  90047. /* When growing, increment 4K at a time */
  90048. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  90049. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  90050. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  90051. #ifdef min
  90052. #undef min
  90053. #endif
  90054. #define min(x,y) ((x)<(y)?(x):(y))
  90055. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  90056. #ifdef _MSC_VER
  90057. #define FLAC__U64L(x) x
  90058. #else
  90059. #define FLAC__U64L(x) x##LLU
  90060. #endif
  90061. #ifndef FLaC__INLINE
  90062. #define FLaC__INLINE
  90063. #endif
  90064. struct FLAC__BitWriter {
  90065. bwword *buffer;
  90066. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  90067. unsigned capacity; /* capacity of buffer in words */
  90068. unsigned words; /* # of complete words in buffer */
  90069. unsigned bits; /* # of used bits in accum */
  90070. };
  90071. /* * WATCHOUT: The current implementation only grows the buffer. */
  90072. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  90073. {
  90074. unsigned new_capacity;
  90075. bwword *new_buffer;
  90076. FLAC__ASSERT(0 != bw);
  90077. FLAC__ASSERT(0 != bw->buffer);
  90078. /* calculate total words needed to store 'bits_to_add' additional bits */
  90079. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  90080. /* it's possible (due to pessimism in the growth estimation that
  90081. * leads to this call) that we don't actually need to grow
  90082. */
  90083. if(bw->capacity >= new_capacity)
  90084. return true;
  90085. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  90086. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  90087. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90088. /* make sure we got everything right */
  90089. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  90090. FLAC__ASSERT(new_capacity > bw->capacity);
  90091. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  90092. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  90093. if(new_buffer == 0)
  90094. return false;
  90095. bw->buffer = new_buffer;
  90096. bw->capacity = new_capacity;
  90097. return true;
  90098. }
  90099. /***********************************************************************
  90100. *
  90101. * Class constructor/destructor
  90102. *
  90103. ***********************************************************************/
  90104. FLAC__BitWriter *FLAC__bitwriter_new(void)
  90105. {
  90106. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  90107. /* note that calloc() sets all members to 0 for us */
  90108. return bw;
  90109. }
  90110. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  90111. {
  90112. FLAC__ASSERT(0 != bw);
  90113. FLAC__bitwriter_free(bw);
  90114. free(bw);
  90115. }
  90116. /***********************************************************************
  90117. *
  90118. * Public class methods
  90119. *
  90120. ***********************************************************************/
  90121. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  90122. {
  90123. FLAC__ASSERT(0 != bw);
  90124. bw->words = bw->bits = 0;
  90125. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  90126. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  90127. if(bw->buffer == 0)
  90128. return false;
  90129. return true;
  90130. }
  90131. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  90132. {
  90133. FLAC__ASSERT(0 != bw);
  90134. if(0 != bw->buffer)
  90135. free(bw->buffer);
  90136. bw->buffer = 0;
  90137. bw->capacity = 0;
  90138. bw->words = bw->bits = 0;
  90139. }
  90140. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  90141. {
  90142. bw->words = bw->bits = 0;
  90143. }
  90144. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  90145. {
  90146. unsigned i, j;
  90147. if(bw == 0) {
  90148. fprintf(out, "bitwriter is NULL\n");
  90149. }
  90150. else {
  90151. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  90152. for(i = 0; i < bw->words; i++) {
  90153. fprintf(out, "%08X: ", i);
  90154. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  90155. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  90156. fprintf(out, "\n");
  90157. }
  90158. if(bw->bits > 0) {
  90159. fprintf(out, "%08X: ", i);
  90160. for(j = 0; j < bw->bits; j++)
  90161. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  90162. fprintf(out, "\n");
  90163. }
  90164. }
  90165. }
  90166. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  90167. {
  90168. const FLAC__byte *buffer;
  90169. size_t bytes;
  90170. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90171. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90172. return false;
  90173. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  90174. FLAC__bitwriter_release_buffer(bw);
  90175. return true;
  90176. }
  90177. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  90178. {
  90179. const FLAC__byte *buffer;
  90180. size_t bytes;
  90181. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  90182. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  90183. return false;
  90184. *crc = FLAC__crc8(buffer, bytes);
  90185. FLAC__bitwriter_release_buffer(bw);
  90186. return true;
  90187. }
  90188. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  90189. {
  90190. return ((bw->bits & 7) == 0);
  90191. }
  90192. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  90193. {
  90194. return FLAC__TOTAL_BITS(bw);
  90195. }
  90196. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  90197. {
  90198. FLAC__ASSERT((bw->bits & 7) == 0);
  90199. /* double protection */
  90200. if(bw->bits & 7)
  90201. return false;
  90202. /* if we have bits in the accumulator we have to flush those to the buffer first */
  90203. if(bw->bits) {
  90204. FLAC__ASSERT(bw->words <= bw->capacity);
  90205. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  90206. return false;
  90207. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  90208. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  90209. }
  90210. /* now we can just return what we have */
  90211. *buffer = (FLAC__byte*)bw->buffer;
  90212. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  90213. return true;
  90214. }
  90215. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  90216. {
  90217. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  90218. * get-mode' flag could be added everywhere and then cleared here
  90219. */
  90220. (void)bw;
  90221. }
  90222. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  90223. {
  90224. unsigned n;
  90225. FLAC__ASSERT(0 != bw);
  90226. FLAC__ASSERT(0 != bw->buffer);
  90227. if(bits == 0)
  90228. return true;
  90229. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90230. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90231. return false;
  90232. /* first part gets to word alignment */
  90233. if(bw->bits) {
  90234. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  90235. bw->accum <<= n;
  90236. bits -= n;
  90237. bw->bits += n;
  90238. if(bw->bits == FLAC__BITS_PER_WORD) {
  90239. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90240. bw->bits = 0;
  90241. }
  90242. else
  90243. return true;
  90244. }
  90245. /* do whole words */
  90246. while(bits >= FLAC__BITS_PER_WORD) {
  90247. bw->buffer[bw->words++] = 0;
  90248. bits -= FLAC__BITS_PER_WORD;
  90249. }
  90250. /* do any leftovers */
  90251. if(bits > 0) {
  90252. bw->accum = 0;
  90253. bw->bits = bits;
  90254. }
  90255. return true;
  90256. }
  90257. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  90258. {
  90259. register unsigned left;
  90260. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90261. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90262. FLAC__ASSERT(0 != bw);
  90263. FLAC__ASSERT(0 != bw->buffer);
  90264. FLAC__ASSERT(bits <= 32);
  90265. if(bits == 0)
  90266. return true;
  90267. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90268. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  90269. return false;
  90270. left = FLAC__BITS_PER_WORD - bw->bits;
  90271. if(bits < left) {
  90272. bw->accum <<= bits;
  90273. bw->accum |= val;
  90274. bw->bits += bits;
  90275. }
  90276. 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 */
  90277. bw->accum <<= left;
  90278. bw->accum |= val >> (bw->bits = bits - left);
  90279. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90280. bw->accum = val;
  90281. }
  90282. else {
  90283. bw->accum = val;
  90284. bw->bits = 0;
  90285. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  90286. }
  90287. return true;
  90288. }
  90289. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  90290. {
  90291. /* zero-out unused bits */
  90292. if(bits < 32)
  90293. val &= (~(0xffffffff << bits));
  90294. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90295. }
  90296. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  90297. {
  90298. /* this could be a little faster but it's not used for much */
  90299. if(bits > 32) {
  90300. return
  90301. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  90302. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  90303. }
  90304. else
  90305. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  90306. }
  90307. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  90308. {
  90309. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  90310. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  90311. return false;
  90312. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  90313. return false;
  90314. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  90315. return false;
  90316. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  90317. return false;
  90318. return true;
  90319. }
  90320. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  90321. {
  90322. unsigned i;
  90323. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  90324. for(i = 0; i < nvals; i++) {
  90325. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  90326. return false;
  90327. }
  90328. return true;
  90329. }
  90330. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  90331. {
  90332. if(val < 32)
  90333. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  90334. else
  90335. return
  90336. FLAC__bitwriter_write_zeroes(bw, val) &&
  90337. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  90338. }
  90339. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  90340. {
  90341. FLAC__uint32 uval;
  90342. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  90343. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90344. uval = (val<<1) ^ (val>>31);
  90345. return 1 + parameter + (uval >> parameter);
  90346. }
  90347. #if 0 /* UNUSED */
  90348. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  90349. {
  90350. unsigned bits, msbs, uval;
  90351. unsigned k;
  90352. FLAC__ASSERT(parameter > 0);
  90353. /* fold signed to unsigned */
  90354. if(val < 0)
  90355. uval = (unsigned)(((-(++val)) << 1) + 1);
  90356. else
  90357. uval = (unsigned)(val << 1);
  90358. k = FLAC__bitmath_ilog2(parameter);
  90359. if(parameter == 1u<<k) {
  90360. FLAC__ASSERT(k <= 30);
  90361. msbs = uval >> k;
  90362. bits = 1 + k + msbs;
  90363. }
  90364. else {
  90365. unsigned q, r, d;
  90366. d = (1 << (k+1)) - parameter;
  90367. q = uval / parameter;
  90368. r = uval - (q * parameter);
  90369. bits = 1 + q + k;
  90370. if(r >= d)
  90371. bits++;
  90372. }
  90373. return bits;
  90374. }
  90375. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  90376. {
  90377. unsigned bits, msbs;
  90378. unsigned k;
  90379. FLAC__ASSERT(parameter > 0);
  90380. k = FLAC__bitmath_ilog2(parameter);
  90381. if(parameter == 1u<<k) {
  90382. FLAC__ASSERT(k <= 30);
  90383. msbs = uval >> k;
  90384. bits = 1 + k + msbs;
  90385. }
  90386. else {
  90387. unsigned q, r, d;
  90388. d = (1 << (k+1)) - parameter;
  90389. q = uval / parameter;
  90390. r = uval - (q * parameter);
  90391. bits = 1 + q + k;
  90392. if(r >= d)
  90393. bits++;
  90394. }
  90395. return bits;
  90396. }
  90397. #endif /* UNUSED */
  90398. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  90399. {
  90400. unsigned total_bits, interesting_bits, msbs;
  90401. FLAC__uint32 uval, pattern;
  90402. FLAC__ASSERT(0 != bw);
  90403. FLAC__ASSERT(0 != bw->buffer);
  90404. FLAC__ASSERT(parameter < 8*sizeof(uval));
  90405. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90406. uval = (val<<1) ^ (val>>31);
  90407. msbs = uval >> parameter;
  90408. interesting_bits = 1 + parameter;
  90409. total_bits = interesting_bits + msbs;
  90410. pattern = 1 << parameter; /* the unary end bit */
  90411. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  90412. if(total_bits <= 32)
  90413. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  90414. else
  90415. return
  90416. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  90417. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  90418. }
  90419. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  90420. {
  90421. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  90422. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  90423. FLAC__uint32 uval;
  90424. unsigned left;
  90425. const unsigned lsbits = 1 + parameter;
  90426. unsigned msbits;
  90427. FLAC__ASSERT(0 != bw);
  90428. FLAC__ASSERT(0 != bw->buffer);
  90429. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  90430. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  90431. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  90432. while(nvals) {
  90433. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  90434. uval = (*vals<<1) ^ (*vals>>31);
  90435. msbits = uval >> parameter;
  90436. #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) */
  90437. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90438. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90439. bw->bits = bw->bits + msbits + lsbits;
  90440. uval |= mask1; /* set stop bit */
  90441. uval &= mask2; /* mask off unused top bits */
  90442. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  90443. bw->accum <<= msbits;
  90444. bw->accum <<= lsbits;
  90445. bw->accum |= uval;
  90446. if(bw->bits == FLAC__BITS_PER_WORD) {
  90447. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90448. bw->bits = 0;
  90449. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  90450. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  90451. FLAC__ASSERT(bw->capacity == bw->words);
  90452. return false;
  90453. }
  90454. }
  90455. }
  90456. else {
  90457. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  90458. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  90459. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  90460. bw->bits = bw->bits + msbits + lsbits;
  90461. uval |= mask1; /* set stop bit */
  90462. uval &= mask2; /* mask off unused top bits */
  90463. bw->accum <<= msbits + lsbits;
  90464. bw->accum |= uval;
  90465. }
  90466. else {
  90467. #endif
  90468. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  90469. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  90470. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  90471. return false;
  90472. if(msbits) {
  90473. /* first part gets to word alignment */
  90474. if(bw->bits) {
  90475. left = FLAC__BITS_PER_WORD - bw->bits;
  90476. if(msbits < left) {
  90477. bw->accum <<= msbits;
  90478. bw->bits += msbits;
  90479. goto break1;
  90480. }
  90481. else {
  90482. bw->accum <<= left;
  90483. msbits -= left;
  90484. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90485. bw->bits = 0;
  90486. }
  90487. }
  90488. /* do whole words */
  90489. while(msbits >= FLAC__BITS_PER_WORD) {
  90490. bw->buffer[bw->words++] = 0;
  90491. msbits -= FLAC__BITS_PER_WORD;
  90492. }
  90493. /* do any leftovers */
  90494. if(msbits > 0) {
  90495. bw->accum = 0;
  90496. bw->bits = msbits;
  90497. }
  90498. }
  90499. break1:
  90500. uval |= mask1; /* set stop bit */
  90501. uval &= mask2; /* mask off unused top bits */
  90502. left = FLAC__BITS_PER_WORD - bw->bits;
  90503. if(lsbits < left) {
  90504. bw->accum <<= lsbits;
  90505. bw->accum |= uval;
  90506. bw->bits += lsbits;
  90507. }
  90508. else {
  90509. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  90510. * be > lsbits (because of previous assertions) so it would have
  90511. * triggered the (lsbits<left) case above.
  90512. */
  90513. FLAC__ASSERT(bw->bits);
  90514. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  90515. bw->accum <<= left;
  90516. bw->accum |= uval >> (bw->bits = lsbits - left);
  90517. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  90518. bw->accum = uval;
  90519. }
  90520. #if 1
  90521. }
  90522. #endif
  90523. vals++;
  90524. nvals--;
  90525. }
  90526. return true;
  90527. }
  90528. #if 0 /* UNUSED */
  90529. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  90530. {
  90531. unsigned total_bits, msbs, uval;
  90532. unsigned k;
  90533. FLAC__ASSERT(0 != bw);
  90534. FLAC__ASSERT(0 != bw->buffer);
  90535. FLAC__ASSERT(parameter > 0);
  90536. /* fold signed to unsigned */
  90537. if(val < 0)
  90538. uval = (unsigned)(((-(++val)) << 1) + 1);
  90539. else
  90540. uval = (unsigned)(val << 1);
  90541. k = FLAC__bitmath_ilog2(parameter);
  90542. if(parameter == 1u<<k) {
  90543. unsigned pattern;
  90544. FLAC__ASSERT(k <= 30);
  90545. msbs = uval >> k;
  90546. total_bits = 1 + k + msbs;
  90547. pattern = 1 << k; /* the unary end bit */
  90548. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90549. if(total_bits <= 32) {
  90550. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90551. return false;
  90552. }
  90553. else {
  90554. /* write the unary MSBs */
  90555. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90556. return false;
  90557. /* write the unary end bit and binary LSBs */
  90558. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90559. return false;
  90560. }
  90561. }
  90562. else {
  90563. unsigned q, r, d;
  90564. d = (1 << (k+1)) - parameter;
  90565. q = uval / parameter;
  90566. r = uval - (q * parameter);
  90567. /* write the unary MSBs */
  90568. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90569. return false;
  90570. /* write the unary end bit */
  90571. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90572. return false;
  90573. /* write the binary LSBs */
  90574. if(r >= d) {
  90575. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90576. return false;
  90577. }
  90578. else {
  90579. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90580. return false;
  90581. }
  90582. }
  90583. return true;
  90584. }
  90585. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90586. {
  90587. unsigned total_bits, msbs;
  90588. unsigned k;
  90589. FLAC__ASSERT(0 != bw);
  90590. FLAC__ASSERT(0 != bw->buffer);
  90591. FLAC__ASSERT(parameter > 0);
  90592. k = FLAC__bitmath_ilog2(parameter);
  90593. if(parameter == 1u<<k) {
  90594. unsigned pattern;
  90595. FLAC__ASSERT(k <= 30);
  90596. msbs = uval >> k;
  90597. total_bits = 1 + k + msbs;
  90598. pattern = 1 << k; /* the unary end bit */
  90599. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90600. if(total_bits <= 32) {
  90601. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90602. return false;
  90603. }
  90604. else {
  90605. /* write the unary MSBs */
  90606. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90607. return false;
  90608. /* write the unary end bit and binary LSBs */
  90609. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90610. return false;
  90611. }
  90612. }
  90613. else {
  90614. unsigned q, r, d;
  90615. d = (1 << (k+1)) - parameter;
  90616. q = uval / parameter;
  90617. r = uval - (q * parameter);
  90618. /* write the unary MSBs */
  90619. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90620. return false;
  90621. /* write the unary end bit */
  90622. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90623. return false;
  90624. /* write the binary LSBs */
  90625. if(r >= d) {
  90626. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90627. return false;
  90628. }
  90629. else {
  90630. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90631. return false;
  90632. }
  90633. }
  90634. return true;
  90635. }
  90636. #endif /* UNUSED */
  90637. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90638. {
  90639. FLAC__bool ok = 1;
  90640. FLAC__ASSERT(0 != bw);
  90641. FLAC__ASSERT(0 != bw->buffer);
  90642. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90643. if(val < 0x80) {
  90644. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90645. }
  90646. else if(val < 0x800) {
  90647. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90648. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90649. }
  90650. else if(val < 0x10000) {
  90651. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90652. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90653. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90654. }
  90655. else if(val < 0x200000) {
  90656. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90657. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90658. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90659. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90660. }
  90661. else if(val < 0x4000000) {
  90662. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90663. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90664. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90665. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90666. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90667. }
  90668. else {
  90669. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90670. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90671. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90672. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90673. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90674. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90675. }
  90676. return ok;
  90677. }
  90678. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90679. {
  90680. FLAC__bool ok = 1;
  90681. FLAC__ASSERT(0 != bw);
  90682. FLAC__ASSERT(0 != bw->buffer);
  90683. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90684. if(val < 0x80) {
  90685. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90686. }
  90687. else if(val < 0x800) {
  90688. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90689. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90690. }
  90691. else if(val < 0x10000) {
  90692. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90693. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90694. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90695. }
  90696. else if(val < 0x200000) {
  90697. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90698. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90699. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90700. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90701. }
  90702. else if(val < 0x4000000) {
  90703. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90704. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90705. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90706. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90707. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90708. }
  90709. else if(val < 0x80000000) {
  90710. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90711. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90712. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90713. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90714. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90715. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90716. }
  90717. else {
  90718. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90719. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90720. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90721. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 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. return ok;
  90727. }
  90728. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90729. {
  90730. /* 0-pad to byte boundary */
  90731. if(bw->bits & 7u)
  90732. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90733. else
  90734. return true;
  90735. }
  90736. #endif
  90737. /********* End of inlined file: bitwriter.c *********/
  90738. /********* Start of inlined file: cpu.c *********/
  90739. /********* Start of inlined file: juce_FlacHeader.h *********/
  90740. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90741. // tasks..
  90742. #define VERSION "1.2.1"
  90743. #define FLAC__NO_DLL 1
  90744. #ifdef _MSC_VER
  90745. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90746. #endif
  90747. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90748. #define FLAC__SYS_DARWIN 1
  90749. #endif
  90750. /********* End of inlined file: juce_FlacHeader.h *********/
  90751. #if JUCE_USE_FLAC
  90752. #if HAVE_CONFIG_H
  90753. # include <config.h>
  90754. #endif
  90755. #include <stdlib.h>
  90756. #include <stdio.h>
  90757. #if defined FLAC__CPU_IA32
  90758. # include <signal.h>
  90759. #elif defined FLAC__CPU_PPC
  90760. # if !defined FLAC__NO_ASM
  90761. # if defined FLAC__SYS_DARWIN
  90762. # include <sys/sysctl.h>
  90763. # include <mach/mach.h>
  90764. # include <mach/mach_host.h>
  90765. # include <mach/host_info.h>
  90766. # include <mach/machine.h>
  90767. # ifndef CPU_SUBTYPE_POWERPC_970
  90768. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90769. # endif
  90770. # else /* FLAC__SYS_DARWIN */
  90771. # include <signal.h>
  90772. # include <setjmp.h>
  90773. static sigjmp_buf jmpbuf;
  90774. static volatile sig_atomic_t canjump = 0;
  90775. static void sigill_handler (int sig)
  90776. {
  90777. if (!canjump) {
  90778. signal (sig, SIG_DFL);
  90779. raise (sig);
  90780. }
  90781. canjump = 0;
  90782. siglongjmp (jmpbuf, 1);
  90783. }
  90784. # endif /* FLAC__SYS_DARWIN */
  90785. # endif /* FLAC__NO_ASM */
  90786. #endif /* FLAC__CPU_PPC */
  90787. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90788. #include <sys/param.h>
  90789. #include <sys/sysctl.h>
  90790. #include <machine/cpu.h>
  90791. #endif
  90792. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90793. #include <sys/types.h>
  90794. #include <sys/sysctl.h>
  90795. #endif
  90796. #if defined(__APPLE__)
  90797. /* how to get sysctlbyname()? */
  90798. #endif
  90799. /* these are flags in EDX of CPUID AX=00000001 */
  90800. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90801. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90802. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90803. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90804. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90805. /* these are flags in ECX of CPUID AX=00000001 */
  90806. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90807. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90808. /* these are flags in EDX of CPUID AX=80000001 */
  90809. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90810. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90811. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90812. /*
  90813. * Extra stuff needed for detection of OS support for SSE on IA-32
  90814. */
  90815. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90816. # if defined(__linux__)
  90817. /*
  90818. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90819. * modify the return address to jump over the offending SSE instruction
  90820. * and also the operation following it that indicates the instruction
  90821. * executed successfully. In this way we use no global variables and
  90822. * stay thread-safe.
  90823. *
  90824. * 3 + 3 + 6:
  90825. * 3 bytes for "xorps xmm0,xmm0"
  90826. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90827. * 6 bytes extra in case our estimate is wrong
  90828. * 12 bytes puts us in the NOP "landing zone"
  90829. */
  90830. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90831. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90832. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90833. {
  90834. (void)signal;
  90835. sc.eip += 3 + 3 + 6;
  90836. }
  90837. # else
  90838. # include <sys/ucontext.h>
  90839. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90840. {
  90841. (void)signal, (void)si;
  90842. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90843. }
  90844. # endif
  90845. # elif defined(_MSC_VER)
  90846. # include <windows.h>
  90847. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90848. # ifdef USE_TRY_CATCH_FLAVOR
  90849. # else
  90850. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  90851. {
  90852. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  90853. ep->ContextRecord->Eip += 3 + 3 + 6;
  90854. return EXCEPTION_CONTINUE_EXECUTION;
  90855. }
  90856. return EXCEPTION_CONTINUE_SEARCH;
  90857. }
  90858. # endif
  90859. # endif
  90860. #endif
  90861. void FLAC__cpu_info(FLAC__CPUInfo *info)
  90862. {
  90863. /*
  90864. * IA32-specific
  90865. */
  90866. #ifdef FLAC__CPU_IA32
  90867. info->type = FLAC__CPUINFO_TYPE_IA32;
  90868. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  90869. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  90870. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  90871. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  90872. info->data.ia32.cmov = false;
  90873. info->data.ia32.mmx = false;
  90874. info->data.ia32.fxsr = false;
  90875. info->data.ia32.sse = false;
  90876. info->data.ia32.sse2 = false;
  90877. info->data.ia32.sse3 = false;
  90878. info->data.ia32.ssse3 = false;
  90879. info->data.ia32._3dnow = false;
  90880. info->data.ia32.ext3dnow = false;
  90881. info->data.ia32.extmmx = false;
  90882. if(info->data.ia32.cpuid) {
  90883. /* http://www.sandpile.org/ia32/cpuid.htm */
  90884. FLAC__uint32 flags_edx, flags_ecx;
  90885. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  90886. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  90887. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  90888. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  90889. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  90890. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  90891. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  90892. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  90893. #ifdef FLAC__USE_3DNOW
  90894. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  90895. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  90896. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  90897. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  90898. #else
  90899. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  90900. #endif
  90901. #ifdef DEBUG
  90902. fprintf(stderr, "CPU info (IA-32):\n");
  90903. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  90904. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  90905. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  90906. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  90907. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  90908. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90909. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  90910. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  90911. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  90912. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  90913. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  90914. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  90915. #endif
  90916. /*
  90917. * now have to check for OS support of SSE/SSE2
  90918. */
  90919. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  90920. #if defined FLAC__NO_SSE_OS
  90921. /* assume user knows better than us; turn it off */
  90922. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90923. #elif defined FLAC__SSE_OS
  90924. /* assume user knows better than us; leave as detected above */
  90925. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  90926. int sse = 0;
  90927. size_t len;
  90928. /* at least one of these must work: */
  90929. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  90930. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  90931. if(!sse)
  90932. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90933. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  90934. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  90935. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  90936. size_t len = sizeof(val);
  90937. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90938. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90939. else { /* double-check SSE2 */
  90940. mib[1] = CPU_SSE2;
  90941. len = sizeof(val);
  90942. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90943. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90944. }
  90945. # else
  90946. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90947. # endif
  90948. #elif defined(__linux__)
  90949. int sse = 0;
  90950. struct sigaction sigill_save;
  90951. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90952. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  90953. #else
  90954. struct sigaction sigill_sse;
  90955. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  90956. __sigemptyset(&sigill_sse.sa_mask);
  90957. 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 */
  90958. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  90959. #endif
  90960. {
  90961. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  90962. /* see sigill_handler_sse_os() for an explanation of the following: */
  90963. asm volatile (
  90964. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  90965. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  90966. "incl %0\n\t" /* SIGILL handler will jump over this */
  90967. /* landing zone */
  90968. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  90969. "nop\n\t"
  90970. "nop\n\t"
  90971. "nop\n\t"
  90972. "nop\n\t"
  90973. "nop\n\t"
  90974. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  90975. "nop\n\t"
  90976. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  90977. : "=r"(sse)
  90978. : "r"(sse)
  90979. );
  90980. sigaction(SIGILL, &sigill_save, NULL);
  90981. }
  90982. if(!sse)
  90983. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90984. #elif defined(_MSC_VER)
  90985. # ifdef USE_TRY_CATCH_FLAVOR
  90986. _try {
  90987. __asm {
  90988. # if _MSC_VER <= 1200
  90989. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90990. _emit 0x0F
  90991. _emit 0x57
  90992. _emit 0xC0
  90993. # else
  90994. xorps xmm0,xmm0
  90995. # endif
  90996. }
  90997. }
  90998. _except(EXCEPTION_EXECUTE_HANDLER) {
  90999. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  91000. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91001. }
  91002. # else
  91003. int sse = 0;
  91004. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  91005. /* see GCC version above for explanation */
  91006. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  91007. /* http://www.codeproject.com/cpp/gccasm.asp */
  91008. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  91009. __asm {
  91010. # if _MSC_VER <= 1200
  91011. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  91012. _emit 0x0F
  91013. _emit 0x57
  91014. _emit 0xC0
  91015. # else
  91016. xorps xmm0,xmm0
  91017. # endif
  91018. inc sse
  91019. nop
  91020. nop
  91021. nop
  91022. nop
  91023. nop
  91024. nop
  91025. nop
  91026. nop
  91027. nop
  91028. }
  91029. SetUnhandledExceptionFilter(save);
  91030. if(!sse)
  91031. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91032. # endif
  91033. #else
  91034. /* no way to test, disable to be safe */
  91035. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  91036. #endif
  91037. #ifdef DEBUG
  91038. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  91039. #endif
  91040. }
  91041. }
  91042. #else
  91043. info->use_asm = false;
  91044. #endif
  91045. /*
  91046. * PPC-specific
  91047. */
  91048. #elif defined FLAC__CPU_PPC
  91049. info->type = FLAC__CPUINFO_TYPE_PPC;
  91050. # if !defined FLAC__NO_ASM
  91051. info->use_asm = true;
  91052. # ifdef FLAC__USE_ALTIVEC
  91053. # if defined FLAC__SYS_DARWIN
  91054. {
  91055. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  91056. size_t len = sizeof(val);
  91057. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  91058. }
  91059. {
  91060. host_basic_info_data_t hostInfo;
  91061. mach_msg_type_number_t infoCount;
  91062. infoCount = HOST_BASIC_INFO_COUNT;
  91063. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  91064. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  91065. }
  91066. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  91067. {
  91068. /* no Darwin, do it the brute-force way */
  91069. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  91070. info->data.ppc.altivec = 0;
  91071. info->data.ppc.ppc64 = 0;
  91072. signal (SIGILL, sigill_handler);
  91073. canjump = 0;
  91074. if (!sigsetjmp (jmpbuf, 1)) {
  91075. canjump = 1;
  91076. asm volatile (
  91077. "mtspr 256, %0\n\t"
  91078. "vand %%v0, %%v0, %%v0"
  91079. :
  91080. : "r" (-1)
  91081. );
  91082. info->data.ppc.altivec = 1;
  91083. }
  91084. canjump = 0;
  91085. if (!sigsetjmp (jmpbuf, 1)) {
  91086. int x = 0;
  91087. canjump = 1;
  91088. /* PPC64 hardware implements the cntlzd instruction */
  91089. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  91090. info->data.ppc.ppc64 = 1;
  91091. }
  91092. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  91093. }
  91094. # endif
  91095. # else /* !FLAC__USE_ALTIVEC */
  91096. info->data.ppc.altivec = 0;
  91097. info->data.ppc.ppc64 = 0;
  91098. # endif
  91099. # else
  91100. info->use_asm = false;
  91101. # endif
  91102. /*
  91103. * unknown CPI
  91104. */
  91105. #else
  91106. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  91107. info->use_asm = false;
  91108. #endif
  91109. }
  91110. #endif
  91111. /********* End of inlined file: cpu.c *********/
  91112. /********* Start of inlined file: crc.c *********/
  91113. /********* Start of inlined file: juce_FlacHeader.h *********/
  91114. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91115. // tasks..
  91116. #define VERSION "1.2.1"
  91117. #define FLAC__NO_DLL 1
  91118. #ifdef _MSC_VER
  91119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91120. #endif
  91121. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91122. #define FLAC__SYS_DARWIN 1
  91123. #endif
  91124. /********* End of inlined file: juce_FlacHeader.h *********/
  91125. #if JUCE_USE_FLAC
  91126. #if HAVE_CONFIG_H
  91127. # include <config.h>
  91128. #endif
  91129. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  91130. FLAC__byte const FLAC__crc8_table[256] = {
  91131. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  91132. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  91133. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  91134. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  91135. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  91136. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  91137. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  91138. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  91139. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  91140. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  91141. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  91142. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  91143. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  91144. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  91145. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  91146. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  91147. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  91148. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  91149. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  91150. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  91151. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  91152. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  91153. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  91154. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  91155. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  91156. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  91157. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  91158. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  91159. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  91160. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  91161. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  91162. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  91163. };
  91164. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  91165. unsigned FLAC__crc16_table[256] = {
  91166. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  91167. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  91168. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  91169. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  91170. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  91171. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  91172. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  91173. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  91174. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  91175. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  91176. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  91177. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  91178. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  91179. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  91180. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  91181. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  91182. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  91183. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  91184. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  91185. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  91186. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  91187. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  91188. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  91189. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  91190. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  91191. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  91192. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  91193. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  91194. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  91195. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  91196. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  91197. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  91198. };
  91199. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  91200. {
  91201. *crc = FLAC__crc8_table[*crc ^ data];
  91202. }
  91203. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  91204. {
  91205. while(len--)
  91206. *crc = FLAC__crc8_table[*crc ^ *data++];
  91207. }
  91208. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  91209. {
  91210. FLAC__uint8 crc = 0;
  91211. while(len--)
  91212. crc = FLAC__crc8_table[crc ^ *data++];
  91213. return crc;
  91214. }
  91215. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  91216. {
  91217. unsigned crc = 0;
  91218. while(len--)
  91219. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  91220. return crc;
  91221. }
  91222. #endif
  91223. /********* End of inlined file: crc.c *********/
  91224. /********* Start of inlined file: fixed.c *********/
  91225. /********* Start of inlined file: juce_FlacHeader.h *********/
  91226. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91227. // tasks..
  91228. #define VERSION "1.2.1"
  91229. #define FLAC__NO_DLL 1
  91230. #ifdef _MSC_VER
  91231. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91232. #endif
  91233. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91234. #define FLAC__SYS_DARWIN 1
  91235. #endif
  91236. /********* End of inlined file: juce_FlacHeader.h *********/
  91237. #if JUCE_USE_FLAC
  91238. #if HAVE_CONFIG_H
  91239. # include <config.h>
  91240. #endif
  91241. #include <math.h>
  91242. #include <string.h>
  91243. /********* Start of inlined file: fixed.h *********/
  91244. #ifndef FLAC__PRIVATE__FIXED_H
  91245. #define FLAC__PRIVATE__FIXED_H
  91246. #ifdef HAVE_CONFIG_H
  91247. #include <config.h>
  91248. #endif
  91249. /********* Start of inlined file: float.h *********/
  91250. #ifndef FLAC__PRIVATE__FLOAT_H
  91251. #define FLAC__PRIVATE__FLOAT_H
  91252. #ifdef HAVE_CONFIG_H
  91253. #include <config.h>
  91254. #endif
  91255. /*
  91256. * These typedefs make it easier to ensure that integer versions of
  91257. * the library really only contain integer operations. All the code
  91258. * in libFLAC should use FLAC__float and FLAC__double in place of
  91259. * float and double, and be protected by checks of the macro
  91260. * FLAC__INTEGER_ONLY_LIBRARY.
  91261. *
  91262. * FLAC__real is the basic floating point type used in LPC analysis.
  91263. */
  91264. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91265. typedef double FLAC__double;
  91266. typedef float FLAC__float;
  91267. /*
  91268. * WATCHOUT: changing FLAC__real will change the signatures of many
  91269. * functions that have assembly language equivalents and break them.
  91270. */
  91271. typedef float FLAC__real;
  91272. #else
  91273. /*
  91274. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  91275. * for the integer part and lower 16 bits for the fractional part.
  91276. */
  91277. typedef FLAC__int32 FLAC__fixedpoint;
  91278. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  91279. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  91280. extern const FLAC__fixedpoint FLAC__FP_ONE;
  91281. extern const FLAC__fixedpoint FLAC__FP_LN2;
  91282. extern const FLAC__fixedpoint FLAC__FP_E;
  91283. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  91284. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  91285. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  91286. /*
  91287. * FLAC__fixedpoint_log2()
  91288. * --------------------------------------------------------------------
  91289. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  91290. * algorithm by Knuth for x >= 1.0
  91291. *
  91292. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  91293. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  91294. *
  91295. * 'precision' roughly limits the number of iterations that are done;
  91296. * use (unsigned)(-1) for maximum precision.
  91297. *
  91298. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  91299. * function will punt and return 0.
  91300. *
  91301. * The return value will also have 'fracbits' fractional bits.
  91302. */
  91303. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  91304. #endif
  91305. #endif
  91306. /********* End of inlined file: float.h *********/
  91307. /********* Start of inlined file: format.h *********/
  91308. #ifndef FLAC__PRIVATE__FORMAT_H
  91309. #define FLAC__PRIVATE__FORMAT_H
  91310. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  91311. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  91312. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  91313. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91314. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91315. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  91316. #endif
  91317. /********* End of inlined file: format.h *********/
  91318. /*
  91319. * FLAC__fixed_compute_best_predictor()
  91320. * --------------------------------------------------------------------
  91321. * Compute the best fixed predictor and the expected bits-per-sample
  91322. * of the residual signal for each order. The _wide() version uses
  91323. * 64-bit integers which is statistically necessary when bits-per-
  91324. * sample + log2(blocksize) > 30
  91325. *
  91326. * IN data[0,data_len-1]
  91327. * IN data_len
  91328. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  91329. */
  91330. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91331. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91332. # ifndef FLAC__NO_ASM
  91333. # ifdef FLAC__CPU_IA32
  91334. # ifdef FLAC__HAS_NASM
  91335. 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]);
  91336. # endif
  91337. # endif
  91338. # endif
  91339. 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]);
  91340. #else
  91341. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91342. 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]);
  91343. #endif
  91344. /*
  91345. * FLAC__fixed_compute_residual()
  91346. * --------------------------------------------------------------------
  91347. * Compute the residual signal obtained from sutracting the predicted
  91348. * signal from the original.
  91349. *
  91350. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91351. * IN data_len length of original signal
  91352. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91353. * OUT residual[0,data_len-1] residual signal
  91354. */
  91355. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  91356. /*
  91357. * FLAC__fixed_restore_signal()
  91358. * --------------------------------------------------------------------
  91359. * Restore the original signal by summing the residual and the
  91360. * predictor.
  91361. *
  91362. * IN residual[0,data_len-1] residual signal
  91363. * IN data_len length of original signal
  91364. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91365. * *** IMPORTANT: the caller must pass in the historical samples:
  91366. * IN data[-order,-1] previously-reconstructed historical samples
  91367. * OUT data[0,data_len-1] original signal
  91368. */
  91369. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  91370. #endif
  91371. /********* End of inlined file: fixed.h *********/
  91372. #ifndef M_LN2
  91373. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91374. #define M_LN2 0.69314718055994530942
  91375. #endif
  91376. #ifdef min
  91377. #undef min
  91378. #endif
  91379. #define min(x,y) ((x) < (y)? (x) : (y))
  91380. #ifdef local_abs
  91381. #undef local_abs
  91382. #endif
  91383. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  91384. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91385. /* rbps stands for residual bits per sample
  91386. *
  91387. * (ln(2) * err)
  91388. * rbps = log (-----------)
  91389. * 2 ( n )
  91390. */
  91391. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  91392. {
  91393. FLAC__uint32 rbps;
  91394. unsigned bits; /* the number of bits required to represent a number */
  91395. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91396. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91397. FLAC__ASSERT(err > 0);
  91398. FLAC__ASSERT(n > 0);
  91399. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91400. if(err <= n)
  91401. return 0;
  91402. /*
  91403. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91404. * These allow us later to know we won't lose too much precision in the
  91405. * fixed-point division (err<<fracbits)/n.
  91406. */
  91407. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  91408. err <<= fracbits;
  91409. err /= n;
  91410. /* err now holds err/n with fracbits fractional bits */
  91411. /*
  91412. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91413. * our purposes.
  91414. */
  91415. FLAC__ASSERT(err > 0);
  91416. bits = FLAC__bitmath_ilog2(err)+1;
  91417. if(bits > 16) {
  91418. err >>= (bits-16);
  91419. fracbits -= (bits-16);
  91420. }
  91421. rbps = (FLAC__uint32)err;
  91422. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91423. rbps *= FLAC__FP_LN2;
  91424. fracbits += 16;
  91425. FLAC__ASSERT(fracbits >= 0);
  91426. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91427. {
  91428. const int f = fracbits & 3;
  91429. if(f) {
  91430. rbps >>= f;
  91431. fracbits -= f;
  91432. }
  91433. }
  91434. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91435. if(rbps == 0)
  91436. return 0;
  91437. /*
  91438. * The return value must have 16 fractional bits. Since the whole part
  91439. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91440. * must be >= -3, these assertion allows us to be able to shift rbps
  91441. * left if necessary to get 16 fracbits without losing any bits of the
  91442. * whole part of rbps.
  91443. *
  91444. * There is a slight chance due to accumulated error that the whole part
  91445. * will require 6 bits, so we use 6 in the assertion. Really though as
  91446. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91447. */
  91448. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91449. FLAC__ASSERT(fracbits >= -3);
  91450. /* now shift the decimal point into place */
  91451. if(fracbits < 16)
  91452. return rbps << (16-fracbits);
  91453. else if(fracbits > 16)
  91454. return rbps >> (fracbits-16);
  91455. else
  91456. return rbps;
  91457. }
  91458. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  91459. {
  91460. FLAC__uint32 rbps;
  91461. unsigned bits; /* the number of bits required to represent a number */
  91462. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91463. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91464. FLAC__ASSERT(err > 0);
  91465. FLAC__ASSERT(n > 0);
  91466. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91467. if(err <= n)
  91468. return 0;
  91469. /*
  91470. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91471. * These allow us later to know we won't lose too much precision in the
  91472. * fixed-point division (err<<fracbits)/n.
  91473. */
  91474. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  91475. err <<= fracbits;
  91476. err /= n;
  91477. /* err now holds err/n with fracbits fractional bits */
  91478. /*
  91479. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91480. * our purposes.
  91481. */
  91482. FLAC__ASSERT(err > 0);
  91483. bits = FLAC__bitmath_ilog2_wide(err)+1;
  91484. if(bits > 16) {
  91485. err >>= (bits-16);
  91486. fracbits -= (bits-16);
  91487. }
  91488. rbps = (FLAC__uint32)err;
  91489. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91490. rbps *= FLAC__FP_LN2;
  91491. fracbits += 16;
  91492. FLAC__ASSERT(fracbits >= 0);
  91493. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91494. {
  91495. const int f = fracbits & 3;
  91496. if(f) {
  91497. rbps >>= f;
  91498. fracbits -= f;
  91499. }
  91500. }
  91501. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91502. if(rbps == 0)
  91503. return 0;
  91504. /*
  91505. * The return value must have 16 fractional bits. Since the whole part
  91506. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91507. * must be >= -3, these assertion allows us to be able to shift rbps
  91508. * left if necessary to get 16 fracbits without losing any bits of the
  91509. * whole part of rbps.
  91510. *
  91511. * There is a slight chance due to accumulated error that the whole part
  91512. * will require 6 bits, so we use 6 in the assertion. Really though as
  91513. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91514. */
  91515. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91516. FLAC__ASSERT(fracbits >= -3);
  91517. /* now shift the decimal point into place */
  91518. if(fracbits < 16)
  91519. return rbps << (16-fracbits);
  91520. else if(fracbits > 16)
  91521. return rbps >> (fracbits-16);
  91522. else
  91523. return rbps;
  91524. }
  91525. #endif
  91526. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91527. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91528. #else
  91529. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91530. #endif
  91531. {
  91532. FLAC__int32 last_error_0 = data[-1];
  91533. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91534. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91535. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91536. FLAC__int32 error, save;
  91537. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91538. unsigned i, order;
  91539. for(i = 0; i < data_len; i++) {
  91540. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91541. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91542. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91543. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91544. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91545. }
  91546. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91547. order = 0;
  91548. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91549. order = 1;
  91550. else if(total_error_2 < min(total_error_3, total_error_4))
  91551. order = 2;
  91552. else if(total_error_3 < total_error_4)
  91553. order = 3;
  91554. else
  91555. order = 4;
  91556. /* Estimate the expected number of bits per residual signal sample. */
  91557. /* 'total_error*' is linearly related to the variance of the residual */
  91558. /* signal, so we use it directly to compute E(|x|) */
  91559. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91560. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91561. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91562. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91563. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91564. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91565. 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);
  91566. 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);
  91567. 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);
  91568. 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);
  91569. 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);
  91570. #else
  91571. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91572. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91573. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91574. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91575. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91576. #endif
  91577. return order;
  91578. }
  91579. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91580. 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])
  91581. #else
  91582. 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])
  91583. #endif
  91584. {
  91585. FLAC__int32 last_error_0 = data[-1];
  91586. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91587. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91588. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91589. FLAC__int32 error, save;
  91590. /* total_error_* are 64-bits to avoid overflow when encoding
  91591. * erratic signals when the bits-per-sample and blocksize are
  91592. * large.
  91593. */
  91594. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91595. unsigned i, order;
  91596. for(i = 0; i < data_len; i++) {
  91597. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91598. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91599. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91600. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91601. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91602. }
  91603. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91604. order = 0;
  91605. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91606. order = 1;
  91607. else if(total_error_2 < min(total_error_3, total_error_4))
  91608. order = 2;
  91609. else if(total_error_3 < total_error_4)
  91610. order = 3;
  91611. else
  91612. order = 4;
  91613. /* Estimate the expected number of bits per residual signal sample. */
  91614. /* 'total_error*' is linearly related to the variance of the residual */
  91615. /* signal, so we use it directly to compute E(|x|) */
  91616. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91617. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91618. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91619. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91620. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91621. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91622. #if defined _MSC_VER || defined __MINGW32__
  91623. /* with MSVC you have to spoon feed it the casting */
  91624. 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);
  91625. 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);
  91626. 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);
  91627. 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);
  91628. 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);
  91629. #else
  91630. 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);
  91631. 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);
  91632. 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);
  91633. 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);
  91634. 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);
  91635. #endif
  91636. #else
  91637. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91638. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91639. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91640. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91641. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91642. #endif
  91643. return order;
  91644. }
  91645. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91646. {
  91647. const int idata_len = (int)data_len;
  91648. int i;
  91649. switch(order) {
  91650. case 0:
  91651. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91652. memcpy(residual, data, sizeof(residual[0])*data_len);
  91653. break;
  91654. case 1:
  91655. for(i = 0; i < idata_len; i++)
  91656. residual[i] = data[i] - data[i-1];
  91657. break;
  91658. case 2:
  91659. for(i = 0; i < idata_len; i++)
  91660. #if 1 /* OPT: may be faster with some compilers on some systems */
  91661. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91662. #else
  91663. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91664. #endif
  91665. break;
  91666. case 3:
  91667. for(i = 0; i < idata_len; i++)
  91668. #if 1 /* OPT: may be faster with some compilers on some systems */
  91669. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91670. #else
  91671. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91672. #endif
  91673. break;
  91674. case 4:
  91675. for(i = 0; i < idata_len; i++)
  91676. #if 1 /* OPT: may be faster with some compilers on some systems */
  91677. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91678. #else
  91679. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91680. #endif
  91681. break;
  91682. default:
  91683. FLAC__ASSERT(0);
  91684. }
  91685. }
  91686. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91687. {
  91688. int i, idata_len = (int)data_len;
  91689. switch(order) {
  91690. case 0:
  91691. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91692. memcpy(data, residual, sizeof(residual[0])*data_len);
  91693. break;
  91694. case 1:
  91695. for(i = 0; i < idata_len; i++)
  91696. data[i] = residual[i] + data[i-1];
  91697. break;
  91698. case 2:
  91699. for(i = 0; i < idata_len; i++)
  91700. #if 1 /* OPT: may be faster with some compilers on some systems */
  91701. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91702. #else
  91703. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91704. #endif
  91705. break;
  91706. case 3:
  91707. for(i = 0; i < idata_len; i++)
  91708. #if 1 /* OPT: may be faster with some compilers on some systems */
  91709. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91710. #else
  91711. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91712. #endif
  91713. break;
  91714. case 4:
  91715. for(i = 0; i < idata_len; i++)
  91716. #if 1 /* OPT: may be faster with some compilers on some systems */
  91717. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91718. #else
  91719. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91720. #endif
  91721. break;
  91722. default:
  91723. FLAC__ASSERT(0);
  91724. }
  91725. }
  91726. #endif
  91727. /********* End of inlined file: fixed.c *********/
  91728. /********* Start of inlined file: float.c *********/
  91729. /********* Start of inlined file: juce_FlacHeader.h *********/
  91730. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91731. // tasks..
  91732. #define VERSION "1.2.1"
  91733. #define FLAC__NO_DLL 1
  91734. #ifdef _MSC_VER
  91735. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91736. #endif
  91737. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91738. #define FLAC__SYS_DARWIN 1
  91739. #endif
  91740. /********* End of inlined file: juce_FlacHeader.h *********/
  91741. #if JUCE_USE_FLAC
  91742. #if HAVE_CONFIG_H
  91743. # include <config.h>
  91744. #endif
  91745. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91746. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91747. #ifdef _MSC_VER
  91748. #define FLAC__U64L(x) x
  91749. #else
  91750. #define FLAC__U64L(x) x##LLU
  91751. #endif
  91752. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91753. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91754. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91755. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91756. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91757. /* Lookup tables for Knuth's logarithm algorithm */
  91758. #define LOG2_LOOKUP_PRECISION 16
  91759. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91760. {
  91761. /*
  91762. * 0 fraction bits
  91763. */
  91764. /* undefined */ 0x00000000,
  91765. /* lg(2/1) = */ 0x00000001,
  91766. /* lg(4/3) = */ 0x00000000,
  91767. /* lg(8/7) = */ 0x00000000,
  91768. /* lg(16/15) = */ 0x00000000,
  91769. /* lg(32/31) = */ 0x00000000,
  91770. /* lg(64/63) = */ 0x00000000,
  91771. /* lg(128/127) = */ 0x00000000,
  91772. /* lg(256/255) = */ 0x00000000,
  91773. /* lg(512/511) = */ 0x00000000,
  91774. /* lg(1024/1023) = */ 0x00000000,
  91775. /* lg(2048/2047) = */ 0x00000000,
  91776. /* lg(4096/4095) = */ 0x00000000,
  91777. /* lg(8192/8191) = */ 0x00000000,
  91778. /* lg(16384/16383) = */ 0x00000000,
  91779. /* lg(32768/32767) = */ 0x00000000
  91780. },
  91781. {
  91782. /*
  91783. * 4 fraction bits
  91784. */
  91785. /* undefined */ 0x00000000,
  91786. /* lg(2/1) = */ 0x00000010,
  91787. /* lg(4/3) = */ 0x00000007,
  91788. /* lg(8/7) = */ 0x00000003,
  91789. /* lg(16/15) = */ 0x00000001,
  91790. /* lg(32/31) = */ 0x00000001,
  91791. /* lg(64/63) = */ 0x00000000,
  91792. /* lg(128/127) = */ 0x00000000,
  91793. /* lg(256/255) = */ 0x00000000,
  91794. /* lg(512/511) = */ 0x00000000,
  91795. /* lg(1024/1023) = */ 0x00000000,
  91796. /* lg(2048/2047) = */ 0x00000000,
  91797. /* lg(4096/4095) = */ 0x00000000,
  91798. /* lg(8192/8191) = */ 0x00000000,
  91799. /* lg(16384/16383) = */ 0x00000000,
  91800. /* lg(32768/32767) = */ 0x00000000
  91801. },
  91802. {
  91803. /*
  91804. * 8 fraction bits
  91805. */
  91806. /* undefined */ 0x00000000,
  91807. /* lg(2/1) = */ 0x00000100,
  91808. /* lg(4/3) = */ 0x0000006a,
  91809. /* lg(8/7) = */ 0x00000031,
  91810. /* lg(16/15) = */ 0x00000018,
  91811. /* lg(32/31) = */ 0x0000000c,
  91812. /* lg(64/63) = */ 0x00000006,
  91813. /* lg(128/127) = */ 0x00000003,
  91814. /* lg(256/255) = */ 0x00000001,
  91815. /* lg(512/511) = */ 0x00000001,
  91816. /* lg(1024/1023) = */ 0x00000000,
  91817. /* lg(2048/2047) = */ 0x00000000,
  91818. /* lg(4096/4095) = */ 0x00000000,
  91819. /* lg(8192/8191) = */ 0x00000000,
  91820. /* lg(16384/16383) = */ 0x00000000,
  91821. /* lg(32768/32767) = */ 0x00000000
  91822. },
  91823. {
  91824. /*
  91825. * 12 fraction bits
  91826. */
  91827. /* undefined */ 0x00000000,
  91828. /* lg(2/1) = */ 0x00001000,
  91829. /* lg(4/3) = */ 0x000006a4,
  91830. /* lg(8/7) = */ 0x00000315,
  91831. /* lg(16/15) = */ 0x0000017d,
  91832. /* lg(32/31) = */ 0x000000bc,
  91833. /* lg(64/63) = */ 0x0000005d,
  91834. /* lg(128/127) = */ 0x0000002e,
  91835. /* lg(256/255) = */ 0x00000017,
  91836. /* lg(512/511) = */ 0x0000000c,
  91837. /* lg(1024/1023) = */ 0x00000006,
  91838. /* lg(2048/2047) = */ 0x00000003,
  91839. /* lg(4096/4095) = */ 0x00000001,
  91840. /* lg(8192/8191) = */ 0x00000001,
  91841. /* lg(16384/16383) = */ 0x00000000,
  91842. /* lg(32768/32767) = */ 0x00000000
  91843. },
  91844. {
  91845. /*
  91846. * 16 fraction bits
  91847. */
  91848. /* undefined */ 0x00000000,
  91849. /* lg(2/1) = */ 0x00010000,
  91850. /* lg(4/3) = */ 0x00006a40,
  91851. /* lg(8/7) = */ 0x00003151,
  91852. /* lg(16/15) = */ 0x000017d6,
  91853. /* lg(32/31) = */ 0x00000bba,
  91854. /* lg(64/63) = */ 0x000005d1,
  91855. /* lg(128/127) = */ 0x000002e6,
  91856. /* lg(256/255) = */ 0x00000172,
  91857. /* lg(512/511) = */ 0x000000b9,
  91858. /* lg(1024/1023) = */ 0x0000005c,
  91859. /* lg(2048/2047) = */ 0x0000002e,
  91860. /* lg(4096/4095) = */ 0x00000017,
  91861. /* lg(8192/8191) = */ 0x0000000c,
  91862. /* lg(16384/16383) = */ 0x00000006,
  91863. /* lg(32768/32767) = */ 0x00000003
  91864. },
  91865. {
  91866. /*
  91867. * 20 fraction bits
  91868. */
  91869. /* undefined */ 0x00000000,
  91870. /* lg(2/1) = */ 0x00100000,
  91871. /* lg(4/3) = */ 0x0006a3fe,
  91872. /* lg(8/7) = */ 0x00031513,
  91873. /* lg(16/15) = */ 0x00017d60,
  91874. /* lg(32/31) = */ 0x0000bb9d,
  91875. /* lg(64/63) = */ 0x00005d10,
  91876. /* lg(128/127) = */ 0x00002e59,
  91877. /* lg(256/255) = */ 0x00001721,
  91878. /* lg(512/511) = */ 0x00000b8e,
  91879. /* lg(1024/1023) = */ 0x000005c6,
  91880. /* lg(2048/2047) = */ 0x000002e3,
  91881. /* lg(4096/4095) = */ 0x00000171,
  91882. /* lg(8192/8191) = */ 0x000000b9,
  91883. /* lg(16384/16383) = */ 0x0000005c,
  91884. /* lg(32768/32767) = */ 0x0000002e
  91885. },
  91886. {
  91887. /*
  91888. * 24 fraction bits
  91889. */
  91890. /* undefined */ 0x00000000,
  91891. /* lg(2/1) = */ 0x01000000,
  91892. /* lg(4/3) = */ 0x006a3fe6,
  91893. /* lg(8/7) = */ 0x00315130,
  91894. /* lg(16/15) = */ 0x0017d605,
  91895. /* lg(32/31) = */ 0x000bb9ca,
  91896. /* lg(64/63) = */ 0x0005d0fc,
  91897. /* lg(128/127) = */ 0x0002e58f,
  91898. /* lg(256/255) = */ 0x0001720e,
  91899. /* lg(512/511) = */ 0x0000b8d8,
  91900. /* lg(1024/1023) = */ 0x00005c61,
  91901. /* lg(2048/2047) = */ 0x00002e2d,
  91902. /* lg(4096/4095) = */ 0x00001716,
  91903. /* lg(8192/8191) = */ 0x00000b8b,
  91904. /* lg(16384/16383) = */ 0x000005c5,
  91905. /* lg(32768/32767) = */ 0x000002e3
  91906. },
  91907. {
  91908. /*
  91909. * 28 fraction bits
  91910. */
  91911. /* undefined */ 0x00000000,
  91912. /* lg(2/1) = */ 0x10000000,
  91913. /* lg(4/3) = */ 0x06a3fe5c,
  91914. /* lg(8/7) = */ 0x03151301,
  91915. /* lg(16/15) = */ 0x017d6049,
  91916. /* lg(32/31) = */ 0x00bb9ca6,
  91917. /* lg(64/63) = */ 0x005d0fba,
  91918. /* lg(128/127) = */ 0x002e58f7,
  91919. /* lg(256/255) = */ 0x001720da,
  91920. /* lg(512/511) = */ 0x000b8d87,
  91921. /* lg(1024/1023) = */ 0x0005c60b,
  91922. /* lg(2048/2047) = */ 0x0002e2d7,
  91923. /* lg(4096/4095) = */ 0x00017160,
  91924. /* lg(8192/8191) = */ 0x0000b8ad,
  91925. /* lg(16384/16383) = */ 0x00005c56,
  91926. /* lg(32768/32767) = */ 0x00002e2b
  91927. }
  91928. };
  91929. #if 0
  91930. static const FLAC__uint64 log2_lookup_wide[] = {
  91931. {
  91932. /*
  91933. * 32 fraction bits
  91934. */
  91935. /* undefined */ 0x00000000,
  91936. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  91937. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  91938. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  91939. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  91940. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  91941. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  91942. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  91943. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  91944. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  91945. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  91946. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  91947. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  91948. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  91949. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  91950. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  91951. },
  91952. {
  91953. /*
  91954. * 48 fraction bits
  91955. */
  91956. /* undefined */ 0x00000000,
  91957. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  91958. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  91959. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  91960. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  91961. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  91962. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  91963. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  91964. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  91965. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  91966. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  91967. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  91968. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  91969. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  91970. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  91971. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  91972. }
  91973. };
  91974. #endif
  91975. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  91976. {
  91977. const FLAC__uint32 ONE = (1u << fracbits);
  91978. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  91979. FLAC__ASSERT(fracbits < 32);
  91980. FLAC__ASSERT((fracbits & 0x3) == 0);
  91981. if(x < ONE)
  91982. return 0;
  91983. if(precision > LOG2_LOOKUP_PRECISION)
  91984. precision = LOG2_LOOKUP_PRECISION;
  91985. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  91986. {
  91987. FLAC__uint32 y = 0;
  91988. FLAC__uint32 z = x >> 1, k = 1;
  91989. while (x > ONE && k < precision) {
  91990. if (x - z >= ONE) {
  91991. x -= z;
  91992. z = x >> k;
  91993. y += table[k];
  91994. }
  91995. else {
  91996. z >>= 1;
  91997. k++;
  91998. }
  91999. }
  92000. return y;
  92001. }
  92002. }
  92003. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92004. #endif
  92005. /********* End of inlined file: float.c *********/
  92006. /********* Start of inlined file: format.c *********/
  92007. /********* Start of inlined file: juce_FlacHeader.h *********/
  92008. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92009. // tasks..
  92010. #define VERSION "1.2.1"
  92011. #define FLAC__NO_DLL 1
  92012. #ifdef _MSC_VER
  92013. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92014. #endif
  92015. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92016. #define FLAC__SYS_DARWIN 1
  92017. #endif
  92018. /********* End of inlined file: juce_FlacHeader.h *********/
  92019. #if JUCE_USE_FLAC
  92020. #if HAVE_CONFIG_H
  92021. # include <config.h>
  92022. #endif
  92023. #include <stdio.h>
  92024. #include <stdlib.h> /* for qsort() */
  92025. #include <string.h> /* for memset() */
  92026. #ifndef FLaC__INLINE
  92027. #define FLaC__INLINE
  92028. #endif
  92029. #ifdef min
  92030. #undef min
  92031. #endif
  92032. #define min(a,b) ((a)<(b)?(a):(b))
  92033. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92034. #ifdef _MSC_VER
  92035. #define FLAC__U64L(x) x
  92036. #else
  92037. #define FLAC__U64L(x) x##LLU
  92038. #endif
  92039. /* VERSION should come from configure */
  92040. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92041. ;
  92042. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92043. /* yet one more hack because of MSVC6: */
  92044. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92045. #else
  92046. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92047. #endif
  92048. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92049. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92050. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92051. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92052. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92053. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92054. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92055. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92056. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92057. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92058. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92059. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92060. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92061. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92062. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92063. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92064. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92065. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92066. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92067. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92068. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92069. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92070. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92071. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92072. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92073. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92074. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92075. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92076. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92077. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92078. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92079. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92080. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92081. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92082. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92083. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92084. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92085. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92086. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92087. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92088. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92089. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92090. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92091. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92092. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92093. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  92094. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  92095. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  92096. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  92097. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  92098. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  92099. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  92100. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  92101. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  92102. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  92103. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  92104. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  92105. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  92106. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  92107. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  92108. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  92109. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  92110. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  92111. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  92112. "PARTITIONED_RICE",
  92113. "PARTITIONED_RICE2"
  92114. };
  92115. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  92116. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  92117. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  92118. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  92119. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  92120. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  92121. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  92122. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  92123. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  92124. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  92125. "CONSTANT",
  92126. "VERBATIM",
  92127. "FIXED",
  92128. "LPC"
  92129. };
  92130. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  92131. "INDEPENDENT",
  92132. "LEFT_SIDE",
  92133. "RIGHT_SIDE",
  92134. "MID_SIDE"
  92135. };
  92136. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  92137. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  92138. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  92139. };
  92140. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  92141. "STREAMINFO",
  92142. "PADDING",
  92143. "APPLICATION",
  92144. "SEEKTABLE",
  92145. "VORBIS_COMMENT",
  92146. "CUESHEET",
  92147. "PICTURE"
  92148. };
  92149. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  92150. "Other",
  92151. "32x32 pixels 'file icon' (PNG only)",
  92152. "Other file icon",
  92153. "Cover (front)",
  92154. "Cover (back)",
  92155. "Leaflet page",
  92156. "Media (e.g. label side of CD)",
  92157. "Lead artist/lead performer/soloist",
  92158. "Artist/performer",
  92159. "Conductor",
  92160. "Band/Orchestra",
  92161. "Composer",
  92162. "Lyricist/text writer",
  92163. "Recording Location",
  92164. "During recording",
  92165. "During performance",
  92166. "Movie/video screen capture",
  92167. "A bright coloured fish",
  92168. "Illustration",
  92169. "Band/artist logotype",
  92170. "Publisher/Studio logotype"
  92171. };
  92172. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  92173. {
  92174. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  92175. return false;
  92176. }
  92177. else
  92178. return true;
  92179. }
  92180. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  92181. {
  92182. if(
  92183. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  92184. (
  92185. sample_rate >= (1u << 16) &&
  92186. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  92187. )
  92188. ) {
  92189. return false;
  92190. }
  92191. else
  92192. return true;
  92193. }
  92194. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92195. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  92196. {
  92197. unsigned i;
  92198. FLAC__uint64 prev_sample_number = 0;
  92199. FLAC__bool got_prev = false;
  92200. FLAC__ASSERT(0 != seek_table);
  92201. for(i = 0; i < seek_table->num_points; i++) {
  92202. if(got_prev) {
  92203. if(
  92204. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  92205. seek_table->points[i].sample_number <= prev_sample_number
  92206. )
  92207. return false;
  92208. }
  92209. prev_sample_number = seek_table->points[i].sample_number;
  92210. got_prev = true;
  92211. }
  92212. return true;
  92213. }
  92214. /* used as the sort predicate for qsort() */
  92215. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  92216. {
  92217. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  92218. if(l->sample_number == r->sample_number)
  92219. return 0;
  92220. else if(l->sample_number < r->sample_number)
  92221. return -1;
  92222. else
  92223. return 1;
  92224. }
  92225. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92226. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  92227. {
  92228. unsigned i, j;
  92229. FLAC__bool first;
  92230. FLAC__ASSERT(0 != seek_table);
  92231. /* sort the seekpoints */
  92232. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  92233. /* uniquify the seekpoints */
  92234. first = true;
  92235. for(i = j = 0; i < seek_table->num_points; i++) {
  92236. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  92237. if(!first) {
  92238. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  92239. continue;
  92240. }
  92241. }
  92242. first = false;
  92243. seek_table->points[j++] = seek_table->points[i];
  92244. }
  92245. for(i = j; i < seek_table->num_points; i++) {
  92246. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  92247. seek_table->points[i].stream_offset = 0;
  92248. seek_table->points[i].frame_samples = 0;
  92249. }
  92250. return j;
  92251. }
  92252. /*
  92253. * also disallows non-shortest-form encodings, c.f.
  92254. * http://www.unicode.org/versions/corrigendum1.html
  92255. * and a more clear explanation at the end of this section:
  92256. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  92257. */
  92258. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  92259. {
  92260. FLAC__ASSERT(0 != utf8);
  92261. if ((utf8[0] & 0x80) == 0) {
  92262. return 1;
  92263. }
  92264. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  92265. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  92266. return 0;
  92267. return 2;
  92268. }
  92269. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  92270. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  92271. return 0;
  92272. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  92273. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  92274. return 0;
  92275. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  92276. return 0;
  92277. return 3;
  92278. }
  92279. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  92280. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  92281. return 0;
  92282. return 4;
  92283. }
  92284. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  92285. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  92286. return 0;
  92287. return 5;
  92288. }
  92289. 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) {
  92290. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  92291. return 0;
  92292. return 6;
  92293. }
  92294. else {
  92295. return 0;
  92296. }
  92297. }
  92298. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  92299. {
  92300. char c;
  92301. for(c = *name; c; c = *(++name))
  92302. if(c < 0x20 || c == 0x3d || c > 0x7d)
  92303. return false;
  92304. return true;
  92305. }
  92306. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  92307. {
  92308. if(length == (unsigned)(-1)) {
  92309. while(*value) {
  92310. unsigned n = utf8len_(value);
  92311. if(n == 0)
  92312. return false;
  92313. value += n;
  92314. }
  92315. }
  92316. else {
  92317. const FLAC__byte *end = value + length;
  92318. while(value < end) {
  92319. unsigned n = utf8len_(value);
  92320. if(n == 0)
  92321. return false;
  92322. value += n;
  92323. }
  92324. if(value != end)
  92325. return false;
  92326. }
  92327. return true;
  92328. }
  92329. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  92330. {
  92331. const FLAC__byte *s, *end;
  92332. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  92333. if(*s < 0x20 || *s > 0x7D)
  92334. return false;
  92335. }
  92336. if(s == end)
  92337. return false;
  92338. s++; /* skip '=' */
  92339. while(s < end) {
  92340. unsigned n = utf8len_(s);
  92341. if(n == 0)
  92342. return false;
  92343. s += n;
  92344. }
  92345. if(s != end)
  92346. return false;
  92347. return true;
  92348. }
  92349. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92350. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  92351. {
  92352. unsigned i, j;
  92353. if(check_cd_da_subset) {
  92354. if(cue_sheet->lead_in < 2 * 44100) {
  92355. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  92356. return false;
  92357. }
  92358. if(cue_sheet->lead_in % 588 != 0) {
  92359. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  92360. return false;
  92361. }
  92362. }
  92363. if(cue_sheet->num_tracks == 0) {
  92364. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  92365. return false;
  92366. }
  92367. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  92368. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  92369. return false;
  92370. }
  92371. for(i = 0; i < cue_sheet->num_tracks; i++) {
  92372. if(cue_sheet->tracks[i].number == 0) {
  92373. if(violation) *violation = "cue sheet may not have a track number 0";
  92374. return false;
  92375. }
  92376. if(check_cd_da_subset) {
  92377. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  92378. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  92379. return false;
  92380. }
  92381. }
  92382. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  92383. if(violation) {
  92384. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  92385. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  92386. else
  92387. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  92388. }
  92389. return false;
  92390. }
  92391. if(i < cue_sheet->num_tracks - 1) {
  92392. if(cue_sheet->tracks[i].num_indices == 0) {
  92393. if(violation) *violation = "cue sheet track must have at least one index point";
  92394. return false;
  92395. }
  92396. if(cue_sheet->tracks[i].indices[0].number > 1) {
  92397. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  92398. return false;
  92399. }
  92400. }
  92401. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  92402. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  92403. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  92404. return false;
  92405. }
  92406. if(j > 0) {
  92407. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  92408. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  92409. return false;
  92410. }
  92411. }
  92412. }
  92413. }
  92414. return true;
  92415. }
  92416. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92417. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  92418. {
  92419. char *p;
  92420. FLAC__byte *b;
  92421. for(p = picture->mime_type; *p; p++) {
  92422. if(*p < 0x20 || *p > 0x7e) {
  92423. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  92424. return false;
  92425. }
  92426. }
  92427. for(b = picture->description; *b; ) {
  92428. unsigned n = utf8len_(b);
  92429. if(n == 0) {
  92430. if(violation) *violation = "description string must be valid UTF-8";
  92431. return false;
  92432. }
  92433. b += n;
  92434. }
  92435. return true;
  92436. }
  92437. /*
  92438. * These routines are private to libFLAC
  92439. */
  92440. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  92441. {
  92442. return
  92443. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  92444. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  92445. blocksize,
  92446. predictor_order
  92447. );
  92448. }
  92449. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  92450. {
  92451. unsigned max_rice_partition_order = 0;
  92452. while(!(blocksize & 1)) {
  92453. max_rice_partition_order++;
  92454. blocksize >>= 1;
  92455. }
  92456. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  92457. }
  92458. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  92459. {
  92460. unsigned max_rice_partition_order = limit;
  92461. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  92462. max_rice_partition_order--;
  92463. FLAC__ASSERT(
  92464. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  92465. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  92466. );
  92467. return max_rice_partition_order;
  92468. }
  92469. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92470. {
  92471. FLAC__ASSERT(0 != object);
  92472. object->parameters = 0;
  92473. object->raw_bits = 0;
  92474. object->capacity_by_order = 0;
  92475. }
  92476. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92477. {
  92478. FLAC__ASSERT(0 != object);
  92479. if(0 != object->parameters)
  92480. free(object->parameters);
  92481. if(0 != object->raw_bits)
  92482. free(object->raw_bits);
  92483. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  92484. }
  92485. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  92486. {
  92487. FLAC__ASSERT(0 != object);
  92488. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  92489. if(object->capacity_by_order < max_partition_order) {
  92490. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  92491. return false;
  92492. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  92493. return false;
  92494. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  92495. object->capacity_by_order = max_partition_order;
  92496. }
  92497. return true;
  92498. }
  92499. #endif
  92500. /********* End of inlined file: format.c *********/
  92501. /********* Start of inlined file: lpc_flac.c *********/
  92502. /********* Start of inlined file: juce_FlacHeader.h *********/
  92503. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92504. // tasks..
  92505. #define VERSION "1.2.1"
  92506. #define FLAC__NO_DLL 1
  92507. #ifdef _MSC_VER
  92508. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92509. #endif
  92510. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92511. #define FLAC__SYS_DARWIN 1
  92512. #endif
  92513. /********* End of inlined file: juce_FlacHeader.h *********/
  92514. #if JUCE_USE_FLAC
  92515. #if HAVE_CONFIG_H
  92516. # include <config.h>
  92517. #endif
  92518. #include <math.h>
  92519. /********* Start of inlined file: lpc.h *********/
  92520. #ifndef FLAC__PRIVATE__LPC_H
  92521. #define FLAC__PRIVATE__LPC_H
  92522. #ifdef HAVE_CONFIG_H
  92523. #include <config.h>
  92524. #endif
  92525. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92526. /*
  92527. * FLAC__lpc_window_data()
  92528. * --------------------------------------------------------------------
  92529. * Applies the given window to the data.
  92530. * OPT: asm implementation
  92531. *
  92532. * IN in[0,data_len-1]
  92533. * IN window[0,data_len-1]
  92534. * OUT out[0,lag-1]
  92535. * IN data_len
  92536. */
  92537. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92538. /*
  92539. * FLAC__lpc_compute_autocorrelation()
  92540. * --------------------------------------------------------------------
  92541. * Compute the autocorrelation for lags between 0 and lag-1.
  92542. * Assumes data[] outside of [0,data_len-1] == 0.
  92543. * Asserts that lag > 0.
  92544. *
  92545. * IN data[0,data_len-1]
  92546. * IN data_len
  92547. * IN 0 < lag <= data_len
  92548. * OUT autoc[0,lag-1]
  92549. */
  92550. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92551. #ifndef FLAC__NO_ASM
  92552. # ifdef FLAC__CPU_IA32
  92553. # ifdef FLAC__HAS_NASM
  92554. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92555. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92556. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92557. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92558. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92559. # endif
  92560. # endif
  92561. #endif
  92562. /*
  92563. * FLAC__lpc_compute_lp_coefficients()
  92564. * --------------------------------------------------------------------
  92565. * Computes LP coefficients for orders 1..max_order.
  92566. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92567. * and there is no point in calculating a predictor.
  92568. *
  92569. * IN autoc[0,max_order] autocorrelation values
  92570. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92571. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92572. * *** IMPORTANT:
  92573. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92574. * OUT error[0,max_order-1] error for each order (more
  92575. * specifically, the variance of
  92576. * the error signal times # of
  92577. * samples in the signal)
  92578. *
  92579. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92580. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92581. * in lp_coeff[7][0,7], etc.
  92582. */
  92583. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92584. /*
  92585. * FLAC__lpc_quantize_coefficients()
  92586. * --------------------------------------------------------------------
  92587. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92588. * must be less than 32 (sizeof(FLAC__int32)*8).
  92589. *
  92590. * IN lp_coeff[0,order-1] LP coefficients
  92591. * IN order LP order
  92592. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92593. * desired precision (in bits, including sign
  92594. * bit) of largest coefficient
  92595. * OUT qlp_coeff[0,order-1] quantized coefficients
  92596. * OUT shift # of bits to shift right to get approximated
  92597. * LP coefficients. NOTE: could be negative.
  92598. * RETURN 0 => quantization OK
  92599. * 1 => coefficients require too much shifting for *shift to
  92600. * fit in the LPC subframe header. 'shift' is unset.
  92601. * 2 => coefficients are all zero, which is bad. 'shift' is
  92602. * unset.
  92603. */
  92604. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92605. /*
  92606. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92607. * --------------------------------------------------------------------
  92608. * Compute the residual signal obtained from sutracting the predicted
  92609. * signal from the original.
  92610. *
  92611. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92612. * IN data_len length of original signal
  92613. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92614. * IN order > 0 LP order
  92615. * IN lp_quantization quantization of LP coefficients in bits
  92616. * OUT residual[0,data_len-1] residual signal
  92617. */
  92618. 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[]);
  92619. 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[]);
  92620. #ifndef FLAC__NO_ASM
  92621. # ifdef FLAC__CPU_IA32
  92622. # ifdef FLAC__HAS_NASM
  92623. 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[]);
  92624. 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[]);
  92625. # endif
  92626. # endif
  92627. #endif
  92628. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92629. /*
  92630. * FLAC__lpc_restore_signal()
  92631. * --------------------------------------------------------------------
  92632. * Restore the original signal by summing the residual and the
  92633. * predictor.
  92634. *
  92635. * IN residual[0,data_len-1] residual signal
  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. * *** IMPORTANT: the caller must pass in the historical samples:
  92641. * IN data[-order,-1] previously-reconstructed historical samples
  92642. * OUT data[0,data_len-1] original signal
  92643. */
  92644. 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[]);
  92645. 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[]);
  92646. #ifndef FLAC__NO_ASM
  92647. # ifdef FLAC__CPU_IA32
  92648. # ifdef FLAC__HAS_NASM
  92649. 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[]);
  92650. 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[]);
  92651. # endif /* FLAC__HAS_NASM */
  92652. # elif defined FLAC__CPU_PPC
  92653. 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[]);
  92654. 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[]);
  92655. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  92656. #endif /* FLAC__NO_ASM */
  92657. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92658. /*
  92659. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  92660. * --------------------------------------------------------------------
  92661. * Compute the expected number of bits per residual signal sample
  92662. * based on the LP error (which is related to the residual variance).
  92663. *
  92664. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  92665. * IN total_samples > 0 # of samples in residual signal
  92666. * RETURN expected bits per sample
  92667. */
  92668. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  92669. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  92670. /*
  92671. * FLAC__lpc_compute_best_order()
  92672. * --------------------------------------------------------------------
  92673. * Compute the best order from the array of signal errors returned
  92674. * during coefficient computation.
  92675. *
  92676. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  92677. * IN max_order > 0 max LP order
  92678. * IN total_samples > 0 # of samples in residual signal
  92679. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  92680. * (includes warmup sample size and quantized LP coefficient)
  92681. * RETURN [1,max_order] best order
  92682. */
  92683. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  92684. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92685. #endif
  92686. /********* End of inlined file: lpc.h *********/
  92687. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  92688. #include <stdio.h>
  92689. #endif
  92690. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92691. #ifndef M_LN2
  92692. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  92693. #define M_LN2 0.69314718055994530942
  92694. #endif
  92695. /* OPT: #undef'ing this may improve the speed on some architectures */
  92696. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  92697. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  92698. {
  92699. unsigned i;
  92700. for(i = 0; i < data_len; i++)
  92701. out[i] = in[i] * window[i];
  92702. }
  92703. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  92704. {
  92705. /* a readable, but slower, version */
  92706. #if 0
  92707. FLAC__real d;
  92708. unsigned i;
  92709. FLAC__ASSERT(lag > 0);
  92710. FLAC__ASSERT(lag <= data_len);
  92711. /*
  92712. * Technically we should subtract the mean first like so:
  92713. * for(i = 0; i < data_len; i++)
  92714. * data[i] -= mean;
  92715. * but it appears not to make enough of a difference to matter, and
  92716. * most signals are already closely centered around zero
  92717. */
  92718. while(lag--) {
  92719. for(i = lag, d = 0.0; i < data_len; i++)
  92720. d += data[i] * data[i - lag];
  92721. autoc[lag] = d;
  92722. }
  92723. #endif
  92724. /*
  92725. * this version tends to run faster because of better data locality
  92726. * ('data_len' is usually much larger than 'lag')
  92727. */
  92728. FLAC__real d;
  92729. unsigned sample, coeff;
  92730. const unsigned limit = data_len - lag;
  92731. FLAC__ASSERT(lag > 0);
  92732. FLAC__ASSERT(lag <= data_len);
  92733. for(coeff = 0; coeff < lag; coeff++)
  92734. autoc[coeff] = 0.0;
  92735. for(sample = 0; sample <= limit; sample++) {
  92736. d = data[sample];
  92737. for(coeff = 0; coeff < lag; coeff++)
  92738. autoc[coeff] += d * data[sample+coeff];
  92739. }
  92740. for(; sample < data_len; sample++) {
  92741. d = data[sample];
  92742. for(coeff = 0; coeff < data_len - sample; coeff++)
  92743. autoc[coeff] += d * data[sample+coeff];
  92744. }
  92745. }
  92746. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  92747. {
  92748. unsigned i, j;
  92749. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  92750. FLAC__ASSERT(0 != max_order);
  92751. FLAC__ASSERT(0 < *max_order);
  92752. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  92753. FLAC__ASSERT(autoc[0] != 0.0);
  92754. err = autoc[0];
  92755. for(i = 0; i < *max_order; i++) {
  92756. /* Sum up this iteration's reflection coefficient. */
  92757. r = -autoc[i+1];
  92758. for(j = 0; j < i; j++)
  92759. r -= lpc[j] * autoc[i-j];
  92760. ref[i] = (r/=err);
  92761. /* Update LPC coefficients and total error. */
  92762. lpc[i]=r;
  92763. for(j = 0; j < (i>>1); j++) {
  92764. FLAC__double tmp = lpc[j];
  92765. lpc[j] += r * lpc[i-1-j];
  92766. lpc[i-1-j] += r * tmp;
  92767. }
  92768. if(i & 1)
  92769. lpc[j] += lpc[j] * r;
  92770. err *= (1.0 - r * r);
  92771. /* save this order */
  92772. for(j = 0; j <= i; j++)
  92773. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  92774. error[i] = err;
  92775. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  92776. if(err == 0.0) {
  92777. *max_order = i+1;
  92778. return;
  92779. }
  92780. }
  92781. }
  92782. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  92783. {
  92784. unsigned i;
  92785. FLAC__double cmax;
  92786. FLAC__int32 qmax, qmin;
  92787. FLAC__ASSERT(precision > 0);
  92788. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  92789. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  92790. precision--;
  92791. qmax = 1 << precision;
  92792. qmin = -qmax;
  92793. qmax--;
  92794. /* calc cmax = max( |lp_coeff[i]| ) */
  92795. cmax = 0.0;
  92796. for(i = 0; i < order; i++) {
  92797. const FLAC__double d = fabs(lp_coeff[i]);
  92798. if(d > cmax)
  92799. cmax = d;
  92800. }
  92801. if(cmax <= 0.0) {
  92802. /* => coefficients are all 0, which means our constant-detect didn't work */
  92803. return 2;
  92804. }
  92805. else {
  92806. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  92807. const int min_shiftlimit = -max_shiftlimit - 1;
  92808. int log2cmax;
  92809. (void)frexp(cmax, &log2cmax);
  92810. log2cmax--;
  92811. *shift = (int)precision - log2cmax - 1;
  92812. if(*shift > max_shiftlimit)
  92813. *shift = max_shiftlimit;
  92814. else if(*shift < min_shiftlimit)
  92815. return 1;
  92816. }
  92817. if(*shift >= 0) {
  92818. FLAC__double error = 0.0;
  92819. FLAC__int32 q;
  92820. for(i = 0; i < order; i++) {
  92821. error += lp_coeff[i] * (1 << *shift);
  92822. #if 1 /* unfortunately lround() is C99 */
  92823. if(error >= 0.0)
  92824. q = (FLAC__int32)(error + 0.5);
  92825. else
  92826. q = (FLAC__int32)(error - 0.5);
  92827. #else
  92828. q = lround(error);
  92829. #endif
  92830. #ifdef FLAC__OVERFLOW_DETECT
  92831. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92832. 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]);
  92833. else if(q < qmin)
  92834. 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]);
  92835. #endif
  92836. if(q > qmax)
  92837. q = qmax;
  92838. else if(q < qmin)
  92839. q = qmin;
  92840. error -= q;
  92841. qlp_coeff[i] = q;
  92842. }
  92843. }
  92844. /* negative shift is very rare but due to design flaw, negative shift is
  92845. * a NOP in the decoder, so it must be handled specially by scaling down
  92846. * coeffs
  92847. */
  92848. else {
  92849. const int nshift = -(*shift);
  92850. FLAC__double error = 0.0;
  92851. FLAC__int32 q;
  92852. #ifdef DEBUG
  92853. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  92854. #endif
  92855. for(i = 0; i < order; i++) {
  92856. error += lp_coeff[i] / (1 << nshift);
  92857. #if 1 /* unfortunately lround() is C99 */
  92858. if(error >= 0.0)
  92859. q = (FLAC__int32)(error + 0.5);
  92860. else
  92861. q = (FLAC__int32)(error - 0.5);
  92862. #else
  92863. q = lround(error);
  92864. #endif
  92865. #ifdef FLAC__OVERFLOW_DETECT
  92866. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  92867. 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]);
  92868. else if(q < qmin)
  92869. 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]);
  92870. #endif
  92871. if(q > qmax)
  92872. q = qmax;
  92873. else if(q < qmin)
  92874. q = qmin;
  92875. error -= q;
  92876. qlp_coeff[i] = q;
  92877. }
  92878. *shift = 0;
  92879. }
  92880. return 0;
  92881. }
  92882. 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[])
  92883. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  92884. {
  92885. FLAC__int64 sumo;
  92886. unsigned i, j;
  92887. FLAC__int32 sum;
  92888. const FLAC__int32 *history;
  92889. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  92890. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  92891. for(i=0;i<order;i++)
  92892. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  92893. fprintf(stderr,"\n");
  92894. #endif
  92895. FLAC__ASSERT(order > 0);
  92896. for(i = 0; i < data_len; i++) {
  92897. sumo = 0;
  92898. sum = 0;
  92899. history = data;
  92900. for(j = 0; j < order; j++) {
  92901. sum += qlp_coeff[j] * (*(--history));
  92902. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  92903. #if defined _MSC_VER
  92904. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  92905. 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);
  92906. #else
  92907. if(sumo > 2147483647ll || sumo < -2147483648ll)
  92908. 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);
  92909. #endif
  92910. }
  92911. *(residual++) = *(data++) - (sum >> lp_quantization);
  92912. }
  92913. /* Here's a slower but clearer version:
  92914. for(i = 0; i < data_len; i++) {
  92915. sum = 0;
  92916. for(j = 0; j < order; j++)
  92917. sum += qlp_coeff[j] * data[i-j-1];
  92918. residual[i] = data[i] - (sum >> lp_quantization);
  92919. }
  92920. */
  92921. }
  92922. #else /* fully unrolled version for normal use */
  92923. {
  92924. int i;
  92925. FLAC__int32 sum;
  92926. FLAC__ASSERT(order > 0);
  92927. FLAC__ASSERT(order <= 32);
  92928. /*
  92929. * We do unique versions up to 12th order since that's the subset limit.
  92930. * Also they are roughly ordered to match frequency of occurrence to
  92931. * minimize branching.
  92932. */
  92933. if(order <= 12) {
  92934. if(order > 8) {
  92935. if(order > 10) {
  92936. if(order == 12) {
  92937. for(i = 0; i < (int)data_len; i++) {
  92938. sum = 0;
  92939. sum += qlp_coeff[11] * data[i-12];
  92940. sum += qlp_coeff[10] * data[i-11];
  92941. sum += qlp_coeff[9] * data[i-10];
  92942. sum += qlp_coeff[8] * data[i-9];
  92943. sum += qlp_coeff[7] * data[i-8];
  92944. sum += qlp_coeff[6] * data[i-7];
  92945. sum += qlp_coeff[5] * data[i-6];
  92946. sum += qlp_coeff[4] * data[i-5];
  92947. sum += qlp_coeff[3] * data[i-4];
  92948. sum += qlp_coeff[2] * data[i-3];
  92949. sum += qlp_coeff[1] * data[i-2];
  92950. sum += qlp_coeff[0] * data[i-1];
  92951. residual[i] = data[i] - (sum >> lp_quantization);
  92952. }
  92953. }
  92954. else { /* order == 11 */
  92955. for(i = 0; i < (int)data_len; i++) {
  92956. sum = 0;
  92957. sum += qlp_coeff[10] * data[i-11];
  92958. sum += qlp_coeff[9] * data[i-10];
  92959. sum += qlp_coeff[8] * data[i-9];
  92960. sum += qlp_coeff[7] * data[i-8];
  92961. sum += qlp_coeff[6] * data[i-7];
  92962. sum += qlp_coeff[5] * data[i-6];
  92963. sum += qlp_coeff[4] * data[i-5];
  92964. sum += qlp_coeff[3] * data[i-4];
  92965. sum += qlp_coeff[2] * data[i-3];
  92966. sum += qlp_coeff[1] * data[i-2];
  92967. sum += qlp_coeff[0] * data[i-1];
  92968. residual[i] = data[i] - (sum >> lp_quantization);
  92969. }
  92970. }
  92971. }
  92972. else {
  92973. if(order == 10) {
  92974. for(i = 0; i < (int)data_len; i++) {
  92975. sum = 0;
  92976. sum += qlp_coeff[9] * data[i-10];
  92977. sum += qlp_coeff[8] * data[i-9];
  92978. sum += qlp_coeff[7] * data[i-8];
  92979. sum += qlp_coeff[6] * data[i-7];
  92980. sum += qlp_coeff[5] * data[i-6];
  92981. sum += qlp_coeff[4] * data[i-5];
  92982. sum += qlp_coeff[3] * data[i-4];
  92983. sum += qlp_coeff[2] * data[i-3];
  92984. sum += qlp_coeff[1] * data[i-2];
  92985. sum += qlp_coeff[0] * data[i-1];
  92986. residual[i] = data[i] - (sum >> lp_quantization);
  92987. }
  92988. }
  92989. else { /* order == 9 */
  92990. for(i = 0; i < (int)data_len; i++) {
  92991. sum = 0;
  92992. sum += qlp_coeff[8] * data[i-9];
  92993. sum += qlp_coeff[7] * data[i-8];
  92994. sum += qlp_coeff[6] * data[i-7];
  92995. sum += qlp_coeff[5] * data[i-6];
  92996. sum += qlp_coeff[4] * data[i-5];
  92997. sum += qlp_coeff[3] * data[i-4];
  92998. sum += qlp_coeff[2] * data[i-3];
  92999. sum += qlp_coeff[1] * data[i-2];
  93000. sum += qlp_coeff[0] * data[i-1];
  93001. residual[i] = data[i] - (sum >> lp_quantization);
  93002. }
  93003. }
  93004. }
  93005. }
  93006. else if(order > 4) {
  93007. if(order > 6) {
  93008. if(order == 8) {
  93009. for(i = 0; i < (int)data_len; i++) {
  93010. sum = 0;
  93011. sum += qlp_coeff[7] * data[i-8];
  93012. sum += qlp_coeff[6] * data[i-7];
  93013. sum += qlp_coeff[5] * data[i-6];
  93014. sum += qlp_coeff[4] * data[i-5];
  93015. sum += qlp_coeff[3] * data[i-4];
  93016. sum += qlp_coeff[2] * data[i-3];
  93017. sum += qlp_coeff[1] * data[i-2];
  93018. sum += qlp_coeff[0] * data[i-1];
  93019. residual[i] = data[i] - (sum >> lp_quantization);
  93020. }
  93021. }
  93022. else { /* order == 7 */
  93023. for(i = 0; i < (int)data_len; i++) {
  93024. sum = 0;
  93025. sum += qlp_coeff[6] * data[i-7];
  93026. sum += qlp_coeff[5] * data[i-6];
  93027. sum += qlp_coeff[4] * data[i-5];
  93028. sum += qlp_coeff[3] * data[i-4];
  93029. sum += qlp_coeff[2] * data[i-3];
  93030. sum += qlp_coeff[1] * data[i-2];
  93031. sum += qlp_coeff[0] * data[i-1];
  93032. residual[i] = data[i] - (sum >> lp_quantization);
  93033. }
  93034. }
  93035. }
  93036. else {
  93037. if(order == 6) {
  93038. for(i = 0; i < (int)data_len; i++) {
  93039. sum = 0;
  93040. sum += qlp_coeff[5] * data[i-6];
  93041. sum += qlp_coeff[4] * data[i-5];
  93042. sum += qlp_coeff[3] * data[i-4];
  93043. sum += qlp_coeff[2] * data[i-3];
  93044. sum += qlp_coeff[1] * data[i-2];
  93045. sum += qlp_coeff[0] * data[i-1];
  93046. residual[i] = data[i] - (sum >> lp_quantization);
  93047. }
  93048. }
  93049. else { /* order == 5 */
  93050. for(i = 0; i < (int)data_len; i++) {
  93051. sum = 0;
  93052. sum += qlp_coeff[4] * data[i-5];
  93053. sum += qlp_coeff[3] * data[i-4];
  93054. sum += qlp_coeff[2] * data[i-3];
  93055. sum += qlp_coeff[1] * data[i-2];
  93056. sum += qlp_coeff[0] * data[i-1];
  93057. residual[i] = data[i] - (sum >> lp_quantization);
  93058. }
  93059. }
  93060. }
  93061. }
  93062. else {
  93063. if(order > 2) {
  93064. if(order == 4) {
  93065. for(i = 0; i < (int)data_len; i++) {
  93066. sum = 0;
  93067. sum += qlp_coeff[3] * data[i-4];
  93068. sum += qlp_coeff[2] * data[i-3];
  93069. sum += qlp_coeff[1] * data[i-2];
  93070. sum += qlp_coeff[0] * data[i-1];
  93071. residual[i] = data[i] - (sum >> lp_quantization);
  93072. }
  93073. }
  93074. else { /* order == 3 */
  93075. for(i = 0; i < (int)data_len; i++) {
  93076. sum = 0;
  93077. sum += qlp_coeff[2] * data[i-3];
  93078. sum += qlp_coeff[1] * data[i-2];
  93079. sum += qlp_coeff[0] * data[i-1];
  93080. residual[i] = data[i] - (sum >> lp_quantization);
  93081. }
  93082. }
  93083. }
  93084. else {
  93085. if(order == 2) {
  93086. for(i = 0; i < (int)data_len; i++) {
  93087. sum = 0;
  93088. sum += qlp_coeff[1] * data[i-2];
  93089. sum += qlp_coeff[0] * data[i-1];
  93090. residual[i] = data[i] - (sum >> lp_quantization);
  93091. }
  93092. }
  93093. else { /* order == 1 */
  93094. for(i = 0; i < (int)data_len; i++)
  93095. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93096. }
  93097. }
  93098. }
  93099. }
  93100. else { /* order > 12 */
  93101. for(i = 0; i < (int)data_len; i++) {
  93102. sum = 0;
  93103. switch(order) {
  93104. case 32: sum += qlp_coeff[31] * data[i-32];
  93105. case 31: sum += qlp_coeff[30] * data[i-31];
  93106. case 30: sum += qlp_coeff[29] * data[i-30];
  93107. case 29: sum += qlp_coeff[28] * data[i-29];
  93108. case 28: sum += qlp_coeff[27] * data[i-28];
  93109. case 27: sum += qlp_coeff[26] * data[i-27];
  93110. case 26: sum += qlp_coeff[25] * data[i-26];
  93111. case 25: sum += qlp_coeff[24] * data[i-25];
  93112. case 24: sum += qlp_coeff[23] * data[i-24];
  93113. case 23: sum += qlp_coeff[22] * data[i-23];
  93114. case 22: sum += qlp_coeff[21] * data[i-22];
  93115. case 21: sum += qlp_coeff[20] * data[i-21];
  93116. case 20: sum += qlp_coeff[19] * data[i-20];
  93117. case 19: sum += qlp_coeff[18] * data[i-19];
  93118. case 18: sum += qlp_coeff[17] * data[i-18];
  93119. case 17: sum += qlp_coeff[16] * data[i-17];
  93120. case 16: sum += qlp_coeff[15] * data[i-16];
  93121. case 15: sum += qlp_coeff[14] * data[i-15];
  93122. case 14: sum += qlp_coeff[13] * data[i-14];
  93123. case 13: sum += qlp_coeff[12] * data[i-13];
  93124. sum += qlp_coeff[11] * data[i-12];
  93125. sum += qlp_coeff[10] * data[i-11];
  93126. sum += qlp_coeff[ 9] * data[i-10];
  93127. sum += qlp_coeff[ 8] * data[i- 9];
  93128. sum += qlp_coeff[ 7] * data[i- 8];
  93129. sum += qlp_coeff[ 6] * data[i- 7];
  93130. sum += qlp_coeff[ 5] * data[i- 6];
  93131. sum += qlp_coeff[ 4] * data[i- 5];
  93132. sum += qlp_coeff[ 3] * data[i- 4];
  93133. sum += qlp_coeff[ 2] * data[i- 3];
  93134. sum += qlp_coeff[ 1] * data[i- 2];
  93135. sum += qlp_coeff[ 0] * data[i- 1];
  93136. }
  93137. residual[i] = data[i] - (sum >> lp_quantization);
  93138. }
  93139. }
  93140. }
  93141. #endif
  93142. 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[])
  93143. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93144. {
  93145. unsigned i, j;
  93146. FLAC__int64 sum;
  93147. const FLAC__int32 *history;
  93148. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93149. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93150. for(i=0;i<order;i++)
  93151. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93152. fprintf(stderr,"\n");
  93153. #endif
  93154. FLAC__ASSERT(order > 0);
  93155. for(i = 0; i < data_len; i++) {
  93156. sum = 0;
  93157. history = data;
  93158. for(j = 0; j < order; j++)
  93159. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93160. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93161. #if defined _MSC_VER
  93162. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93163. #else
  93164. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93165. #endif
  93166. break;
  93167. }
  93168. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  93169. #if defined _MSC_VER
  93170. 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));
  93171. #else
  93172. 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)));
  93173. #endif
  93174. break;
  93175. }
  93176. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  93177. }
  93178. }
  93179. #else /* fully unrolled version for normal use */
  93180. {
  93181. int i;
  93182. FLAC__int64 sum;
  93183. FLAC__ASSERT(order > 0);
  93184. FLAC__ASSERT(order <= 32);
  93185. /*
  93186. * We do unique versions up to 12th order since that's the subset limit.
  93187. * Also they are roughly ordered to match frequency of occurrence to
  93188. * minimize branching.
  93189. */
  93190. if(order <= 12) {
  93191. if(order > 8) {
  93192. if(order > 10) {
  93193. if(order == 12) {
  93194. for(i = 0; i < (int)data_len; i++) {
  93195. sum = 0;
  93196. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93197. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93198. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93199. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93200. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93201. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93202. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93203. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93204. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93205. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93206. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93207. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93208. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93209. }
  93210. }
  93211. else { /* order == 11 */
  93212. for(i = 0; i < (int)data_len; i++) {
  93213. sum = 0;
  93214. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93215. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93216. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93217. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93218. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93219. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93220. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93221. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93222. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93223. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93224. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93225. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93226. }
  93227. }
  93228. }
  93229. else {
  93230. if(order == 10) {
  93231. for(i = 0; i < (int)data_len; i++) {
  93232. sum = 0;
  93233. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93234. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93235. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93236. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93237. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93238. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93239. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93240. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93241. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93242. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93243. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93244. }
  93245. }
  93246. else { /* order == 9 */
  93247. for(i = 0; i < (int)data_len; i++) {
  93248. sum = 0;
  93249. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93250. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93251. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93252. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93253. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93254. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93255. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93256. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93257. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93258. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93259. }
  93260. }
  93261. }
  93262. }
  93263. else if(order > 4) {
  93264. if(order > 6) {
  93265. if(order == 8) {
  93266. for(i = 0; i < (int)data_len; i++) {
  93267. sum = 0;
  93268. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93269. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93270. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93271. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93272. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93273. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93274. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93275. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93276. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93277. }
  93278. }
  93279. else { /* order == 7 */
  93280. for(i = 0; i < (int)data_len; i++) {
  93281. sum = 0;
  93282. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93283. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93284. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93285. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93286. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93287. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93288. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93289. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93290. }
  93291. }
  93292. }
  93293. else {
  93294. if(order == 6) {
  93295. for(i = 0; i < (int)data_len; i++) {
  93296. sum = 0;
  93297. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93298. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93299. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93300. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93301. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93302. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93303. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93304. }
  93305. }
  93306. else { /* order == 5 */
  93307. for(i = 0; i < (int)data_len; i++) {
  93308. sum = 0;
  93309. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93310. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93311. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93312. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93313. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93314. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93315. }
  93316. }
  93317. }
  93318. }
  93319. else {
  93320. if(order > 2) {
  93321. if(order == 4) {
  93322. for(i = 0; i < (int)data_len; i++) {
  93323. sum = 0;
  93324. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93325. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93326. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93327. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93328. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93329. }
  93330. }
  93331. else { /* order == 3 */
  93332. for(i = 0; i < (int)data_len; i++) {
  93333. sum = 0;
  93334. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93335. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93336. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93337. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93338. }
  93339. }
  93340. }
  93341. else {
  93342. if(order == 2) {
  93343. for(i = 0; i < (int)data_len; i++) {
  93344. sum = 0;
  93345. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93346. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93347. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93348. }
  93349. }
  93350. else { /* order == 1 */
  93351. for(i = 0; i < (int)data_len; i++)
  93352. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93353. }
  93354. }
  93355. }
  93356. }
  93357. else { /* order > 12 */
  93358. for(i = 0; i < (int)data_len; i++) {
  93359. sum = 0;
  93360. switch(order) {
  93361. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93362. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93363. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93364. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93365. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93366. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93367. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93368. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93369. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93370. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93371. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93372. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93373. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93374. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93375. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93376. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93377. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93378. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93379. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93380. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93381. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93382. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93383. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93384. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93385. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93386. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93387. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93388. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93389. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93390. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93391. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93392. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93393. }
  93394. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93395. }
  93396. }
  93397. }
  93398. #endif
  93399. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93400. 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[])
  93401. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93402. {
  93403. FLAC__int64 sumo;
  93404. unsigned i, j;
  93405. FLAC__int32 sum;
  93406. const FLAC__int32 *r = residual, *history;
  93407. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93408. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93409. for(i=0;i<order;i++)
  93410. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93411. fprintf(stderr,"\n");
  93412. #endif
  93413. FLAC__ASSERT(order > 0);
  93414. for(i = 0; i < data_len; i++) {
  93415. sumo = 0;
  93416. sum = 0;
  93417. history = data;
  93418. for(j = 0; j < order; j++) {
  93419. sum += qlp_coeff[j] * (*(--history));
  93420. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93421. #if defined _MSC_VER
  93422. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93423. 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);
  93424. #else
  93425. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93426. 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);
  93427. #endif
  93428. }
  93429. *(data++) = *(r++) + (sum >> lp_quantization);
  93430. }
  93431. /* Here's a slower but clearer version:
  93432. for(i = 0; i < data_len; i++) {
  93433. sum = 0;
  93434. for(j = 0; j < order; j++)
  93435. sum += qlp_coeff[j] * data[i-j-1];
  93436. data[i] = residual[i] + (sum >> lp_quantization);
  93437. }
  93438. */
  93439. }
  93440. #else /* fully unrolled version for normal use */
  93441. {
  93442. int i;
  93443. FLAC__int32 sum;
  93444. FLAC__ASSERT(order > 0);
  93445. FLAC__ASSERT(order <= 32);
  93446. /*
  93447. * We do unique versions up to 12th order since that's the subset limit.
  93448. * Also they are roughly ordered to match frequency of occurrence to
  93449. * minimize branching.
  93450. */
  93451. if(order <= 12) {
  93452. if(order > 8) {
  93453. if(order > 10) {
  93454. if(order == 12) {
  93455. for(i = 0; i < (int)data_len; i++) {
  93456. sum = 0;
  93457. sum += qlp_coeff[11] * data[i-12];
  93458. sum += qlp_coeff[10] * data[i-11];
  93459. sum += qlp_coeff[9] * data[i-10];
  93460. sum += qlp_coeff[8] * data[i-9];
  93461. sum += qlp_coeff[7] * data[i-8];
  93462. sum += qlp_coeff[6] * data[i-7];
  93463. sum += qlp_coeff[5] * data[i-6];
  93464. sum += qlp_coeff[4] * data[i-5];
  93465. sum += qlp_coeff[3] * data[i-4];
  93466. sum += qlp_coeff[2] * data[i-3];
  93467. sum += qlp_coeff[1] * data[i-2];
  93468. sum += qlp_coeff[0] * data[i-1];
  93469. data[i] = residual[i] + (sum >> lp_quantization);
  93470. }
  93471. }
  93472. else { /* order == 11 */
  93473. for(i = 0; i < (int)data_len; i++) {
  93474. sum = 0;
  93475. sum += qlp_coeff[10] * data[i-11];
  93476. sum += qlp_coeff[9] * data[i-10];
  93477. sum += qlp_coeff[8] * data[i-9];
  93478. sum += qlp_coeff[7] * data[i-8];
  93479. sum += qlp_coeff[6] * data[i-7];
  93480. sum += qlp_coeff[5] * data[i-6];
  93481. sum += qlp_coeff[4] * data[i-5];
  93482. sum += qlp_coeff[3] * data[i-4];
  93483. sum += qlp_coeff[2] * data[i-3];
  93484. sum += qlp_coeff[1] * data[i-2];
  93485. sum += qlp_coeff[0] * data[i-1];
  93486. data[i] = residual[i] + (sum >> lp_quantization);
  93487. }
  93488. }
  93489. }
  93490. else {
  93491. if(order == 10) {
  93492. for(i = 0; i < (int)data_len; i++) {
  93493. sum = 0;
  93494. sum += qlp_coeff[9] * data[i-10];
  93495. sum += qlp_coeff[8] * data[i-9];
  93496. sum += qlp_coeff[7] * data[i-8];
  93497. sum += qlp_coeff[6] * data[i-7];
  93498. sum += qlp_coeff[5] * data[i-6];
  93499. sum += qlp_coeff[4] * data[i-5];
  93500. sum += qlp_coeff[3] * data[i-4];
  93501. sum += qlp_coeff[2] * data[i-3];
  93502. sum += qlp_coeff[1] * data[i-2];
  93503. sum += qlp_coeff[0] * data[i-1];
  93504. data[i] = residual[i] + (sum >> lp_quantization);
  93505. }
  93506. }
  93507. else { /* order == 9 */
  93508. for(i = 0; i < (int)data_len; i++) {
  93509. sum = 0;
  93510. sum += qlp_coeff[8] * data[i-9];
  93511. sum += qlp_coeff[7] * data[i-8];
  93512. sum += qlp_coeff[6] * data[i-7];
  93513. sum += qlp_coeff[5] * data[i-6];
  93514. sum += qlp_coeff[4] * data[i-5];
  93515. sum += qlp_coeff[3] * data[i-4];
  93516. sum += qlp_coeff[2] * data[i-3];
  93517. sum += qlp_coeff[1] * data[i-2];
  93518. sum += qlp_coeff[0] * data[i-1];
  93519. data[i] = residual[i] + (sum >> lp_quantization);
  93520. }
  93521. }
  93522. }
  93523. }
  93524. else if(order > 4) {
  93525. if(order > 6) {
  93526. if(order == 8) {
  93527. for(i = 0; i < (int)data_len; i++) {
  93528. sum = 0;
  93529. sum += qlp_coeff[7] * data[i-8];
  93530. sum += qlp_coeff[6] * data[i-7];
  93531. sum += qlp_coeff[5] * data[i-6];
  93532. sum += qlp_coeff[4] * data[i-5];
  93533. sum += qlp_coeff[3] * data[i-4];
  93534. sum += qlp_coeff[2] * data[i-3];
  93535. sum += qlp_coeff[1] * data[i-2];
  93536. sum += qlp_coeff[0] * data[i-1];
  93537. data[i] = residual[i] + (sum >> lp_quantization);
  93538. }
  93539. }
  93540. else { /* order == 7 */
  93541. for(i = 0; i < (int)data_len; i++) {
  93542. sum = 0;
  93543. sum += qlp_coeff[6] * data[i-7];
  93544. sum += qlp_coeff[5] * data[i-6];
  93545. sum += qlp_coeff[4] * data[i-5];
  93546. sum += qlp_coeff[3] * data[i-4];
  93547. sum += qlp_coeff[2] * data[i-3];
  93548. sum += qlp_coeff[1] * data[i-2];
  93549. sum += qlp_coeff[0] * data[i-1];
  93550. data[i] = residual[i] + (sum >> lp_quantization);
  93551. }
  93552. }
  93553. }
  93554. else {
  93555. if(order == 6) {
  93556. for(i = 0; i < (int)data_len; i++) {
  93557. sum = 0;
  93558. sum += qlp_coeff[5] * data[i-6];
  93559. sum += qlp_coeff[4] * data[i-5];
  93560. sum += qlp_coeff[3] * data[i-4];
  93561. sum += qlp_coeff[2] * data[i-3];
  93562. sum += qlp_coeff[1] * data[i-2];
  93563. sum += qlp_coeff[0] * data[i-1];
  93564. data[i] = residual[i] + (sum >> lp_quantization);
  93565. }
  93566. }
  93567. else { /* order == 5 */
  93568. for(i = 0; i < (int)data_len; i++) {
  93569. sum = 0;
  93570. sum += qlp_coeff[4] * data[i-5];
  93571. sum += qlp_coeff[3] * data[i-4];
  93572. sum += qlp_coeff[2] * data[i-3];
  93573. sum += qlp_coeff[1] * data[i-2];
  93574. sum += qlp_coeff[0] * data[i-1];
  93575. data[i] = residual[i] + (sum >> lp_quantization);
  93576. }
  93577. }
  93578. }
  93579. }
  93580. else {
  93581. if(order > 2) {
  93582. if(order == 4) {
  93583. for(i = 0; i < (int)data_len; i++) {
  93584. sum = 0;
  93585. sum += qlp_coeff[3] * data[i-4];
  93586. sum += qlp_coeff[2] * data[i-3];
  93587. sum += qlp_coeff[1] * data[i-2];
  93588. sum += qlp_coeff[0] * data[i-1];
  93589. data[i] = residual[i] + (sum >> lp_quantization);
  93590. }
  93591. }
  93592. else { /* order == 3 */
  93593. for(i = 0; i < (int)data_len; i++) {
  93594. sum = 0;
  93595. sum += qlp_coeff[2] * data[i-3];
  93596. sum += qlp_coeff[1] * data[i-2];
  93597. sum += qlp_coeff[0] * data[i-1];
  93598. data[i] = residual[i] + (sum >> lp_quantization);
  93599. }
  93600. }
  93601. }
  93602. else {
  93603. if(order == 2) {
  93604. for(i = 0; i < (int)data_len; i++) {
  93605. sum = 0;
  93606. sum += qlp_coeff[1] * data[i-2];
  93607. sum += qlp_coeff[0] * data[i-1];
  93608. data[i] = residual[i] + (sum >> lp_quantization);
  93609. }
  93610. }
  93611. else { /* order == 1 */
  93612. for(i = 0; i < (int)data_len; i++)
  93613. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93614. }
  93615. }
  93616. }
  93617. }
  93618. else { /* order > 12 */
  93619. for(i = 0; i < (int)data_len; i++) {
  93620. sum = 0;
  93621. switch(order) {
  93622. case 32: sum += qlp_coeff[31] * data[i-32];
  93623. case 31: sum += qlp_coeff[30] * data[i-31];
  93624. case 30: sum += qlp_coeff[29] * data[i-30];
  93625. case 29: sum += qlp_coeff[28] * data[i-29];
  93626. case 28: sum += qlp_coeff[27] * data[i-28];
  93627. case 27: sum += qlp_coeff[26] * data[i-27];
  93628. case 26: sum += qlp_coeff[25] * data[i-26];
  93629. case 25: sum += qlp_coeff[24] * data[i-25];
  93630. case 24: sum += qlp_coeff[23] * data[i-24];
  93631. case 23: sum += qlp_coeff[22] * data[i-23];
  93632. case 22: sum += qlp_coeff[21] * data[i-22];
  93633. case 21: sum += qlp_coeff[20] * data[i-21];
  93634. case 20: sum += qlp_coeff[19] * data[i-20];
  93635. case 19: sum += qlp_coeff[18] * data[i-19];
  93636. case 18: sum += qlp_coeff[17] * data[i-18];
  93637. case 17: sum += qlp_coeff[16] * data[i-17];
  93638. case 16: sum += qlp_coeff[15] * data[i-16];
  93639. case 15: sum += qlp_coeff[14] * data[i-15];
  93640. case 14: sum += qlp_coeff[13] * data[i-14];
  93641. case 13: sum += qlp_coeff[12] * data[i-13];
  93642. sum += qlp_coeff[11] * data[i-12];
  93643. sum += qlp_coeff[10] * data[i-11];
  93644. sum += qlp_coeff[ 9] * data[i-10];
  93645. sum += qlp_coeff[ 8] * data[i- 9];
  93646. sum += qlp_coeff[ 7] * data[i- 8];
  93647. sum += qlp_coeff[ 6] * data[i- 7];
  93648. sum += qlp_coeff[ 5] * data[i- 6];
  93649. sum += qlp_coeff[ 4] * data[i- 5];
  93650. sum += qlp_coeff[ 3] * data[i- 4];
  93651. sum += qlp_coeff[ 2] * data[i- 3];
  93652. sum += qlp_coeff[ 1] * data[i- 2];
  93653. sum += qlp_coeff[ 0] * data[i- 1];
  93654. }
  93655. data[i] = residual[i] + (sum >> lp_quantization);
  93656. }
  93657. }
  93658. }
  93659. #endif
  93660. 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[])
  93661. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93662. {
  93663. unsigned i, j;
  93664. FLAC__int64 sum;
  93665. const FLAC__int32 *r = residual, *history;
  93666. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93667. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93668. for(i=0;i<order;i++)
  93669. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93670. fprintf(stderr,"\n");
  93671. #endif
  93672. FLAC__ASSERT(order > 0);
  93673. for(i = 0; i < data_len; i++) {
  93674. sum = 0;
  93675. history = data;
  93676. for(j = 0; j < order; j++)
  93677. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93678. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93679. #ifdef _MSC_VER
  93680. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93681. #else
  93682. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93683. #endif
  93684. break;
  93685. }
  93686. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  93687. #ifdef _MSC_VER
  93688. 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));
  93689. #else
  93690. 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)));
  93691. #endif
  93692. break;
  93693. }
  93694. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  93695. }
  93696. }
  93697. #else /* fully unrolled version for normal use */
  93698. {
  93699. int i;
  93700. FLAC__int64 sum;
  93701. FLAC__ASSERT(order > 0);
  93702. FLAC__ASSERT(order <= 32);
  93703. /*
  93704. * We do unique versions up to 12th order since that's the subset limit.
  93705. * Also they are roughly ordered to match frequency of occurrence to
  93706. * minimize branching.
  93707. */
  93708. if(order <= 12) {
  93709. if(order > 8) {
  93710. if(order > 10) {
  93711. if(order == 12) {
  93712. for(i = 0; i < (int)data_len; i++) {
  93713. sum = 0;
  93714. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93715. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93716. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93717. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93718. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93719. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93720. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93721. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93722. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93723. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93724. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93725. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93726. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93727. }
  93728. }
  93729. else { /* order == 11 */
  93730. for(i = 0; i < (int)data_len; i++) {
  93731. sum = 0;
  93732. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93733. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93734. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93735. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93736. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93737. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93738. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93739. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93740. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93741. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93742. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93743. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93744. }
  93745. }
  93746. }
  93747. else {
  93748. if(order == 10) {
  93749. for(i = 0; i < (int)data_len; i++) {
  93750. sum = 0;
  93751. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93752. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93753. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93754. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93755. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93756. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93757. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93758. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93759. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93760. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93761. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93762. }
  93763. }
  93764. else { /* order == 9 */
  93765. for(i = 0; i < (int)data_len; i++) {
  93766. sum = 0;
  93767. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93768. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93769. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93770. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93771. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93772. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93773. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93774. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93775. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93776. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93777. }
  93778. }
  93779. }
  93780. }
  93781. else if(order > 4) {
  93782. if(order > 6) {
  93783. if(order == 8) {
  93784. for(i = 0; i < (int)data_len; i++) {
  93785. sum = 0;
  93786. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93787. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93788. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93789. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93790. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93791. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93792. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93793. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93794. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93795. }
  93796. }
  93797. else { /* order == 7 */
  93798. for(i = 0; i < (int)data_len; i++) {
  93799. sum = 0;
  93800. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93801. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93802. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93803. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93804. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93805. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93806. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93807. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93808. }
  93809. }
  93810. }
  93811. else {
  93812. if(order == 6) {
  93813. for(i = 0; i < (int)data_len; i++) {
  93814. sum = 0;
  93815. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93816. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93817. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93818. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93819. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93820. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93821. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93822. }
  93823. }
  93824. else { /* order == 5 */
  93825. for(i = 0; i < (int)data_len; i++) {
  93826. sum = 0;
  93827. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93828. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93829. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93830. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93831. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93832. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93833. }
  93834. }
  93835. }
  93836. }
  93837. else {
  93838. if(order > 2) {
  93839. if(order == 4) {
  93840. for(i = 0; i < (int)data_len; i++) {
  93841. sum = 0;
  93842. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93843. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93844. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93845. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93846. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93847. }
  93848. }
  93849. else { /* order == 3 */
  93850. for(i = 0; i < (int)data_len; i++) {
  93851. sum = 0;
  93852. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93853. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93854. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93855. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93856. }
  93857. }
  93858. }
  93859. else {
  93860. if(order == 2) {
  93861. for(i = 0; i < (int)data_len; i++) {
  93862. sum = 0;
  93863. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93864. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93865. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93866. }
  93867. }
  93868. else { /* order == 1 */
  93869. for(i = 0; i < (int)data_len; i++)
  93870. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93871. }
  93872. }
  93873. }
  93874. }
  93875. else { /* order > 12 */
  93876. for(i = 0; i < (int)data_len; i++) {
  93877. sum = 0;
  93878. switch(order) {
  93879. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93880. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93881. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93882. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93883. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93884. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93885. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93886. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93887. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93888. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93889. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93890. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93891. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93892. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93893. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93894. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93895. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93896. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93897. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93898. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93899. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93900. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93901. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93902. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93903. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93904. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93905. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93906. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93907. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93908. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93909. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93910. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93911. }
  93912. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  93913. }
  93914. }
  93915. }
  93916. #endif
  93917. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93918. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  93919. {
  93920. FLAC__double error_scale;
  93921. FLAC__ASSERT(total_samples > 0);
  93922. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93923. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  93924. }
  93925. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  93926. {
  93927. if(lpc_error > 0.0) {
  93928. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  93929. if(bps >= 0.0)
  93930. return bps;
  93931. else
  93932. return 0.0;
  93933. }
  93934. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  93935. return 1e32;
  93936. }
  93937. else {
  93938. return 0.0;
  93939. }
  93940. }
  93941. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  93942. {
  93943. 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 */
  93944. FLAC__double bits, best_bits, error_scale;
  93945. FLAC__ASSERT(max_order > 0);
  93946. FLAC__ASSERT(total_samples > 0);
  93947. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  93948. best_index = 0;
  93949. best_bits = (unsigned)(-1);
  93950. for(index = 0, order = 1; index < max_order; index++, order++) {
  93951. 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);
  93952. if(bits < best_bits) {
  93953. best_index = index;
  93954. best_bits = bits;
  93955. }
  93956. }
  93957. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  93958. }
  93959. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93960. #endif
  93961. /********* End of inlined file: lpc_flac.c *********/
  93962. /********* Start of inlined file: md5.c *********/
  93963. /********* Start of inlined file: juce_FlacHeader.h *********/
  93964. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93965. // tasks..
  93966. #define VERSION "1.2.1"
  93967. #define FLAC__NO_DLL 1
  93968. #ifdef _MSC_VER
  93969. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93970. #endif
  93971. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  93972. #define FLAC__SYS_DARWIN 1
  93973. #endif
  93974. /********* End of inlined file: juce_FlacHeader.h *********/
  93975. #if JUCE_USE_FLAC
  93976. #if HAVE_CONFIG_H
  93977. # include <config.h>
  93978. #endif
  93979. #include <stdlib.h> /* for malloc() */
  93980. #include <string.h> /* for memcpy() */
  93981. /********* Start of inlined file: md5.h *********/
  93982. #ifndef FLAC__PRIVATE__MD5_H
  93983. #define FLAC__PRIVATE__MD5_H
  93984. /*
  93985. * This is the header file for the MD5 message-digest algorithm.
  93986. * The algorithm is due to Ron Rivest. This code was
  93987. * written by Colin Plumb in 1993, no copyright is claimed.
  93988. * This code is in the public domain; do with it what you wish.
  93989. *
  93990. * Equivalent code is available from RSA Data Security, Inc.
  93991. * This code has been tested against that, and is equivalent,
  93992. * except that you don't need to include two pages of legalese
  93993. * with every copy.
  93994. *
  93995. * To compute the message digest of a chunk of bytes, declare an
  93996. * MD5Context structure, pass it to MD5Init, call MD5Update as
  93997. * needed on buffers full of bytes, and then call MD5Final, which
  93998. * will fill a supplied 16-byte array with the digest.
  93999. *
  94000. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94001. * header definitions; now uses stuff from dpkg's config.h
  94002. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94003. * Still in the public domain.
  94004. *
  94005. * Josh Coalson: made some changes to integrate with libFLAC.
  94006. * Still in the public domain, with no warranty.
  94007. */
  94008. typedef struct {
  94009. FLAC__uint32 in[16];
  94010. FLAC__uint32 buf[4];
  94011. FLAC__uint32 bytes[2];
  94012. FLAC__byte *internal_buf;
  94013. size_t capacity;
  94014. } FLAC__MD5Context;
  94015. void FLAC__MD5Init(FLAC__MD5Context *context);
  94016. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94017. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94018. #endif
  94019. /********* End of inlined file: md5.h *********/
  94020. #ifndef FLaC__INLINE
  94021. #define FLaC__INLINE
  94022. #endif
  94023. /*
  94024. * This code implements the MD5 message-digest algorithm.
  94025. * The algorithm is due to Ron Rivest. This code was
  94026. * written by Colin Plumb in 1993, no copyright is claimed.
  94027. * This code is in the public domain; do with it what you wish.
  94028. *
  94029. * Equivalent code is available from RSA Data Security, Inc.
  94030. * This code has been tested against that, and is equivalent,
  94031. * except that you don't need to include two pages of legalese
  94032. * with every copy.
  94033. *
  94034. * To compute the message digest of a chunk of bytes, declare an
  94035. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94036. * needed on buffers full of bytes, and then call MD5Final, which
  94037. * will fill a supplied 16-byte array with the digest.
  94038. *
  94039. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94040. * definitions; now uses stuff from dpkg's config.h.
  94041. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94042. * Still in the public domain.
  94043. *
  94044. * Josh Coalson: made some changes to integrate with libFLAC.
  94045. * Still in the public domain.
  94046. */
  94047. /* The four core functions - F1 is optimized somewhat */
  94048. /* #define F1(x, y, z) (x & y | ~x & z) */
  94049. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94050. #define F2(x, y, z) F1(z, x, y)
  94051. #define F3(x, y, z) (x ^ y ^ z)
  94052. #define F4(x, y, z) (y ^ (x | ~z))
  94053. /* This is the central step in the MD5 algorithm. */
  94054. #define MD5STEP(f,w,x,y,z,in,s) \
  94055. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94056. /*
  94057. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94058. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94059. * the data and converts bytes into longwords for this routine.
  94060. */
  94061. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94062. {
  94063. register FLAC__uint32 a, b, c, d;
  94064. a = buf[0];
  94065. b = buf[1];
  94066. c = buf[2];
  94067. d = buf[3];
  94068. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94069. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94070. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94071. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94072. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94073. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94074. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94075. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94076. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94077. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94078. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94079. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94080. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94081. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94082. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94083. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94084. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94085. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94086. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94087. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94088. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94089. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94090. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94091. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94092. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94093. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  94094. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  94095. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  94096. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  94097. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  94098. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  94099. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  94100. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  94101. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  94102. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  94103. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  94104. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  94105. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  94106. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  94107. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  94108. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  94109. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  94110. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  94111. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  94112. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  94113. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  94114. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  94115. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  94116. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  94117. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  94118. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  94119. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  94120. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  94121. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  94122. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  94123. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  94124. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  94125. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  94126. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  94127. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  94128. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  94129. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  94130. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  94131. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  94132. buf[0] += a;
  94133. buf[1] += b;
  94134. buf[2] += c;
  94135. buf[3] += d;
  94136. }
  94137. #if WORDS_BIGENDIAN
  94138. //@@@@@@ OPT: use bswap/intrinsics
  94139. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  94140. {
  94141. register FLAC__uint32 x;
  94142. do {
  94143. x = *buf;
  94144. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  94145. *buf++ = (x >> 16) | (x << 16);
  94146. } while (--words);
  94147. }
  94148. static void byteSwapX16(FLAC__uint32 *buf)
  94149. {
  94150. register FLAC__uint32 x;
  94151. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94152. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94153. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94154. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94155. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94156. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94157. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94158. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94159. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94160. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94161. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94162. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94163. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94164. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94165. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94166. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  94167. }
  94168. #else
  94169. #define byteSwap(buf, words)
  94170. #define byteSwapX16(buf)
  94171. #endif
  94172. /*
  94173. * Update context to reflect the concatenation of another buffer full
  94174. * of bytes.
  94175. */
  94176. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  94177. {
  94178. FLAC__uint32 t;
  94179. /* Update byte count */
  94180. t = ctx->bytes[0];
  94181. if ((ctx->bytes[0] = t + len) < t)
  94182. ctx->bytes[1]++; /* Carry from low to high */
  94183. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  94184. if (t > len) {
  94185. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  94186. return;
  94187. }
  94188. /* First chunk is an odd size */
  94189. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  94190. byteSwapX16(ctx->in);
  94191. FLAC__MD5Transform(ctx->buf, ctx->in);
  94192. buf += t;
  94193. len -= t;
  94194. /* Process data in 64-byte chunks */
  94195. while (len >= 64) {
  94196. memcpy(ctx->in, buf, 64);
  94197. byteSwapX16(ctx->in);
  94198. FLAC__MD5Transform(ctx->buf, ctx->in);
  94199. buf += 64;
  94200. len -= 64;
  94201. }
  94202. /* Handle any remaining bytes of data. */
  94203. memcpy(ctx->in, buf, len);
  94204. }
  94205. /*
  94206. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  94207. * initialization constants.
  94208. */
  94209. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  94210. {
  94211. ctx->buf[0] = 0x67452301;
  94212. ctx->buf[1] = 0xefcdab89;
  94213. ctx->buf[2] = 0x98badcfe;
  94214. ctx->buf[3] = 0x10325476;
  94215. ctx->bytes[0] = 0;
  94216. ctx->bytes[1] = 0;
  94217. ctx->internal_buf = 0;
  94218. ctx->capacity = 0;
  94219. }
  94220. /*
  94221. * Final wrapup - pad to 64-byte boundary with the bit pattern
  94222. * 1 0* (64-bit count of bits processed, MSB-first)
  94223. */
  94224. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  94225. {
  94226. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  94227. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  94228. /* Set the first char of padding to 0x80. There is always room. */
  94229. *p++ = 0x80;
  94230. /* Bytes of padding needed to make 56 bytes (-8..55) */
  94231. count = 56 - 1 - count;
  94232. if (count < 0) { /* Padding forces an extra block */
  94233. memset(p, 0, count + 8);
  94234. byteSwapX16(ctx->in);
  94235. FLAC__MD5Transform(ctx->buf, ctx->in);
  94236. p = (FLAC__byte *)ctx->in;
  94237. count = 56;
  94238. }
  94239. memset(p, 0, count);
  94240. byteSwap(ctx->in, 14);
  94241. /* Append length in bits and transform */
  94242. ctx->in[14] = ctx->bytes[0] << 3;
  94243. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  94244. FLAC__MD5Transform(ctx->buf, ctx->in);
  94245. byteSwap(ctx->buf, 4);
  94246. memcpy(digest, ctx->buf, 16);
  94247. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  94248. if(0 != ctx->internal_buf) {
  94249. free(ctx->internal_buf);
  94250. ctx->internal_buf = 0;
  94251. ctx->capacity = 0;
  94252. }
  94253. }
  94254. /*
  94255. * Convert the incoming audio signal to a byte stream
  94256. */
  94257. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94258. {
  94259. unsigned channel, sample;
  94260. register FLAC__int32 a_word;
  94261. register FLAC__byte *buf_ = buf;
  94262. #if WORDS_BIGENDIAN
  94263. #else
  94264. if(channels == 2 && bytes_per_sample == 2) {
  94265. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  94266. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  94267. for(sample = 0; sample < samples; sample++, buf1_+=2)
  94268. *buf1_ = (FLAC__int16)signal[1][sample];
  94269. }
  94270. else if(channels == 1 && bytes_per_sample == 2) {
  94271. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  94272. for(sample = 0; sample < samples; sample++)
  94273. *buf1_++ = (FLAC__int16)signal[0][sample];
  94274. }
  94275. else
  94276. #endif
  94277. if(bytes_per_sample == 2) {
  94278. if(channels == 2) {
  94279. for(sample = 0; sample < samples; sample++) {
  94280. a_word = signal[0][sample];
  94281. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94282. *buf_++ = (FLAC__byte)a_word;
  94283. a_word = signal[1][sample];
  94284. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94285. *buf_++ = (FLAC__byte)a_word;
  94286. }
  94287. }
  94288. else if(channels == 1) {
  94289. for(sample = 0; sample < samples; sample++) {
  94290. a_word = signal[0][sample];
  94291. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94292. *buf_++ = (FLAC__byte)a_word;
  94293. }
  94294. }
  94295. else {
  94296. for(sample = 0; sample < samples; sample++) {
  94297. for(channel = 0; channel < channels; channel++) {
  94298. a_word = signal[channel][sample];
  94299. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94300. *buf_++ = (FLAC__byte)a_word;
  94301. }
  94302. }
  94303. }
  94304. }
  94305. else if(bytes_per_sample == 3) {
  94306. if(channels == 2) {
  94307. for(sample = 0; sample < samples; sample++) {
  94308. a_word = signal[0][sample];
  94309. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94310. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94311. *buf_++ = (FLAC__byte)a_word;
  94312. a_word = signal[1][sample];
  94313. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94314. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94315. *buf_++ = (FLAC__byte)a_word;
  94316. }
  94317. }
  94318. else if(channels == 1) {
  94319. for(sample = 0; sample < samples; sample++) {
  94320. a_word = signal[0][sample];
  94321. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94322. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94323. *buf_++ = (FLAC__byte)a_word;
  94324. }
  94325. }
  94326. else {
  94327. for(sample = 0; sample < samples; sample++) {
  94328. for(channel = 0; channel < channels; channel++) {
  94329. a_word = signal[channel][sample];
  94330. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94331. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94332. *buf_++ = (FLAC__byte)a_word;
  94333. }
  94334. }
  94335. }
  94336. }
  94337. else if(bytes_per_sample == 1) {
  94338. if(channels == 2) {
  94339. for(sample = 0; sample < samples; sample++) {
  94340. a_word = signal[0][sample];
  94341. *buf_++ = (FLAC__byte)a_word;
  94342. a_word = signal[1][sample];
  94343. *buf_++ = (FLAC__byte)a_word;
  94344. }
  94345. }
  94346. else if(channels == 1) {
  94347. for(sample = 0; sample < samples; sample++) {
  94348. a_word = signal[0][sample];
  94349. *buf_++ = (FLAC__byte)a_word;
  94350. }
  94351. }
  94352. else {
  94353. for(sample = 0; sample < samples; sample++) {
  94354. for(channel = 0; channel < channels; channel++) {
  94355. a_word = signal[channel][sample];
  94356. *buf_++ = (FLAC__byte)a_word;
  94357. }
  94358. }
  94359. }
  94360. }
  94361. else { /* bytes_per_sample == 4, maybe optimize more later */
  94362. for(sample = 0; sample < samples; sample++) {
  94363. for(channel = 0; channel < channels; channel++) {
  94364. a_word = signal[channel][sample];
  94365. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94366. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94367. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94368. *buf_++ = (FLAC__byte)a_word;
  94369. }
  94370. }
  94371. }
  94372. }
  94373. /*
  94374. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  94375. */
  94376. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94377. {
  94378. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  94379. /* overflow check */
  94380. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  94381. return false;
  94382. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  94383. return false;
  94384. if(ctx->capacity < bytes_needed) {
  94385. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  94386. if(0 == tmp) {
  94387. free(ctx->internal_buf);
  94388. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  94389. return false;
  94390. }
  94391. ctx->internal_buf = tmp;
  94392. ctx->capacity = bytes_needed;
  94393. }
  94394. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  94395. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  94396. return true;
  94397. }
  94398. #endif
  94399. /********* End of inlined file: md5.c *********/
  94400. /********* Start of inlined file: memory.c *********/
  94401. /********* Start of inlined file: juce_FlacHeader.h *********/
  94402. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94403. // tasks..
  94404. #define VERSION "1.2.1"
  94405. #define FLAC__NO_DLL 1
  94406. #ifdef _MSC_VER
  94407. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94408. #endif
  94409. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94410. #define FLAC__SYS_DARWIN 1
  94411. #endif
  94412. /********* End of inlined file: juce_FlacHeader.h *********/
  94413. #if JUCE_USE_FLAC
  94414. #if HAVE_CONFIG_H
  94415. # include <config.h>
  94416. #endif
  94417. /********* Start of inlined file: memory.h *********/
  94418. #ifndef FLAC__PRIVATE__MEMORY_H
  94419. #define FLAC__PRIVATE__MEMORY_H
  94420. #ifdef HAVE_CONFIG_H
  94421. #include <config.h>
  94422. #endif
  94423. #include <stdlib.h> /* for size_t */
  94424. /* Returns the unaligned address returned by malloc.
  94425. * Use free() on this address to deallocate.
  94426. */
  94427. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  94428. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  94429. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  94430. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  94431. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  94432. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94433. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  94434. #endif
  94435. #endif
  94436. /********* End of inlined file: memory.h *********/
  94437. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  94438. {
  94439. void *x;
  94440. FLAC__ASSERT(0 != aligned_address);
  94441. #ifdef FLAC__ALIGN_MALLOC_DATA
  94442. /* align on 32-byte (256-bit) boundary */
  94443. x = safe_malloc_add_2op_(bytes, /*+*/31);
  94444. #ifdef SIZEOF_VOIDP
  94445. #if SIZEOF_VOIDP == 4
  94446. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  94447. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94448. #elif SIZEOF_VOIDP == 8
  94449. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94450. #else
  94451. # error Unsupported sizeof(void*)
  94452. #endif
  94453. #else
  94454. /* there's got to be a better way to do this right for all archs */
  94455. if(sizeof(void*) == sizeof(unsigned))
  94456. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  94457. else if(sizeof(void*) == sizeof(FLAC__uint64))
  94458. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  94459. else
  94460. return 0;
  94461. #endif
  94462. #else
  94463. x = safe_malloc_(bytes);
  94464. *aligned_address = x;
  94465. #endif
  94466. return x;
  94467. }
  94468. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  94469. {
  94470. FLAC__int32 *pu; /* unaligned pointer */
  94471. union { /* union needed to comply with C99 pointer aliasing rules */
  94472. FLAC__int32 *pa; /* aligned pointer */
  94473. void *pv; /* aligned pointer alias */
  94474. } u;
  94475. FLAC__ASSERT(elements > 0);
  94476. FLAC__ASSERT(0 != unaligned_pointer);
  94477. FLAC__ASSERT(0 != aligned_pointer);
  94478. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94479. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94480. return false;
  94481. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  94482. if(0 == pu) {
  94483. return false;
  94484. }
  94485. else {
  94486. if(*unaligned_pointer != 0)
  94487. free(*unaligned_pointer);
  94488. *unaligned_pointer = pu;
  94489. *aligned_pointer = u.pa;
  94490. return true;
  94491. }
  94492. }
  94493. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  94494. {
  94495. FLAC__uint32 *pu; /* unaligned pointer */
  94496. union { /* union needed to comply with C99 pointer aliasing rules */
  94497. FLAC__uint32 *pa; /* aligned pointer */
  94498. void *pv; /* aligned pointer alias */
  94499. } u;
  94500. FLAC__ASSERT(elements > 0);
  94501. FLAC__ASSERT(0 != unaligned_pointer);
  94502. FLAC__ASSERT(0 != aligned_pointer);
  94503. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94504. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94505. return false;
  94506. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94507. if(0 == pu) {
  94508. return false;
  94509. }
  94510. else {
  94511. if(*unaligned_pointer != 0)
  94512. free(*unaligned_pointer);
  94513. *unaligned_pointer = pu;
  94514. *aligned_pointer = u.pa;
  94515. return true;
  94516. }
  94517. }
  94518. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  94519. {
  94520. FLAC__uint64 *pu; /* unaligned pointer */
  94521. union { /* union needed to comply with C99 pointer aliasing rules */
  94522. FLAC__uint64 *pa; /* aligned pointer */
  94523. void *pv; /* aligned pointer alias */
  94524. } u;
  94525. FLAC__ASSERT(elements > 0);
  94526. FLAC__ASSERT(0 != unaligned_pointer);
  94527. FLAC__ASSERT(0 != aligned_pointer);
  94528. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94529. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94530. return false;
  94531. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94532. if(0 == pu) {
  94533. return false;
  94534. }
  94535. else {
  94536. if(*unaligned_pointer != 0)
  94537. free(*unaligned_pointer);
  94538. *unaligned_pointer = pu;
  94539. *aligned_pointer = u.pa;
  94540. return true;
  94541. }
  94542. }
  94543. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  94544. {
  94545. unsigned *pu; /* unaligned pointer */
  94546. union { /* union needed to comply with C99 pointer aliasing rules */
  94547. unsigned *pa; /* aligned pointer */
  94548. void *pv; /* aligned pointer alias */
  94549. } u;
  94550. FLAC__ASSERT(elements > 0);
  94551. FLAC__ASSERT(0 != unaligned_pointer);
  94552. FLAC__ASSERT(0 != aligned_pointer);
  94553. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94554. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94555. return false;
  94556. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94557. if(0 == pu) {
  94558. return false;
  94559. }
  94560. else {
  94561. if(*unaligned_pointer != 0)
  94562. free(*unaligned_pointer);
  94563. *unaligned_pointer = pu;
  94564. *aligned_pointer = u.pa;
  94565. return true;
  94566. }
  94567. }
  94568. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94569. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  94570. {
  94571. FLAC__real *pu; /* unaligned pointer */
  94572. union { /* union needed to comply with C99 pointer aliasing rules */
  94573. FLAC__real *pa; /* aligned pointer */
  94574. void *pv; /* aligned pointer alias */
  94575. } u;
  94576. FLAC__ASSERT(elements > 0);
  94577. FLAC__ASSERT(0 != unaligned_pointer);
  94578. FLAC__ASSERT(0 != aligned_pointer);
  94579. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  94580. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  94581. return false;
  94582. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  94583. if(0 == pu) {
  94584. return false;
  94585. }
  94586. else {
  94587. if(*unaligned_pointer != 0)
  94588. free(*unaligned_pointer);
  94589. *unaligned_pointer = pu;
  94590. *aligned_pointer = u.pa;
  94591. return true;
  94592. }
  94593. }
  94594. #endif
  94595. #endif
  94596. /********* End of inlined file: memory.c *********/
  94597. /********* Start of inlined file: stream_decoder.c *********/
  94598. /********* Start of inlined file: juce_FlacHeader.h *********/
  94599. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94600. // tasks..
  94601. #define VERSION "1.2.1"
  94602. #define FLAC__NO_DLL 1
  94603. #ifdef _MSC_VER
  94604. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94605. #endif
  94606. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94607. #define FLAC__SYS_DARWIN 1
  94608. #endif
  94609. /********* End of inlined file: juce_FlacHeader.h *********/
  94610. #if JUCE_USE_FLAC
  94611. #if HAVE_CONFIG_H
  94612. # include <config.h>
  94613. #endif
  94614. #if defined _MSC_VER || defined __MINGW32__
  94615. #include <io.h> /* for _setmode() */
  94616. #include <fcntl.h> /* for _O_BINARY */
  94617. #endif
  94618. #if defined __CYGWIN__ || defined __EMX__
  94619. #include <io.h> /* for setmode(), O_BINARY */
  94620. #include <fcntl.h> /* for _O_BINARY */
  94621. #endif
  94622. #include <stdio.h>
  94623. #include <stdlib.h> /* for malloc() */
  94624. #include <string.h> /* for memset/memcpy() */
  94625. #include <sys/stat.h> /* for stat() */
  94626. #include <sys/types.h> /* for off_t */
  94627. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  94628. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  94629. #define fseeko fseek
  94630. #define ftello ftell
  94631. #endif
  94632. #endif
  94633. /********* Start of inlined file: stream_decoder.h *********/
  94634. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  94635. #define FLAC__PROTECTED__STREAM_DECODER_H
  94636. #if FLAC__HAS_OGG
  94637. #include "include/private/ogg_decoder_aspect.h"
  94638. #endif
  94639. typedef struct FLAC__StreamDecoderProtected {
  94640. FLAC__StreamDecoderState state;
  94641. unsigned channels;
  94642. FLAC__ChannelAssignment channel_assignment;
  94643. unsigned bits_per_sample;
  94644. unsigned sample_rate; /* in Hz */
  94645. unsigned blocksize; /* in samples (per channel) */
  94646. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  94647. #if FLAC__HAS_OGG
  94648. FLAC__OggDecoderAspect ogg_decoder_aspect;
  94649. #endif
  94650. } FLAC__StreamDecoderProtected;
  94651. /*
  94652. * return the number of input bytes consumed
  94653. */
  94654. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  94655. #endif
  94656. /********* End of inlined file: stream_decoder.h *********/
  94657. #ifdef max
  94658. #undef max
  94659. #endif
  94660. #define max(a,b) ((a)>(b)?(a):(b))
  94661. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94662. #ifdef _MSC_VER
  94663. #define FLAC__U64L(x) x
  94664. #else
  94665. #define FLAC__U64L(x) x##LLU
  94666. #endif
  94667. /* technically this should be in an "export.c" but this is convenient enough */
  94668. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  94669. #if FLAC__HAS_OGG
  94670. 1
  94671. #else
  94672. 0
  94673. #endif
  94674. ;
  94675. /***********************************************************************
  94676. *
  94677. * Private static data
  94678. *
  94679. ***********************************************************************/
  94680. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  94681. /***********************************************************************
  94682. *
  94683. * Private class method prototypes
  94684. *
  94685. ***********************************************************************/
  94686. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  94687. static FILE *get_binary_stdin_(void);
  94688. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  94689. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  94690. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  94691. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  94692. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94693. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  94694. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  94695. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  94696. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  94697. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  94698. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  94699. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  94700. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  94701. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94702. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94703. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94704. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  94705. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  94706. 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);
  94707. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  94708. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  94709. #if FLAC__HAS_OGG
  94710. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  94711. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94712. #endif
  94713. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  94714. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  94715. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94716. #if FLAC__HAS_OGG
  94717. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  94718. #endif
  94719. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  94720. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  94721. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  94722. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  94723. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  94724. /***********************************************************************
  94725. *
  94726. * Private class data
  94727. *
  94728. ***********************************************************************/
  94729. typedef struct FLAC__StreamDecoderPrivate {
  94730. #if FLAC__HAS_OGG
  94731. FLAC__bool is_ogg;
  94732. #endif
  94733. FLAC__StreamDecoderReadCallback read_callback;
  94734. FLAC__StreamDecoderSeekCallback seek_callback;
  94735. FLAC__StreamDecoderTellCallback tell_callback;
  94736. FLAC__StreamDecoderLengthCallback length_callback;
  94737. FLAC__StreamDecoderEofCallback eof_callback;
  94738. FLAC__StreamDecoderWriteCallback write_callback;
  94739. FLAC__StreamDecoderMetadataCallback metadata_callback;
  94740. FLAC__StreamDecoderErrorCallback error_callback;
  94741. /* generic 32-bit datapath: */
  94742. 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[]);
  94743. /* generic 64-bit datapath: */
  94744. 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[]);
  94745. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  94746. 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[]);
  94747. /* 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: */
  94748. 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[]);
  94749. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  94750. void *client_data;
  94751. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  94752. FLAC__BitReader *input;
  94753. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  94754. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  94755. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  94756. unsigned output_capacity, output_channels;
  94757. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  94758. FLAC__uint64 samples_decoded;
  94759. FLAC__bool has_stream_info, has_seek_table;
  94760. FLAC__StreamMetadata stream_info;
  94761. FLAC__StreamMetadata seek_table;
  94762. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  94763. FLAC__byte *metadata_filter_ids;
  94764. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  94765. FLAC__Frame frame;
  94766. FLAC__bool cached; /* true if there is a byte in lookahead */
  94767. FLAC__CPUInfo cpuinfo;
  94768. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  94769. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  94770. /* unaligned (original) pointers to allocated data */
  94771. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  94772. 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 */
  94773. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  94774. FLAC__bool is_seeking;
  94775. FLAC__MD5Context md5context;
  94776. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  94777. /* (the rest of these are only used for seeking) */
  94778. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  94779. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  94780. FLAC__uint64 target_sample;
  94781. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  94782. #if FLAC__HAS_OGG
  94783. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  94784. #endif
  94785. } FLAC__StreamDecoderPrivate;
  94786. /***********************************************************************
  94787. *
  94788. * Public static class data
  94789. *
  94790. ***********************************************************************/
  94791. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  94792. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  94793. "FLAC__STREAM_DECODER_READ_METADATA",
  94794. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  94795. "FLAC__STREAM_DECODER_READ_FRAME",
  94796. "FLAC__STREAM_DECODER_END_OF_STREAM",
  94797. "FLAC__STREAM_DECODER_OGG_ERROR",
  94798. "FLAC__STREAM_DECODER_SEEK_ERROR",
  94799. "FLAC__STREAM_DECODER_ABORTED",
  94800. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  94801. "FLAC__STREAM_DECODER_UNINITIALIZED"
  94802. };
  94803. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  94804. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  94805. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  94806. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  94807. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  94808. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  94809. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  94810. };
  94811. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  94812. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  94813. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  94814. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  94815. };
  94816. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  94817. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  94818. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  94819. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  94820. };
  94821. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  94822. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  94823. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  94824. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  94825. };
  94826. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  94827. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  94828. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  94829. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  94830. };
  94831. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  94832. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  94833. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  94834. };
  94835. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  94836. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  94837. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  94838. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  94839. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  94840. };
  94841. /***********************************************************************
  94842. *
  94843. * Class constructor/destructor
  94844. *
  94845. ***********************************************************************/
  94846. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  94847. {
  94848. FLAC__StreamDecoder *decoder;
  94849. unsigned i;
  94850. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  94851. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  94852. if(decoder == 0) {
  94853. return 0;
  94854. }
  94855. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  94856. if(decoder->protected_ == 0) {
  94857. free(decoder);
  94858. return 0;
  94859. }
  94860. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  94861. if(decoder->private_ == 0) {
  94862. free(decoder->protected_);
  94863. free(decoder);
  94864. return 0;
  94865. }
  94866. decoder->private_->input = FLAC__bitreader_new();
  94867. if(decoder->private_->input == 0) {
  94868. free(decoder->private_);
  94869. free(decoder->protected_);
  94870. free(decoder);
  94871. return 0;
  94872. }
  94873. decoder->private_->metadata_filter_ids_capacity = 16;
  94874. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  94875. FLAC__bitreader_delete(decoder->private_->input);
  94876. free(decoder->private_);
  94877. free(decoder->protected_);
  94878. free(decoder);
  94879. return 0;
  94880. }
  94881. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  94882. decoder->private_->output[i] = 0;
  94883. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  94884. }
  94885. decoder->private_->output_capacity = 0;
  94886. decoder->private_->output_channels = 0;
  94887. decoder->private_->has_seek_table = false;
  94888. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94889. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  94890. decoder->private_->file = 0;
  94891. set_defaults_dec(decoder);
  94892. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  94893. return decoder;
  94894. }
  94895. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  94896. {
  94897. unsigned i;
  94898. FLAC__ASSERT(0 != decoder);
  94899. FLAC__ASSERT(0 != decoder->protected_);
  94900. FLAC__ASSERT(0 != decoder->private_);
  94901. FLAC__ASSERT(0 != decoder->private_->input);
  94902. (void)FLAC__stream_decoder_finish(decoder);
  94903. if(0 != decoder->private_->metadata_filter_ids)
  94904. free(decoder->private_->metadata_filter_ids);
  94905. FLAC__bitreader_delete(decoder->private_->input);
  94906. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  94907. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  94908. free(decoder->private_);
  94909. free(decoder->protected_);
  94910. free(decoder);
  94911. }
  94912. /***********************************************************************
  94913. *
  94914. * Public class methods
  94915. *
  94916. ***********************************************************************/
  94917. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  94918. FLAC__StreamDecoder *decoder,
  94919. FLAC__StreamDecoderReadCallback read_callback,
  94920. FLAC__StreamDecoderSeekCallback seek_callback,
  94921. FLAC__StreamDecoderTellCallback tell_callback,
  94922. FLAC__StreamDecoderLengthCallback length_callback,
  94923. FLAC__StreamDecoderEofCallback eof_callback,
  94924. FLAC__StreamDecoderWriteCallback write_callback,
  94925. FLAC__StreamDecoderMetadataCallback metadata_callback,
  94926. FLAC__StreamDecoderErrorCallback error_callback,
  94927. void *client_data,
  94928. FLAC__bool is_ogg
  94929. )
  94930. {
  94931. FLAC__ASSERT(0 != decoder);
  94932. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  94933. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  94934. #if !FLAC__HAS_OGG
  94935. if(is_ogg)
  94936. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  94937. #endif
  94938. if(
  94939. 0 == read_callback ||
  94940. 0 == write_callback ||
  94941. 0 == error_callback ||
  94942. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  94943. )
  94944. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  94945. #if FLAC__HAS_OGG
  94946. decoder->private_->is_ogg = is_ogg;
  94947. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  94948. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  94949. #endif
  94950. /*
  94951. * get the CPU info and set the function pointers
  94952. */
  94953. FLAC__cpu_info(&decoder->private_->cpuinfo);
  94954. /* first default to the non-asm routines */
  94955. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  94956. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  94957. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  94958. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  94959. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  94960. /* now override with asm where appropriate */
  94961. #ifndef FLAC__NO_ASM
  94962. if(decoder->private_->cpuinfo.use_asm) {
  94963. #ifdef FLAC__CPU_IA32
  94964. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  94965. #ifdef FLAC__HAS_NASM
  94966. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  94967. if(decoder->private_->cpuinfo.data.ia32.bswap)
  94968. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  94969. #endif
  94970. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  94971. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94972. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94973. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  94974. }
  94975. else {
  94976. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  94977. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  94978. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  94979. }
  94980. #endif
  94981. #elif defined FLAC__CPU_PPC
  94982. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  94983. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  94984. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  94985. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  94986. }
  94987. #endif
  94988. }
  94989. #endif
  94990. /* from here on, errors are fatal */
  94991. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  94992. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94993. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  94994. }
  94995. decoder->private_->read_callback = read_callback;
  94996. decoder->private_->seek_callback = seek_callback;
  94997. decoder->private_->tell_callback = tell_callback;
  94998. decoder->private_->length_callback = length_callback;
  94999. decoder->private_->eof_callback = eof_callback;
  95000. decoder->private_->write_callback = write_callback;
  95001. decoder->private_->metadata_callback = metadata_callback;
  95002. decoder->private_->error_callback = error_callback;
  95003. decoder->private_->client_data = client_data;
  95004. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95005. decoder->private_->samples_decoded = 0;
  95006. decoder->private_->has_stream_info = false;
  95007. decoder->private_->cached = false;
  95008. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95009. decoder->private_->is_seeking = false;
  95010. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95011. if(!FLAC__stream_decoder_reset(decoder)) {
  95012. /* above call sets the state for us */
  95013. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95014. }
  95015. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95016. }
  95017. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95018. FLAC__StreamDecoder *decoder,
  95019. FLAC__StreamDecoderReadCallback read_callback,
  95020. FLAC__StreamDecoderSeekCallback seek_callback,
  95021. FLAC__StreamDecoderTellCallback tell_callback,
  95022. FLAC__StreamDecoderLengthCallback length_callback,
  95023. FLAC__StreamDecoderEofCallback eof_callback,
  95024. FLAC__StreamDecoderWriteCallback write_callback,
  95025. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95026. FLAC__StreamDecoderErrorCallback error_callback,
  95027. void *client_data
  95028. )
  95029. {
  95030. return init_stream_internal_dec(
  95031. decoder,
  95032. read_callback,
  95033. seek_callback,
  95034. tell_callback,
  95035. length_callback,
  95036. eof_callback,
  95037. write_callback,
  95038. metadata_callback,
  95039. error_callback,
  95040. client_data,
  95041. /*is_ogg=*/false
  95042. );
  95043. }
  95044. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95045. FLAC__StreamDecoder *decoder,
  95046. FLAC__StreamDecoderReadCallback read_callback,
  95047. FLAC__StreamDecoderSeekCallback seek_callback,
  95048. FLAC__StreamDecoderTellCallback tell_callback,
  95049. FLAC__StreamDecoderLengthCallback length_callback,
  95050. FLAC__StreamDecoderEofCallback eof_callback,
  95051. FLAC__StreamDecoderWriteCallback write_callback,
  95052. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95053. FLAC__StreamDecoderErrorCallback error_callback,
  95054. void *client_data
  95055. )
  95056. {
  95057. return init_stream_internal_dec(
  95058. decoder,
  95059. read_callback,
  95060. seek_callback,
  95061. tell_callback,
  95062. length_callback,
  95063. eof_callback,
  95064. write_callback,
  95065. metadata_callback,
  95066. error_callback,
  95067. client_data,
  95068. /*is_ogg=*/true
  95069. );
  95070. }
  95071. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95072. FLAC__StreamDecoder *decoder,
  95073. FILE *file,
  95074. FLAC__StreamDecoderWriteCallback write_callback,
  95075. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95076. FLAC__StreamDecoderErrorCallback error_callback,
  95077. void *client_data,
  95078. FLAC__bool is_ogg
  95079. )
  95080. {
  95081. FLAC__ASSERT(0 != decoder);
  95082. FLAC__ASSERT(0 != file);
  95083. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95084. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95085. if(0 == write_callback || 0 == error_callback)
  95086. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95087. /*
  95088. * To make sure that our file does not go unclosed after an error, we
  95089. * must assign the FILE pointer before any further error can occur in
  95090. * this routine.
  95091. */
  95092. if(file == stdin)
  95093. file = get_binary_stdin_(); /* just to be safe */
  95094. decoder->private_->file = file;
  95095. return init_stream_internal_dec(
  95096. decoder,
  95097. file_read_callback_dec,
  95098. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95099. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95100. decoder->private_->file == stdin? 0: file_length_callback_,
  95101. file_eof_callback_,
  95102. write_callback,
  95103. metadata_callback,
  95104. error_callback,
  95105. client_data,
  95106. is_ogg
  95107. );
  95108. }
  95109. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  95110. FLAC__StreamDecoder *decoder,
  95111. FILE *file,
  95112. FLAC__StreamDecoderWriteCallback write_callback,
  95113. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95114. FLAC__StreamDecoderErrorCallback error_callback,
  95115. void *client_data
  95116. )
  95117. {
  95118. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95119. }
  95120. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  95121. FLAC__StreamDecoder *decoder,
  95122. FILE *file,
  95123. FLAC__StreamDecoderWriteCallback write_callback,
  95124. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95125. FLAC__StreamDecoderErrorCallback error_callback,
  95126. void *client_data
  95127. )
  95128. {
  95129. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95130. }
  95131. static FLAC__StreamDecoderInitStatus init_file_internal_(
  95132. FLAC__StreamDecoder *decoder,
  95133. const char *filename,
  95134. FLAC__StreamDecoderWriteCallback write_callback,
  95135. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95136. FLAC__StreamDecoderErrorCallback error_callback,
  95137. void *client_data,
  95138. FLAC__bool is_ogg
  95139. )
  95140. {
  95141. FILE *file;
  95142. FLAC__ASSERT(0 != decoder);
  95143. /*
  95144. * To make sure that our file does not go unclosed after an error, we
  95145. * have to do the same entrance checks here that are later performed
  95146. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  95147. */
  95148. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95149. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95150. if(0 == write_callback || 0 == error_callback)
  95151. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95152. file = filename? fopen(filename, "rb") : stdin;
  95153. if(0 == file)
  95154. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  95155. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  95156. }
  95157. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  95158. FLAC__StreamDecoder *decoder,
  95159. const char *filename,
  95160. FLAC__StreamDecoderWriteCallback write_callback,
  95161. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95162. FLAC__StreamDecoderErrorCallback error_callback,
  95163. void *client_data
  95164. )
  95165. {
  95166. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95167. }
  95168. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  95169. FLAC__StreamDecoder *decoder,
  95170. const char *filename,
  95171. FLAC__StreamDecoderWriteCallback write_callback,
  95172. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95173. FLAC__StreamDecoderErrorCallback error_callback,
  95174. void *client_data
  95175. )
  95176. {
  95177. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95178. }
  95179. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  95180. {
  95181. FLAC__bool md5_failed = false;
  95182. unsigned i;
  95183. FLAC__ASSERT(0 != decoder);
  95184. FLAC__ASSERT(0 != decoder->private_);
  95185. FLAC__ASSERT(0 != decoder->protected_);
  95186. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  95187. return true;
  95188. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  95189. * always call FLAC__MD5Final()
  95190. */
  95191. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  95192. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95193. free(decoder->private_->seek_table.data.seek_table.points);
  95194. decoder->private_->seek_table.data.seek_table.points = 0;
  95195. decoder->private_->has_seek_table = false;
  95196. }
  95197. FLAC__bitreader_free(decoder->private_->input);
  95198. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95199. /* WATCHOUT:
  95200. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95201. * output arrays have a buffer of up to 3 zeroes in front
  95202. * (at negative indices) for alignment purposes; we use 4
  95203. * to keep the data well-aligned.
  95204. */
  95205. if(0 != decoder->private_->output[i]) {
  95206. free(decoder->private_->output[i]-4);
  95207. decoder->private_->output[i] = 0;
  95208. }
  95209. if(0 != decoder->private_->residual_unaligned[i]) {
  95210. free(decoder->private_->residual_unaligned[i]);
  95211. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95212. }
  95213. }
  95214. decoder->private_->output_capacity = 0;
  95215. decoder->private_->output_channels = 0;
  95216. #if FLAC__HAS_OGG
  95217. if(decoder->private_->is_ogg)
  95218. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  95219. #endif
  95220. if(0 != decoder->private_->file) {
  95221. if(decoder->private_->file != stdin)
  95222. fclose(decoder->private_->file);
  95223. decoder->private_->file = 0;
  95224. }
  95225. if(decoder->private_->do_md5_checking) {
  95226. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  95227. md5_failed = true;
  95228. }
  95229. decoder->private_->is_seeking = false;
  95230. set_defaults_dec(decoder);
  95231. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95232. return !md5_failed;
  95233. }
  95234. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  95235. {
  95236. FLAC__ASSERT(0 != decoder);
  95237. FLAC__ASSERT(0 != decoder->private_);
  95238. FLAC__ASSERT(0 != decoder->protected_);
  95239. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95240. return false;
  95241. #if FLAC__HAS_OGG
  95242. /* can't check decoder->private_->is_ogg since that's not set until init time */
  95243. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  95244. return true;
  95245. #else
  95246. (void)value;
  95247. return false;
  95248. #endif
  95249. }
  95250. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  95251. {
  95252. FLAC__ASSERT(0 != decoder);
  95253. FLAC__ASSERT(0 != decoder->protected_);
  95254. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95255. return false;
  95256. decoder->protected_->md5_checking = value;
  95257. return true;
  95258. }
  95259. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95260. {
  95261. FLAC__ASSERT(0 != decoder);
  95262. FLAC__ASSERT(0 != decoder->private_);
  95263. FLAC__ASSERT(0 != decoder->protected_);
  95264. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95265. /* double protection */
  95266. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95267. return false;
  95268. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95269. return false;
  95270. decoder->private_->metadata_filter[type] = true;
  95271. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95272. decoder->private_->metadata_filter_ids_count = 0;
  95273. return true;
  95274. }
  95275. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95276. {
  95277. FLAC__ASSERT(0 != decoder);
  95278. FLAC__ASSERT(0 != decoder->private_);
  95279. FLAC__ASSERT(0 != decoder->protected_);
  95280. FLAC__ASSERT(0 != id);
  95281. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95282. return false;
  95283. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95284. return true;
  95285. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95286. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95287. 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))) {
  95288. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95289. return false;
  95290. }
  95291. decoder->private_->metadata_filter_ids_capacity *= 2;
  95292. }
  95293. 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));
  95294. decoder->private_->metadata_filter_ids_count++;
  95295. return true;
  95296. }
  95297. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  95298. {
  95299. unsigned i;
  95300. FLAC__ASSERT(0 != decoder);
  95301. FLAC__ASSERT(0 != decoder->private_);
  95302. FLAC__ASSERT(0 != decoder->protected_);
  95303. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95304. return false;
  95305. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  95306. decoder->private_->metadata_filter[i] = true;
  95307. decoder->private_->metadata_filter_ids_count = 0;
  95308. return true;
  95309. }
  95310. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  95311. {
  95312. FLAC__ASSERT(0 != decoder);
  95313. FLAC__ASSERT(0 != decoder->private_);
  95314. FLAC__ASSERT(0 != decoder->protected_);
  95315. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  95316. /* double protection */
  95317. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  95318. return false;
  95319. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95320. return false;
  95321. decoder->private_->metadata_filter[type] = false;
  95322. if(type == FLAC__METADATA_TYPE_APPLICATION)
  95323. decoder->private_->metadata_filter_ids_count = 0;
  95324. return true;
  95325. }
  95326. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  95327. {
  95328. FLAC__ASSERT(0 != decoder);
  95329. FLAC__ASSERT(0 != decoder->private_);
  95330. FLAC__ASSERT(0 != decoder->protected_);
  95331. FLAC__ASSERT(0 != id);
  95332. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95333. return false;
  95334. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  95335. return true;
  95336. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  95337. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  95338. 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))) {
  95339. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95340. return false;
  95341. }
  95342. decoder->private_->metadata_filter_ids_capacity *= 2;
  95343. }
  95344. 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));
  95345. decoder->private_->metadata_filter_ids_count++;
  95346. return true;
  95347. }
  95348. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  95349. {
  95350. FLAC__ASSERT(0 != decoder);
  95351. FLAC__ASSERT(0 != decoder->private_);
  95352. FLAC__ASSERT(0 != decoder->protected_);
  95353. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95354. return false;
  95355. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95356. decoder->private_->metadata_filter_ids_count = 0;
  95357. return true;
  95358. }
  95359. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  95360. {
  95361. FLAC__ASSERT(0 != decoder);
  95362. FLAC__ASSERT(0 != decoder->protected_);
  95363. return decoder->protected_->state;
  95364. }
  95365. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  95366. {
  95367. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  95368. }
  95369. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  95370. {
  95371. FLAC__ASSERT(0 != decoder);
  95372. FLAC__ASSERT(0 != decoder->protected_);
  95373. return decoder->protected_->md5_checking;
  95374. }
  95375. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  95376. {
  95377. FLAC__ASSERT(0 != decoder);
  95378. FLAC__ASSERT(0 != decoder->protected_);
  95379. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  95380. }
  95381. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  95382. {
  95383. FLAC__ASSERT(0 != decoder);
  95384. FLAC__ASSERT(0 != decoder->protected_);
  95385. return decoder->protected_->channels;
  95386. }
  95387. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  95388. {
  95389. FLAC__ASSERT(0 != decoder);
  95390. FLAC__ASSERT(0 != decoder->protected_);
  95391. return decoder->protected_->channel_assignment;
  95392. }
  95393. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  95394. {
  95395. FLAC__ASSERT(0 != decoder);
  95396. FLAC__ASSERT(0 != decoder->protected_);
  95397. return decoder->protected_->bits_per_sample;
  95398. }
  95399. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  95400. {
  95401. FLAC__ASSERT(0 != decoder);
  95402. FLAC__ASSERT(0 != decoder->protected_);
  95403. return decoder->protected_->sample_rate;
  95404. }
  95405. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  95406. {
  95407. FLAC__ASSERT(0 != decoder);
  95408. FLAC__ASSERT(0 != decoder->protected_);
  95409. return decoder->protected_->blocksize;
  95410. }
  95411. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  95412. {
  95413. FLAC__ASSERT(0 != decoder);
  95414. FLAC__ASSERT(0 != decoder->private_);
  95415. FLAC__ASSERT(0 != position);
  95416. #if FLAC__HAS_OGG
  95417. if(decoder->private_->is_ogg)
  95418. return false;
  95419. #endif
  95420. if(0 == decoder->private_->tell_callback)
  95421. return false;
  95422. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  95423. return false;
  95424. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  95425. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  95426. return false;
  95427. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  95428. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  95429. return true;
  95430. }
  95431. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  95432. {
  95433. FLAC__ASSERT(0 != decoder);
  95434. FLAC__ASSERT(0 != decoder->private_);
  95435. FLAC__ASSERT(0 != decoder->protected_);
  95436. decoder->private_->samples_decoded = 0;
  95437. decoder->private_->do_md5_checking = false;
  95438. #if FLAC__HAS_OGG
  95439. if(decoder->private_->is_ogg)
  95440. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  95441. #endif
  95442. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  95443. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95444. return false;
  95445. }
  95446. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95447. return true;
  95448. }
  95449. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  95450. {
  95451. FLAC__ASSERT(0 != decoder);
  95452. FLAC__ASSERT(0 != decoder->private_);
  95453. FLAC__ASSERT(0 != decoder->protected_);
  95454. if(!FLAC__stream_decoder_flush(decoder)) {
  95455. /* above call sets the state for us */
  95456. return false;
  95457. }
  95458. #if FLAC__HAS_OGG
  95459. /*@@@ could go in !internal_reset_hack block below */
  95460. if(decoder->private_->is_ogg)
  95461. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  95462. #endif
  95463. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  95464. * (internal_reset_hack) don't try to rewind since we are already at
  95465. * the beginning of the stream and don't want to fail if the input is
  95466. * not seekable.
  95467. */
  95468. if(!decoder->private_->internal_reset_hack) {
  95469. if(decoder->private_->file == stdin)
  95470. return false; /* can't rewind stdin, reset fails */
  95471. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  95472. return false; /* seekable and seek fails, reset fails */
  95473. }
  95474. else
  95475. decoder->private_->internal_reset_hack = false;
  95476. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  95477. decoder->private_->has_stream_info = false;
  95478. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  95479. free(decoder->private_->seek_table.data.seek_table.points);
  95480. decoder->private_->seek_table.data.seek_table.points = 0;
  95481. decoder->private_->has_seek_table = false;
  95482. }
  95483. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95484. /*
  95485. * This goes in reset() and not flush() because according to the spec, a
  95486. * fixed-blocksize stream must stay that way through the whole stream.
  95487. */
  95488. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95489. /* We initialize the FLAC__MD5Context even though we may never use it. This
  95490. * is because md5 checking may be turned on to start and then turned off if
  95491. * a seek occurs. So we init the context here and finalize it in
  95492. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  95493. * properly.
  95494. */
  95495. FLAC__MD5Init(&decoder->private_->md5context);
  95496. decoder->private_->first_frame_offset = 0;
  95497. decoder->private_->unparseable_frame_count = 0;
  95498. return true;
  95499. }
  95500. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  95501. {
  95502. FLAC__bool got_a_frame;
  95503. FLAC__ASSERT(0 != decoder);
  95504. FLAC__ASSERT(0 != decoder->protected_);
  95505. while(1) {
  95506. switch(decoder->protected_->state) {
  95507. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95508. if(!find_metadata_(decoder))
  95509. return false; /* above function sets the status for us */
  95510. break;
  95511. case FLAC__STREAM_DECODER_READ_METADATA:
  95512. if(!read_metadata_(decoder))
  95513. return false; /* above function sets the status for us */
  95514. else
  95515. return true;
  95516. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95517. if(!frame_sync_(decoder))
  95518. return true; /* above function sets the status for us */
  95519. break;
  95520. case FLAC__STREAM_DECODER_READ_FRAME:
  95521. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  95522. return false; /* above function sets the status for us */
  95523. if(got_a_frame)
  95524. return true; /* above function sets the status for us */
  95525. break;
  95526. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95527. case FLAC__STREAM_DECODER_ABORTED:
  95528. return true;
  95529. default:
  95530. FLAC__ASSERT(0);
  95531. return false;
  95532. }
  95533. }
  95534. }
  95535. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  95536. {
  95537. FLAC__ASSERT(0 != decoder);
  95538. FLAC__ASSERT(0 != decoder->protected_);
  95539. while(1) {
  95540. switch(decoder->protected_->state) {
  95541. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95542. if(!find_metadata_(decoder))
  95543. return false; /* above function sets the status for us */
  95544. break;
  95545. case FLAC__STREAM_DECODER_READ_METADATA:
  95546. if(!read_metadata_(decoder))
  95547. return false; /* above function sets the status for us */
  95548. break;
  95549. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95550. case FLAC__STREAM_DECODER_READ_FRAME:
  95551. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95552. case FLAC__STREAM_DECODER_ABORTED:
  95553. return true;
  95554. default:
  95555. FLAC__ASSERT(0);
  95556. return false;
  95557. }
  95558. }
  95559. }
  95560. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  95561. {
  95562. FLAC__bool dummy;
  95563. FLAC__ASSERT(0 != decoder);
  95564. FLAC__ASSERT(0 != decoder->protected_);
  95565. while(1) {
  95566. switch(decoder->protected_->state) {
  95567. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95568. if(!find_metadata_(decoder))
  95569. return false; /* above function sets the status for us */
  95570. break;
  95571. case FLAC__STREAM_DECODER_READ_METADATA:
  95572. if(!read_metadata_(decoder))
  95573. return false; /* above function sets the status for us */
  95574. break;
  95575. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95576. if(!frame_sync_(decoder))
  95577. return true; /* above function sets the status for us */
  95578. break;
  95579. case FLAC__STREAM_DECODER_READ_FRAME:
  95580. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  95581. return false; /* above function sets the status for us */
  95582. break;
  95583. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95584. case FLAC__STREAM_DECODER_ABORTED:
  95585. return true;
  95586. default:
  95587. FLAC__ASSERT(0);
  95588. return false;
  95589. }
  95590. }
  95591. }
  95592. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  95593. {
  95594. FLAC__bool got_a_frame;
  95595. FLAC__ASSERT(0 != decoder);
  95596. FLAC__ASSERT(0 != decoder->protected_);
  95597. while(1) {
  95598. switch(decoder->protected_->state) {
  95599. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  95600. case FLAC__STREAM_DECODER_READ_METADATA:
  95601. return false; /* above function sets the status for us */
  95602. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  95603. if(!frame_sync_(decoder))
  95604. return true; /* above function sets the status for us */
  95605. break;
  95606. case FLAC__STREAM_DECODER_READ_FRAME:
  95607. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  95608. return false; /* above function sets the status for us */
  95609. if(got_a_frame)
  95610. return true; /* above function sets the status for us */
  95611. break;
  95612. case FLAC__STREAM_DECODER_END_OF_STREAM:
  95613. case FLAC__STREAM_DECODER_ABORTED:
  95614. return true;
  95615. default:
  95616. FLAC__ASSERT(0);
  95617. return false;
  95618. }
  95619. }
  95620. }
  95621. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  95622. {
  95623. FLAC__uint64 length;
  95624. FLAC__ASSERT(0 != decoder);
  95625. if(
  95626. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  95627. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  95628. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  95629. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  95630. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  95631. )
  95632. return false;
  95633. if(0 == decoder->private_->seek_callback)
  95634. return false;
  95635. FLAC__ASSERT(decoder->private_->seek_callback);
  95636. FLAC__ASSERT(decoder->private_->tell_callback);
  95637. FLAC__ASSERT(decoder->private_->length_callback);
  95638. FLAC__ASSERT(decoder->private_->eof_callback);
  95639. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  95640. return false;
  95641. decoder->private_->is_seeking = true;
  95642. /* turn off md5 checking if a seek is attempted */
  95643. decoder->private_->do_md5_checking = false;
  95644. /* 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) */
  95645. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  95646. decoder->private_->is_seeking = false;
  95647. return false;
  95648. }
  95649. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  95650. if(
  95651. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  95652. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  95653. ) {
  95654. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  95655. /* above call sets the state for us */
  95656. decoder->private_->is_seeking = false;
  95657. return false;
  95658. }
  95659. /* check this again in case we didn't know total_samples the first time */
  95660. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  95661. decoder->private_->is_seeking = false;
  95662. return false;
  95663. }
  95664. }
  95665. {
  95666. const FLAC__bool ok =
  95667. #if FLAC__HAS_OGG
  95668. decoder->private_->is_ogg?
  95669. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  95670. #endif
  95671. seek_to_absolute_sample_(decoder, length, sample)
  95672. ;
  95673. decoder->private_->is_seeking = false;
  95674. return ok;
  95675. }
  95676. }
  95677. /***********************************************************************
  95678. *
  95679. * Protected class methods
  95680. *
  95681. ***********************************************************************/
  95682. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  95683. {
  95684. FLAC__ASSERT(0 != decoder);
  95685. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95686. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  95687. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  95688. }
  95689. /***********************************************************************
  95690. *
  95691. * Private class methods
  95692. *
  95693. ***********************************************************************/
  95694. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  95695. {
  95696. #if FLAC__HAS_OGG
  95697. decoder->private_->is_ogg = false;
  95698. #endif
  95699. decoder->private_->read_callback = 0;
  95700. decoder->private_->seek_callback = 0;
  95701. decoder->private_->tell_callback = 0;
  95702. decoder->private_->length_callback = 0;
  95703. decoder->private_->eof_callback = 0;
  95704. decoder->private_->write_callback = 0;
  95705. decoder->private_->metadata_callback = 0;
  95706. decoder->private_->error_callback = 0;
  95707. decoder->private_->client_data = 0;
  95708. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  95709. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  95710. decoder->private_->metadata_filter_ids_count = 0;
  95711. decoder->protected_->md5_checking = false;
  95712. #if FLAC__HAS_OGG
  95713. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  95714. #endif
  95715. }
  95716. /*
  95717. * This will forcibly set stdin to binary mode (for OSes that require it)
  95718. */
  95719. FILE *get_binary_stdin_(void)
  95720. {
  95721. /* if something breaks here it is probably due to the presence or
  95722. * absence of an underscore before the identifiers 'setmode',
  95723. * 'fileno', and/or 'O_BINARY'; check your system header files.
  95724. */
  95725. #if defined _MSC_VER || defined __MINGW32__
  95726. _setmode(_fileno(stdin), _O_BINARY);
  95727. #elif defined __CYGWIN__
  95728. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  95729. setmode(_fileno(stdin), _O_BINARY);
  95730. #elif defined __EMX__
  95731. setmode(fileno(stdin), O_BINARY);
  95732. #endif
  95733. return stdin;
  95734. }
  95735. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  95736. {
  95737. unsigned i;
  95738. FLAC__int32 *tmp;
  95739. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  95740. return true;
  95741. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  95742. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95743. if(0 != decoder->private_->output[i]) {
  95744. free(decoder->private_->output[i]-4);
  95745. decoder->private_->output[i] = 0;
  95746. }
  95747. if(0 != decoder->private_->residual_unaligned[i]) {
  95748. free(decoder->private_->residual_unaligned[i]);
  95749. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95750. }
  95751. }
  95752. for(i = 0; i < channels; i++) {
  95753. /* WATCHOUT:
  95754. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  95755. * output arrays have a buffer of up to 3 zeroes in front
  95756. * (at negative indices) for alignment purposes; we use 4
  95757. * to keep the data well-aligned.
  95758. */
  95759. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  95760. if(tmp == 0) {
  95761. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95762. return false;
  95763. }
  95764. memset(tmp, 0, sizeof(FLAC__int32)*4);
  95765. decoder->private_->output[i] = tmp + 4;
  95766. /* WATCHOUT:
  95767. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  95768. */
  95769. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  95770. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95771. return false;
  95772. }
  95773. }
  95774. decoder->private_->output_capacity = size;
  95775. decoder->private_->output_channels = channels;
  95776. return true;
  95777. }
  95778. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  95779. {
  95780. size_t i;
  95781. FLAC__ASSERT(0 != decoder);
  95782. FLAC__ASSERT(0 != decoder->private_);
  95783. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  95784. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  95785. return true;
  95786. return false;
  95787. }
  95788. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  95789. {
  95790. FLAC__uint32 x;
  95791. unsigned i, id_;
  95792. FLAC__bool first = true;
  95793. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95794. for(i = id_ = 0; i < 4; ) {
  95795. if(decoder->private_->cached) {
  95796. x = (FLAC__uint32)decoder->private_->lookahead;
  95797. decoder->private_->cached = false;
  95798. }
  95799. else {
  95800. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95801. return false; /* read_callback_ sets the state for us */
  95802. }
  95803. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  95804. first = true;
  95805. i++;
  95806. id_ = 0;
  95807. continue;
  95808. }
  95809. if(x == ID3V2_TAG_[id_]) {
  95810. id_++;
  95811. i = 0;
  95812. if(id_ == 3) {
  95813. if(!skip_id3v2_tag_(decoder))
  95814. return false; /* skip_id3v2_tag_ sets the state for us */
  95815. }
  95816. continue;
  95817. }
  95818. id_ = 0;
  95819. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95820. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  95821. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  95822. return false; /* read_callback_ sets the state for us */
  95823. /* 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 */
  95824. /* else we have to check if the second byte is the end of a sync code */
  95825. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  95826. decoder->private_->lookahead = (FLAC__byte)x;
  95827. decoder->private_->cached = true;
  95828. }
  95829. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  95830. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  95831. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  95832. return true;
  95833. }
  95834. }
  95835. i = 0;
  95836. if(first) {
  95837. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  95838. first = false;
  95839. }
  95840. }
  95841. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  95842. return true;
  95843. }
  95844. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  95845. {
  95846. FLAC__bool is_last;
  95847. FLAC__uint32 i, x, type, length;
  95848. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  95849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  95850. return false; /* read_callback_ sets the state for us */
  95851. is_last = x? true : false;
  95852. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  95853. return false; /* read_callback_ sets the state for us */
  95854. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  95855. return false; /* read_callback_ sets the state for us */
  95856. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  95857. if(!read_metadata_streaminfo_(decoder, is_last, length))
  95858. return false;
  95859. decoder->private_->has_stream_info = true;
  95860. 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))
  95861. decoder->private_->do_md5_checking = false;
  95862. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  95863. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  95864. }
  95865. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  95866. if(!read_metadata_seektable_(decoder, is_last, length))
  95867. return false;
  95868. decoder->private_->has_seek_table = true;
  95869. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  95870. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  95871. }
  95872. else {
  95873. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  95874. unsigned real_length = length;
  95875. FLAC__StreamMetadata block;
  95876. block.is_last = is_last;
  95877. block.type = (FLAC__MetadataType)type;
  95878. block.length = length;
  95879. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  95880. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  95881. return false; /* read_callback_ sets the state for us */
  95882. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  95883. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  95884. return false;
  95885. }
  95886. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  95887. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  95888. skip_it = !skip_it;
  95889. }
  95890. if(skip_it) {
  95891. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95892. return false; /* read_callback_ sets the state for us */
  95893. }
  95894. else {
  95895. switch(type) {
  95896. case FLAC__METADATA_TYPE_PADDING:
  95897. /* skip the padding bytes */
  95898. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  95899. return false; /* read_callback_ sets the state for us */
  95900. break;
  95901. case FLAC__METADATA_TYPE_APPLICATION:
  95902. /* remember, we read the ID already */
  95903. if(real_length > 0) {
  95904. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  95905. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95906. return false;
  95907. }
  95908. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  95909. return false; /* read_callback_ sets the state for us */
  95910. }
  95911. else
  95912. block.data.application.data = 0;
  95913. break;
  95914. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95915. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  95916. return false;
  95917. break;
  95918. case FLAC__METADATA_TYPE_CUESHEET:
  95919. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  95920. return false;
  95921. break;
  95922. case FLAC__METADATA_TYPE_PICTURE:
  95923. if(!read_metadata_picture_(decoder, &block.data.picture))
  95924. return false;
  95925. break;
  95926. case FLAC__METADATA_TYPE_STREAMINFO:
  95927. case FLAC__METADATA_TYPE_SEEKTABLE:
  95928. FLAC__ASSERT(0);
  95929. break;
  95930. default:
  95931. if(real_length > 0) {
  95932. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  95933. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95934. return false;
  95935. }
  95936. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  95937. return false; /* read_callback_ sets the state for us */
  95938. }
  95939. else
  95940. block.data.unknown.data = 0;
  95941. break;
  95942. }
  95943. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  95944. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  95945. /* now we have to free any malloc()ed data in the block */
  95946. switch(type) {
  95947. case FLAC__METADATA_TYPE_PADDING:
  95948. break;
  95949. case FLAC__METADATA_TYPE_APPLICATION:
  95950. if(0 != block.data.application.data)
  95951. free(block.data.application.data);
  95952. break;
  95953. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  95954. if(0 != block.data.vorbis_comment.vendor_string.entry)
  95955. free(block.data.vorbis_comment.vendor_string.entry);
  95956. if(block.data.vorbis_comment.num_comments > 0)
  95957. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  95958. if(0 != block.data.vorbis_comment.comments[i].entry)
  95959. free(block.data.vorbis_comment.comments[i].entry);
  95960. if(0 != block.data.vorbis_comment.comments)
  95961. free(block.data.vorbis_comment.comments);
  95962. break;
  95963. case FLAC__METADATA_TYPE_CUESHEET:
  95964. if(block.data.cue_sheet.num_tracks > 0)
  95965. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  95966. if(0 != block.data.cue_sheet.tracks[i].indices)
  95967. free(block.data.cue_sheet.tracks[i].indices);
  95968. if(0 != block.data.cue_sheet.tracks)
  95969. free(block.data.cue_sheet.tracks);
  95970. break;
  95971. case FLAC__METADATA_TYPE_PICTURE:
  95972. if(0 != block.data.picture.mime_type)
  95973. free(block.data.picture.mime_type);
  95974. if(0 != block.data.picture.description)
  95975. free(block.data.picture.description);
  95976. if(0 != block.data.picture.data)
  95977. free(block.data.picture.data);
  95978. break;
  95979. case FLAC__METADATA_TYPE_STREAMINFO:
  95980. case FLAC__METADATA_TYPE_SEEKTABLE:
  95981. FLAC__ASSERT(0);
  95982. default:
  95983. if(0 != block.data.unknown.data)
  95984. free(block.data.unknown.data);
  95985. break;
  95986. }
  95987. }
  95988. }
  95989. if(is_last) {
  95990. /* if this fails, it's OK, it's just a hint for the seek routine */
  95991. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  95992. decoder->private_->first_frame_offset = 0;
  95993. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  95994. }
  95995. return true;
  95996. }
  95997. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  95998. {
  95999. FLAC__uint32 x;
  96000. unsigned bits, used_bits = 0;
  96001. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96002. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96003. decoder->private_->stream_info.is_last = is_last;
  96004. decoder->private_->stream_info.length = length;
  96005. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96006. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96007. return false; /* read_callback_ sets the state for us */
  96008. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96009. used_bits += bits;
  96010. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96011. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96012. return false; /* read_callback_ sets the state for us */
  96013. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96014. used_bits += bits;
  96015. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96016. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96017. return false; /* read_callback_ sets the state for us */
  96018. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96019. used_bits += bits;
  96020. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96021. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96022. return false; /* read_callback_ sets the state for us */
  96023. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96024. used_bits += bits;
  96025. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96026. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96027. return false; /* read_callback_ sets the state for us */
  96028. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96029. used_bits += bits;
  96030. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96031. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96032. return false; /* read_callback_ sets the state for us */
  96033. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96034. used_bits += bits;
  96035. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96036. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96037. return false; /* read_callback_ sets the state for us */
  96038. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96039. used_bits += bits;
  96040. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96041. 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))
  96042. return false; /* read_callback_ sets the state for us */
  96043. used_bits += bits;
  96044. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96045. return false; /* read_callback_ sets the state for us */
  96046. used_bits += 16*8;
  96047. /* skip the rest of the block */
  96048. FLAC__ASSERT(used_bits % 8 == 0);
  96049. length -= (used_bits / 8);
  96050. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96051. return false; /* read_callback_ sets the state for us */
  96052. return true;
  96053. }
  96054. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96055. {
  96056. FLAC__uint32 i, x;
  96057. FLAC__uint64 xx;
  96058. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96059. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96060. decoder->private_->seek_table.is_last = is_last;
  96061. decoder->private_->seek_table.length = length;
  96062. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96063. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96064. 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)))) {
  96065. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96066. return false;
  96067. }
  96068. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96069. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96070. return false; /* read_callback_ sets the state for us */
  96071. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96072. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96073. return false; /* read_callback_ sets the state for us */
  96074. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96075. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96076. return false; /* read_callback_ sets the state for us */
  96077. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96078. }
  96079. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96080. /* if there is a partial point left, skip over it */
  96081. if(length > 0) {
  96082. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96083. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96084. return false; /* read_callback_ sets the state for us */
  96085. }
  96086. return true;
  96087. }
  96088. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96089. {
  96090. FLAC__uint32 i;
  96091. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96092. /* read vendor string */
  96093. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96094. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96095. return false; /* read_callback_ sets the state for us */
  96096. if(obj->vendor_string.length > 0) {
  96097. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96098. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96099. return false;
  96100. }
  96101. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96102. return false; /* read_callback_ sets the state for us */
  96103. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  96104. }
  96105. else
  96106. obj->vendor_string.entry = 0;
  96107. /* read num comments */
  96108. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  96109. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  96110. return false; /* read_callback_ sets the state for us */
  96111. /* read comments */
  96112. if(obj->num_comments > 0) {
  96113. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  96114. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96115. return false;
  96116. }
  96117. for(i = 0; i < obj->num_comments; i++) {
  96118. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96119. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  96120. return false; /* read_callback_ sets the state for us */
  96121. if(obj->comments[i].length > 0) {
  96122. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  96123. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96124. return false;
  96125. }
  96126. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  96127. return false; /* read_callback_ sets the state for us */
  96128. obj->comments[i].entry[obj->comments[i].length] = '\0';
  96129. }
  96130. else
  96131. obj->comments[i].entry = 0;
  96132. }
  96133. }
  96134. else {
  96135. obj->comments = 0;
  96136. }
  96137. return true;
  96138. }
  96139. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  96140. {
  96141. FLAC__uint32 i, j, x;
  96142. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96143. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  96144. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  96145. 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))
  96146. return false; /* read_callback_ sets the state for us */
  96147. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  96148. return false; /* read_callback_ sets the state for us */
  96149. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  96150. return false; /* read_callback_ sets the state for us */
  96151. obj->is_cd = x? true : false;
  96152. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  96153. return false; /* read_callback_ sets the state for us */
  96154. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  96155. return false; /* read_callback_ sets the state for us */
  96156. obj->num_tracks = x;
  96157. if(obj->num_tracks > 0) {
  96158. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  96159. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96160. return false;
  96161. }
  96162. for(i = 0; i < obj->num_tracks; i++) {
  96163. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  96164. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  96165. return false; /* read_callback_ sets the state for us */
  96166. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  96167. return false; /* read_callback_ sets the state for us */
  96168. track->number = (FLAC__byte)x;
  96169. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  96170. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  96171. return false; /* read_callback_ sets the state for us */
  96172. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  96173. return false; /* read_callback_ sets the state for us */
  96174. track->type = x;
  96175. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  96176. return false; /* read_callback_ sets the state for us */
  96177. track->pre_emphasis = x;
  96178. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  96179. return false; /* read_callback_ sets the state for us */
  96180. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  96181. return false; /* read_callback_ sets the state for us */
  96182. track->num_indices = (FLAC__byte)x;
  96183. if(track->num_indices > 0) {
  96184. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  96185. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96186. return false;
  96187. }
  96188. for(j = 0; j < track->num_indices; j++) {
  96189. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  96190. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  96191. return false; /* read_callback_ sets the state for us */
  96192. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  96193. return false; /* read_callback_ sets the state for us */
  96194. index->number = (FLAC__byte)x;
  96195. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  96196. return false; /* read_callback_ sets the state for us */
  96197. }
  96198. }
  96199. }
  96200. }
  96201. return true;
  96202. }
  96203. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  96204. {
  96205. FLAC__uint32 x;
  96206. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96207. /* read type */
  96208. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  96209. return false; /* read_callback_ sets the state for us */
  96210. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  96211. /* read MIME type */
  96212. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  96213. return false; /* read_callback_ sets the state for us */
  96214. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  96215. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96216. return false;
  96217. }
  96218. if(x > 0) {
  96219. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  96220. return false; /* read_callback_ sets the state for us */
  96221. }
  96222. obj->mime_type[x] = '\0';
  96223. /* read description */
  96224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  96225. return false; /* read_callback_ sets the state for us */
  96226. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  96227. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96228. return false;
  96229. }
  96230. if(x > 0) {
  96231. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  96232. return false; /* read_callback_ sets the state for us */
  96233. }
  96234. obj->description[x] = '\0';
  96235. /* read width */
  96236. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  96237. return false; /* read_callback_ sets the state for us */
  96238. /* read height */
  96239. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  96240. return false; /* read_callback_ sets the state for us */
  96241. /* read depth */
  96242. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  96243. return false; /* read_callback_ sets the state for us */
  96244. /* read colors */
  96245. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  96246. return false; /* read_callback_ sets the state for us */
  96247. /* read data */
  96248. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  96249. return false; /* read_callback_ sets the state for us */
  96250. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  96251. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96252. return false;
  96253. }
  96254. if(obj->data_length > 0) {
  96255. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  96256. return false; /* read_callback_ sets the state for us */
  96257. }
  96258. return true;
  96259. }
  96260. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  96261. {
  96262. FLAC__uint32 x;
  96263. unsigned i, skip;
  96264. /* skip the version and flags bytes */
  96265. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  96266. return false; /* read_callback_ sets the state for us */
  96267. /* get the size (in bytes) to skip */
  96268. skip = 0;
  96269. for(i = 0; i < 4; i++) {
  96270. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96271. return false; /* read_callback_ sets the state for us */
  96272. skip <<= 7;
  96273. skip |= (x & 0x7f);
  96274. }
  96275. /* skip the rest of the tag */
  96276. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  96277. return false; /* read_callback_ sets the state for us */
  96278. return true;
  96279. }
  96280. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  96281. {
  96282. FLAC__uint32 x;
  96283. FLAC__bool first = true;
  96284. /* If we know the total number of samples in the stream, stop if we've read that many. */
  96285. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  96286. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  96287. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96288. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  96289. return true;
  96290. }
  96291. }
  96292. /* make sure we're byte aligned */
  96293. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  96294. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  96295. return false; /* read_callback_ sets the state for us */
  96296. }
  96297. while(1) {
  96298. if(decoder->private_->cached) {
  96299. x = (FLAC__uint32)decoder->private_->lookahead;
  96300. decoder->private_->cached = false;
  96301. }
  96302. else {
  96303. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96304. return false; /* read_callback_ sets the state for us */
  96305. }
  96306. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96307. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96308. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96309. return false; /* read_callback_ sets the state for us */
  96310. /* 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 */
  96311. /* else we have to check if the second byte is the end of a sync code */
  96312. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96313. decoder->private_->lookahead = (FLAC__byte)x;
  96314. decoder->private_->cached = true;
  96315. }
  96316. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96317. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96318. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96319. return true;
  96320. }
  96321. }
  96322. if(first) {
  96323. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96324. first = false;
  96325. }
  96326. }
  96327. return true;
  96328. }
  96329. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  96330. {
  96331. unsigned channel;
  96332. unsigned i;
  96333. FLAC__int32 mid, side;
  96334. unsigned frame_crc; /* the one we calculate from the input stream */
  96335. FLAC__uint32 x;
  96336. *got_a_frame = false;
  96337. /* init the CRC */
  96338. frame_crc = 0;
  96339. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  96340. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  96341. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  96342. if(!read_frame_header_(decoder))
  96343. return false;
  96344. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  96345. return true;
  96346. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  96347. return false;
  96348. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96349. /*
  96350. * first figure the correct bits-per-sample of the subframe
  96351. */
  96352. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  96353. switch(decoder->private_->frame.header.channel_assignment) {
  96354. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96355. /* no adjustment needed */
  96356. break;
  96357. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96358. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96359. if(channel == 1)
  96360. bps++;
  96361. break;
  96362. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96363. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96364. if(channel == 0)
  96365. bps++;
  96366. break;
  96367. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96368. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96369. if(channel == 1)
  96370. bps++;
  96371. break;
  96372. default:
  96373. FLAC__ASSERT(0);
  96374. }
  96375. /*
  96376. * now read it
  96377. */
  96378. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  96379. return false;
  96380. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96381. return true;
  96382. }
  96383. if(!read_zero_padding_(decoder))
  96384. return false;
  96385. 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) */
  96386. return true;
  96387. /*
  96388. * Read the frame CRC-16 from the footer and check
  96389. */
  96390. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  96391. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  96392. return false; /* read_callback_ sets the state for us */
  96393. if(frame_crc == x) {
  96394. if(do_full_decode) {
  96395. /* Undo any special channel coding */
  96396. switch(decoder->private_->frame.header.channel_assignment) {
  96397. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  96398. /* do nothing */
  96399. break;
  96400. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  96401. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96402. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96403. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  96404. break;
  96405. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  96406. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96407. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96408. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  96409. break;
  96410. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  96411. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  96412. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96413. #if 1
  96414. mid = decoder->private_->output[0][i];
  96415. side = decoder->private_->output[1][i];
  96416. mid <<= 1;
  96417. mid |= (side & 1); /* i.e. if 'side' is odd... */
  96418. decoder->private_->output[0][i] = (mid + side) >> 1;
  96419. decoder->private_->output[1][i] = (mid - side) >> 1;
  96420. #else
  96421. /* OPT: without 'side' temp variable */
  96422. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  96423. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  96424. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  96425. #endif
  96426. }
  96427. break;
  96428. default:
  96429. FLAC__ASSERT(0);
  96430. break;
  96431. }
  96432. }
  96433. }
  96434. else {
  96435. /* Bad frame, emit error and zero the output signal */
  96436. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  96437. if(do_full_decode) {
  96438. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  96439. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96440. }
  96441. }
  96442. }
  96443. *got_a_frame = true;
  96444. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  96445. if(decoder->private_->next_fixed_block_size)
  96446. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  96447. /* put the latest values into the public section of the decoder instance */
  96448. decoder->protected_->channels = decoder->private_->frame.header.channels;
  96449. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  96450. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  96451. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  96452. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  96453. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  96454. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  96455. /* write it */
  96456. if(do_full_decode) {
  96457. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  96458. return false;
  96459. }
  96460. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96461. return true;
  96462. }
  96463. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  96464. {
  96465. FLAC__uint32 x;
  96466. FLAC__uint64 xx;
  96467. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  96468. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  96469. unsigned raw_header_len;
  96470. FLAC__bool is_unparseable = false;
  96471. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96472. /* init the raw header with the saved bits from synchronization */
  96473. raw_header[0] = decoder->private_->header_warmup[0];
  96474. raw_header[1] = decoder->private_->header_warmup[1];
  96475. raw_header_len = 2;
  96476. /* check to make sure that reserved bit is 0 */
  96477. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  96478. is_unparseable = true;
  96479. /*
  96480. * Note that along the way as we read the header, we look for a sync
  96481. * code inside. If we find one it would indicate that our original
  96482. * sync was bad since there cannot be a sync code in a valid header.
  96483. *
  96484. * Three kinds of things can go wrong when reading the frame header:
  96485. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  96486. * If we don't find a sync code, it can end up looking like we read
  96487. * a valid but unparseable header, until getting to the frame header
  96488. * CRC. Even then we could get a false positive on the CRC.
  96489. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  96490. * future encoder).
  96491. * 3) We may be on a damaged frame which appears valid but unparseable.
  96492. *
  96493. * For all these reasons, we try and read a complete frame header as
  96494. * long as it seems valid, even if unparseable, up until the frame
  96495. * header CRC.
  96496. */
  96497. /*
  96498. * read in the raw header as bytes so we can CRC it, and parse it on the way
  96499. */
  96500. for(i = 0; i < 2; i++) {
  96501. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96502. return false; /* read_callback_ sets the state for us */
  96503. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96504. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  96505. decoder->private_->lookahead = (FLAC__byte)x;
  96506. decoder->private_->cached = true;
  96507. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96508. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96509. return true;
  96510. }
  96511. raw_header[raw_header_len++] = (FLAC__byte)x;
  96512. }
  96513. switch(x = raw_header[2] >> 4) {
  96514. case 0:
  96515. is_unparseable = true;
  96516. break;
  96517. case 1:
  96518. decoder->private_->frame.header.blocksize = 192;
  96519. break;
  96520. case 2:
  96521. case 3:
  96522. case 4:
  96523. case 5:
  96524. decoder->private_->frame.header.blocksize = 576 << (x-2);
  96525. break;
  96526. case 6:
  96527. case 7:
  96528. blocksize_hint = x;
  96529. break;
  96530. case 8:
  96531. case 9:
  96532. case 10:
  96533. case 11:
  96534. case 12:
  96535. case 13:
  96536. case 14:
  96537. case 15:
  96538. decoder->private_->frame.header.blocksize = 256 << (x-8);
  96539. break;
  96540. default:
  96541. FLAC__ASSERT(0);
  96542. break;
  96543. }
  96544. switch(x = raw_header[2] & 0x0f) {
  96545. case 0:
  96546. if(decoder->private_->has_stream_info)
  96547. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  96548. else
  96549. is_unparseable = true;
  96550. break;
  96551. case 1:
  96552. decoder->private_->frame.header.sample_rate = 88200;
  96553. break;
  96554. case 2:
  96555. decoder->private_->frame.header.sample_rate = 176400;
  96556. break;
  96557. case 3:
  96558. decoder->private_->frame.header.sample_rate = 192000;
  96559. break;
  96560. case 4:
  96561. decoder->private_->frame.header.sample_rate = 8000;
  96562. break;
  96563. case 5:
  96564. decoder->private_->frame.header.sample_rate = 16000;
  96565. break;
  96566. case 6:
  96567. decoder->private_->frame.header.sample_rate = 22050;
  96568. break;
  96569. case 7:
  96570. decoder->private_->frame.header.sample_rate = 24000;
  96571. break;
  96572. case 8:
  96573. decoder->private_->frame.header.sample_rate = 32000;
  96574. break;
  96575. case 9:
  96576. decoder->private_->frame.header.sample_rate = 44100;
  96577. break;
  96578. case 10:
  96579. decoder->private_->frame.header.sample_rate = 48000;
  96580. break;
  96581. case 11:
  96582. decoder->private_->frame.header.sample_rate = 96000;
  96583. break;
  96584. case 12:
  96585. case 13:
  96586. case 14:
  96587. sample_rate_hint = x;
  96588. break;
  96589. case 15:
  96590. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96591. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96592. return true;
  96593. default:
  96594. FLAC__ASSERT(0);
  96595. }
  96596. x = (unsigned)(raw_header[3] >> 4);
  96597. if(x & 8) {
  96598. decoder->private_->frame.header.channels = 2;
  96599. switch(x & 7) {
  96600. case 0:
  96601. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  96602. break;
  96603. case 1:
  96604. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  96605. break;
  96606. case 2:
  96607. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  96608. break;
  96609. default:
  96610. is_unparseable = true;
  96611. break;
  96612. }
  96613. }
  96614. else {
  96615. decoder->private_->frame.header.channels = (unsigned)x + 1;
  96616. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  96617. }
  96618. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  96619. case 0:
  96620. if(decoder->private_->has_stream_info)
  96621. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  96622. else
  96623. is_unparseable = true;
  96624. break;
  96625. case 1:
  96626. decoder->private_->frame.header.bits_per_sample = 8;
  96627. break;
  96628. case 2:
  96629. decoder->private_->frame.header.bits_per_sample = 12;
  96630. break;
  96631. case 4:
  96632. decoder->private_->frame.header.bits_per_sample = 16;
  96633. break;
  96634. case 5:
  96635. decoder->private_->frame.header.bits_per_sample = 20;
  96636. break;
  96637. case 6:
  96638. decoder->private_->frame.header.bits_per_sample = 24;
  96639. break;
  96640. case 3:
  96641. case 7:
  96642. is_unparseable = true;
  96643. break;
  96644. default:
  96645. FLAC__ASSERT(0);
  96646. break;
  96647. }
  96648. /* check to make sure that reserved bit is 0 */
  96649. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  96650. is_unparseable = true;
  96651. /* read the frame's starting sample number (or frame number as the case may be) */
  96652. if(
  96653. raw_header[1] & 0x01 ||
  96654. /*@@@ 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 */
  96655. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  96656. ) { /* variable blocksize */
  96657. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  96658. return false; /* read_callback_ sets the state for us */
  96659. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  96660. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96661. decoder->private_->cached = true;
  96662. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96663. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96664. return true;
  96665. }
  96666. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96667. decoder->private_->frame.header.number.sample_number = xx;
  96668. }
  96669. else { /* fixed blocksize */
  96670. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  96671. return false; /* read_callback_ sets the state for us */
  96672. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  96673. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  96674. decoder->private_->cached = true;
  96675. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96676. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96677. return true;
  96678. }
  96679. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  96680. decoder->private_->frame.header.number.frame_number = x;
  96681. }
  96682. if(blocksize_hint) {
  96683. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96684. return false; /* read_callback_ sets the state for us */
  96685. raw_header[raw_header_len++] = (FLAC__byte)x;
  96686. if(blocksize_hint == 7) {
  96687. FLAC__uint32 _x;
  96688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96689. return false; /* read_callback_ sets the state for us */
  96690. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96691. x = (x << 8) | _x;
  96692. }
  96693. decoder->private_->frame.header.blocksize = x+1;
  96694. }
  96695. if(sample_rate_hint) {
  96696. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96697. return false; /* read_callback_ sets the state for us */
  96698. raw_header[raw_header_len++] = (FLAC__byte)x;
  96699. if(sample_rate_hint != 12) {
  96700. FLAC__uint32 _x;
  96701. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  96702. return false; /* read_callback_ sets the state for us */
  96703. raw_header[raw_header_len++] = (FLAC__byte)_x;
  96704. x = (x << 8) | _x;
  96705. }
  96706. if(sample_rate_hint == 12)
  96707. decoder->private_->frame.header.sample_rate = x*1000;
  96708. else if(sample_rate_hint == 13)
  96709. decoder->private_->frame.header.sample_rate = x;
  96710. else
  96711. decoder->private_->frame.header.sample_rate = x*10;
  96712. }
  96713. /* read the CRC-8 byte */
  96714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96715. return false; /* read_callback_ sets the state for us */
  96716. crc8 = (FLAC__byte)x;
  96717. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  96718. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  96719. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96720. return true;
  96721. }
  96722. /* calculate the sample number from the frame number if needed */
  96723. decoder->private_->next_fixed_block_size = 0;
  96724. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  96725. x = decoder->private_->frame.header.number.frame_number;
  96726. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  96727. if(decoder->private_->fixed_block_size)
  96728. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  96729. else if(decoder->private_->has_stream_info) {
  96730. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  96731. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  96732. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  96733. }
  96734. else
  96735. is_unparseable = true;
  96736. }
  96737. else if(x == 0) {
  96738. decoder->private_->frame.header.number.sample_number = 0;
  96739. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  96740. }
  96741. else {
  96742. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  96743. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  96744. }
  96745. }
  96746. if(is_unparseable) {
  96747. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96748. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96749. return true;
  96750. }
  96751. return true;
  96752. }
  96753. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96754. {
  96755. FLAC__uint32 x;
  96756. FLAC__bool wasted_bits;
  96757. unsigned i;
  96758. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  96759. return false; /* read_callback_ sets the state for us */
  96760. wasted_bits = (x & 1);
  96761. x &= 0xfe;
  96762. if(wasted_bits) {
  96763. unsigned u;
  96764. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  96765. return false; /* read_callback_ sets the state for us */
  96766. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  96767. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  96768. }
  96769. else
  96770. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  96771. /*
  96772. * Lots of magic numbers here
  96773. */
  96774. if(x & 0x80) {
  96775. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96776. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96777. return true;
  96778. }
  96779. else if(x == 0) {
  96780. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  96781. return false;
  96782. }
  96783. else if(x == 2) {
  96784. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  96785. return false;
  96786. }
  96787. else if(x < 16) {
  96788. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96789. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96790. return true;
  96791. }
  96792. else if(x <= 24) {
  96793. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  96794. return false;
  96795. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96796. return true;
  96797. }
  96798. else if(x < 64) {
  96799. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96800. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96801. return true;
  96802. }
  96803. else {
  96804. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  96805. return false;
  96806. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  96807. return true;
  96808. }
  96809. if(wasted_bits && do_full_decode) {
  96810. x = decoder->private_->frame.subframes[channel].wasted_bits;
  96811. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96812. decoder->private_->output[channel][i] <<= x;
  96813. }
  96814. return true;
  96815. }
  96816. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96817. {
  96818. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  96819. FLAC__int32 x;
  96820. unsigned i;
  96821. FLAC__int32 *output = decoder->private_->output[channel];
  96822. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  96823. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96824. return false; /* read_callback_ sets the state for us */
  96825. subframe->value = x;
  96826. /* decode the subframe */
  96827. if(do_full_decode) {
  96828. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  96829. output[i] = x;
  96830. }
  96831. return true;
  96832. }
  96833. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96834. {
  96835. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  96836. FLAC__int32 i32;
  96837. FLAC__uint32 u32;
  96838. unsigned u;
  96839. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  96840. subframe->residual = decoder->private_->residual[channel];
  96841. subframe->order = order;
  96842. /* read warm-up samples */
  96843. for(u = 0; u < order; u++) {
  96844. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96845. return false; /* read_callback_ sets the state for us */
  96846. subframe->warmup[u] = i32;
  96847. }
  96848. /* read entropy coding method info */
  96849. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96850. return false; /* read_callback_ sets the state for us */
  96851. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96852. switch(subframe->entropy_coding_method.type) {
  96853. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96854. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96855. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96856. return false; /* read_callback_ sets the state for us */
  96857. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96858. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96859. break;
  96860. default:
  96861. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96862. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96863. return true;
  96864. }
  96865. /* read residual */
  96866. switch(subframe->entropy_coding_method.type) {
  96867. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96868. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96869. 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))
  96870. return false;
  96871. break;
  96872. default:
  96873. FLAC__ASSERT(0);
  96874. }
  96875. /* decode the subframe */
  96876. if(do_full_decode) {
  96877. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96878. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  96879. }
  96880. return true;
  96881. }
  96882. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  96883. {
  96884. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  96885. FLAC__int32 i32;
  96886. FLAC__uint32 u32;
  96887. unsigned u;
  96888. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  96889. subframe->residual = decoder->private_->residual[channel];
  96890. subframe->order = order;
  96891. /* read warm-up samples */
  96892. for(u = 0; u < order; u++) {
  96893. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  96894. return false; /* read_callback_ sets the state for us */
  96895. subframe->warmup[u] = i32;
  96896. }
  96897. /* read qlp coeff precision */
  96898. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  96899. return false; /* read_callback_ sets the state for us */
  96900. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  96901. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96902. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96903. return true;
  96904. }
  96905. subframe->qlp_coeff_precision = u32+1;
  96906. /* read qlp shift */
  96907. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  96908. return false; /* read_callback_ sets the state for us */
  96909. subframe->quantization_level = i32;
  96910. /* read quantized lp coefficiencts */
  96911. for(u = 0; u < order; u++) {
  96912. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  96913. return false; /* read_callback_ sets the state for us */
  96914. subframe->qlp_coeff[u] = i32;
  96915. }
  96916. /* read entropy coding method info */
  96917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  96918. return false; /* read_callback_ sets the state for us */
  96919. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  96920. switch(subframe->entropy_coding_method.type) {
  96921. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96922. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96923. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96924. return false; /* read_callback_ sets the state for us */
  96925. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  96926. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  96927. break;
  96928. default:
  96929. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  96930. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96931. return true;
  96932. }
  96933. /* read residual */
  96934. switch(subframe->entropy_coding_method.type) {
  96935. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  96936. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  96937. 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))
  96938. return false;
  96939. break;
  96940. default:
  96941. FLAC__ASSERT(0);
  96942. }
  96943. /* decode the subframe */
  96944. if(do_full_decode) {
  96945. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  96946. /*@@@@@@ technically not pessimistic enough, should be more like
  96947. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  96948. */
  96949. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  96950. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  96951. if(order <= 8)
  96952. 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);
  96953. else
  96954. 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);
  96955. }
  96956. else
  96957. 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);
  96958. else
  96959. 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);
  96960. }
  96961. return true;
  96962. }
  96963. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  96964. {
  96965. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  96966. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  96967. unsigned i;
  96968. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  96969. subframe->data = residual;
  96970. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  96971. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  96972. return false; /* read_callback_ sets the state for us */
  96973. residual[i] = x;
  96974. }
  96975. /* decode the subframe */
  96976. if(do_full_decode)
  96977. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  96978. return true;
  96979. }
  96980. 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)
  96981. {
  96982. FLAC__uint32 rice_parameter;
  96983. int i;
  96984. unsigned partition, sample, u;
  96985. const unsigned partitions = 1u << partition_order;
  96986. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  96987. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  96988. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  96989. /* sanity checks */
  96990. if(partition_order == 0) {
  96991. if(decoder->private_->frame.header.blocksize < predictor_order) {
  96992. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96993. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96994. return true;
  96995. }
  96996. }
  96997. else {
  96998. if(partition_samples < predictor_order) {
  96999. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97000. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97001. return true;
  97002. }
  97003. }
  97004. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97005. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97006. return false;
  97007. }
  97008. sample = 0;
  97009. for(partition = 0; partition < partitions; partition++) {
  97010. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97011. return false; /* read_callback_ sets the state for us */
  97012. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97013. if(rice_parameter < pesc) {
  97014. partitioned_rice_contents->raw_bits[partition] = 0;
  97015. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97016. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97017. return false; /* read_callback_ sets the state for us */
  97018. sample += u;
  97019. }
  97020. else {
  97021. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97022. return false; /* read_callback_ sets the state for us */
  97023. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97024. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97025. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97026. return false; /* read_callback_ sets the state for us */
  97027. residual[sample] = i;
  97028. }
  97029. }
  97030. }
  97031. return true;
  97032. }
  97033. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97034. {
  97035. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97036. FLAC__uint32 zero = 0;
  97037. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97038. return false; /* read_callback_ sets the state for us */
  97039. if(zero != 0) {
  97040. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97041. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97042. }
  97043. }
  97044. return true;
  97045. }
  97046. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97047. {
  97048. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97049. if(
  97050. #if FLAC__HAS_OGG
  97051. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97052. !decoder->private_->is_ogg &&
  97053. #endif
  97054. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97055. ) {
  97056. *bytes = 0;
  97057. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97058. return false;
  97059. }
  97060. else if(*bytes > 0) {
  97061. /* While seeking, it is possible for our seek to land in the
  97062. * middle of audio data that looks exactly like a frame header
  97063. * from a future version of an encoder. When that happens, our
  97064. * error callback will get an
  97065. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97066. * unparseable_frame_count. But there is a remote possibility
  97067. * that it is properly synced at such a "future-codec frame",
  97068. * so to make sure, we wait to see many "unparseable" errors in
  97069. * a row before bailing out.
  97070. */
  97071. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97072. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97073. return false;
  97074. }
  97075. else {
  97076. const FLAC__StreamDecoderReadStatus status =
  97077. #if FLAC__HAS_OGG
  97078. decoder->private_->is_ogg?
  97079. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97080. #endif
  97081. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97082. ;
  97083. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97084. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97085. return false;
  97086. }
  97087. else if(*bytes == 0) {
  97088. if(
  97089. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97090. (
  97091. #if FLAC__HAS_OGG
  97092. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97093. !decoder->private_->is_ogg &&
  97094. #endif
  97095. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97096. )
  97097. ) {
  97098. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97099. return false;
  97100. }
  97101. else
  97102. return true;
  97103. }
  97104. else
  97105. return true;
  97106. }
  97107. }
  97108. else {
  97109. /* abort to avoid a deadlock */
  97110. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97111. return false;
  97112. }
  97113. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  97114. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  97115. * and at the same time hit the end of the stream (for example, seeking
  97116. * to a point that is after the beginning of the last Ogg page). There
  97117. * is no way to report an Ogg sync loss through the callbacks (see note
  97118. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  97119. * So to keep the decoder from stopping at this point we gate the call
  97120. * to the eof_callback and let the Ogg decoder aspect set the
  97121. * end-of-stream state when it is needed.
  97122. */
  97123. }
  97124. #if FLAC__HAS_OGG
  97125. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  97126. {
  97127. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  97128. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  97129. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97130. /* we don't really have a way to handle lost sync via read
  97131. * callback so we'll let it pass and let the underlying
  97132. * FLAC decoder catch the error
  97133. */
  97134. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  97135. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97136. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  97137. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97138. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  97139. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  97140. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  97141. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  97142. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  97143. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97144. default:
  97145. FLAC__ASSERT(0);
  97146. /* double protection */
  97147. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97148. }
  97149. }
  97150. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97151. {
  97152. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  97153. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  97154. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  97155. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  97156. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  97157. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  97158. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  97159. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97160. default:
  97161. /* double protection: */
  97162. FLAC__ASSERT(0);
  97163. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97164. }
  97165. }
  97166. #endif
  97167. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  97168. {
  97169. if(decoder->private_->is_seeking) {
  97170. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  97171. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  97172. FLAC__uint64 target_sample = decoder->private_->target_sample;
  97173. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97174. #if FLAC__HAS_OGG
  97175. decoder->private_->got_a_frame = true;
  97176. #endif
  97177. decoder->private_->last_frame = *frame; /* save the frame */
  97178. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  97179. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  97180. /* kick out of seek mode */
  97181. decoder->private_->is_seeking = false;
  97182. /* shift out the samples before target_sample */
  97183. if(delta > 0) {
  97184. unsigned channel;
  97185. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  97186. for(channel = 0; channel < frame->header.channels; channel++)
  97187. newbuffer[channel] = buffer[channel] + delta;
  97188. decoder->private_->last_frame.header.blocksize -= delta;
  97189. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  97190. /* write the relevant samples */
  97191. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  97192. }
  97193. else {
  97194. /* write the relevant samples */
  97195. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97196. }
  97197. }
  97198. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  97199. }
  97200. /*
  97201. * If we never got STREAMINFO, turn off MD5 checking to save
  97202. * cycles since we don't have a sum to compare to anyway
  97203. */
  97204. if(!decoder->private_->has_stream_info)
  97205. decoder->private_->do_md5_checking = false;
  97206. if(decoder->private_->do_md5_checking) {
  97207. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  97208. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  97209. }
  97210. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  97211. }
  97212. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  97213. {
  97214. if(!decoder->private_->is_seeking)
  97215. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  97216. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  97217. decoder->private_->unparseable_frame_count++;
  97218. }
  97219. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97220. {
  97221. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  97222. FLAC__int64 pos = -1;
  97223. int i;
  97224. unsigned approx_bytes_per_frame;
  97225. FLAC__bool first_seek = true;
  97226. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  97227. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  97228. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97229. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  97230. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  97231. /* take these from the current frame in case they've changed mid-stream */
  97232. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  97233. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  97234. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  97235. /* use values from stream info if we didn't decode a frame */
  97236. if(channels == 0)
  97237. channels = decoder->private_->stream_info.data.stream_info.channels;
  97238. if(bps == 0)
  97239. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97240. /* we are just guessing here */
  97241. if(max_framesize > 0)
  97242. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  97243. /*
  97244. * Check if it's a known fixed-blocksize stream. Note that though
  97245. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  97246. * never get a STREAMINFO block when decoding so the value of
  97247. * min_blocksize might be zero.
  97248. */
  97249. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  97250. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  97251. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  97252. }
  97253. else
  97254. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  97255. /*
  97256. * First, we set an upper and lower bound on where in the
  97257. * stream we will search. For now we assume the worst case
  97258. * scenario, which is our best guess at the beginning of
  97259. * the first frame and end of the stream.
  97260. */
  97261. lower_bound = first_frame_offset;
  97262. lower_bound_sample = 0;
  97263. upper_bound = stream_length;
  97264. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  97265. /*
  97266. * Now we refine the bounds if we have a seektable with
  97267. * suitable points. Note that according to the spec they
  97268. * must be ordered by ascending sample number.
  97269. *
  97270. * Note: to protect against invalid seek tables we will ignore points
  97271. * that have frame_samples==0 or sample_number>=total_samples
  97272. */
  97273. if(seek_table) {
  97274. FLAC__uint64 new_lower_bound = lower_bound;
  97275. FLAC__uint64 new_upper_bound = upper_bound;
  97276. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  97277. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  97278. /* find the closest seek point <= target_sample, if it exists */
  97279. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  97280. if(
  97281. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97282. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97283. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97284. seek_table->points[i].sample_number <= target_sample
  97285. )
  97286. break;
  97287. }
  97288. if(i >= 0) { /* i.e. we found a suitable seek point... */
  97289. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97290. new_lower_bound_sample = seek_table->points[i].sample_number;
  97291. }
  97292. /* find the closest seek point > target_sample, if it exists */
  97293. for(i = 0; i < (int)seek_table->num_points; i++) {
  97294. if(
  97295. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  97296. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  97297. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  97298. seek_table->points[i].sample_number > target_sample
  97299. )
  97300. break;
  97301. }
  97302. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  97303. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  97304. new_upper_bound_sample = seek_table->points[i].sample_number;
  97305. }
  97306. /* final protection against unsorted seek tables; keep original values if bogus */
  97307. if(new_upper_bound >= new_lower_bound) {
  97308. lower_bound = new_lower_bound;
  97309. upper_bound = new_upper_bound;
  97310. lower_bound_sample = new_lower_bound_sample;
  97311. upper_bound_sample = new_upper_bound_sample;
  97312. }
  97313. }
  97314. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  97315. /* there are 2 insidious ways that the following equality occurs, which
  97316. * we need to fix:
  97317. * 1) total_samples is 0 (unknown) and target_sample is 0
  97318. * 2) total_samples is 0 (unknown) and target_sample happens to be
  97319. * exactly equal to the last seek point in the seek table; this
  97320. * means there is no seek point above it, and upper_bound_samples
  97321. * remains equal to the estimate (of target_samples) we made above
  97322. * in either case it does not hurt to move upper_bound_sample up by 1
  97323. */
  97324. if(upper_bound_sample == lower_bound_sample)
  97325. upper_bound_sample++;
  97326. decoder->private_->target_sample = target_sample;
  97327. while(1) {
  97328. /* check if the bounds are still ok */
  97329. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  97330. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97331. return false;
  97332. }
  97333. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97334. #if defined _MSC_VER || defined __MINGW32__
  97335. /* with VC++ you have to spoon feed it the casting */
  97336. 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;
  97337. #else
  97338. 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;
  97339. #endif
  97340. #else
  97341. /* a little less accurate: */
  97342. if(upper_bound - lower_bound < 0xffffffff)
  97343. 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;
  97344. else /* @@@ WATCHOUT, ~2TB limit */
  97345. 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;
  97346. #endif
  97347. if(pos >= (FLAC__int64)upper_bound)
  97348. pos = (FLAC__int64)upper_bound - 1;
  97349. if(pos < (FLAC__int64)lower_bound)
  97350. pos = (FLAC__int64)lower_bound;
  97351. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97352. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97353. return false;
  97354. }
  97355. if(!FLAC__stream_decoder_flush(decoder)) {
  97356. /* above call sets the state for us */
  97357. return false;
  97358. }
  97359. /* Now we need to get a frame. First we need to reset our
  97360. * unparseable_frame_count; if we get too many unparseable
  97361. * frames in a row, the read callback will return
  97362. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  97363. * FLAC__stream_decoder_process_single() to return false.
  97364. */
  97365. decoder->private_->unparseable_frame_count = 0;
  97366. if(!FLAC__stream_decoder_process_single(decoder)) {
  97367. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97368. return false;
  97369. }
  97370. /* our write callback will change the state when it gets to the target frame */
  97371. /* 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 */
  97372. #if 0
  97373. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  97374. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  97375. break;
  97376. #endif
  97377. if(!decoder->private_->is_seeking)
  97378. break;
  97379. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97380. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97381. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  97382. if (pos == (FLAC__int64)lower_bound) {
  97383. /* can't move back any more than the first frame, something is fatally wrong */
  97384. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97385. return false;
  97386. }
  97387. /* our last move backwards wasn't big enough, try again */
  97388. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  97389. continue;
  97390. }
  97391. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  97392. first_seek = false;
  97393. /* make sure we are not seeking in corrupted stream */
  97394. if (this_frame_sample < lower_bound_sample) {
  97395. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97396. return false;
  97397. }
  97398. /* we need to narrow the search */
  97399. if(target_sample < this_frame_sample) {
  97400. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97401. /*@@@@@@ what will decode position be if at end of stream? */
  97402. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  97403. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97404. return false;
  97405. }
  97406. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  97407. }
  97408. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  97409. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  97410. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  97411. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97412. return false;
  97413. }
  97414. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  97415. }
  97416. }
  97417. return true;
  97418. }
  97419. #if FLAC__HAS_OGG
  97420. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  97421. {
  97422. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  97423. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  97424. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  97425. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  97426. FLAC__bool did_a_seek;
  97427. unsigned iteration = 0;
  97428. /* In the first iterations, we will calculate the target byte position
  97429. * by the distance from the target sample to left_sample and
  97430. * right_sample (let's call it "proportional search"). After that, we
  97431. * will switch to binary search.
  97432. */
  97433. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  97434. /* We will switch to a linear search once our current sample is less
  97435. * than this number of samples ahead of the target sample
  97436. */
  97437. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  97438. /* If the total number of samples is unknown, use a large value, and
  97439. * force binary search immediately.
  97440. */
  97441. if(right_sample == 0) {
  97442. right_sample = (FLAC__uint64)(-1);
  97443. BINARY_SEARCH_AFTER_ITERATION = 0;
  97444. }
  97445. decoder->private_->target_sample = target_sample;
  97446. for( ; ; iteration++) {
  97447. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  97448. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  97449. pos = (right_pos + left_pos) / 2;
  97450. }
  97451. else {
  97452. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97453. #if defined _MSC_VER || defined __MINGW32__
  97454. /* with MSVC you have to spoon feed it the casting */
  97455. 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));
  97456. #else
  97457. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  97458. #endif
  97459. #else
  97460. /* a little less accurate: */
  97461. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  97462. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  97463. else /* @@@ WATCHOUT, ~2TB limit */
  97464. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  97465. #endif
  97466. /* @@@ TODO: might want to limit pos to some distance
  97467. * before EOF, to make sure we land before the last frame,
  97468. * thereby getting a this_frame_sample and so having a better
  97469. * estimate.
  97470. */
  97471. }
  97472. /* physical seek */
  97473. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  97474. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97475. return false;
  97476. }
  97477. if(!FLAC__stream_decoder_flush(decoder)) {
  97478. /* above call sets the state for us */
  97479. return false;
  97480. }
  97481. did_a_seek = true;
  97482. }
  97483. else
  97484. did_a_seek = false;
  97485. decoder->private_->got_a_frame = false;
  97486. if(!FLAC__stream_decoder_process_single(decoder)) {
  97487. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97488. return false;
  97489. }
  97490. if(!decoder->private_->got_a_frame) {
  97491. if(did_a_seek) {
  97492. /* this can happen if we seek to a point after the last frame; we drop
  97493. * to binary search right away in this case to avoid any wasted
  97494. * iterations of proportional search.
  97495. */
  97496. right_pos = pos;
  97497. BINARY_SEARCH_AFTER_ITERATION = 0;
  97498. }
  97499. else {
  97500. /* this can probably only happen if total_samples is unknown and the
  97501. * target_sample is past the end of the stream
  97502. */
  97503. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97504. return false;
  97505. }
  97506. }
  97507. /* our write callback will change the state when it gets to the target frame */
  97508. else if(!decoder->private_->is_seeking) {
  97509. break;
  97510. }
  97511. else {
  97512. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  97513. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97514. if (did_a_seek) {
  97515. if (this_frame_sample <= target_sample) {
  97516. /* The 'equal' case should not happen, since
  97517. * FLAC__stream_decoder_process_single()
  97518. * should recognize that it has hit the
  97519. * target sample and we would exit through
  97520. * the 'break' above.
  97521. */
  97522. FLAC__ASSERT(this_frame_sample != target_sample);
  97523. left_sample = this_frame_sample;
  97524. /* sanity check to avoid infinite loop */
  97525. if (left_pos == pos) {
  97526. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97527. return false;
  97528. }
  97529. left_pos = pos;
  97530. }
  97531. else if(this_frame_sample > target_sample) {
  97532. right_sample = this_frame_sample;
  97533. /* sanity check to avoid infinite loop */
  97534. if (right_pos == pos) {
  97535. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  97536. return false;
  97537. }
  97538. right_pos = pos;
  97539. }
  97540. }
  97541. }
  97542. }
  97543. return true;
  97544. }
  97545. #endif
  97546. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97547. {
  97548. (void)client_data;
  97549. if(*bytes > 0) {
  97550. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  97551. if(ferror(decoder->private_->file))
  97552. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97553. else if(*bytes == 0)
  97554. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97555. else
  97556. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97557. }
  97558. else
  97559. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  97560. }
  97561. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  97562. {
  97563. (void)client_data;
  97564. if(decoder->private_->file == stdin)
  97565. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  97566. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  97567. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  97568. else
  97569. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  97570. }
  97571. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  97572. {
  97573. off_t pos;
  97574. (void)client_data;
  97575. if(decoder->private_->file == stdin)
  97576. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  97577. else if((pos = ftello(decoder->private_->file)) < 0)
  97578. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  97579. else {
  97580. *absolute_byte_offset = (FLAC__uint64)pos;
  97581. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  97582. }
  97583. }
  97584. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  97585. {
  97586. struct stat filestats;
  97587. (void)client_data;
  97588. if(decoder->private_->file == stdin)
  97589. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  97590. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  97591. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  97592. else {
  97593. *stream_length = (FLAC__uint64)filestats.st_size;
  97594. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  97595. }
  97596. }
  97597. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  97598. {
  97599. (void)client_data;
  97600. return feof(decoder->private_->file)? true : false;
  97601. }
  97602. #endif
  97603. /********* End of inlined file: stream_decoder.c *********/
  97604. /********* Start of inlined file: stream_encoder.c *********/
  97605. /********* Start of inlined file: juce_FlacHeader.h *********/
  97606. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97607. // tasks..
  97608. #define VERSION "1.2.1"
  97609. #define FLAC__NO_DLL 1
  97610. #ifdef _MSC_VER
  97611. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97612. #endif
  97613. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  97614. #define FLAC__SYS_DARWIN 1
  97615. #endif
  97616. /********* End of inlined file: juce_FlacHeader.h *********/
  97617. #if JUCE_USE_FLAC
  97618. #if HAVE_CONFIG_H
  97619. # include <config.h>
  97620. #endif
  97621. #if defined _MSC_VER || defined __MINGW32__
  97622. #include <io.h> /* for _setmode() */
  97623. #include <fcntl.h> /* for _O_BINARY */
  97624. #endif
  97625. #if defined __CYGWIN__ || defined __EMX__
  97626. #include <io.h> /* for setmode(), O_BINARY */
  97627. #include <fcntl.h> /* for _O_BINARY */
  97628. #endif
  97629. #include <limits.h>
  97630. #include <stdio.h>
  97631. #include <stdlib.h> /* for malloc() */
  97632. #include <string.h> /* for memcpy() */
  97633. #include <sys/types.h> /* for off_t */
  97634. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  97635. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  97636. #define fseeko fseek
  97637. #define ftello ftell
  97638. #endif
  97639. #endif
  97640. /********* Start of inlined file: stream_encoder.h *********/
  97641. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  97642. #define FLAC__PROTECTED__STREAM_ENCODER_H
  97643. #if FLAC__HAS_OGG
  97644. #include "private/ogg_encoder_aspect.h"
  97645. #endif
  97646. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97647. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  97648. typedef enum {
  97649. FLAC__APODIZATION_BARTLETT,
  97650. FLAC__APODIZATION_BARTLETT_HANN,
  97651. FLAC__APODIZATION_BLACKMAN,
  97652. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  97653. FLAC__APODIZATION_CONNES,
  97654. FLAC__APODIZATION_FLATTOP,
  97655. FLAC__APODIZATION_GAUSS,
  97656. FLAC__APODIZATION_HAMMING,
  97657. FLAC__APODIZATION_HANN,
  97658. FLAC__APODIZATION_KAISER_BESSEL,
  97659. FLAC__APODIZATION_NUTTALL,
  97660. FLAC__APODIZATION_RECTANGLE,
  97661. FLAC__APODIZATION_TRIANGLE,
  97662. FLAC__APODIZATION_TUKEY,
  97663. FLAC__APODIZATION_WELCH
  97664. } FLAC__ApodizationFunction;
  97665. typedef struct {
  97666. FLAC__ApodizationFunction type;
  97667. union {
  97668. struct {
  97669. FLAC__real stddev;
  97670. } gauss;
  97671. struct {
  97672. FLAC__real p;
  97673. } tukey;
  97674. } parameters;
  97675. } FLAC__ApodizationSpecification;
  97676. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97677. typedef struct FLAC__StreamEncoderProtected {
  97678. FLAC__StreamEncoderState state;
  97679. FLAC__bool verify;
  97680. FLAC__bool streamable_subset;
  97681. FLAC__bool do_md5;
  97682. FLAC__bool do_mid_side_stereo;
  97683. FLAC__bool loose_mid_side_stereo;
  97684. unsigned channels;
  97685. unsigned bits_per_sample;
  97686. unsigned sample_rate;
  97687. unsigned blocksize;
  97688. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97689. unsigned num_apodizations;
  97690. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  97691. #endif
  97692. unsigned max_lpc_order;
  97693. unsigned qlp_coeff_precision;
  97694. FLAC__bool do_qlp_coeff_prec_search;
  97695. FLAC__bool do_exhaustive_model_search;
  97696. FLAC__bool do_escape_coding;
  97697. unsigned min_residual_partition_order;
  97698. unsigned max_residual_partition_order;
  97699. unsigned rice_parameter_search_dist;
  97700. FLAC__uint64 total_samples_estimate;
  97701. FLAC__StreamMetadata **metadata;
  97702. unsigned num_metadata_blocks;
  97703. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  97704. #if FLAC__HAS_OGG
  97705. FLAC__OggEncoderAspect ogg_encoder_aspect;
  97706. #endif
  97707. } FLAC__StreamEncoderProtected;
  97708. #endif
  97709. /********* End of inlined file: stream_encoder.h *********/
  97710. #if FLAC__HAS_OGG
  97711. #include "include/private/ogg_helper.h"
  97712. #include "include/private/ogg_mapping.h"
  97713. #endif
  97714. /********* Start of inlined file: stream_encoder_framing.h *********/
  97715. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97716. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  97717. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  97718. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  97719. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97720. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97721. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97722. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  97723. #endif
  97724. /********* End of inlined file: stream_encoder_framing.h *********/
  97725. /********* Start of inlined file: window.h *********/
  97726. #ifndef FLAC__PRIVATE__WINDOW_H
  97727. #define FLAC__PRIVATE__WINDOW_H
  97728. #ifdef HAVE_CONFIG_H
  97729. #include <config.h>
  97730. #endif
  97731. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97732. /*
  97733. * FLAC__window_*()
  97734. * --------------------------------------------------------------------
  97735. * Calculates window coefficients according to different apodization
  97736. * functions.
  97737. *
  97738. * OUT window[0,L-1]
  97739. * IN L (number of points in window)
  97740. */
  97741. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  97742. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  97743. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  97744. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  97745. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  97746. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  97747. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  97748. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  97749. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  97750. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  97751. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  97752. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  97753. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  97754. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  97755. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  97756. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97757. #endif
  97758. /********* End of inlined file: window.h *********/
  97759. #ifndef FLaC__INLINE
  97760. #define FLaC__INLINE
  97761. #endif
  97762. #ifdef min
  97763. #undef min
  97764. #endif
  97765. #define min(x,y) ((x)<(y)?(x):(y))
  97766. #ifdef max
  97767. #undef max
  97768. #endif
  97769. #define max(x,y) ((x)>(y)?(x):(y))
  97770. /* Exact Rice codeword length calculation is off by default. The simple
  97771. * (and fast) estimation (of how many bits a residual value will be
  97772. * encoded with) in this encoder is very good, almost always yielding
  97773. * compression within 0.1% of exact calculation.
  97774. */
  97775. #undef EXACT_RICE_BITS_CALCULATION
  97776. /* Rice parameter searching is off by default. The simple (and fast)
  97777. * parameter estimation in this encoder is very good, almost always
  97778. * yielding compression within 0.1% of the optimal parameters.
  97779. */
  97780. #undef ENABLE_RICE_PARAMETER_SEARCH
  97781. typedef struct {
  97782. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  97783. unsigned size; /* of each data[] in samples */
  97784. unsigned tail;
  97785. } verify_input_fifo;
  97786. typedef struct {
  97787. const FLAC__byte *data;
  97788. unsigned capacity;
  97789. unsigned bytes;
  97790. } verify_output;
  97791. typedef enum {
  97792. ENCODER_IN_MAGIC = 0,
  97793. ENCODER_IN_METADATA = 1,
  97794. ENCODER_IN_AUDIO = 2
  97795. } EncoderStateHint;
  97796. static struct CompressionLevels {
  97797. FLAC__bool do_mid_side_stereo;
  97798. FLAC__bool loose_mid_side_stereo;
  97799. unsigned max_lpc_order;
  97800. unsigned qlp_coeff_precision;
  97801. FLAC__bool do_qlp_coeff_prec_search;
  97802. FLAC__bool do_escape_coding;
  97803. FLAC__bool do_exhaustive_model_search;
  97804. unsigned min_residual_partition_order;
  97805. unsigned max_residual_partition_order;
  97806. unsigned rice_parameter_search_dist;
  97807. } compression_levels_[] = {
  97808. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  97809. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  97810. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  97811. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  97812. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  97813. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  97814. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  97815. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  97816. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  97817. };
  97818. /***********************************************************************
  97819. *
  97820. * Private class method prototypes
  97821. *
  97822. ***********************************************************************/
  97823. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  97824. static void free_(FLAC__StreamEncoder *encoder);
  97825. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  97826. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  97827. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  97828. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  97829. #if FLAC__HAS_OGG
  97830. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  97831. #endif
  97832. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  97833. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  97834. static FLAC__bool process_subframe_(
  97835. FLAC__StreamEncoder *encoder,
  97836. unsigned min_partition_order,
  97837. unsigned max_partition_order,
  97838. const FLAC__FrameHeader *frame_header,
  97839. unsigned subframe_bps,
  97840. const FLAC__int32 integer_signal[],
  97841. FLAC__Subframe *subframe[2],
  97842. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  97843. FLAC__int32 *residual[2],
  97844. unsigned *best_subframe,
  97845. unsigned *best_bits
  97846. );
  97847. static FLAC__bool add_subframe_(
  97848. FLAC__StreamEncoder *encoder,
  97849. unsigned blocksize,
  97850. unsigned subframe_bps,
  97851. const FLAC__Subframe *subframe,
  97852. FLAC__BitWriter *frame
  97853. );
  97854. static unsigned evaluate_constant_subframe_(
  97855. FLAC__StreamEncoder *encoder,
  97856. const FLAC__int32 signal,
  97857. unsigned blocksize,
  97858. unsigned subframe_bps,
  97859. FLAC__Subframe *subframe
  97860. );
  97861. static unsigned evaluate_fixed_subframe_(
  97862. FLAC__StreamEncoder *encoder,
  97863. const FLAC__int32 signal[],
  97864. FLAC__int32 residual[],
  97865. FLAC__uint64 abs_residual_partition_sums[],
  97866. unsigned raw_bits_per_partition[],
  97867. unsigned blocksize,
  97868. unsigned subframe_bps,
  97869. unsigned order,
  97870. unsigned rice_parameter,
  97871. unsigned rice_parameter_limit,
  97872. unsigned min_partition_order,
  97873. unsigned max_partition_order,
  97874. FLAC__bool do_escape_coding,
  97875. unsigned rice_parameter_search_dist,
  97876. FLAC__Subframe *subframe,
  97877. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97878. );
  97879. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97880. static unsigned evaluate_lpc_subframe_(
  97881. FLAC__StreamEncoder *encoder,
  97882. const FLAC__int32 signal[],
  97883. FLAC__int32 residual[],
  97884. FLAC__uint64 abs_residual_partition_sums[],
  97885. unsigned raw_bits_per_partition[],
  97886. const FLAC__real lp_coeff[],
  97887. unsigned blocksize,
  97888. unsigned subframe_bps,
  97889. unsigned order,
  97890. unsigned qlp_coeff_precision,
  97891. unsigned rice_parameter,
  97892. unsigned rice_parameter_limit,
  97893. unsigned min_partition_order,
  97894. unsigned max_partition_order,
  97895. FLAC__bool do_escape_coding,
  97896. unsigned rice_parameter_search_dist,
  97897. FLAC__Subframe *subframe,
  97898. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  97899. );
  97900. #endif
  97901. static unsigned evaluate_verbatim_subframe_(
  97902. FLAC__StreamEncoder *encoder,
  97903. const FLAC__int32 signal[],
  97904. unsigned blocksize,
  97905. unsigned subframe_bps,
  97906. FLAC__Subframe *subframe
  97907. );
  97908. static unsigned find_best_partition_order_(
  97909. struct FLAC__StreamEncoderPrivate *private_,
  97910. const FLAC__int32 residual[],
  97911. FLAC__uint64 abs_residual_partition_sums[],
  97912. unsigned raw_bits_per_partition[],
  97913. unsigned residual_samples,
  97914. unsigned predictor_order,
  97915. unsigned rice_parameter,
  97916. unsigned rice_parameter_limit,
  97917. unsigned min_partition_order,
  97918. unsigned max_partition_order,
  97919. unsigned bps,
  97920. FLAC__bool do_escape_coding,
  97921. unsigned rice_parameter_search_dist,
  97922. FLAC__EntropyCodingMethod *best_ecm
  97923. );
  97924. static void precompute_partition_info_sums_(
  97925. const FLAC__int32 residual[],
  97926. FLAC__uint64 abs_residual_partition_sums[],
  97927. unsigned residual_samples,
  97928. unsigned predictor_order,
  97929. unsigned min_partition_order,
  97930. unsigned max_partition_order,
  97931. unsigned bps
  97932. );
  97933. static void precompute_partition_info_escapes_(
  97934. const FLAC__int32 residual[],
  97935. unsigned raw_bits_per_partition[],
  97936. unsigned residual_samples,
  97937. unsigned predictor_order,
  97938. unsigned min_partition_order,
  97939. unsigned max_partition_order
  97940. );
  97941. static FLAC__bool set_partitioned_rice_(
  97942. #ifdef EXACT_RICE_BITS_CALCULATION
  97943. const FLAC__int32 residual[],
  97944. #endif
  97945. const FLAC__uint64 abs_residual_partition_sums[],
  97946. const unsigned raw_bits_per_partition[],
  97947. const unsigned residual_samples,
  97948. const unsigned predictor_order,
  97949. const unsigned suggested_rice_parameter,
  97950. const unsigned rice_parameter_limit,
  97951. const unsigned rice_parameter_search_dist,
  97952. const unsigned partition_order,
  97953. const FLAC__bool search_for_escapes,
  97954. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  97955. unsigned *bits
  97956. );
  97957. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  97958. /* verify-related routines: */
  97959. static void append_to_verify_fifo_(
  97960. verify_input_fifo *fifo,
  97961. const FLAC__int32 * const input[],
  97962. unsigned input_offset,
  97963. unsigned channels,
  97964. unsigned wide_samples
  97965. );
  97966. static void append_to_verify_fifo_interleaved_(
  97967. verify_input_fifo *fifo,
  97968. const FLAC__int32 input[],
  97969. unsigned input_offset,
  97970. unsigned channels,
  97971. unsigned wide_samples
  97972. );
  97973. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97974. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  97975. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  97976. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  97977. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  97978. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  97979. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  97980. 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);
  97981. static FILE *get_binary_stdout_(void);
  97982. /***********************************************************************
  97983. *
  97984. * Private class data
  97985. *
  97986. ***********************************************************************/
  97987. typedef struct FLAC__StreamEncoderPrivate {
  97988. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  97989. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  97990. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  97991. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97992. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  97993. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  97994. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  97995. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  97996. #endif
  97997. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  97998. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  97999. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98000. FLAC__int32 *residual_workspace_mid_side[2][2];
  98001. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  98002. FLAC__Subframe subframe_workspace_mid_side[2][2];
  98003. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98004. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  98005. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  98006. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  98007. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  98008. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  98009. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  98010. unsigned best_subframe_mid_side[2];
  98011. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  98012. unsigned best_subframe_bits_mid_side[2];
  98013. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  98014. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  98015. FLAC__BitWriter *frame; /* the current frame being worked on */
  98016. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  98017. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  98018. FLAC__ChannelAssignment last_channel_assignment;
  98019. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  98020. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  98021. unsigned current_sample_number;
  98022. unsigned current_frame_number;
  98023. FLAC__MD5Context md5context;
  98024. FLAC__CPUInfo cpuinfo;
  98025. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98026. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98027. #else
  98028. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  98029. #endif
  98030. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98031. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  98032. 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[]);
  98033. 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[]);
  98034. 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[]);
  98035. #endif
  98036. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  98037. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  98038. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  98039. FLAC__bool disable_constant_subframes;
  98040. FLAC__bool disable_fixed_subframes;
  98041. FLAC__bool disable_verbatim_subframes;
  98042. #if FLAC__HAS_OGG
  98043. FLAC__bool is_ogg;
  98044. #endif
  98045. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  98046. FLAC__StreamEncoderSeekCallback seek_callback;
  98047. FLAC__StreamEncoderTellCallback tell_callback;
  98048. FLAC__StreamEncoderWriteCallback write_callback;
  98049. FLAC__StreamEncoderMetadataCallback metadata_callback;
  98050. FLAC__StreamEncoderProgressCallback progress_callback;
  98051. void *client_data;
  98052. unsigned first_seekpoint_to_check;
  98053. FILE *file; /* only used when encoding to a file */
  98054. FLAC__uint64 bytes_written;
  98055. FLAC__uint64 samples_written;
  98056. unsigned frames_written;
  98057. unsigned total_frames_estimate;
  98058. /* unaligned (original) pointers to allocated data */
  98059. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  98060. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  98061. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98062. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  98063. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  98064. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  98065. FLAC__real *windowed_signal_unaligned;
  98066. #endif
  98067. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  98068. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  98069. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  98070. unsigned *raw_bits_per_partition_unaligned;
  98071. /*
  98072. * These fields have been moved here from private function local
  98073. * declarations merely to save stack space during encoding.
  98074. */
  98075. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98076. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  98077. #endif
  98078. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  98079. /*
  98080. * The data for the verify section
  98081. */
  98082. struct {
  98083. FLAC__StreamDecoder *decoder;
  98084. EncoderStateHint state_hint;
  98085. FLAC__bool needs_magic_hack;
  98086. verify_input_fifo input_fifo;
  98087. verify_output output;
  98088. struct {
  98089. FLAC__uint64 absolute_sample;
  98090. unsigned frame_number;
  98091. unsigned channel;
  98092. unsigned sample;
  98093. FLAC__int32 expected;
  98094. FLAC__int32 got;
  98095. } error_stats;
  98096. } verify;
  98097. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  98098. } FLAC__StreamEncoderPrivate;
  98099. /***********************************************************************
  98100. *
  98101. * Public static class data
  98102. *
  98103. ***********************************************************************/
  98104. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  98105. "FLAC__STREAM_ENCODER_OK",
  98106. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  98107. "FLAC__STREAM_ENCODER_OGG_ERROR",
  98108. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  98109. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  98110. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  98111. "FLAC__STREAM_ENCODER_IO_ERROR",
  98112. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  98113. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  98114. };
  98115. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  98116. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  98117. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  98118. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  98119. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  98120. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  98121. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  98122. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  98123. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  98124. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  98125. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  98126. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  98127. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  98128. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  98129. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  98130. };
  98131. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  98132. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  98133. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  98134. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  98135. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  98136. };
  98137. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  98138. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  98139. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  98140. };
  98141. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  98142. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  98143. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  98144. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  98145. };
  98146. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  98147. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  98148. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  98149. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  98150. };
  98151. /* Number of samples that will be overread to watch for end of stream. By
  98152. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  98153. * always try to read blocksize+1 samples before encoding a block, so that
  98154. * even if the stream has a total sample count that is an integral multiple
  98155. * of the blocksize, we will still notice when we are encoding the last
  98156. * block. This is needed, for example, to correctly set the end-of-stream
  98157. * marker in Ogg FLAC.
  98158. *
  98159. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  98160. * not really any reason to change it.
  98161. */
  98162. static const unsigned OVERREAD_ = 1;
  98163. /***********************************************************************
  98164. *
  98165. * Class constructor/destructor
  98166. *
  98167. */
  98168. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  98169. {
  98170. FLAC__StreamEncoder *encoder;
  98171. unsigned i;
  98172. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  98173. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  98174. if(encoder == 0) {
  98175. return 0;
  98176. }
  98177. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  98178. if(encoder->protected_ == 0) {
  98179. free(encoder);
  98180. return 0;
  98181. }
  98182. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  98183. if(encoder->private_ == 0) {
  98184. free(encoder->protected_);
  98185. free(encoder);
  98186. return 0;
  98187. }
  98188. encoder->private_->frame = FLAC__bitwriter_new();
  98189. if(encoder->private_->frame == 0) {
  98190. free(encoder->private_);
  98191. free(encoder->protected_);
  98192. free(encoder);
  98193. return 0;
  98194. }
  98195. encoder->private_->file = 0;
  98196. set_defaults_enc(encoder);
  98197. encoder->private_->is_being_deleted = false;
  98198. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98199. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  98200. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  98201. }
  98202. for(i = 0; i < 2; i++) {
  98203. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  98204. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  98205. }
  98206. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98207. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  98208. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  98209. }
  98210. for(i = 0; i < 2; i++) {
  98211. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  98212. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  98213. }
  98214. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98215. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98216. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  98217. }
  98218. for(i = 0; i < 2; i++) {
  98219. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98220. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  98221. }
  98222. for(i = 0; i < 2; i++)
  98223. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  98224. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98225. return encoder;
  98226. }
  98227. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  98228. {
  98229. unsigned i;
  98230. FLAC__ASSERT(0 != encoder);
  98231. FLAC__ASSERT(0 != encoder->protected_);
  98232. FLAC__ASSERT(0 != encoder->private_);
  98233. FLAC__ASSERT(0 != encoder->private_->frame);
  98234. encoder->private_->is_being_deleted = true;
  98235. (void)FLAC__stream_encoder_finish(encoder);
  98236. if(0 != encoder->private_->verify.decoder)
  98237. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  98238. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  98239. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  98240. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&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_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  98244. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&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_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  98248. FLAC__bitwriter_delete(encoder->private_->frame);
  98249. free(encoder->private_);
  98250. free(encoder->protected_);
  98251. free(encoder);
  98252. }
  98253. /***********************************************************************
  98254. *
  98255. * Public class methods
  98256. *
  98257. ***********************************************************************/
  98258. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  98259. FLAC__StreamEncoder *encoder,
  98260. FLAC__StreamEncoderReadCallback read_callback,
  98261. FLAC__StreamEncoderWriteCallback write_callback,
  98262. FLAC__StreamEncoderSeekCallback seek_callback,
  98263. FLAC__StreamEncoderTellCallback tell_callback,
  98264. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98265. void *client_data,
  98266. FLAC__bool is_ogg
  98267. )
  98268. {
  98269. unsigned i;
  98270. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  98271. FLAC__ASSERT(0 != encoder);
  98272. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98273. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98274. #if !FLAC__HAS_OGG
  98275. if(is_ogg)
  98276. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  98277. #endif
  98278. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  98279. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  98280. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  98281. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  98282. if(encoder->protected_->channels != 2) {
  98283. encoder->protected_->do_mid_side_stereo = false;
  98284. encoder->protected_->loose_mid_side_stereo = false;
  98285. }
  98286. else if(!encoder->protected_->do_mid_side_stereo)
  98287. encoder->protected_->loose_mid_side_stereo = false;
  98288. if(encoder->protected_->bits_per_sample >= 32)
  98289. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  98290. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  98291. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  98292. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  98293. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  98294. if(encoder->protected_->blocksize == 0) {
  98295. if(encoder->protected_->max_lpc_order == 0)
  98296. encoder->protected_->blocksize = 1152;
  98297. else
  98298. encoder->protected_->blocksize = 4096;
  98299. }
  98300. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  98301. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  98302. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  98303. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  98304. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  98305. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  98306. if(encoder->protected_->qlp_coeff_precision == 0) {
  98307. if(encoder->protected_->bits_per_sample < 16) {
  98308. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  98309. /* @@@ until then we'll make a guess */
  98310. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  98311. }
  98312. else if(encoder->protected_->bits_per_sample == 16) {
  98313. if(encoder->protected_->blocksize <= 192)
  98314. encoder->protected_->qlp_coeff_precision = 7;
  98315. else if(encoder->protected_->blocksize <= 384)
  98316. encoder->protected_->qlp_coeff_precision = 8;
  98317. else if(encoder->protected_->blocksize <= 576)
  98318. encoder->protected_->qlp_coeff_precision = 9;
  98319. else if(encoder->protected_->blocksize <= 1152)
  98320. encoder->protected_->qlp_coeff_precision = 10;
  98321. else if(encoder->protected_->blocksize <= 2304)
  98322. encoder->protected_->qlp_coeff_precision = 11;
  98323. else if(encoder->protected_->blocksize <= 4608)
  98324. encoder->protected_->qlp_coeff_precision = 12;
  98325. else
  98326. encoder->protected_->qlp_coeff_precision = 13;
  98327. }
  98328. else {
  98329. if(encoder->protected_->blocksize <= 384)
  98330. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  98331. else if(encoder->protected_->blocksize <= 1152)
  98332. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  98333. else
  98334. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98335. }
  98336. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  98337. }
  98338. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  98339. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  98340. if(encoder->protected_->streamable_subset) {
  98341. if(
  98342. encoder->protected_->blocksize != 192 &&
  98343. encoder->protected_->blocksize != 576 &&
  98344. encoder->protected_->blocksize != 1152 &&
  98345. encoder->protected_->blocksize != 2304 &&
  98346. encoder->protected_->blocksize != 4608 &&
  98347. encoder->protected_->blocksize != 256 &&
  98348. encoder->protected_->blocksize != 512 &&
  98349. encoder->protected_->blocksize != 1024 &&
  98350. encoder->protected_->blocksize != 2048 &&
  98351. encoder->protected_->blocksize != 4096 &&
  98352. encoder->protected_->blocksize != 8192 &&
  98353. encoder->protected_->blocksize != 16384
  98354. )
  98355. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98356. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  98357. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98358. if(
  98359. encoder->protected_->bits_per_sample != 8 &&
  98360. encoder->protected_->bits_per_sample != 12 &&
  98361. encoder->protected_->bits_per_sample != 16 &&
  98362. encoder->protected_->bits_per_sample != 20 &&
  98363. encoder->protected_->bits_per_sample != 24
  98364. )
  98365. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98366. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  98367. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98368. if(
  98369. encoder->protected_->sample_rate <= 48000 &&
  98370. (
  98371. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  98372. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  98373. )
  98374. ) {
  98375. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  98376. }
  98377. }
  98378. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  98379. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  98380. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  98381. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  98382. #if FLAC__HAS_OGG
  98383. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  98384. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  98385. unsigned i;
  98386. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  98387. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98388. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  98389. for( ; i > 0; i--)
  98390. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  98391. encoder->protected_->metadata[0] = vc;
  98392. break;
  98393. }
  98394. }
  98395. }
  98396. #endif
  98397. /* keep track of any SEEKTABLE block */
  98398. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  98399. unsigned i;
  98400. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98401. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98402. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  98403. break; /* take only the first one */
  98404. }
  98405. }
  98406. }
  98407. /* validate metadata */
  98408. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  98409. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98410. metadata_has_seektable = false;
  98411. metadata_has_vorbis_comment = false;
  98412. metadata_picture_has_type1 = false;
  98413. metadata_picture_has_type2 = false;
  98414. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98415. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  98416. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  98417. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98418. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  98419. if(metadata_has_seektable) /* only one is allowed */
  98420. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98421. metadata_has_seektable = true;
  98422. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  98423. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98424. }
  98425. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  98426. if(metadata_has_vorbis_comment) /* only one is allowed */
  98427. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98428. metadata_has_vorbis_comment = true;
  98429. }
  98430. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  98431. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  98432. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98433. }
  98434. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  98435. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  98436. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98437. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  98438. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  98439. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98440. metadata_picture_has_type1 = true;
  98441. /* standard icon must be 32x32 pixel PNG */
  98442. if(
  98443. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  98444. (
  98445. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  98446. m->data.picture.width != 32 ||
  98447. m->data.picture.height != 32
  98448. )
  98449. )
  98450. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98451. }
  98452. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  98453. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  98454. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  98455. metadata_picture_has_type2 = true;
  98456. }
  98457. }
  98458. }
  98459. encoder->private_->input_capacity = 0;
  98460. for(i = 0; i < encoder->protected_->channels; i++) {
  98461. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  98462. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98463. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  98464. #endif
  98465. }
  98466. for(i = 0; i < 2; i++) {
  98467. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  98468. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98469. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  98470. #endif
  98471. }
  98472. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98473. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  98474. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  98475. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  98476. #endif
  98477. for(i = 0; i < encoder->protected_->channels; i++) {
  98478. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  98479. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  98480. encoder->private_->best_subframe[i] = 0;
  98481. }
  98482. for(i = 0; i < 2; i++) {
  98483. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  98484. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  98485. encoder->private_->best_subframe_mid_side[i] = 0;
  98486. }
  98487. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  98488. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  98489. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98490. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  98491. #else
  98492. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  98493. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  98494. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  98495. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  98496. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  98497. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  98498. 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);
  98499. #endif
  98500. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  98501. encoder->private_->loose_mid_side_stereo_frames = 1;
  98502. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98503. encoder->private_->current_sample_number = 0;
  98504. encoder->private_->current_frame_number = 0;
  98505. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  98506. 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? */
  98507. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  98508. /*
  98509. * get the CPU info and set the function pointers
  98510. */
  98511. FLAC__cpu_info(&encoder->private_->cpuinfo);
  98512. /* first default to the non-asm routines */
  98513. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98514. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  98515. #endif
  98516. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  98517. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98518. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98519. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  98520. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  98521. #endif
  98522. /* now override with asm where appropriate */
  98523. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98524. # ifndef FLAC__NO_ASM
  98525. if(encoder->private_->cpuinfo.use_asm) {
  98526. # ifdef FLAC__CPU_IA32
  98527. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  98528. # ifdef FLAC__HAS_NASM
  98529. if(encoder->private_->cpuinfo.data.ia32.sse) {
  98530. if(encoder->protected_->max_lpc_order < 4)
  98531. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  98532. else if(encoder->protected_->max_lpc_order < 8)
  98533. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  98534. else if(encoder->protected_->max_lpc_order < 12)
  98535. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  98536. else
  98537. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98538. }
  98539. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  98540. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  98541. else
  98542. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  98543. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  98544. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98545. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  98546. }
  98547. else {
  98548. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98549. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  98550. }
  98551. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  98552. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  98553. # endif /* FLAC__HAS_NASM */
  98554. # endif /* FLAC__CPU_IA32 */
  98555. }
  98556. # endif /* !FLAC__NO_ASM */
  98557. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  98558. /* finally override based on wide-ness if necessary */
  98559. if(encoder->private_->use_wide_by_block) {
  98560. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  98561. }
  98562. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  98563. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  98564. #if FLAC__HAS_OGG
  98565. encoder->private_->is_ogg = is_ogg;
  98566. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  98567. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98568. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98569. }
  98570. #endif
  98571. encoder->private_->read_callback = read_callback;
  98572. encoder->private_->write_callback = write_callback;
  98573. encoder->private_->seek_callback = seek_callback;
  98574. encoder->private_->tell_callback = tell_callback;
  98575. encoder->private_->metadata_callback = metadata_callback;
  98576. encoder->private_->client_data = client_data;
  98577. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  98578. /* the above function sets the state for us in case of an error */
  98579. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98580. }
  98581. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  98582. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98583. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98584. }
  98585. /*
  98586. * Set up the verify stuff if necessary
  98587. */
  98588. if(encoder->protected_->verify) {
  98589. /*
  98590. * First, set up the fifo which will hold the
  98591. * original signal to compare against
  98592. */
  98593. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  98594. for(i = 0; i < encoder->protected_->channels; i++) {
  98595. 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))) {
  98596. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98597. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98598. }
  98599. }
  98600. encoder->private_->verify.input_fifo.tail = 0;
  98601. /*
  98602. * Now set up a stream decoder for verification
  98603. */
  98604. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  98605. if(0 == encoder->private_->verify.decoder) {
  98606. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98607. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98608. }
  98609. 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) {
  98610. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  98611. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98612. }
  98613. }
  98614. encoder->private_->verify.error_stats.absolute_sample = 0;
  98615. encoder->private_->verify.error_stats.frame_number = 0;
  98616. encoder->private_->verify.error_stats.channel = 0;
  98617. encoder->private_->verify.error_stats.sample = 0;
  98618. encoder->private_->verify.error_stats.expected = 0;
  98619. encoder->private_->verify.error_stats.got = 0;
  98620. /*
  98621. * These must be done before we write any metadata, because that
  98622. * calls the write_callback, which uses these values.
  98623. */
  98624. encoder->private_->first_seekpoint_to_check = 0;
  98625. encoder->private_->samples_written = 0;
  98626. encoder->protected_->streaminfo_offset = 0;
  98627. encoder->protected_->seektable_offset = 0;
  98628. encoder->protected_->audio_offset = 0;
  98629. /*
  98630. * write the stream header
  98631. */
  98632. if(encoder->protected_->verify)
  98633. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  98634. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  98635. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98636. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98637. }
  98638. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98639. /* the above function sets the state for us in case of an error */
  98640. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98641. }
  98642. /*
  98643. * write the STREAMINFO metadata block
  98644. */
  98645. if(encoder->protected_->verify)
  98646. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  98647. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  98648. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  98649. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  98650. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  98651. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  98652. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  98653. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  98654. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  98655. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  98656. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  98657. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  98658. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  98659. if(encoder->protected_->do_md5)
  98660. FLAC__MD5Init(&encoder->private_->md5context);
  98661. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  98662. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98663. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98664. }
  98665. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98666. /* the above function sets the state for us in case of an error */
  98667. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98668. }
  98669. /*
  98670. * Now that the STREAMINFO block is written, we can init this to an
  98671. * absurdly-high value...
  98672. */
  98673. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  98674. /* ... and clear this to 0 */
  98675. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  98676. /*
  98677. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  98678. * if not, we will write an empty one (FLAC__add_metadata_block()
  98679. * automatically supplies the vendor string).
  98680. *
  98681. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  98682. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  98683. * true it will have already insured that the metadata list is properly
  98684. * ordered.)
  98685. */
  98686. if(!metadata_has_vorbis_comment) {
  98687. FLAC__StreamMetadata vorbis_comment;
  98688. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  98689. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  98690. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  98691. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  98692. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  98693. vorbis_comment.data.vorbis_comment.num_comments = 0;
  98694. vorbis_comment.data.vorbis_comment.comments = 0;
  98695. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  98696. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98697. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98698. }
  98699. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98700. /* the above function sets the state for us in case of an error */
  98701. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98702. }
  98703. }
  98704. /*
  98705. * write the user's metadata blocks
  98706. */
  98707. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  98708. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  98709. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  98710. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98711. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98712. }
  98713. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  98714. /* the above function sets the state for us in case of an error */
  98715. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98716. }
  98717. }
  98718. /* now that all the metadata is written, we save the stream offset */
  98719. 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 */
  98720. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  98721. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98722. }
  98723. if(encoder->protected_->verify)
  98724. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  98725. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  98726. }
  98727. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  98728. FLAC__StreamEncoder *encoder,
  98729. FLAC__StreamEncoderWriteCallback write_callback,
  98730. FLAC__StreamEncoderSeekCallback seek_callback,
  98731. FLAC__StreamEncoderTellCallback tell_callback,
  98732. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98733. void *client_data
  98734. )
  98735. {
  98736. return init_stream_internal_enc(
  98737. encoder,
  98738. /*read_callback=*/0,
  98739. write_callback,
  98740. seek_callback,
  98741. tell_callback,
  98742. metadata_callback,
  98743. client_data,
  98744. /*is_ogg=*/false
  98745. );
  98746. }
  98747. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  98748. FLAC__StreamEncoder *encoder,
  98749. FLAC__StreamEncoderReadCallback read_callback,
  98750. FLAC__StreamEncoderWriteCallback write_callback,
  98751. FLAC__StreamEncoderSeekCallback seek_callback,
  98752. FLAC__StreamEncoderTellCallback tell_callback,
  98753. FLAC__StreamEncoderMetadataCallback metadata_callback,
  98754. void *client_data
  98755. )
  98756. {
  98757. return init_stream_internal_enc(
  98758. encoder,
  98759. read_callback,
  98760. write_callback,
  98761. seek_callback,
  98762. tell_callback,
  98763. metadata_callback,
  98764. client_data,
  98765. /*is_ogg=*/true
  98766. );
  98767. }
  98768. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  98769. FLAC__StreamEncoder *encoder,
  98770. FILE *file,
  98771. FLAC__StreamEncoderProgressCallback progress_callback,
  98772. void *client_data,
  98773. FLAC__bool is_ogg
  98774. )
  98775. {
  98776. FLAC__StreamEncoderInitStatus init_status;
  98777. FLAC__ASSERT(0 != encoder);
  98778. FLAC__ASSERT(0 != file);
  98779. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98780. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98781. /* double protection */
  98782. if(file == 0) {
  98783. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98784. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98785. }
  98786. /*
  98787. * To make sure that our file does not go unclosed after an error, we
  98788. * must assign the FILE pointer before any further error can occur in
  98789. * this routine.
  98790. */
  98791. if(file == stdout)
  98792. file = get_binary_stdout_(); /* just to be safe */
  98793. encoder->private_->file = file;
  98794. encoder->private_->progress_callback = progress_callback;
  98795. encoder->private_->bytes_written = 0;
  98796. encoder->private_->samples_written = 0;
  98797. encoder->private_->frames_written = 0;
  98798. init_status = init_stream_internal_enc(
  98799. encoder,
  98800. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  98801. file_write_callback_,
  98802. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  98803. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  98804. /*metadata_callback=*/0,
  98805. client_data,
  98806. is_ogg
  98807. );
  98808. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  98809. /* the above function sets the state for us in case of an error */
  98810. return init_status;
  98811. }
  98812. {
  98813. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  98814. FLAC__ASSERT(blocksize != 0);
  98815. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  98816. }
  98817. return init_status;
  98818. }
  98819. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  98820. FLAC__StreamEncoder *encoder,
  98821. FILE *file,
  98822. FLAC__StreamEncoderProgressCallback progress_callback,
  98823. void *client_data
  98824. )
  98825. {
  98826. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  98827. }
  98828. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  98829. FLAC__StreamEncoder *encoder,
  98830. FILE *file,
  98831. FLAC__StreamEncoderProgressCallback progress_callback,
  98832. void *client_data
  98833. )
  98834. {
  98835. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  98836. }
  98837. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  98838. FLAC__StreamEncoder *encoder,
  98839. const char *filename,
  98840. FLAC__StreamEncoderProgressCallback progress_callback,
  98841. void *client_data,
  98842. FLAC__bool is_ogg
  98843. )
  98844. {
  98845. FILE *file;
  98846. FLAC__ASSERT(0 != encoder);
  98847. /*
  98848. * To make sure that our file does not go unclosed after an error, we
  98849. * have to do the same entrance checks here that are later performed
  98850. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  98851. */
  98852. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98853. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  98854. file = filename? fopen(filename, "w+b") : stdout;
  98855. if(file == 0) {
  98856. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  98857. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  98858. }
  98859. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  98860. }
  98861. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  98862. FLAC__StreamEncoder *encoder,
  98863. const char *filename,
  98864. FLAC__StreamEncoderProgressCallback progress_callback,
  98865. void *client_data
  98866. )
  98867. {
  98868. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  98869. }
  98870. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  98871. FLAC__StreamEncoder *encoder,
  98872. const char *filename,
  98873. FLAC__StreamEncoderProgressCallback progress_callback,
  98874. void *client_data
  98875. )
  98876. {
  98877. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  98878. }
  98879. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  98880. {
  98881. FLAC__bool error = false;
  98882. FLAC__ASSERT(0 != encoder);
  98883. FLAC__ASSERT(0 != encoder->private_);
  98884. FLAC__ASSERT(0 != encoder->protected_);
  98885. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  98886. return true;
  98887. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  98888. if(encoder->private_->current_sample_number != 0) {
  98889. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  98890. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  98891. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  98892. error = true;
  98893. }
  98894. }
  98895. if(encoder->protected_->do_md5)
  98896. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  98897. if(!encoder->private_->is_being_deleted) {
  98898. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  98899. if(encoder->private_->seek_callback) {
  98900. #if FLAC__HAS_OGG
  98901. if(encoder->private_->is_ogg)
  98902. update_ogg_metadata_(encoder);
  98903. else
  98904. #endif
  98905. update_metadata_(encoder);
  98906. /* check if an error occurred while updating metadata */
  98907. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  98908. error = true;
  98909. }
  98910. if(encoder->private_->metadata_callback)
  98911. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  98912. }
  98913. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  98914. if(!error)
  98915. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  98916. error = true;
  98917. }
  98918. }
  98919. if(0 != encoder->private_->file) {
  98920. if(encoder->private_->file != stdout)
  98921. fclose(encoder->private_->file);
  98922. encoder->private_->file = 0;
  98923. }
  98924. #if FLAC__HAS_OGG
  98925. if(encoder->private_->is_ogg)
  98926. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  98927. #endif
  98928. free_(encoder);
  98929. set_defaults_enc(encoder);
  98930. if(!error)
  98931. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  98932. return !error;
  98933. }
  98934. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  98935. {
  98936. FLAC__ASSERT(0 != encoder);
  98937. FLAC__ASSERT(0 != encoder->private_);
  98938. FLAC__ASSERT(0 != encoder->protected_);
  98939. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98940. return false;
  98941. #if FLAC__HAS_OGG
  98942. /* can't check encoder->private_->is_ogg since that's not set until init time */
  98943. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  98944. return true;
  98945. #else
  98946. (void)value;
  98947. return false;
  98948. #endif
  98949. }
  98950. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98951. {
  98952. FLAC__ASSERT(0 != encoder);
  98953. FLAC__ASSERT(0 != encoder->private_);
  98954. FLAC__ASSERT(0 != encoder->protected_);
  98955. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98956. return false;
  98957. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  98958. encoder->protected_->verify = value;
  98959. #endif
  98960. return true;
  98961. }
  98962. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98963. {
  98964. FLAC__ASSERT(0 != encoder);
  98965. FLAC__ASSERT(0 != encoder->private_);
  98966. FLAC__ASSERT(0 != encoder->protected_);
  98967. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98968. return false;
  98969. encoder->protected_->streamable_subset = value;
  98970. return true;
  98971. }
  98972. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  98973. {
  98974. FLAC__ASSERT(0 != encoder);
  98975. FLAC__ASSERT(0 != encoder->private_);
  98976. FLAC__ASSERT(0 != encoder->protected_);
  98977. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98978. return false;
  98979. encoder->protected_->do_md5 = value;
  98980. return true;
  98981. }
  98982. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  98983. {
  98984. FLAC__ASSERT(0 != encoder);
  98985. FLAC__ASSERT(0 != encoder->private_);
  98986. FLAC__ASSERT(0 != encoder->protected_);
  98987. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98988. return false;
  98989. encoder->protected_->channels = value;
  98990. return true;
  98991. }
  98992. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  98993. {
  98994. FLAC__ASSERT(0 != encoder);
  98995. FLAC__ASSERT(0 != encoder->private_);
  98996. FLAC__ASSERT(0 != encoder->protected_);
  98997. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  98998. return false;
  98999. encoder->protected_->bits_per_sample = value;
  99000. return true;
  99001. }
  99002. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  99003. {
  99004. FLAC__ASSERT(0 != encoder);
  99005. FLAC__ASSERT(0 != encoder->private_);
  99006. FLAC__ASSERT(0 != encoder->protected_);
  99007. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99008. return false;
  99009. encoder->protected_->sample_rate = value;
  99010. return true;
  99011. }
  99012. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  99013. {
  99014. FLAC__bool ok = true;
  99015. FLAC__ASSERT(0 != encoder);
  99016. FLAC__ASSERT(0 != encoder->private_);
  99017. FLAC__ASSERT(0 != encoder->protected_);
  99018. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99019. return false;
  99020. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  99021. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  99022. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  99023. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  99024. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99025. #if 0
  99026. /* was: */
  99027. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  99028. /* but it's too hard to specify the string in a locale-specific way */
  99029. #else
  99030. encoder->protected_->num_apodizations = 1;
  99031. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99032. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99033. #endif
  99034. #endif
  99035. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  99036. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  99037. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  99038. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  99039. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  99040. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  99041. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  99042. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  99043. return ok;
  99044. }
  99045. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  99046. {
  99047. FLAC__ASSERT(0 != encoder);
  99048. FLAC__ASSERT(0 != encoder->private_);
  99049. FLAC__ASSERT(0 != encoder->protected_);
  99050. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99051. return false;
  99052. encoder->protected_->blocksize = value;
  99053. return true;
  99054. }
  99055. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99056. {
  99057. FLAC__ASSERT(0 != encoder);
  99058. FLAC__ASSERT(0 != encoder->private_);
  99059. FLAC__ASSERT(0 != encoder->protected_);
  99060. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99061. return false;
  99062. encoder->protected_->do_mid_side_stereo = value;
  99063. return true;
  99064. }
  99065. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99066. {
  99067. FLAC__ASSERT(0 != encoder);
  99068. FLAC__ASSERT(0 != encoder->private_);
  99069. FLAC__ASSERT(0 != encoder->protected_);
  99070. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99071. return false;
  99072. encoder->protected_->loose_mid_side_stereo = value;
  99073. return true;
  99074. }
  99075. /*@@@@add to tests*/
  99076. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  99077. {
  99078. FLAC__ASSERT(0 != encoder);
  99079. FLAC__ASSERT(0 != encoder->private_);
  99080. FLAC__ASSERT(0 != encoder->protected_);
  99081. FLAC__ASSERT(0 != specification);
  99082. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99083. return false;
  99084. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  99085. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  99086. #else
  99087. encoder->protected_->num_apodizations = 0;
  99088. while(1) {
  99089. const char *s = strchr(specification, ';');
  99090. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  99091. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  99092. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  99093. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  99094. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  99095. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  99096. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  99097. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  99098. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  99099. else if(n==6 && 0 == strncmp("connes" , specification, n))
  99100. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  99101. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  99102. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  99103. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  99104. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  99105. if (stddev > 0.0 && stddev <= 0.5) {
  99106. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  99107. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  99108. }
  99109. }
  99110. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  99111. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  99112. else if(n==4 && 0 == strncmp("hann" , specification, n))
  99113. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  99114. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  99115. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  99116. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  99117. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  99118. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  99119. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  99120. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  99121. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  99122. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  99123. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  99124. if (p >= 0.0 && p <= 1.0) {
  99125. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  99126. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  99127. }
  99128. }
  99129. else if(n==5 && 0 == strncmp("welch" , specification, n))
  99130. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  99131. if (encoder->protected_->num_apodizations == 32)
  99132. break;
  99133. if (s)
  99134. specification = s+1;
  99135. else
  99136. break;
  99137. }
  99138. if(encoder->protected_->num_apodizations == 0) {
  99139. encoder->protected_->num_apodizations = 1;
  99140. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99141. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99142. }
  99143. #endif
  99144. return true;
  99145. }
  99146. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  99147. {
  99148. FLAC__ASSERT(0 != encoder);
  99149. FLAC__ASSERT(0 != encoder->private_);
  99150. FLAC__ASSERT(0 != encoder->protected_);
  99151. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99152. return false;
  99153. encoder->protected_->max_lpc_order = value;
  99154. return true;
  99155. }
  99156. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  99157. {
  99158. FLAC__ASSERT(0 != encoder);
  99159. FLAC__ASSERT(0 != encoder->private_);
  99160. FLAC__ASSERT(0 != encoder->protected_);
  99161. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99162. return false;
  99163. encoder->protected_->qlp_coeff_precision = value;
  99164. return true;
  99165. }
  99166. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99167. {
  99168. FLAC__ASSERT(0 != encoder);
  99169. FLAC__ASSERT(0 != encoder->private_);
  99170. FLAC__ASSERT(0 != encoder->protected_);
  99171. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99172. return false;
  99173. encoder->protected_->do_qlp_coeff_prec_search = value;
  99174. return true;
  99175. }
  99176. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99177. {
  99178. FLAC__ASSERT(0 != encoder);
  99179. FLAC__ASSERT(0 != encoder->private_);
  99180. FLAC__ASSERT(0 != encoder->protected_);
  99181. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99182. return false;
  99183. #if 0
  99184. /*@@@ deprecated: */
  99185. encoder->protected_->do_escape_coding = value;
  99186. #else
  99187. (void)value;
  99188. #endif
  99189. return true;
  99190. }
  99191. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99192. {
  99193. FLAC__ASSERT(0 != encoder);
  99194. FLAC__ASSERT(0 != encoder->private_);
  99195. FLAC__ASSERT(0 != encoder->protected_);
  99196. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99197. return false;
  99198. encoder->protected_->do_exhaustive_model_search = value;
  99199. return true;
  99200. }
  99201. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99202. {
  99203. FLAC__ASSERT(0 != encoder);
  99204. FLAC__ASSERT(0 != encoder->private_);
  99205. FLAC__ASSERT(0 != encoder->protected_);
  99206. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99207. return false;
  99208. encoder->protected_->min_residual_partition_order = value;
  99209. return true;
  99210. }
  99211. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  99212. {
  99213. FLAC__ASSERT(0 != encoder);
  99214. FLAC__ASSERT(0 != encoder->private_);
  99215. FLAC__ASSERT(0 != encoder->protected_);
  99216. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99217. return false;
  99218. encoder->protected_->max_residual_partition_order = value;
  99219. return true;
  99220. }
  99221. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  99222. {
  99223. FLAC__ASSERT(0 != encoder);
  99224. FLAC__ASSERT(0 != encoder->private_);
  99225. FLAC__ASSERT(0 != encoder->protected_);
  99226. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99227. return false;
  99228. #if 0
  99229. /*@@@ deprecated: */
  99230. encoder->protected_->rice_parameter_search_dist = value;
  99231. #else
  99232. (void)value;
  99233. #endif
  99234. return true;
  99235. }
  99236. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  99237. {
  99238. FLAC__ASSERT(0 != encoder);
  99239. FLAC__ASSERT(0 != encoder->private_);
  99240. FLAC__ASSERT(0 != encoder->protected_);
  99241. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99242. return false;
  99243. encoder->protected_->total_samples_estimate = value;
  99244. return true;
  99245. }
  99246. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  99247. {
  99248. FLAC__ASSERT(0 != encoder);
  99249. FLAC__ASSERT(0 != encoder->private_);
  99250. FLAC__ASSERT(0 != encoder->protected_);
  99251. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99252. return false;
  99253. if(0 == metadata)
  99254. num_blocks = 0;
  99255. if(0 == num_blocks)
  99256. metadata = 0;
  99257. /* realloc() does not do exactly what we want so... */
  99258. if(encoder->protected_->metadata) {
  99259. free(encoder->protected_->metadata);
  99260. encoder->protected_->metadata = 0;
  99261. encoder->protected_->num_metadata_blocks = 0;
  99262. }
  99263. if(num_blocks) {
  99264. FLAC__StreamMetadata **m;
  99265. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  99266. return false;
  99267. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  99268. encoder->protected_->metadata = m;
  99269. encoder->protected_->num_metadata_blocks = num_blocks;
  99270. }
  99271. #if FLAC__HAS_OGG
  99272. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  99273. return false;
  99274. #endif
  99275. return true;
  99276. }
  99277. /*
  99278. * These three functions are not static, but not publically exposed in
  99279. * include/FLAC/ either. They are used by the test suite.
  99280. */
  99281. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99282. {
  99283. FLAC__ASSERT(0 != encoder);
  99284. FLAC__ASSERT(0 != encoder->private_);
  99285. FLAC__ASSERT(0 != encoder->protected_);
  99286. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99287. return false;
  99288. encoder->private_->disable_constant_subframes = value;
  99289. return true;
  99290. }
  99291. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99292. {
  99293. FLAC__ASSERT(0 != encoder);
  99294. FLAC__ASSERT(0 != encoder->private_);
  99295. FLAC__ASSERT(0 != encoder->protected_);
  99296. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99297. return false;
  99298. encoder->private_->disable_fixed_subframes = value;
  99299. return true;
  99300. }
  99301. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99302. {
  99303. FLAC__ASSERT(0 != encoder);
  99304. FLAC__ASSERT(0 != encoder->private_);
  99305. FLAC__ASSERT(0 != encoder->protected_);
  99306. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99307. return false;
  99308. encoder->private_->disable_verbatim_subframes = value;
  99309. return true;
  99310. }
  99311. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  99312. {
  99313. FLAC__ASSERT(0 != encoder);
  99314. FLAC__ASSERT(0 != encoder->private_);
  99315. FLAC__ASSERT(0 != encoder->protected_);
  99316. return encoder->protected_->state;
  99317. }
  99318. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  99319. {
  99320. FLAC__ASSERT(0 != encoder);
  99321. FLAC__ASSERT(0 != encoder->private_);
  99322. FLAC__ASSERT(0 != encoder->protected_);
  99323. if(encoder->protected_->verify)
  99324. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  99325. else
  99326. return FLAC__STREAM_DECODER_UNINITIALIZED;
  99327. }
  99328. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  99329. {
  99330. FLAC__ASSERT(0 != encoder);
  99331. FLAC__ASSERT(0 != encoder->private_);
  99332. FLAC__ASSERT(0 != encoder->protected_);
  99333. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  99334. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  99335. else
  99336. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  99337. }
  99338. 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)
  99339. {
  99340. FLAC__ASSERT(0 != encoder);
  99341. FLAC__ASSERT(0 != encoder->private_);
  99342. FLAC__ASSERT(0 != encoder->protected_);
  99343. if(0 != absolute_sample)
  99344. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  99345. if(0 != frame_number)
  99346. *frame_number = encoder->private_->verify.error_stats.frame_number;
  99347. if(0 != channel)
  99348. *channel = encoder->private_->verify.error_stats.channel;
  99349. if(0 != sample)
  99350. *sample = encoder->private_->verify.error_stats.sample;
  99351. if(0 != expected)
  99352. *expected = encoder->private_->verify.error_stats.expected;
  99353. if(0 != got)
  99354. *got = encoder->private_->verify.error_stats.got;
  99355. }
  99356. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  99357. {
  99358. FLAC__ASSERT(0 != encoder);
  99359. FLAC__ASSERT(0 != encoder->private_);
  99360. FLAC__ASSERT(0 != encoder->protected_);
  99361. return encoder->protected_->verify;
  99362. }
  99363. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  99364. {
  99365. FLAC__ASSERT(0 != encoder);
  99366. FLAC__ASSERT(0 != encoder->private_);
  99367. FLAC__ASSERT(0 != encoder->protected_);
  99368. return encoder->protected_->streamable_subset;
  99369. }
  99370. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  99371. {
  99372. FLAC__ASSERT(0 != encoder);
  99373. FLAC__ASSERT(0 != encoder->private_);
  99374. FLAC__ASSERT(0 != encoder->protected_);
  99375. return encoder->protected_->do_md5;
  99376. }
  99377. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  99378. {
  99379. FLAC__ASSERT(0 != encoder);
  99380. FLAC__ASSERT(0 != encoder->private_);
  99381. FLAC__ASSERT(0 != encoder->protected_);
  99382. return encoder->protected_->channels;
  99383. }
  99384. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  99385. {
  99386. FLAC__ASSERT(0 != encoder);
  99387. FLAC__ASSERT(0 != encoder->private_);
  99388. FLAC__ASSERT(0 != encoder->protected_);
  99389. return encoder->protected_->bits_per_sample;
  99390. }
  99391. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  99392. {
  99393. FLAC__ASSERT(0 != encoder);
  99394. FLAC__ASSERT(0 != encoder->private_);
  99395. FLAC__ASSERT(0 != encoder->protected_);
  99396. return encoder->protected_->sample_rate;
  99397. }
  99398. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  99399. {
  99400. FLAC__ASSERT(0 != encoder);
  99401. FLAC__ASSERT(0 != encoder->private_);
  99402. FLAC__ASSERT(0 != encoder->protected_);
  99403. return encoder->protected_->blocksize;
  99404. }
  99405. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99406. {
  99407. FLAC__ASSERT(0 != encoder);
  99408. FLAC__ASSERT(0 != encoder->private_);
  99409. FLAC__ASSERT(0 != encoder->protected_);
  99410. return encoder->protected_->do_mid_side_stereo;
  99411. }
  99412. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  99413. {
  99414. FLAC__ASSERT(0 != encoder);
  99415. FLAC__ASSERT(0 != encoder->private_);
  99416. FLAC__ASSERT(0 != encoder->protected_);
  99417. return encoder->protected_->loose_mid_side_stereo;
  99418. }
  99419. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  99420. {
  99421. FLAC__ASSERT(0 != encoder);
  99422. FLAC__ASSERT(0 != encoder->private_);
  99423. FLAC__ASSERT(0 != encoder->protected_);
  99424. return encoder->protected_->max_lpc_order;
  99425. }
  99426. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  99427. {
  99428. FLAC__ASSERT(0 != encoder);
  99429. FLAC__ASSERT(0 != encoder->private_);
  99430. FLAC__ASSERT(0 != encoder->protected_);
  99431. return encoder->protected_->qlp_coeff_precision;
  99432. }
  99433. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  99434. {
  99435. FLAC__ASSERT(0 != encoder);
  99436. FLAC__ASSERT(0 != encoder->private_);
  99437. FLAC__ASSERT(0 != encoder->protected_);
  99438. return encoder->protected_->do_qlp_coeff_prec_search;
  99439. }
  99440. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  99441. {
  99442. FLAC__ASSERT(0 != encoder);
  99443. FLAC__ASSERT(0 != encoder->private_);
  99444. FLAC__ASSERT(0 != encoder->protected_);
  99445. return encoder->protected_->do_escape_coding;
  99446. }
  99447. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  99448. {
  99449. FLAC__ASSERT(0 != encoder);
  99450. FLAC__ASSERT(0 != encoder->private_);
  99451. FLAC__ASSERT(0 != encoder->protected_);
  99452. return encoder->protected_->do_exhaustive_model_search;
  99453. }
  99454. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99455. {
  99456. FLAC__ASSERT(0 != encoder);
  99457. FLAC__ASSERT(0 != encoder->private_);
  99458. FLAC__ASSERT(0 != encoder->protected_);
  99459. return encoder->protected_->min_residual_partition_order;
  99460. }
  99461. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  99462. {
  99463. FLAC__ASSERT(0 != encoder);
  99464. FLAC__ASSERT(0 != encoder->private_);
  99465. FLAC__ASSERT(0 != encoder->protected_);
  99466. return encoder->protected_->max_residual_partition_order;
  99467. }
  99468. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  99469. {
  99470. FLAC__ASSERT(0 != encoder);
  99471. FLAC__ASSERT(0 != encoder->private_);
  99472. FLAC__ASSERT(0 != encoder->protected_);
  99473. return encoder->protected_->rice_parameter_search_dist;
  99474. }
  99475. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  99476. {
  99477. FLAC__ASSERT(0 != encoder);
  99478. FLAC__ASSERT(0 != encoder->private_);
  99479. FLAC__ASSERT(0 != encoder->protected_);
  99480. return encoder->protected_->total_samples_estimate;
  99481. }
  99482. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  99483. {
  99484. unsigned i, j = 0, channel;
  99485. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99486. FLAC__ASSERT(0 != encoder);
  99487. FLAC__ASSERT(0 != encoder->private_);
  99488. FLAC__ASSERT(0 != encoder->protected_);
  99489. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99490. do {
  99491. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  99492. if(encoder->protected_->verify)
  99493. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  99494. for(channel = 0; channel < channels; channel++)
  99495. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  99496. if(encoder->protected_->do_mid_side_stereo) {
  99497. FLAC__ASSERT(channels == 2);
  99498. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99499. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99500. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  99501. 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' ! */
  99502. }
  99503. }
  99504. else
  99505. j += n;
  99506. encoder->private_->current_sample_number += n;
  99507. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99508. if(encoder->private_->current_sample_number > blocksize) {
  99509. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  99510. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99511. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99512. return false;
  99513. /* move unprocessed overread samples to beginnings of arrays */
  99514. for(channel = 0; channel < channels; channel++)
  99515. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99516. if(encoder->protected_->do_mid_side_stereo) {
  99517. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99518. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99519. }
  99520. encoder->private_->current_sample_number = 1;
  99521. }
  99522. } while(j < samples);
  99523. return true;
  99524. }
  99525. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  99526. {
  99527. unsigned i, j, k, channel;
  99528. FLAC__int32 x, mid, side;
  99529. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  99530. FLAC__ASSERT(0 != encoder);
  99531. FLAC__ASSERT(0 != encoder->private_);
  99532. FLAC__ASSERT(0 != encoder->protected_);
  99533. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99534. j = k = 0;
  99535. /*
  99536. * we have several flavors of the same basic loop, optimized for
  99537. * different conditions:
  99538. */
  99539. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  99540. /*
  99541. * stereo coding: unroll channel loop
  99542. */
  99543. do {
  99544. if(encoder->protected_->verify)
  99545. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99546. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99547. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99548. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  99549. x = buffer[k++];
  99550. encoder->private_->integer_signal[1][i] = x;
  99551. mid += x;
  99552. side -= x;
  99553. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  99554. encoder->private_->integer_signal_mid_side[1][i] = side;
  99555. encoder->private_->integer_signal_mid_side[0][i] = mid;
  99556. }
  99557. encoder->private_->current_sample_number = i;
  99558. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99559. if(i > blocksize) {
  99560. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99561. return false;
  99562. /* move unprocessed overread samples to beginnings of arrays */
  99563. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99564. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99565. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  99566. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  99567. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  99568. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  99569. encoder->private_->current_sample_number = 1;
  99570. }
  99571. } while(j < samples);
  99572. }
  99573. else {
  99574. /*
  99575. * independent channel coding: buffer each channel in inner loop
  99576. */
  99577. do {
  99578. if(encoder->protected_->verify)
  99579. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  99580. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  99581. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  99582. for(channel = 0; channel < channels; channel++)
  99583. encoder->private_->integer_signal[channel][i] = buffer[k++];
  99584. }
  99585. encoder->private_->current_sample_number = i;
  99586. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  99587. if(i > blocksize) {
  99588. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  99589. return false;
  99590. /* move unprocessed overread samples to beginnings of arrays */
  99591. FLAC__ASSERT(i == blocksize+OVERREAD_);
  99592. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  99593. for(channel = 0; channel < channels; channel++)
  99594. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  99595. encoder->private_->current_sample_number = 1;
  99596. }
  99597. } while(j < samples);
  99598. }
  99599. return true;
  99600. }
  99601. /***********************************************************************
  99602. *
  99603. * Private class methods
  99604. *
  99605. ***********************************************************************/
  99606. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  99607. {
  99608. FLAC__ASSERT(0 != encoder);
  99609. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99610. encoder->protected_->verify = true;
  99611. #else
  99612. encoder->protected_->verify = false;
  99613. #endif
  99614. encoder->protected_->streamable_subset = true;
  99615. encoder->protected_->do_md5 = true;
  99616. encoder->protected_->do_mid_side_stereo = false;
  99617. encoder->protected_->loose_mid_side_stereo = false;
  99618. encoder->protected_->channels = 2;
  99619. encoder->protected_->bits_per_sample = 16;
  99620. encoder->protected_->sample_rate = 44100;
  99621. encoder->protected_->blocksize = 0;
  99622. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99623. encoder->protected_->num_apodizations = 1;
  99624. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  99625. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  99626. #endif
  99627. encoder->protected_->max_lpc_order = 0;
  99628. encoder->protected_->qlp_coeff_precision = 0;
  99629. encoder->protected_->do_qlp_coeff_prec_search = false;
  99630. encoder->protected_->do_exhaustive_model_search = false;
  99631. encoder->protected_->do_escape_coding = false;
  99632. encoder->protected_->min_residual_partition_order = 0;
  99633. encoder->protected_->max_residual_partition_order = 0;
  99634. encoder->protected_->rice_parameter_search_dist = 0;
  99635. encoder->protected_->total_samples_estimate = 0;
  99636. encoder->protected_->metadata = 0;
  99637. encoder->protected_->num_metadata_blocks = 0;
  99638. encoder->private_->seek_table = 0;
  99639. encoder->private_->disable_constant_subframes = false;
  99640. encoder->private_->disable_fixed_subframes = false;
  99641. encoder->private_->disable_verbatim_subframes = false;
  99642. #if FLAC__HAS_OGG
  99643. encoder->private_->is_ogg = false;
  99644. #endif
  99645. encoder->private_->read_callback = 0;
  99646. encoder->private_->write_callback = 0;
  99647. encoder->private_->seek_callback = 0;
  99648. encoder->private_->tell_callback = 0;
  99649. encoder->private_->metadata_callback = 0;
  99650. encoder->private_->progress_callback = 0;
  99651. encoder->private_->client_data = 0;
  99652. #if FLAC__HAS_OGG
  99653. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  99654. #endif
  99655. }
  99656. void free_(FLAC__StreamEncoder *encoder)
  99657. {
  99658. unsigned i, channel;
  99659. FLAC__ASSERT(0 != encoder);
  99660. if(encoder->protected_->metadata) {
  99661. free(encoder->protected_->metadata);
  99662. encoder->protected_->metadata = 0;
  99663. encoder->protected_->num_metadata_blocks = 0;
  99664. }
  99665. for(i = 0; i < encoder->protected_->channels; i++) {
  99666. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  99667. free(encoder->private_->integer_signal_unaligned[i]);
  99668. encoder->private_->integer_signal_unaligned[i] = 0;
  99669. }
  99670. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99671. if(0 != encoder->private_->real_signal_unaligned[i]) {
  99672. free(encoder->private_->real_signal_unaligned[i]);
  99673. encoder->private_->real_signal_unaligned[i] = 0;
  99674. }
  99675. #endif
  99676. }
  99677. for(i = 0; i < 2; i++) {
  99678. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  99679. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  99680. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  99681. }
  99682. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99683. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  99684. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  99685. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  99686. }
  99687. #endif
  99688. }
  99689. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99690. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  99691. if(0 != encoder->private_->window_unaligned[i]) {
  99692. free(encoder->private_->window_unaligned[i]);
  99693. encoder->private_->window_unaligned[i] = 0;
  99694. }
  99695. }
  99696. if(0 != encoder->private_->windowed_signal_unaligned) {
  99697. free(encoder->private_->windowed_signal_unaligned);
  99698. encoder->private_->windowed_signal_unaligned = 0;
  99699. }
  99700. #endif
  99701. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  99702. for(i = 0; i < 2; i++) {
  99703. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  99704. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  99705. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  99706. }
  99707. }
  99708. }
  99709. for(channel = 0; channel < 2; channel++) {
  99710. for(i = 0; i < 2; i++) {
  99711. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  99712. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  99713. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  99714. }
  99715. }
  99716. }
  99717. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  99718. free(encoder->private_->abs_residual_partition_sums_unaligned);
  99719. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  99720. }
  99721. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  99722. free(encoder->private_->raw_bits_per_partition_unaligned);
  99723. encoder->private_->raw_bits_per_partition_unaligned = 0;
  99724. }
  99725. if(encoder->protected_->verify) {
  99726. for(i = 0; i < encoder->protected_->channels; i++) {
  99727. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  99728. free(encoder->private_->verify.input_fifo.data[i]);
  99729. encoder->private_->verify.input_fifo.data[i] = 0;
  99730. }
  99731. }
  99732. }
  99733. FLAC__bitwriter_free(encoder->private_->frame);
  99734. }
  99735. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  99736. {
  99737. FLAC__bool ok;
  99738. unsigned i, channel;
  99739. FLAC__ASSERT(new_blocksize > 0);
  99740. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  99741. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  99742. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  99743. if(new_blocksize <= encoder->private_->input_capacity)
  99744. return true;
  99745. ok = true;
  99746. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  99747. * requires that the input arrays (in our case the integer signals)
  99748. * have a buffer of up to 3 zeroes in front (at negative indices) for
  99749. * alignment purposes; we use 4 in front to keep the data well-aligned.
  99750. */
  99751. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  99752. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  99753. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  99754. encoder->private_->integer_signal[i] += 4;
  99755. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99756. #if 0 /* @@@ currently unused */
  99757. if(encoder->protected_->max_lpc_order > 0)
  99758. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  99759. #endif
  99760. #endif
  99761. }
  99762. for(i = 0; ok && i < 2; i++) {
  99763. 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]);
  99764. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  99765. encoder->private_->integer_signal_mid_side[i] += 4;
  99766. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99767. #if 0 /* @@@ currently unused */
  99768. if(encoder->protected_->max_lpc_order > 0)
  99769. 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]);
  99770. #endif
  99771. #endif
  99772. }
  99773. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99774. if(ok && encoder->protected_->max_lpc_order > 0) {
  99775. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  99776. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  99777. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  99778. }
  99779. #endif
  99780. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  99781. for(i = 0; ok && i < 2; i++) {
  99782. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  99783. }
  99784. }
  99785. for(channel = 0; ok && channel < 2; channel++) {
  99786. for(i = 0; ok && i < 2; i++) {
  99787. 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]);
  99788. }
  99789. }
  99790. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  99791. /*@@@ 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) */
  99792. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  99793. if(encoder->protected_->do_escape_coding)
  99794. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  99795. /* now adjust the windows if the blocksize has changed */
  99796. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99797. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  99798. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  99799. switch(encoder->protected_->apodizations[i].type) {
  99800. case FLAC__APODIZATION_BARTLETT:
  99801. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  99802. break;
  99803. case FLAC__APODIZATION_BARTLETT_HANN:
  99804. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  99805. break;
  99806. case FLAC__APODIZATION_BLACKMAN:
  99807. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  99808. break;
  99809. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  99810. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  99811. break;
  99812. case FLAC__APODIZATION_CONNES:
  99813. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  99814. break;
  99815. case FLAC__APODIZATION_FLATTOP:
  99816. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  99817. break;
  99818. case FLAC__APODIZATION_GAUSS:
  99819. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  99820. break;
  99821. case FLAC__APODIZATION_HAMMING:
  99822. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  99823. break;
  99824. case FLAC__APODIZATION_HANN:
  99825. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99826. break;
  99827. case FLAC__APODIZATION_KAISER_BESSEL:
  99828. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  99829. break;
  99830. case FLAC__APODIZATION_NUTTALL:
  99831. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  99832. break;
  99833. case FLAC__APODIZATION_RECTANGLE:
  99834. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  99835. break;
  99836. case FLAC__APODIZATION_TRIANGLE:
  99837. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  99838. break;
  99839. case FLAC__APODIZATION_TUKEY:
  99840. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  99841. break;
  99842. case FLAC__APODIZATION_WELCH:
  99843. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  99844. break;
  99845. default:
  99846. FLAC__ASSERT(0);
  99847. /* double protection */
  99848. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  99849. break;
  99850. }
  99851. }
  99852. }
  99853. #endif
  99854. if(ok)
  99855. encoder->private_->input_capacity = new_blocksize;
  99856. else
  99857. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99858. return ok;
  99859. }
  99860. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  99861. {
  99862. const FLAC__byte *buffer;
  99863. size_t bytes;
  99864. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  99865. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  99866. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99867. return false;
  99868. }
  99869. if(encoder->protected_->verify) {
  99870. encoder->private_->verify.output.data = buffer;
  99871. encoder->private_->verify.output.bytes = bytes;
  99872. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  99873. encoder->private_->verify.needs_magic_hack = true;
  99874. }
  99875. else {
  99876. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  99877. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99878. FLAC__bitwriter_clear(encoder->private_->frame);
  99879. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  99880. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99881. return false;
  99882. }
  99883. }
  99884. }
  99885. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99886. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99887. FLAC__bitwriter_clear(encoder->private_->frame);
  99888. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99889. return false;
  99890. }
  99891. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  99892. FLAC__bitwriter_clear(encoder->private_->frame);
  99893. if(samples > 0) {
  99894. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  99895. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  99896. }
  99897. return true;
  99898. }
  99899. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  99900. {
  99901. FLAC__StreamEncoderWriteStatus status;
  99902. FLAC__uint64 output_position = 0;
  99903. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  99904. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  99905. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99906. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99907. }
  99908. /*
  99909. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  99910. */
  99911. if(samples == 0) {
  99912. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  99913. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  99914. encoder->protected_->streaminfo_offset = output_position;
  99915. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  99916. encoder->protected_->seektable_offset = output_position;
  99917. }
  99918. /*
  99919. * Mark the current seek point if hit (if audio_offset == 0 that
  99920. * means we're still writing metadata and haven't hit the first
  99921. * frame yet)
  99922. */
  99923. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  99924. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99925. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  99926. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  99927. FLAC__uint64 test_sample;
  99928. unsigned i;
  99929. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  99930. test_sample = encoder->private_->seek_table->points[i].sample_number;
  99931. if(test_sample > frame_last_sample) {
  99932. break;
  99933. }
  99934. else if(test_sample >= frame_first_sample) {
  99935. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  99936. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  99937. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  99938. encoder->private_->first_seekpoint_to_check++;
  99939. /* DO NOT: "break;" and here's why:
  99940. * The seektable template may contain more than one target
  99941. * sample for any given frame; we will keep looping, generating
  99942. * duplicate seekpoints for them, and we'll clean it up later,
  99943. * just before writing the seektable back to the metadata.
  99944. */
  99945. }
  99946. else {
  99947. encoder->private_->first_seekpoint_to_check++;
  99948. }
  99949. }
  99950. }
  99951. #if FLAC__HAS_OGG
  99952. if(encoder->private_->is_ogg) {
  99953. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  99954. &encoder->protected_->ogg_encoder_aspect,
  99955. buffer,
  99956. bytes,
  99957. samples,
  99958. encoder->private_->current_frame_number,
  99959. is_last_block,
  99960. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  99961. encoder,
  99962. encoder->private_->client_data
  99963. );
  99964. }
  99965. else
  99966. #endif
  99967. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  99968. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  99969. encoder->private_->bytes_written += bytes;
  99970. encoder->private_->samples_written += samples;
  99971. /* we keep a high watermark on the number of frames written because
  99972. * when the encoder goes back to write metadata, 'current_frame'
  99973. * will drop back to 0.
  99974. */
  99975. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  99976. }
  99977. else
  99978. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99979. return status;
  99980. }
  99981. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  99982. void update_metadata_(const FLAC__StreamEncoder *encoder)
  99983. {
  99984. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  99985. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  99986. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  99987. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  99988. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  99989. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  99990. FLAC__StreamEncoderSeekStatus seek_status;
  99991. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  99992. /* All this is based on intimate knowledge of the stream header
  99993. * layout, but a change to the header format that would break this
  99994. * would also break all streams encoded in the previous format.
  99995. */
  99996. /*
  99997. * Write MD5 signature
  99998. */
  99999. {
  100000. const unsigned md5_offset =
  100001. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100002. (
  100003. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100004. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100005. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100006. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100007. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100008. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100009. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100010. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100011. ) / 8;
  100012. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  100013. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100014. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100015. return;
  100016. }
  100017. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100018. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100019. return;
  100020. }
  100021. }
  100022. /*
  100023. * Write total samples
  100024. */
  100025. {
  100026. const unsigned total_samples_byte_offset =
  100027. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100028. (
  100029. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100030. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100031. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100032. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100033. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100034. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100035. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  100036. - 4
  100037. ) / 8;
  100038. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  100039. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100040. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100041. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100042. b[4] = (FLAC__byte)(samples & 0xFF);
  100043. 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) {
  100044. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100045. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100046. return;
  100047. }
  100048. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100049. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100050. return;
  100051. }
  100052. }
  100053. /*
  100054. * Write min/max framesize
  100055. */
  100056. {
  100057. const unsigned min_framesize_offset =
  100058. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100059. (
  100060. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100061. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100062. ) / 8;
  100063. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  100064. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100065. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100066. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100067. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100068. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100069. 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) {
  100070. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100071. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100072. return;
  100073. }
  100074. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100075. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100076. return;
  100077. }
  100078. }
  100079. /*
  100080. * Write seektable
  100081. */
  100082. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100083. unsigned i;
  100084. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100085. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100086. 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) {
  100087. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  100088. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100089. return;
  100090. }
  100091. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  100092. FLAC__uint64 xx;
  100093. unsigned x;
  100094. xx = encoder->private_->seek_table->points[i].sample_number;
  100095. b[7] = (FLAC__byte)xx; xx >>= 8;
  100096. b[6] = (FLAC__byte)xx; xx >>= 8;
  100097. b[5] = (FLAC__byte)xx; xx >>= 8;
  100098. b[4] = (FLAC__byte)xx; xx >>= 8;
  100099. b[3] = (FLAC__byte)xx; xx >>= 8;
  100100. b[2] = (FLAC__byte)xx; xx >>= 8;
  100101. b[1] = (FLAC__byte)xx; xx >>= 8;
  100102. b[0] = (FLAC__byte)xx; xx >>= 8;
  100103. xx = encoder->private_->seek_table->points[i].stream_offset;
  100104. b[15] = (FLAC__byte)xx; xx >>= 8;
  100105. b[14] = (FLAC__byte)xx; xx >>= 8;
  100106. b[13] = (FLAC__byte)xx; xx >>= 8;
  100107. b[12] = (FLAC__byte)xx; xx >>= 8;
  100108. b[11] = (FLAC__byte)xx; xx >>= 8;
  100109. b[10] = (FLAC__byte)xx; xx >>= 8;
  100110. b[9] = (FLAC__byte)xx; xx >>= 8;
  100111. b[8] = (FLAC__byte)xx; xx >>= 8;
  100112. x = encoder->private_->seek_table->points[i].frame_samples;
  100113. b[17] = (FLAC__byte)x; x >>= 8;
  100114. b[16] = (FLAC__byte)x; x >>= 8;
  100115. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100116. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100117. return;
  100118. }
  100119. }
  100120. }
  100121. }
  100122. #if FLAC__HAS_OGG
  100123. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100124. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  100125. {
  100126. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  100127. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  100128. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  100129. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  100130. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  100131. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  100132. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  100133. FLAC__STREAM_SYNC_LENGTH
  100134. ;
  100135. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100136. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100137. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100138. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100139. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100140. ogg_page page;
  100141. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100142. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  100143. /* Pre-check that client supports seeking, since we don't want the
  100144. * ogg_helper code to ever have to deal with this condition.
  100145. */
  100146. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  100147. return;
  100148. /* All this is based on intimate knowledge of the stream header
  100149. * layout, but a change to the header format that would break this
  100150. * would also break all streams encoded in the previous format.
  100151. */
  100152. /**
  100153. ** Write STREAMINFO stats
  100154. **/
  100155. simple_ogg_page__init(&page);
  100156. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100157. simple_ogg_page__clear(&page);
  100158. return; /* state already set */
  100159. }
  100160. /*
  100161. * Write MD5 signature
  100162. */
  100163. {
  100164. const unsigned md5_offset =
  100165. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100166. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100167. (
  100168. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100169. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  100170. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  100171. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  100172. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  100173. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  100174. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  100175. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  100176. ) / 8;
  100177. if(md5_offset + 16 > (unsigned)page.body_len) {
  100178. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100179. simple_ogg_page__clear(&page);
  100180. return;
  100181. }
  100182. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  100183. }
  100184. /*
  100185. * Write total samples
  100186. */
  100187. {
  100188. const unsigned total_samples_byte_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. - 4
  100200. ) / 8;
  100201. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  100202. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100203. simple_ogg_page__clear(&page);
  100204. return;
  100205. }
  100206. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  100207. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  100208. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  100209. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  100210. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  100211. b[4] = (FLAC__byte)(samples & 0xFF);
  100212. memcpy(page.body + total_samples_byte_offset, b, 5);
  100213. }
  100214. /*
  100215. * Write min/max framesize
  100216. */
  100217. {
  100218. const unsigned min_framesize_offset =
  100219. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  100220. FLAC__STREAM_METADATA_HEADER_LENGTH +
  100221. (
  100222. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  100223. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  100224. ) / 8;
  100225. if(min_framesize_offset + 6 > (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)((min_framesize >> 16) & 0xFF);
  100231. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  100232. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  100233. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  100234. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  100235. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  100236. memcpy(page.body + min_framesize_offset, b, 6);
  100237. }
  100238. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100239. simple_ogg_page__clear(&page);
  100240. return; /* state already set */
  100241. }
  100242. simple_ogg_page__clear(&page);
  100243. /*
  100244. * Write seektable
  100245. */
  100246. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  100247. unsigned i;
  100248. FLAC__byte *p;
  100249. FLAC__format_seektable_sort(encoder->private_->seek_table);
  100250. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  100251. simple_ogg_page__init(&page);
  100252. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  100253. simple_ogg_page__clear(&page);
  100254. return; /* state already set */
  100255. }
  100256. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  100257. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  100258. simple_ogg_page__clear(&page);
  100259. return;
  100260. }
  100261. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  100262. FLAC__uint64 xx;
  100263. unsigned x;
  100264. xx = encoder->private_->seek_table->points[i].sample_number;
  100265. b[7] = (FLAC__byte)xx; xx >>= 8;
  100266. b[6] = (FLAC__byte)xx; xx >>= 8;
  100267. b[5] = (FLAC__byte)xx; xx >>= 8;
  100268. b[4] = (FLAC__byte)xx; xx >>= 8;
  100269. b[3] = (FLAC__byte)xx; xx >>= 8;
  100270. b[2] = (FLAC__byte)xx; xx >>= 8;
  100271. b[1] = (FLAC__byte)xx; xx >>= 8;
  100272. b[0] = (FLAC__byte)xx; xx >>= 8;
  100273. xx = encoder->private_->seek_table->points[i].stream_offset;
  100274. b[15] = (FLAC__byte)xx; xx >>= 8;
  100275. b[14] = (FLAC__byte)xx; xx >>= 8;
  100276. b[13] = (FLAC__byte)xx; xx >>= 8;
  100277. b[12] = (FLAC__byte)xx; xx >>= 8;
  100278. b[11] = (FLAC__byte)xx; xx >>= 8;
  100279. b[10] = (FLAC__byte)xx; xx >>= 8;
  100280. b[9] = (FLAC__byte)xx; xx >>= 8;
  100281. b[8] = (FLAC__byte)xx; xx >>= 8;
  100282. x = encoder->private_->seek_table->points[i].frame_samples;
  100283. b[17] = (FLAC__byte)x; x >>= 8;
  100284. b[16] = (FLAC__byte)x; x >>= 8;
  100285. memcpy(p, b, 18);
  100286. }
  100287. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  100288. simple_ogg_page__clear(&page);
  100289. return; /* state already set */
  100290. }
  100291. simple_ogg_page__clear(&page);
  100292. }
  100293. }
  100294. #endif
  100295. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  100296. {
  100297. FLAC__uint16 crc;
  100298. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100299. /*
  100300. * Accumulate raw signal to the MD5 signature
  100301. */
  100302. 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)) {
  100303. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100304. return false;
  100305. }
  100306. /*
  100307. * Process the frame header and subframes into the frame bitbuffer
  100308. */
  100309. if(!process_subframes_(encoder, is_fractional_block)) {
  100310. /* the above function sets the state for us in case of an error */
  100311. return false;
  100312. }
  100313. /*
  100314. * Zero-pad the frame to a byte_boundary
  100315. */
  100316. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  100317. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100318. return false;
  100319. }
  100320. /*
  100321. * CRC-16 the whole thing
  100322. */
  100323. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100324. if(
  100325. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  100326. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  100327. ) {
  100328. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100329. return false;
  100330. }
  100331. /*
  100332. * Write it
  100333. */
  100334. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  100335. /* the above function sets the state for us in case of an error */
  100336. return false;
  100337. }
  100338. /*
  100339. * Get ready for the next frame
  100340. */
  100341. encoder->private_->current_sample_number = 0;
  100342. encoder->private_->current_frame_number++;
  100343. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  100344. return true;
  100345. }
  100346. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  100347. {
  100348. FLAC__FrameHeader frame_header;
  100349. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  100350. FLAC__bool do_independent, do_mid_side;
  100351. /*
  100352. * Calculate the min,max Rice partition orders
  100353. */
  100354. if(is_fractional_block) {
  100355. max_partition_order = 0;
  100356. }
  100357. else {
  100358. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  100359. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  100360. }
  100361. min_partition_order = min(min_partition_order, max_partition_order);
  100362. /*
  100363. * Setup the frame
  100364. */
  100365. frame_header.blocksize = encoder->protected_->blocksize;
  100366. frame_header.sample_rate = encoder->protected_->sample_rate;
  100367. frame_header.channels = encoder->protected_->channels;
  100368. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  100369. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  100370. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  100371. frame_header.number.frame_number = encoder->private_->current_frame_number;
  100372. /*
  100373. * Figure out what channel assignments to try
  100374. */
  100375. if(encoder->protected_->do_mid_side_stereo) {
  100376. if(encoder->protected_->loose_mid_side_stereo) {
  100377. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  100378. do_independent = true;
  100379. do_mid_side = true;
  100380. }
  100381. else {
  100382. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  100383. do_mid_side = !do_independent;
  100384. }
  100385. }
  100386. else {
  100387. do_independent = true;
  100388. do_mid_side = true;
  100389. }
  100390. }
  100391. else {
  100392. do_independent = true;
  100393. do_mid_side = false;
  100394. }
  100395. FLAC__ASSERT(do_independent || do_mid_side);
  100396. /*
  100397. * Check for wasted bits; set effective bps for each subframe
  100398. */
  100399. if(do_independent) {
  100400. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100401. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  100402. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  100403. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  100404. }
  100405. }
  100406. if(do_mid_side) {
  100407. FLAC__ASSERT(encoder->protected_->channels == 2);
  100408. for(channel = 0; channel < 2; channel++) {
  100409. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  100410. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  100411. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  100412. }
  100413. }
  100414. /*
  100415. * First do a normal encoding pass of each independent channel
  100416. */
  100417. if(do_independent) {
  100418. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100419. if(!
  100420. process_subframe_(
  100421. encoder,
  100422. min_partition_order,
  100423. max_partition_order,
  100424. &frame_header,
  100425. encoder->private_->subframe_bps[channel],
  100426. encoder->private_->integer_signal[channel],
  100427. encoder->private_->subframe_workspace_ptr[channel],
  100428. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  100429. encoder->private_->residual_workspace[channel],
  100430. encoder->private_->best_subframe+channel,
  100431. encoder->private_->best_subframe_bits+channel
  100432. )
  100433. )
  100434. return false;
  100435. }
  100436. }
  100437. /*
  100438. * Now do mid and side channels if requested
  100439. */
  100440. if(do_mid_side) {
  100441. FLAC__ASSERT(encoder->protected_->channels == 2);
  100442. for(channel = 0; channel < 2; channel++) {
  100443. if(!
  100444. process_subframe_(
  100445. encoder,
  100446. min_partition_order,
  100447. max_partition_order,
  100448. &frame_header,
  100449. encoder->private_->subframe_bps_mid_side[channel],
  100450. encoder->private_->integer_signal_mid_side[channel],
  100451. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  100452. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  100453. encoder->private_->residual_workspace_mid_side[channel],
  100454. encoder->private_->best_subframe_mid_side+channel,
  100455. encoder->private_->best_subframe_bits_mid_side+channel
  100456. )
  100457. )
  100458. return false;
  100459. }
  100460. }
  100461. /*
  100462. * Compose the frame bitbuffer
  100463. */
  100464. if(do_mid_side) {
  100465. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  100466. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  100467. FLAC__ChannelAssignment channel_assignment;
  100468. FLAC__ASSERT(encoder->protected_->channels == 2);
  100469. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  100470. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  100471. }
  100472. else {
  100473. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  100474. unsigned min_bits;
  100475. int ca;
  100476. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  100477. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  100478. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  100479. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  100480. FLAC__ASSERT(do_independent && do_mid_side);
  100481. /* We have to figure out which channel assignent results in the smallest frame */
  100482. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  100483. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  100484. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  100485. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  100486. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  100487. min_bits = bits[channel_assignment];
  100488. for(ca = 1; ca <= 3; ca++) {
  100489. if(bits[ca] < min_bits) {
  100490. min_bits = bits[ca];
  100491. channel_assignment = (FLAC__ChannelAssignment)ca;
  100492. }
  100493. }
  100494. }
  100495. frame_header.channel_assignment = channel_assignment;
  100496. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100497. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100498. return false;
  100499. }
  100500. switch(channel_assignment) {
  100501. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100502. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100503. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100504. break;
  100505. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100506. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  100507. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100508. break;
  100509. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100510. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100511. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  100512. break;
  100513. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100514. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  100515. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  100516. break;
  100517. default:
  100518. FLAC__ASSERT(0);
  100519. }
  100520. switch(channel_assignment) {
  100521. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100522. left_bps = encoder->private_->subframe_bps [0];
  100523. right_bps = encoder->private_->subframe_bps [1];
  100524. break;
  100525. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100526. left_bps = encoder->private_->subframe_bps [0];
  100527. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100528. break;
  100529. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100530. left_bps = encoder->private_->subframe_bps_mid_side[1];
  100531. right_bps = encoder->private_->subframe_bps [1];
  100532. break;
  100533. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100534. left_bps = encoder->private_->subframe_bps_mid_side[0];
  100535. right_bps = encoder->private_->subframe_bps_mid_side[1];
  100536. break;
  100537. default:
  100538. FLAC__ASSERT(0);
  100539. }
  100540. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  100541. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  100542. return false;
  100543. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  100544. return false;
  100545. }
  100546. else {
  100547. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  100548. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100549. return false;
  100550. }
  100551. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100552. 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)) {
  100553. /* the above function sets the state for us in case of an error */
  100554. return false;
  100555. }
  100556. }
  100557. }
  100558. if(encoder->protected_->loose_mid_side_stereo) {
  100559. encoder->private_->loose_mid_side_stereo_frame_count++;
  100560. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  100561. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  100562. }
  100563. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  100564. return true;
  100565. }
  100566. FLAC__bool process_subframe_(
  100567. FLAC__StreamEncoder *encoder,
  100568. unsigned min_partition_order,
  100569. unsigned max_partition_order,
  100570. const FLAC__FrameHeader *frame_header,
  100571. unsigned subframe_bps,
  100572. const FLAC__int32 integer_signal[],
  100573. FLAC__Subframe *subframe[2],
  100574. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  100575. FLAC__int32 *residual[2],
  100576. unsigned *best_subframe,
  100577. unsigned *best_bits
  100578. )
  100579. {
  100580. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100581. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100582. #else
  100583. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  100584. #endif
  100585. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100586. FLAC__double lpc_residual_bits_per_sample;
  100587. 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 */
  100588. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  100589. unsigned min_lpc_order, max_lpc_order, lpc_order;
  100590. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  100591. #endif
  100592. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  100593. unsigned rice_parameter;
  100594. unsigned _candidate_bits, _best_bits;
  100595. unsigned _best_subframe;
  100596. /* only use RICE2 partitions if stream bps > 16 */
  100597. 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;
  100598. FLAC__ASSERT(frame_header->blocksize > 0);
  100599. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  100600. _best_subframe = 0;
  100601. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  100602. _best_bits = UINT_MAX;
  100603. else
  100604. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100605. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  100606. unsigned signal_is_constant = false;
  100607. 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);
  100608. /* check for constant subframe */
  100609. if(
  100610. !encoder->private_->disable_constant_subframes &&
  100611. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100612. fixed_residual_bits_per_sample[1] == 0.0
  100613. #else
  100614. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  100615. #endif
  100616. ) {
  100617. /* the above means it's possible all samples are the same value; now double-check it: */
  100618. unsigned i;
  100619. signal_is_constant = true;
  100620. for(i = 1; i < frame_header->blocksize; i++) {
  100621. if(integer_signal[0] != integer_signal[i]) {
  100622. signal_is_constant = false;
  100623. break;
  100624. }
  100625. }
  100626. }
  100627. if(signal_is_constant) {
  100628. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  100629. if(_candidate_bits < _best_bits) {
  100630. _best_subframe = !_best_subframe;
  100631. _best_bits = _candidate_bits;
  100632. }
  100633. }
  100634. else {
  100635. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  100636. /* encode fixed */
  100637. if(encoder->protected_->do_exhaustive_model_search) {
  100638. min_fixed_order = 0;
  100639. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  100640. }
  100641. else {
  100642. min_fixed_order = max_fixed_order = guess_fixed_order;
  100643. }
  100644. if(max_fixed_order >= frame_header->blocksize)
  100645. max_fixed_order = frame_header->blocksize - 1;
  100646. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  100647. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100648. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  100649. continue; /* don't even try */
  100650. 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 */
  100651. #else
  100652. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  100653. continue; /* don't even try */
  100654. 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 */
  100655. #endif
  100656. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100657. if(rice_parameter >= rice_parameter_limit) {
  100658. #ifdef DEBUG_VERBOSE
  100659. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  100660. #endif
  100661. rice_parameter = rice_parameter_limit - 1;
  100662. }
  100663. _candidate_bits =
  100664. evaluate_fixed_subframe_(
  100665. encoder,
  100666. integer_signal,
  100667. residual[!_best_subframe],
  100668. encoder->private_->abs_residual_partition_sums,
  100669. encoder->private_->raw_bits_per_partition,
  100670. frame_header->blocksize,
  100671. subframe_bps,
  100672. fixed_order,
  100673. rice_parameter,
  100674. rice_parameter_limit,
  100675. min_partition_order,
  100676. max_partition_order,
  100677. encoder->protected_->do_escape_coding,
  100678. encoder->protected_->rice_parameter_search_dist,
  100679. subframe[!_best_subframe],
  100680. partitioned_rice_contents[!_best_subframe]
  100681. );
  100682. if(_candidate_bits < _best_bits) {
  100683. _best_subframe = !_best_subframe;
  100684. _best_bits = _candidate_bits;
  100685. }
  100686. }
  100687. }
  100688. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100689. /* encode lpc */
  100690. if(encoder->protected_->max_lpc_order > 0) {
  100691. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  100692. max_lpc_order = frame_header->blocksize-1;
  100693. else
  100694. max_lpc_order = encoder->protected_->max_lpc_order;
  100695. if(max_lpc_order > 0) {
  100696. unsigned a;
  100697. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  100698. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  100699. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  100700. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  100701. if(autoc[0] != 0.0) {
  100702. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  100703. if(encoder->protected_->do_exhaustive_model_search) {
  100704. min_lpc_order = 1;
  100705. }
  100706. else {
  100707. const unsigned guess_lpc_order =
  100708. FLAC__lpc_compute_best_order(
  100709. lpc_error,
  100710. max_lpc_order,
  100711. frame_header->blocksize,
  100712. subframe_bps + (
  100713. encoder->protected_->do_qlp_coeff_prec_search?
  100714. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  100715. encoder->protected_->qlp_coeff_precision
  100716. )
  100717. );
  100718. min_lpc_order = max_lpc_order = guess_lpc_order;
  100719. }
  100720. if(max_lpc_order >= frame_header->blocksize)
  100721. max_lpc_order = frame_header->blocksize - 1;
  100722. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  100723. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  100724. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  100725. continue; /* don't even try */
  100726. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  100727. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  100728. if(rice_parameter >= rice_parameter_limit) {
  100729. #ifdef DEBUG_VERBOSE
  100730. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  100731. #endif
  100732. rice_parameter = rice_parameter_limit - 1;
  100733. }
  100734. if(encoder->protected_->do_qlp_coeff_prec_search) {
  100735. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  100736. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  100737. if(subframe_bps <= 17) {
  100738. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  100739. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  100740. }
  100741. else
  100742. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  100743. }
  100744. else {
  100745. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  100746. }
  100747. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  100748. _candidate_bits =
  100749. evaluate_lpc_subframe_(
  100750. encoder,
  100751. integer_signal,
  100752. residual[!_best_subframe],
  100753. encoder->private_->abs_residual_partition_sums,
  100754. encoder->private_->raw_bits_per_partition,
  100755. encoder->private_->lp_coeff[lpc_order-1],
  100756. frame_header->blocksize,
  100757. subframe_bps,
  100758. lpc_order,
  100759. qlp_coeff_precision,
  100760. rice_parameter,
  100761. rice_parameter_limit,
  100762. min_partition_order,
  100763. max_partition_order,
  100764. encoder->protected_->do_escape_coding,
  100765. encoder->protected_->rice_parameter_search_dist,
  100766. subframe[!_best_subframe],
  100767. partitioned_rice_contents[!_best_subframe]
  100768. );
  100769. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  100770. if(_candidate_bits < _best_bits) {
  100771. _best_subframe = !_best_subframe;
  100772. _best_bits = _candidate_bits;
  100773. }
  100774. }
  100775. }
  100776. }
  100777. }
  100778. }
  100779. }
  100780. }
  100781. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100782. }
  100783. }
  100784. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  100785. if(_best_bits == UINT_MAX) {
  100786. FLAC__ASSERT(_best_subframe == 0);
  100787. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  100788. }
  100789. *best_subframe = _best_subframe;
  100790. *best_bits = _best_bits;
  100791. return true;
  100792. }
  100793. FLAC__bool add_subframe_(
  100794. FLAC__StreamEncoder *encoder,
  100795. unsigned blocksize,
  100796. unsigned subframe_bps,
  100797. const FLAC__Subframe *subframe,
  100798. FLAC__BitWriter *frame
  100799. )
  100800. {
  100801. switch(subframe->type) {
  100802. case FLAC__SUBFRAME_TYPE_CONSTANT:
  100803. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  100804. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100805. return false;
  100806. }
  100807. break;
  100808. case FLAC__SUBFRAME_TYPE_FIXED:
  100809. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  100810. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100811. return false;
  100812. }
  100813. break;
  100814. case FLAC__SUBFRAME_TYPE_LPC:
  100815. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  100816. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100817. return false;
  100818. }
  100819. break;
  100820. case FLAC__SUBFRAME_TYPE_VERBATIM:
  100821. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  100822. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  100823. return false;
  100824. }
  100825. break;
  100826. default:
  100827. FLAC__ASSERT(0);
  100828. }
  100829. return true;
  100830. }
  100831. #define SPOTCHECK_ESTIMATE 0
  100832. #if SPOTCHECK_ESTIMATE
  100833. static void spotcheck_subframe_estimate_(
  100834. FLAC__StreamEncoder *encoder,
  100835. unsigned blocksize,
  100836. unsigned subframe_bps,
  100837. const FLAC__Subframe *subframe,
  100838. unsigned estimate
  100839. )
  100840. {
  100841. FLAC__bool ret;
  100842. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  100843. if(frame == 0) {
  100844. fprintf(stderr, "EST: can't allocate frame\n");
  100845. return;
  100846. }
  100847. if(!FLAC__bitwriter_init(frame)) {
  100848. fprintf(stderr, "EST: can't init frame\n");
  100849. return;
  100850. }
  100851. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  100852. FLAC__ASSERT(ret);
  100853. {
  100854. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  100855. if(estimate != actual)
  100856. 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);
  100857. }
  100858. FLAC__bitwriter_delete(frame);
  100859. }
  100860. #endif
  100861. unsigned evaluate_constant_subframe_(
  100862. FLAC__StreamEncoder *encoder,
  100863. const FLAC__int32 signal,
  100864. unsigned blocksize,
  100865. unsigned subframe_bps,
  100866. FLAC__Subframe *subframe
  100867. )
  100868. {
  100869. unsigned estimate;
  100870. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  100871. subframe->data.constant.value = signal;
  100872. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  100873. #if SPOTCHECK_ESTIMATE
  100874. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100875. #else
  100876. (void)encoder, (void)blocksize;
  100877. #endif
  100878. return estimate;
  100879. }
  100880. unsigned evaluate_fixed_subframe_(
  100881. FLAC__StreamEncoder *encoder,
  100882. const FLAC__int32 signal[],
  100883. FLAC__int32 residual[],
  100884. FLAC__uint64 abs_residual_partition_sums[],
  100885. unsigned raw_bits_per_partition[],
  100886. unsigned blocksize,
  100887. unsigned subframe_bps,
  100888. unsigned order,
  100889. unsigned rice_parameter,
  100890. unsigned rice_parameter_limit,
  100891. unsigned min_partition_order,
  100892. unsigned max_partition_order,
  100893. FLAC__bool do_escape_coding,
  100894. unsigned rice_parameter_search_dist,
  100895. FLAC__Subframe *subframe,
  100896. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100897. )
  100898. {
  100899. unsigned i, residual_bits, estimate;
  100900. const unsigned residual_samples = blocksize - order;
  100901. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  100902. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  100903. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100904. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100905. subframe->data.fixed.residual = residual;
  100906. residual_bits =
  100907. find_best_partition_order_(
  100908. encoder->private_,
  100909. residual,
  100910. abs_residual_partition_sums,
  100911. raw_bits_per_partition,
  100912. residual_samples,
  100913. order,
  100914. rice_parameter,
  100915. rice_parameter_limit,
  100916. min_partition_order,
  100917. max_partition_order,
  100918. subframe_bps,
  100919. do_escape_coding,
  100920. rice_parameter_search_dist,
  100921. &subframe->data.fixed.entropy_coding_method
  100922. );
  100923. subframe->data.fixed.order = order;
  100924. for(i = 0; i < order; i++)
  100925. subframe->data.fixed.warmup[i] = signal[i];
  100926. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  100927. #if SPOTCHECK_ESTIMATE
  100928. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  100929. #endif
  100930. return estimate;
  100931. }
  100932. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100933. unsigned evaluate_lpc_subframe_(
  100934. FLAC__StreamEncoder *encoder,
  100935. const FLAC__int32 signal[],
  100936. FLAC__int32 residual[],
  100937. FLAC__uint64 abs_residual_partition_sums[],
  100938. unsigned raw_bits_per_partition[],
  100939. const FLAC__real lp_coeff[],
  100940. unsigned blocksize,
  100941. unsigned subframe_bps,
  100942. unsigned order,
  100943. unsigned qlp_coeff_precision,
  100944. unsigned rice_parameter,
  100945. unsigned rice_parameter_limit,
  100946. unsigned min_partition_order,
  100947. unsigned max_partition_order,
  100948. FLAC__bool do_escape_coding,
  100949. unsigned rice_parameter_search_dist,
  100950. FLAC__Subframe *subframe,
  100951. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  100952. )
  100953. {
  100954. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  100955. unsigned i, residual_bits, estimate;
  100956. int quantization, ret;
  100957. const unsigned residual_samples = blocksize - order;
  100958. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  100959. if(subframe_bps <= 16) {
  100960. FLAC__ASSERT(order > 0);
  100961. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  100962. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  100963. }
  100964. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  100965. if(ret != 0)
  100966. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  100967. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  100968. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  100969. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100970. else
  100971. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100972. else
  100973. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  100974. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  100975. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  100976. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  100977. subframe->data.lpc.residual = residual;
  100978. residual_bits =
  100979. find_best_partition_order_(
  100980. encoder->private_,
  100981. residual,
  100982. abs_residual_partition_sums,
  100983. raw_bits_per_partition,
  100984. residual_samples,
  100985. order,
  100986. rice_parameter,
  100987. rice_parameter_limit,
  100988. min_partition_order,
  100989. max_partition_order,
  100990. subframe_bps,
  100991. do_escape_coding,
  100992. rice_parameter_search_dist,
  100993. &subframe->data.lpc.entropy_coding_method
  100994. );
  100995. subframe->data.lpc.order = order;
  100996. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  100997. subframe->data.lpc.quantization_level = quantization;
  100998. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  100999. for(i = 0; i < order; i++)
  101000. subframe->data.lpc.warmup[i] = signal[i];
  101001. 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;
  101002. #if SPOTCHECK_ESTIMATE
  101003. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101004. #endif
  101005. return estimate;
  101006. }
  101007. #endif
  101008. unsigned evaluate_verbatim_subframe_(
  101009. FLAC__StreamEncoder *encoder,
  101010. const FLAC__int32 signal[],
  101011. unsigned blocksize,
  101012. unsigned subframe_bps,
  101013. FLAC__Subframe *subframe
  101014. )
  101015. {
  101016. unsigned estimate;
  101017. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101018. subframe->data.verbatim.data = signal;
  101019. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  101020. #if SPOTCHECK_ESTIMATE
  101021. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101022. #else
  101023. (void)encoder;
  101024. #endif
  101025. return estimate;
  101026. }
  101027. unsigned find_best_partition_order_(
  101028. FLAC__StreamEncoderPrivate *private_,
  101029. const FLAC__int32 residual[],
  101030. FLAC__uint64 abs_residual_partition_sums[],
  101031. unsigned raw_bits_per_partition[],
  101032. unsigned residual_samples,
  101033. unsigned predictor_order,
  101034. unsigned rice_parameter,
  101035. unsigned rice_parameter_limit,
  101036. unsigned min_partition_order,
  101037. unsigned max_partition_order,
  101038. unsigned bps,
  101039. FLAC__bool do_escape_coding,
  101040. unsigned rice_parameter_search_dist,
  101041. FLAC__EntropyCodingMethod *best_ecm
  101042. )
  101043. {
  101044. unsigned residual_bits, best_residual_bits = 0;
  101045. unsigned best_parameters_index = 0;
  101046. unsigned best_partition_order = 0;
  101047. const unsigned blocksize = residual_samples + predictor_order;
  101048. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  101049. min_partition_order = min(min_partition_order, max_partition_order);
  101050. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  101051. if(do_escape_coding)
  101052. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  101053. {
  101054. int partition_order;
  101055. unsigned sum;
  101056. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  101057. if(!
  101058. set_partitioned_rice_(
  101059. #ifdef EXACT_RICE_BITS_CALCULATION
  101060. residual,
  101061. #endif
  101062. abs_residual_partition_sums+sum,
  101063. raw_bits_per_partition+sum,
  101064. residual_samples,
  101065. predictor_order,
  101066. rice_parameter,
  101067. rice_parameter_limit,
  101068. rice_parameter_search_dist,
  101069. (unsigned)partition_order,
  101070. do_escape_coding,
  101071. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  101072. &residual_bits
  101073. )
  101074. )
  101075. {
  101076. FLAC__ASSERT(best_residual_bits != 0);
  101077. break;
  101078. }
  101079. sum += 1u << partition_order;
  101080. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  101081. best_residual_bits = residual_bits;
  101082. best_parameters_index = !best_parameters_index;
  101083. best_partition_order = partition_order;
  101084. }
  101085. }
  101086. }
  101087. best_ecm->data.partitioned_rice.order = best_partition_order;
  101088. {
  101089. /*
  101090. * We are allowed to de-const the pointer based on our special
  101091. * knowledge; it is const to the outside world.
  101092. */
  101093. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  101094. unsigned partition;
  101095. /* save best parameters and raw_bits */
  101096. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  101097. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  101098. if(do_escape_coding)
  101099. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  101100. /*
  101101. * Now need to check if the type should be changed to
  101102. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  101103. * size of the rice parameters.
  101104. */
  101105. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  101106. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  101107. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  101108. break;
  101109. }
  101110. }
  101111. }
  101112. return best_residual_bits;
  101113. }
  101114. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101115. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  101116. const FLAC__int32 residual[],
  101117. FLAC__uint64 abs_residual_partition_sums[],
  101118. unsigned blocksize,
  101119. unsigned predictor_order,
  101120. unsigned min_partition_order,
  101121. unsigned max_partition_order
  101122. );
  101123. #endif
  101124. void precompute_partition_info_sums_(
  101125. const FLAC__int32 residual[],
  101126. FLAC__uint64 abs_residual_partition_sums[],
  101127. unsigned residual_samples,
  101128. unsigned predictor_order,
  101129. unsigned min_partition_order,
  101130. unsigned max_partition_order,
  101131. unsigned bps
  101132. )
  101133. {
  101134. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  101135. unsigned partitions = 1u << max_partition_order;
  101136. FLAC__ASSERT(default_partition_samples > predictor_order);
  101137. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  101138. /* slightly pessimistic but still catches all common cases */
  101139. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101140. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101141. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  101142. return;
  101143. }
  101144. #endif
  101145. /* first do max_partition_order */
  101146. {
  101147. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  101148. /* slightly pessimistic but still catches all common cases */
  101149. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  101150. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  101151. FLAC__uint32 abs_residual_partition_sum;
  101152. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101153. end += default_partition_samples;
  101154. abs_residual_partition_sum = 0;
  101155. for( ; residual_sample < end; residual_sample++)
  101156. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101157. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101158. }
  101159. }
  101160. else { /* have to pessimistically use 64 bits for accumulator */
  101161. FLAC__uint64 abs_residual_partition_sum;
  101162. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101163. end += default_partition_samples;
  101164. abs_residual_partition_sum = 0;
  101165. for( ; residual_sample < end; residual_sample++)
  101166. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  101167. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  101168. }
  101169. }
  101170. }
  101171. /* now merge partitions for lower orders */
  101172. {
  101173. unsigned from_partition = 0, to_partition = partitions;
  101174. int partition_order;
  101175. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  101176. unsigned i;
  101177. partitions >>= 1;
  101178. for(i = 0; i < partitions; i++) {
  101179. abs_residual_partition_sums[to_partition++] =
  101180. abs_residual_partition_sums[from_partition ] +
  101181. abs_residual_partition_sums[from_partition+1];
  101182. from_partition += 2;
  101183. }
  101184. }
  101185. }
  101186. }
  101187. void precompute_partition_info_escapes_(
  101188. const FLAC__int32 residual[],
  101189. unsigned raw_bits_per_partition[],
  101190. unsigned residual_samples,
  101191. unsigned predictor_order,
  101192. unsigned min_partition_order,
  101193. unsigned max_partition_order
  101194. )
  101195. {
  101196. int partition_order;
  101197. unsigned from_partition, to_partition = 0;
  101198. const unsigned blocksize = residual_samples + predictor_order;
  101199. /* first do max_partition_order */
  101200. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  101201. FLAC__int32 r;
  101202. FLAC__uint32 rmax;
  101203. unsigned partition, partition_sample, partition_samples, residual_sample;
  101204. const unsigned partitions = 1u << partition_order;
  101205. const unsigned default_partition_samples = blocksize >> partition_order;
  101206. FLAC__ASSERT(default_partition_samples > predictor_order);
  101207. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101208. partition_samples = default_partition_samples;
  101209. if(partition == 0)
  101210. partition_samples -= predictor_order;
  101211. rmax = 0;
  101212. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  101213. r = residual[residual_sample++];
  101214. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  101215. if(r < 0)
  101216. rmax |= ~r;
  101217. else
  101218. rmax |= r;
  101219. }
  101220. /* now we know all residual values are in the range [-rmax-1,rmax] */
  101221. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  101222. }
  101223. to_partition = partitions;
  101224. break; /*@@@ yuck, should remove the 'for' loop instead */
  101225. }
  101226. /* now merge partitions for lower orders */
  101227. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  101228. unsigned m;
  101229. unsigned i;
  101230. const unsigned partitions = 1u << partition_order;
  101231. for(i = 0; i < partitions; i++) {
  101232. m = raw_bits_per_partition[from_partition];
  101233. from_partition++;
  101234. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  101235. from_partition++;
  101236. to_partition++;
  101237. }
  101238. }
  101239. }
  101240. #ifdef EXACT_RICE_BITS_CALCULATION
  101241. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101242. const unsigned rice_parameter,
  101243. const unsigned partition_samples,
  101244. const FLAC__int32 *residual
  101245. )
  101246. {
  101247. unsigned i, partition_bits =
  101248. 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 */
  101249. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  101250. ;
  101251. for(i = 0; i < partition_samples; i++)
  101252. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  101253. return partition_bits;
  101254. }
  101255. #else
  101256. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  101257. const unsigned rice_parameter,
  101258. const unsigned partition_samples,
  101259. const FLAC__uint64 abs_residual_partition_sum
  101260. )
  101261. {
  101262. return
  101263. 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 */
  101264. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  101265. (
  101266. rice_parameter?
  101267. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  101268. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  101269. )
  101270. - (partition_samples >> 1)
  101271. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  101272. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  101273. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  101274. * So the subtraction term tries to guess how many extra bits were contributed.
  101275. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  101276. */
  101277. ;
  101278. }
  101279. #endif
  101280. FLAC__bool set_partitioned_rice_(
  101281. #ifdef EXACT_RICE_BITS_CALCULATION
  101282. const FLAC__int32 residual[],
  101283. #endif
  101284. const FLAC__uint64 abs_residual_partition_sums[],
  101285. const unsigned raw_bits_per_partition[],
  101286. const unsigned residual_samples,
  101287. const unsigned predictor_order,
  101288. const unsigned suggested_rice_parameter,
  101289. const unsigned rice_parameter_limit,
  101290. const unsigned rice_parameter_search_dist,
  101291. const unsigned partition_order,
  101292. const FLAC__bool search_for_escapes,
  101293. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  101294. unsigned *bits
  101295. )
  101296. {
  101297. unsigned rice_parameter, partition_bits;
  101298. unsigned best_partition_bits, best_rice_parameter = 0;
  101299. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  101300. unsigned *parameters, *raw_bits;
  101301. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101302. unsigned min_rice_parameter, max_rice_parameter;
  101303. #else
  101304. (void)rice_parameter_search_dist;
  101305. #endif
  101306. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101307. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  101308. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  101309. parameters = partitioned_rice_contents->parameters;
  101310. raw_bits = partitioned_rice_contents->raw_bits;
  101311. if(partition_order == 0) {
  101312. best_partition_bits = (unsigned)(-1);
  101313. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101314. if(rice_parameter_search_dist) {
  101315. if(suggested_rice_parameter < rice_parameter_search_dist)
  101316. min_rice_parameter = 0;
  101317. else
  101318. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  101319. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  101320. if(max_rice_parameter >= rice_parameter_limit) {
  101321. #ifdef DEBUG_VERBOSE
  101322. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  101323. #endif
  101324. max_rice_parameter = rice_parameter_limit - 1;
  101325. }
  101326. }
  101327. else
  101328. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  101329. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101330. #else
  101331. rice_parameter = suggested_rice_parameter;
  101332. #endif
  101333. #ifdef EXACT_RICE_BITS_CALCULATION
  101334. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  101335. #else
  101336. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  101337. #endif
  101338. if(partition_bits < best_partition_bits) {
  101339. best_rice_parameter = rice_parameter;
  101340. best_partition_bits = partition_bits;
  101341. }
  101342. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101343. }
  101344. #endif
  101345. if(search_for_escapes) {
  101346. 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;
  101347. if(partition_bits <= best_partition_bits) {
  101348. raw_bits[0] = raw_bits_per_partition[0];
  101349. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101350. best_partition_bits = partition_bits;
  101351. }
  101352. else
  101353. raw_bits[0] = 0;
  101354. }
  101355. parameters[0] = best_rice_parameter;
  101356. bits_ += best_partition_bits;
  101357. }
  101358. else {
  101359. unsigned partition, residual_sample;
  101360. unsigned partition_samples;
  101361. FLAC__uint64 mean, k;
  101362. const unsigned partitions = 1u << partition_order;
  101363. for(partition = residual_sample = 0; partition < partitions; partition++) {
  101364. partition_samples = (residual_samples+predictor_order) >> partition_order;
  101365. if(partition == 0) {
  101366. if(partition_samples <= predictor_order)
  101367. return false;
  101368. else
  101369. partition_samples -= predictor_order;
  101370. }
  101371. mean = abs_residual_partition_sums[partition];
  101372. /* we are basically calculating the size in bits of the
  101373. * average residual magnitude in the partition:
  101374. * rice_parameter = floor(log2(mean/partition_samples))
  101375. * 'mean' is not a good name for the variable, it is
  101376. * actually the sum of magnitudes of all residual values
  101377. * in the partition, so the actual mean is
  101378. * mean/partition_samples
  101379. */
  101380. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  101381. ;
  101382. if(rice_parameter >= rice_parameter_limit) {
  101383. #ifdef DEBUG_VERBOSE
  101384. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  101385. #endif
  101386. rice_parameter = rice_parameter_limit - 1;
  101387. }
  101388. best_partition_bits = (unsigned)(-1);
  101389. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101390. if(rice_parameter_search_dist) {
  101391. if(rice_parameter < rice_parameter_search_dist)
  101392. min_rice_parameter = 0;
  101393. else
  101394. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  101395. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  101396. if(max_rice_parameter >= rice_parameter_limit) {
  101397. #ifdef DEBUG_VERBOSE
  101398. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  101399. #endif
  101400. max_rice_parameter = rice_parameter_limit - 1;
  101401. }
  101402. }
  101403. else
  101404. min_rice_parameter = max_rice_parameter = rice_parameter;
  101405. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  101406. #endif
  101407. #ifdef EXACT_RICE_BITS_CALCULATION
  101408. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  101409. #else
  101410. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  101411. #endif
  101412. if(partition_bits < best_partition_bits) {
  101413. best_rice_parameter = rice_parameter;
  101414. best_partition_bits = partition_bits;
  101415. }
  101416. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  101417. }
  101418. #endif
  101419. if(search_for_escapes) {
  101420. 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;
  101421. if(partition_bits <= best_partition_bits) {
  101422. raw_bits[partition] = raw_bits_per_partition[partition];
  101423. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  101424. best_partition_bits = partition_bits;
  101425. }
  101426. else
  101427. raw_bits[partition] = 0;
  101428. }
  101429. parameters[partition] = best_rice_parameter;
  101430. bits_ += best_partition_bits;
  101431. residual_sample += partition_samples;
  101432. }
  101433. }
  101434. *bits = bits_;
  101435. return true;
  101436. }
  101437. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  101438. {
  101439. unsigned i, shift;
  101440. FLAC__int32 x = 0;
  101441. for(i = 0; i < samples && !(x&1); i++)
  101442. x |= signal[i];
  101443. if(x == 0) {
  101444. shift = 0;
  101445. }
  101446. else {
  101447. for(shift = 0; !(x&1); shift++)
  101448. x >>= 1;
  101449. }
  101450. if(shift > 0) {
  101451. for(i = 0; i < samples; i++)
  101452. signal[i] >>= shift;
  101453. }
  101454. return shift;
  101455. }
  101456. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101457. {
  101458. unsigned channel;
  101459. for(channel = 0; channel < channels; channel++)
  101460. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  101461. fifo->tail += wide_samples;
  101462. FLAC__ASSERT(fifo->tail <= fifo->size);
  101463. }
  101464. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  101465. {
  101466. unsigned channel;
  101467. unsigned sample, wide_sample;
  101468. unsigned tail = fifo->tail;
  101469. sample = input_offset * channels;
  101470. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  101471. for(channel = 0; channel < channels; channel++)
  101472. fifo->data[channel][tail] = input[sample++];
  101473. tail++;
  101474. }
  101475. fifo->tail = tail;
  101476. FLAC__ASSERT(fifo->tail <= fifo->size);
  101477. }
  101478. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101479. {
  101480. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101481. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  101482. (void)decoder;
  101483. if(encoder->private_->verify.needs_magic_hack) {
  101484. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  101485. *bytes = FLAC__STREAM_SYNC_LENGTH;
  101486. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  101487. encoder->private_->verify.needs_magic_hack = false;
  101488. }
  101489. else {
  101490. if(encoded_bytes == 0) {
  101491. /*
  101492. * If we get here, a FIFO underflow has occurred,
  101493. * which means there is a bug somewhere.
  101494. */
  101495. FLAC__ASSERT(0);
  101496. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101497. }
  101498. else if(encoded_bytes < *bytes)
  101499. *bytes = encoded_bytes;
  101500. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  101501. encoder->private_->verify.output.data += *bytes;
  101502. encoder->private_->verify.output.bytes -= *bytes;
  101503. }
  101504. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101505. }
  101506. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  101507. {
  101508. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  101509. unsigned channel;
  101510. const unsigned channels = frame->header.channels;
  101511. const unsigned blocksize = frame->header.blocksize;
  101512. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  101513. (void)decoder;
  101514. for(channel = 0; channel < channels; channel++) {
  101515. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  101516. unsigned i, sample = 0;
  101517. FLAC__int32 expect = 0, got = 0;
  101518. for(i = 0; i < blocksize; i++) {
  101519. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  101520. sample = i;
  101521. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  101522. got = (FLAC__int32)buffer[channel][i];
  101523. break;
  101524. }
  101525. }
  101526. FLAC__ASSERT(i < blocksize);
  101527. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101528. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  101529. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  101530. encoder->private_->verify.error_stats.channel = channel;
  101531. encoder->private_->verify.error_stats.sample = sample;
  101532. encoder->private_->verify.error_stats.expected = expect;
  101533. encoder->private_->verify.error_stats.got = got;
  101534. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  101535. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101536. }
  101537. }
  101538. /* dequeue the frame from the fifo */
  101539. encoder->private_->verify.input_fifo.tail -= blocksize;
  101540. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  101541. for(channel = 0; channel < channels; channel++)
  101542. 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]));
  101543. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101544. }
  101545. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  101546. {
  101547. (void)decoder, (void)metadata, (void)client_data;
  101548. }
  101549. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  101550. {
  101551. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  101552. (void)decoder, (void)status;
  101553. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  101554. }
  101555. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101556. {
  101557. (void)client_data;
  101558. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  101559. if (*bytes == 0) {
  101560. if (feof(encoder->private_->file))
  101561. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  101562. else if (ferror(encoder->private_->file))
  101563. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  101564. }
  101565. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  101566. }
  101567. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  101568. {
  101569. (void)client_data;
  101570. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  101571. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  101572. else
  101573. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  101574. }
  101575. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  101576. {
  101577. off_t offset;
  101578. (void)client_data;
  101579. offset = ftello(encoder->private_->file);
  101580. if(offset < 0) {
  101581. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  101582. }
  101583. else {
  101584. *absolute_byte_offset = (FLAC__uint64)offset;
  101585. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  101586. }
  101587. }
  101588. #ifdef FLAC__VALGRIND_TESTING
  101589. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  101590. {
  101591. size_t ret = fwrite(ptr, size, nmemb, stream);
  101592. if(!ferror(stream))
  101593. fflush(stream);
  101594. return ret;
  101595. }
  101596. #else
  101597. #define local__fwrite fwrite
  101598. #endif
  101599. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  101600. {
  101601. (void)client_data, (void)current_frame;
  101602. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  101603. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  101604. #if FLAC__HAS_OGG
  101605. /* We would like to be able to use 'samples > 0' in the
  101606. * clause here but currently because of the nature of our
  101607. * Ogg writing implementation, 'samples' is always 0 (see
  101608. * ogg_encoder_aspect.c). The downside is extra progress
  101609. * callbacks.
  101610. */
  101611. encoder->private_->is_ogg? true :
  101612. #endif
  101613. samples > 0
  101614. );
  101615. if(call_it) {
  101616. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  101617. * because at this point in the callback chain, the stats
  101618. * have not been updated. Only after we return and control
  101619. * gets back to write_frame_() are the stats updated
  101620. */
  101621. 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);
  101622. }
  101623. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  101624. }
  101625. else
  101626. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  101627. }
  101628. /*
  101629. * This will forcibly set stdout to binary mode (for OSes that require it)
  101630. */
  101631. FILE *get_binary_stdout_(void)
  101632. {
  101633. /* if something breaks here it is probably due to the presence or
  101634. * absence of an underscore before the identifiers 'setmode',
  101635. * 'fileno', and/or 'O_BINARY'; check your system header files.
  101636. */
  101637. #if defined _MSC_VER || defined __MINGW32__
  101638. _setmode(_fileno(stdout), _O_BINARY);
  101639. #elif defined __CYGWIN__
  101640. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  101641. setmode(_fileno(stdout), _O_BINARY);
  101642. #elif defined __EMX__
  101643. setmode(fileno(stdout), O_BINARY);
  101644. #endif
  101645. return stdout;
  101646. }
  101647. #endif
  101648. /********* End of inlined file: stream_encoder.c *********/
  101649. /********* Start of inlined file: stream_encoder_framing.c *********/
  101650. /********* Start of inlined file: juce_FlacHeader.h *********/
  101651. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  101652. // tasks..
  101653. #define VERSION "1.2.1"
  101654. #define FLAC__NO_DLL 1
  101655. #ifdef _MSC_VER
  101656. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  101657. #endif
  101658. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  101659. #define FLAC__SYS_DARWIN 1
  101660. #endif
  101661. /********* End of inlined file: juce_FlacHeader.h *********/
  101662. #if JUCE_USE_FLAC
  101663. #if HAVE_CONFIG_H
  101664. # include <config.h>
  101665. #endif
  101666. #include <stdio.h>
  101667. #include <string.h> /* for strlen() */
  101668. #ifdef max
  101669. #undef max
  101670. #endif
  101671. #define max(x,y) ((x)>(y)?(x):(y))
  101672. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  101673. 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);
  101674. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  101675. {
  101676. unsigned i, j;
  101677. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  101678. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  101679. return false;
  101680. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  101681. return false;
  101682. /*
  101683. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  101684. */
  101685. i = metadata->length;
  101686. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  101687. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  101688. i -= metadata->data.vorbis_comment.vendor_string.length;
  101689. i += vendor_string_length;
  101690. }
  101691. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  101692. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  101693. return false;
  101694. switch(metadata->type) {
  101695. case FLAC__METADATA_TYPE_STREAMINFO:
  101696. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  101697. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  101698. return false;
  101699. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  101700. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  101701. return false;
  101702. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  101703. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  101704. return false;
  101705. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  101706. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  101707. return false;
  101708. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  101709. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  101710. return false;
  101711. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  101712. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  101713. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  101714. return false;
  101715. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  101716. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101717. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  101718. return false;
  101719. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  101720. return false;
  101721. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  101722. return false;
  101723. break;
  101724. case FLAC__METADATA_TYPE_PADDING:
  101725. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  101726. return false;
  101727. break;
  101728. case FLAC__METADATA_TYPE_APPLICATION:
  101729. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  101730. return false;
  101731. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  101732. return false;
  101733. break;
  101734. case FLAC__METADATA_TYPE_SEEKTABLE:
  101735. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  101736. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  101737. return false;
  101738. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  101739. return false;
  101740. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  101741. return false;
  101742. }
  101743. break;
  101744. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  101745. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  101746. return false;
  101747. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  101748. return false;
  101749. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  101750. return false;
  101751. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  101752. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  101753. return false;
  101754. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  101755. return false;
  101756. }
  101757. break;
  101758. case FLAC__METADATA_TYPE_CUESHEET:
  101759. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  101760. 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))
  101761. return false;
  101762. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  101763. return false;
  101764. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  101765. return false;
  101766. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  101767. return false;
  101768. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  101769. return false;
  101770. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  101771. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  101772. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  101773. return false;
  101774. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  101775. return false;
  101776. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  101777. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  101778. return false;
  101779. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  101780. return false;
  101781. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  101782. return false;
  101783. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  101784. return false;
  101785. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  101786. return false;
  101787. for(j = 0; j < track->num_indices; j++) {
  101788. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  101789. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  101790. return false;
  101791. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  101792. return false;
  101793. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  101794. return false;
  101795. }
  101796. }
  101797. break;
  101798. case FLAC__METADATA_TYPE_PICTURE:
  101799. {
  101800. size_t len;
  101801. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  101802. return false;
  101803. len = strlen(metadata->data.picture.mime_type);
  101804. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  101805. return false;
  101806. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  101807. return false;
  101808. len = strlen((const char *)metadata->data.picture.description);
  101809. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  101810. return false;
  101811. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  101812. return false;
  101813. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  101814. return false;
  101815. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  101816. return false;
  101817. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  101818. return false;
  101819. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  101820. return false;
  101821. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  101822. return false;
  101823. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  101824. return false;
  101825. }
  101826. break;
  101827. default:
  101828. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  101829. return false;
  101830. break;
  101831. }
  101832. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101833. return true;
  101834. }
  101835. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  101836. {
  101837. unsigned u, blocksize_hint, sample_rate_hint;
  101838. FLAC__byte crc;
  101839. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  101840. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  101841. return false;
  101842. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  101843. return false;
  101844. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  101845. return false;
  101846. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  101847. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  101848. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  101849. blocksize_hint = 0;
  101850. switch(header->blocksize) {
  101851. case 192: u = 1; break;
  101852. case 576: u = 2; break;
  101853. case 1152: u = 3; break;
  101854. case 2304: u = 4; break;
  101855. case 4608: u = 5; break;
  101856. case 256: u = 8; break;
  101857. case 512: u = 9; break;
  101858. case 1024: u = 10; break;
  101859. case 2048: u = 11; break;
  101860. case 4096: u = 12; break;
  101861. case 8192: u = 13; break;
  101862. case 16384: u = 14; break;
  101863. case 32768: u = 15; break;
  101864. default:
  101865. if(header->blocksize <= 0x100)
  101866. blocksize_hint = u = 6;
  101867. else
  101868. blocksize_hint = u = 7;
  101869. break;
  101870. }
  101871. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  101872. return false;
  101873. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  101874. sample_rate_hint = 0;
  101875. switch(header->sample_rate) {
  101876. case 88200: u = 1; break;
  101877. case 176400: u = 2; break;
  101878. case 192000: u = 3; break;
  101879. case 8000: u = 4; break;
  101880. case 16000: u = 5; break;
  101881. case 22050: u = 6; break;
  101882. case 24000: u = 7; break;
  101883. case 32000: u = 8; break;
  101884. case 44100: u = 9; break;
  101885. case 48000: u = 10; break;
  101886. case 96000: u = 11; break;
  101887. default:
  101888. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  101889. sample_rate_hint = u = 12;
  101890. else if(header->sample_rate % 10 == 0)
  101891. sample_rate_hint = u = 14;
  101892. else if(header->sample_rate <= 0xffff)
  101893. sample_rate_hint = u = 13;
  101894. else
  101895. u = 0;
  101896. break;
  101897. }
  101898. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  101899. return false;
  101900. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  101901. switch(header->channel_assignment) {
  101902. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101903. u = header->channels - 1;
  101904. break;
  101905. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101906. FLAC__ASSERT(header->channels == 2);
  101907. u = 8;
  101908. break;
  101909. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101910. FLAC__ASSERT(header->channels == 2);
  101911. u = 9;
  101912. break;
  101913. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101914. FLAC__ASSERT(header->channels == 2);
  101915. u = 10;
  101916. break;
  101917. default:
  101918. FLAC__ASSERT(0);
  101919. }
  101920. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  101921. return false;
  101922. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  101923. switch(header->bits_per_sample) {
  101924. case 8 : u = 1; break;
  101925. case 12: u = 2; break;
  101926. case 16: u = 4; break;
  101927. case 20: u = 5; break;
  101928. case 24: u = 6; break;
  101929. default: u = 0; break;
  101930. }
  101931. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  101932. return false;
  101933. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  101934. return false;
  101935. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101936. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  101937. return false;
  101938. }
  101939. else {
  101940. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  101941. return false;
  101942. }
  101943. if(blocksize_hint)
  101944. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  101945. return false;
  101946. switch(sample_rate_hint) {
  101947. case 12:
  101948. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  101949. return false;
  101950. break;
  101951. case 13:
  101952. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  101953. return false;
  101954. break;
  101955. case 14:
  101956. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  101957. return false;
  101958. break;
  101959. }
  101960. /* write the CRC */
  101961. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  101962. return false;
  101963. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  101964. return false;
  101965. return true;
  101966. }
  101967. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101968. {
  101969. FLAC__bool ok;
  101970. ok =
  101971. 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) &&
  101972. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  101973. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  101974. ;
  101975. return ok;
  101976. }
  101977. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  101978. {
  101979. unsigned i;
  101980. 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))
  101981. return false;
  101982. if(wasted_bits)
  101983. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  101984. return false;
  101985. for(i = 0; i < subframe->order; i++)
  101986. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  101987. return false;
  101988. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  101989. return false;
  101990. switch(subframe->entropy_coding_method.type) {
  101991. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101992. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101993. if(!add_residual_partitioned_rice_(
  101994. bw,
  101995. subframe->residual,
  101996. residual_samples,
  101997. subframe->order,
  101998. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  101999. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102000. subframe->entropy_coding_method.data.partitioned_rice.order,
  102001. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102002. ))
  102003. return false;
  102004. break;
  102005. default:
  102006. FLAC__ASSERT(0);
  102007. }
  102008. return true;
  102009. }
  102010. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102011. {
  102012. unsigned i;
  102013. 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))
  102014. return false;
  102015. if(wasted_bits)
  102016. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102017. return false;
  102018. for(i = 0; i < subframe->order; i++)
  102019. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  102020. return false;
  102021. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  102022. return false;
  102023. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  102024. return false;
  102025. for(i = 0; i < subframe->order; i++)
  102026. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  102027. return false;
  102028. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  102029. return false;
  102030. switch(subframe->entropy_coding_method.type) {
  102031. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102032. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102033. if(!add_residual_partitioned_rice_(
  102034. bw,
  102035. subframe->residual,
  102036. residual_samples,
  102037. subframe->order,
  102038. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  102039. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  102040. subframe->entropy_coding_method.data.partitioned_rice.order,
  102041. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  102042. ))
  102043. return false;
  102044. break;
  102045. default:
  102046. FLAC__ASSERT(0);
  102047. }
  102048. return true;
  102049. }
  102050. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  102051. {
  102052. unsigned i;
  102053. const FLAC__int32 *signal = subframe->data;
  102054. 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))
  102055. return false;
  102056. if(wasted_bits)
  102057. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  102058. return false;
  102059. for(i = 0; i < samples; i++)
  102060. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  102061. return false;
  102062. return true;
  102063. }
  102064. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  102065. {
  102066. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  102067. return false;
  102068. switch(method->type) {
  102069. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  102070. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  102071. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102072. return false;
  102073. break;
  102074. default:
  102075. FLAC__ASSERT(0);
  102076. }
  102077. return true;
  102078. }
  102079. 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)
  102080. {
  102081. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  102082. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  102083. if(partition_order == 0) {
  102084. unsigned i;
  102085. if(raw_bits[0] == 0) {
  102086. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  102087. return false;
  102088. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  102089. return false;
  102090. }
  102091. else {
  102092. FLAC__ASSERT(rice_parameters[0] == 0);
  102093. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102094. return false;
  102095. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102096. return false;
  102097. for(i = 0; i < residual_samples; i++) {
  102098. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  102099. return false;
  102100. }
  102101. }
  102102. return true;
  102103. }
  102104. else {
  102105. unsigned i, j, k = 0, k_last = 0;
  102106. unsigned partition_samples;
  102107. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  102108. for(i = 0; i < (1u<<partition_order); i++) {
  102109. partition_samples = default_partition_samples;
  102110. if(i == 0)
  102111. partition_samples -= predictor_order;
  102112. k += partition_samples;
  102113. if(raw_bits[i] == 0) {
  102114. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  102115. return false;
  102116. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  102117. return false;
  102118. }
  102119. else {
  102120. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  102121. return false;
  102122. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  102123. return false;
  102124. for(j = k_last; j < k; j++) {
  102125. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  102126. return false;
  102127. }
  102128. }
  102129. k_last = k;
  102130. }
  102131. return true;
  102132. }
  102133. }
  102134. #endif
  102135. /********* End of inlined file: stream_encoder_framing.c *********/
  102136. /********* Start of inlined file: window_flac.c *********/
  102137. /********* Start of inlined file: juce_FlacHeader.h *********/
  102138. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102139. // tasks..
  102140. #define VERSION "1.2.1"
  102141. #define FLAC__NO_DLL 1
  102142. #ifdef _MSC_VER
  102143. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102144. #endif
  102145. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  102146. #define FLAC__SYS_DARWIN 1
  102147. #endif
  102148. /********* End of inlined file: juce_FlacHeader.h *********/
  102149. #if JUCE_USE_FLAC
  102150. #if HAVE_CONFIG_H
  102151. # include <config.h>
  102152. #endif
  102153. #include <math.h>
  102154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102155. #ifndef M_PI
  102156. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  102157. #define M_PI 3.14159265358979323846
  102158. #endif
  102159. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  102160. {
  102161. const FLAC__int32 N = L - 1;
  102162. FLAC__int32 n;
  102163. if (L & 1) {
  102164. for (n = 0; n <= N/2; n++)
  102165. window[n] = 2.0f * n / (float)N;
  102166. for (; n <= N; n++)
  102167. window[n] = 2.0f - 2.0f * n / (float)N;
  102168. }
  102169. else {
  102170. for (n = 0; n <= L/2-1; n++)
  102171. window[n] = 2.0f * n / (float)N;
  102172. for (; n <= N; n++)
  102173. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  102174. }
  102175. }
  102176. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  102177. {
  102178. const FLAC__int32 N = L - 1;
  102179. FLAC__int32 n;
  102180. for (n = 0; n < L; n++)
  102181. 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)));
  102182. }
  102183. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  102184. {
  102185. const FLAC__int32 N = L - 1;
  102186. FLAC__int32 n;
  102187. for (n = 0; n < L; n++)
  102188. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  102189. }
  102190. /* 4-term -92dB side-lobe */
  102191. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  102192. {
  102193. const FLAC__int32 N = L - 1;
  102194. FLAC__int32 n;
  102195. for (n = 0; n <= N; n++)
  102196. 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));
  102197. }
  102198. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  102199. {
  102200. const FLAC__int32 N = L - 1;
  102201. const double N2 = (double)N / 2.;
  102202. FLAC__int32 n;
  102203. for (n = 0; n <= N; n++) {
  102204. double k = ((double)n - N2) / N2;
  102205. k = 1.0f - k * k;
  102206. window[n] = (FLAC__real)(k * k);
  102207. }
  102208. }
  102209. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  102210. {
  102211. const FLAC__int32 N = L - 1;
  102212. FLAC__int32 n;
  102213. for (n = 0; n < L; n++)
  102214. 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));
  102215. }
  102216. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  102217. {
  102218. const FLAC__int32 N = L - 1;
  102219. const double N2 = (double)N / 2.;
  102220. FLAC__int32 n;
  102221. for (n = 0; n <= N; n++) {
  102222. const double k = ((double)n - N2) / (stddev * N2);
  102223. window[n] = (FLAC__real)exp(-0.5f * k * k);
  102224. }
  102225. }
  102226. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  102227. {
  102228. const FLAC__int32 N = L - 1;
  102229. FLAC__int32 n;
  102230. for (n = 0; n < L; n++)
  102231. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  102232. }
  102233. void FLAC__window_hann(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)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  102239. }
  102240. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  102241. {
  102242. const FLAC__int32 N = L - 1;
  102243. FLAC__int32 n;
  102244. for (n = 0; n < L; n++)
  102245. 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));
  102246. }
  102247. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  102248. {
  102249. const FLAC__int32 N = L - 1;
  102250. FLAC__int32 n;
  102251. for (n = 0; n < L; n++)
  102252. 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));
  102253. }
  102254. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  102255. {
  102256. FLAC__int32 n;
  102257. for (n = 0; n < L; n++)
  102258. window[n] = 1.0f;
  102259. }
  102260. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  102261. {
  102262. FLAC__int32 n;
  102263. if (L & 1) {
  102264. for (n = 1; n <= L+1/2; n++)
  102265. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  102266. for (; n <= L; n++)
  102267. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  102268. }
  102269. else {
  102270. for (n = 1; n <= L/2; n++)
  102271. window[n-1] = 2.0f * n / (float)L;
  102272. for (; n <= L; n++)
  102273. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  102274. }
  102275. }
  102276. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  102277. {
  102278. if (p <= 0.0)
  102279. FLAC__window_rectangle(window, L);
  102280. else if (p >= 1.0)
  102281. FLAC__window_hann(window, L);
  102282. else {
  102283. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  102284. FLAC__int32 n;
  102285. /* start with rectangle... */
  102286. FLAC__window_rectangle(window, L);
  102287. /* ...replace ends with hann */
  102288. if (Np > 0) {
  102289. for (n = 0; n <= Np; n++) {
  102290. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  102291. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  102292. }
  102293. }
  102294. }
  102295. }
  102296. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  102297. {
  102298. const FLAC__int32 N = L - 1;
  102299. const double N2 = (double)N / 2.;
  102300. FLAC__int32 n;
  102301. for (n = 0; n <= N; n++) {
  102302. const double k = ((double)n - N2) / N2;
  102303. window[n] = (FLAC__real)(1.0f - k * k);
  102304. }
  102305. }
  102306. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102307. #endif
  102308. /********* End of inlined file: window_flac.c *********/
  102309. #else
  102310. #include <FLAC/all.h>
  102311. #endif
  102312. }
  102313. #ifdef _MSC_VER
  102314. #pragma warning (pop)
  102315. #endif
  102316. BEGIN_JUCE_NAMESPACE
  102317. using namespace FlacNamespace;
  102318. #define flacFormatName TRANS("FLAC file")
  102319. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  102320. class FlacReader : public AudioFormatReader
  102321. {
  102322. FLAC__StreamDecoder* decoder;
  102323. AudioSampleBuffer reservoir;
  102324. int reservoirStart, samplesInReservoir;
  102325. bool ok, scanningForLength;
  102326. public:
  102327. FlacReader (InputStream* const in)
  102328. : AudioFormatReader (in, flacFormatName),
  102329. reservoir (2, 0),
  102330. reservoirStart (0),
  102331. samplesInReservoir (0),
  102332. scanningForLength (false)
  102333. {
  102334. using namespace FlacNamespace;
  102335. lengthInSamples = 0;
  102336. decoder = FLAC__stream_decoder_new();
  102337. ok = FLAC__stream_decoder_init_stream (decoder,
  102338. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  102339. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  102340. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  102341. if (ok)
  102342. {
  102343. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102344. if (lengthInSamples == 0 && sampleRate > 0)
  102345. {
  102346. // the length hasn't been stored in the metadata, so we'll need to
  102347. // work it out the length the hard way, by scanning the whole file..
  102348. scanningForLength = true;
  102349. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  102350. scanningForLength = false;
  102351. const int64 tempLength = lengthInSamples;
  102352. FLAC__stream_decoder_reset (decoder);
  102353. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  102354. lengthInSamples = tempLength;
  102355. }
  102356. }
  102357. }
  102358. ~FlacReader()
  102359. {
  102360. FLAC__stream_decoder_delete (decoder);
  102361. }
  102362. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  102363. {
  102364. sampleRate = info.sample_rate;
  102365. bitsPerSample = info.bits_per_sample;
  102366. lengthInSamples = (unsigned int) info.total_samples;
  102367. numChannels = info.channels;
  102368. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  102369. }
  102370. // returns the number of samples read
  102371. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  102372. int64 startSampleInFile, int numSamples)
  102373. {
  102374. using namespace FlacNamespace;
  102375. if (! ok)
  102376. return false;
  102377. while (numSamples > 0)
  102378. {
  102379. if (startSampleInFile >= reservoirStart
  102380. && startSampleInFile < reservoirStart + samplesInReservoir)
  102381. {
  102382. const int num = (int) jmin ((int64) numSamples,
  102383. reservoirStart + samplesInReservoir - startSampleInFile);
  102384. jassert (num > 0);
  102385. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  102386. if (destSamples[i] != 0)
  102387. memcpy (destSamples[i] + startOffsetInDestBuffer,
  102388. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  102389. sizeof (int) * num);
  102390. startOffsetInDestBuffer += num;
  102391. startSampleInFile += num;
  102392. numSamples -= num;
  102393. }
  102394. else
  102395. {
  102396. if (startSampleInFile < reservoirStart
  102397. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  102398. {
  102399. if (startSampleInFile >= (int) lengthInSamples)
  102400. {
  102401. samplesInReservoir = 0;
  102402. break;
  102403. }
  102404. // had some problems with flac crashing if the read pos is aligned more
  102405. // accurately than this. Probably fixed in newer versions of the library, though.
  102406. reservoirStart = (int) (startSampleInFile & ~511);
  102407. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  102408. }
  102409. else
  102410. {
  102411. reservoirStart += samplesInReservoir;
  102412. }
  102413. samplesInReservoir = 0;
  102414. FLAC__stream_decoder_process_single (decoder);
  102415. if (samplesInReservoir == 0)
  102416. break;
  102417. }
  102418. }
  102419. if (numSamples > 0)
  102420. {
  102421. for (int i = numDestChannels; --i >= 0;)
  102422. if (destSamples[i] != 0)
  102423. zeromem (destSamples[i] + startOffsetInDestBuffer,
  102424. sizeof (int) * numSamples);
  102425. }
  102426. return true;
  102427. }
  102428. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  102429. {
  102430. if (scanningForLength)
  102431. {
  102432. lengthInSamples += numSamples;
  102433. }
  102434. else
  102435. {
  102436. if (numSamples > reservoir.getNumSamples())
  102437. reservoir.setSize (numChannels, numSamples, false, false, true);
  102438. const int bitsToShift = 32 - bitsPerSample;
  102439. for (int i = 0; i < (int) numChannels; ++i)
  102440. {
  102441. const FLAC__int32* src = buffer[i];
  102442. int n = i;
  102443. while (src == 0 && n > 0)
  102444. src = buffer [--n];
  102445. if (src != 0)
  102446. {
  102447. int* dest = (int*) reservoir.getSampleData(i);
  102448. for (int j = 0; j < numSamples; ++j)
  102449. dest[j] = src[j] << bitsToShift;
  102450. }
  102451. }
  102452. samplesInReservoir = numSamples;
  102453. }
  102454. }
  102455. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  102456. {
  102457. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  102458. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102459. }
  102460. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  102461. {
  102462. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  102463. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102464. }
  102465. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  102466. {
  102467. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  102468. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102469. }
  102470. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  102471. {
  102472. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  102473. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102474. }
  102475. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  102476. {
  102477. return ((const FlacReader*) client_data)->input->isExhausted();
  102478. }
  102479. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  102480. const FLAC__Frame* frame,
  102481. const FLAC__int32* const buffer[],
  102482. void* client_data)
  102483. {
  102484. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  102485. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102486. }
  102487. static void metadataCallback_ (const FLAC__StreamDecoder*,
  102488. const FLAC__StreamMetadata* metadata,
  102489. void* client_data)
  102490. {
  102491. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  102492. }
  102493. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  102494. {
  102495. }
  102496. juce_UseDebuggingNewOperator
  102497. };
  102498. class FlacWriter : public AudioFormatWriter
  102499. {
  102500. FLAC__StreamEncoder* encoder;
  102501. MemoryBlock temp;
  102502. public:
  102503. bool ok;
  102504. FlacWriter (OutputStream* const out,
  102505. const double sampleRate,
  102506. const int numChannels,
  102507. const int bitsPerSample_)
  102508. : AudioFormatWriter (out, flacFormatName,
  102509. sampleRate,
  102510. numChannels,
  102511. bitsPerSample_)
  102512. {
  102513. using namespace FlacNamespace;
  102514. encoder = FLAC__stream_encoder_new();
  102515. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  102516. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  102517. FLAC__stream_encoder_set_channels (encoder, numChannels);
  102518. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  102519. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  102520. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  102521. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  102522. ok = FLAC__stream_encoder_init_stream (encoder,
  102523. encodeWriteCallback, encodeSeekCallback,
  102524. encodeTellCallback, encodeMetadataCallback,
  102525. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  102526. }
  102527. ~FlacWriter()
  102528. {
  102529. if (ok)
  102530. {
  102531. FLAC__stream_encoder_finish (encoder);
  102532. output->flush();
  102533. }
  102534. else
  102535. {
  102536. output = 0; // to stop the base class deleting this, as it needs to be returned
  102537. // to the caller of createWriter()
  102538. }
  102539. FLAC__stream_encoder_delete (encoder);
  102540. }
  102541. bool write (const int** samplesToWrite, int numSamples)
  102542. {
  102543. if (! ok)
  102544. return false;
  102545. int* buf[3];
  102546. const int bitsToShift = 32 - bitsPerSample;
  102547. if (bitsToShift > 0)
  102548. {
  102549. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  102550. temp.setSize (sizeof (int) * numSamples * numChannels);
  102551. buf[0] = (int*) temp.getData();
  102552. buf[1] = buf[0] + numSamples;
  102553. buf[2] = 0;
  102554. for (int i = numChannels; --i >= 0;)
  102555. {
  102556. if (samplesToWrite[i] != 0)
  102557. {
  102558. for (int j = 0; j < numSamples; ++j)
  102559. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  102560. }
  102561. }
  102562. samplesToWrite = (const int**) buf;
  102563. }
  102564. return FLAC__stream_encoder_process (encoder,
  102565. (const FLAC__int32**) samplesToWrite,
  102566. numSamples) != 0;
  102567. }
  102568. bool writeData (const void* const data, const int size) const
  102569. {
  102570. return output->write (data, size);
  102571. }
  102572. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  102573. {
  102574. b += bytes;
  102575. for (int i = 0; i < bytes; ++i)
  102576. {
  102577. *(--b) = (FLAC__byte) (val & 0xff);
  102578. val >>= 8;
  102579. }
  102580. }
  102581. void writeMetaData (const FLAC__StreamMetadata* metadata)
  102582. {
  102583. using namespace FlacNamespace;
  102584. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  102585. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  102586. const unsigned int channelsMinus1 = info.channels - 1;
  102587. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  102588. packUint32 (info.min_blocksize, buffer, 2);
  102589. packUint32 (info.max_blocksize, buffer + 2, 2);
  102590. packUint32 (info.min_framesize, buffer + 4, 3);
  102591. packUint32 (info.max_framesize, buffer + 7, 3);
  102592. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  102593. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  102594. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  102595. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  102596. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  102597. memcpy (buffer + 18, info.md5sum, 16);
  102598. const bool ok = output->setPosition (4);
  102599. (void) ok;
  102600. // if this fails, you've given it an output stream that can't seek! It needs
  102601. // to be able to seek back to write the header
  102602. jassert (ok);
  102603. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102604. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  102605. }
  102606. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  102607. const FLAC__byte buffer[],
  102608. size_t bytes,
  102609. unsigned int /*samples*/,
  102610. unsigned int /*current_frame*/,
  102611. void* client_data)
  102612. {
  102613. using namespace FlacNamespace;
  102614. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  102615. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  102616. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102617. }
  102618. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  102619. {
  102620. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  102621. }
  102622. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  102623. {
  102624. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  102625. }
  102626. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  102627. const FLAC__StreamMetadata* metadata,
  102628. void* client_data)
  102629. {
  102630. ((FlacWriter*) client_data)->writeMetaData (metadata);
  102631. }
  102632. juce_UseDebuggingNewOperator
  102633. };
  102634. FlacAudioFormat::FlacAudioFormat()
  102635. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  102636. {
  102637. }
  102638. FlacAudioFormat::~FlacAudioFormat()
  102639. {
  102640. }
  102641. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  102642. {
  102643. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  102644. return Array <int> (rates);
  102645. }
  102646. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  102647. {
  102648. const int depths[] = { 16, 24, 0 };
  102649. return Array <int> (depths);
  102650. }
  102651. bool FlacAudioFormat::canDoStereo()
  102652. {
  102653. return true;
  102654. }
  102655. bool FlacAudioFormat::canDoMono()
  102656. {
  102657. return true;
  102658. }
  102659. bool FlacAudioFormat::isCompressed()
  102660. {
  102661. return true;
  102662. }
  102663. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  102664. const bool deleteStreamIfOpeningFails)
  102665. {
  102666. FlacReader* r = new FlacReader (in);
  102667. if (r->sampleRate == 0)
  102668. {
  102669. if (! deleteStreamIfOpeningFails)
  102670. r->input = 0;
  102671. deleteAndZero (r);
  102672. }
  102673. return r;
  102674. }
  102675. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  102676. double sampleRate,
  102677. unsigned int numberOfChannels,
  102678. int bitsPerSample,
  102679. const StringPairArray& /*metadataValues*/,
  102680. int /*qualityOptionIndex*/)
  102681. {
  102682. if (getPossibleBitDepths().contains (bitsPerSample))
  102683. {
  102684. FlacWriter* w = new FlacWriter (out,
  102685. sampleRate,
  102686. numberOfChannels,
  102687. bitsPerSample);
  102688. if (! w->ok)
  102689. deleteAndZero (w);
  102690. return w;
  102691. }
  102692. return 0;
  102693. }
  102694. END_JUCE_NAMESPACE
  102695. #endif
  102696. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  102697. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  102698. #if JUCE_USE_OGGVORBIS
  102699. #if JUCE_MAC
  102700. #define __MACOSX__ 1
  102701. #endif
  102702. namespace OggVorbisNamespace
  102703. {
  102704. #if JUCE_INCLUDE_OGGVORBIS_CODE
  102705. /********* Start of inlined file: vorbisenc.h *********/
  102706. #ifndef _OV_ENC_H_
  102707. #define _OV_ENC_H_
  102708. #ifdef __cplusplus
  102709. extern "C"
  102710. {
  102711. #endif /* __cplusplus */
  102712. /********* Start of inlined file: codec.h *********/
  102713. #ifndef _vorbis_codec_h_
  102714. #define _vorbis_codec_h_
  102715. #ifdef __cplusplus
  102716. extern "C"
  102717. {
  102718. #endif /* __cplusplus */
  102719. /********* Start of inlined file: ogg.h *********/
  102720. #ifndef _OGG_H
  102721. #define _OGG_H
  102722. #ifdef __cplusplus
  102723. extern "C" {
  102724. #endif
  102725. /********* Start of inlined file: os_types.h *********/
  102726. #ifndef _OS_TYPES_H
  102727. #define _OS_TYPES_H
  102728. /* make it easy on the folks that want to compile the libs with a
  102729. different malloc than stdlib */
  102730. #define _ogg_malloc malloc
  102731. #define _ogg_calloc calloc
  102732. #define _ogg_realloc realloc
  102733. #define _ogg_free free
  102734. #if defined(_WIN32)
  102735. # if defined(__CYGWIN__)
  102736. # include <_G_config.h>
  102737. typedef _G_int64_t ogg_int64_t;
  102738. typedef _G_int32_t ogg_int32_t;
  102739. typedef _G_uint32_t ogg_uint32_t;
  102740. typedef _G_int16_t ogg_int16_t;
  102741. typedef _G_uint16_t ogg_uint16_t;
  102742. # elif defined(__MINGW32__)
  102743. typedef short ogg_int16_t;
  102744. typedef unsigned short ogg_uint16_t;
  102745. typedef int ogg_int32_t;
  102746. typedef unsigned int ogg_uint32_t;
  102747. typedef long long ogg_int64_t;
  102748. typedef unsigned long long ogg_uint64_t;
  102749. # elif defined(__MWERKS__)
  102750. typedef long long ogg_int64_t;
  102751. typedef int ogg_int32_t;
  102752. typedef unsigned int ogg_uint32_t;
  102753. typedef short ogg_int16_t;
  102754. typedef unsigned short ogg_uint16_t;
  102755. # else
  102756. /* MSVC/Borland */
  102757. typedef __int64 ogg_int64_t;
  102758. typedef __int32 ogg_int32_t;
  102759. typedef unsigned __int32 ogg_uint32_t;
  102760. typedef __int16 ogg_int16_t;
  102761. typedef unsigned __int16 ogg_uint16_t;
  102762. # endif
  102763. #elif defined(__MACOS__)
  102764. # include <sys/types.h>
  102765. typedef SInt16 ogg_int16_t;
  102766. typedef UInt16 ogg_uint16_t;
  102767. typedef SInt32 ogg_int32_t;
  102768. typedef UInt32 ogg_uint32_t;
  102769. typedef SInt64 ogg_int64_t;
  102770. #elif defined(__MACOSX__) /* MacOS X Framework build */
  102771. # include <sys/types.h>
  102772. typedef int16_t ogg_int16_t;
  102773. typedef u_int16_t ogg_uint16_t;
  102774. typedef int32_t ogg_int32_t;
  102775. typedef u_int32_t ogg_uint32_t;
  102776. typedef int64_t ogg_int64_t;
  102777. #elif defined(__BEOS__)
  102778. /* Be */
  102779. # include <inttypes.h>
  102780. typedef int16_t ogg_int16_t;
  102781. typedef u_int16_t ogg_uint16_t;
  102782. typedef int32_t ogg_int32_t;
  102783. typedef u_int32_t ogg_uint32_t;
  102784. typedef int64_t ogg_int64_t;
  102785. #elif defined (__EMX__)
  102786. /* OS/2 GCC */
  102787. typedef short ogg_int16_t;
  102788. typedef unsigned short ogg_uint16_t;
  102789. typedef int ogg_int32_t;
  102790. typedef unsigned int ogg_uint32_t;
  102791. typedef long long ogg_int64_t;
  102792. #elif defined (DJGPP)
  102793. /* DJGPP */
  102794. typedef short ogg_int16_t;
  102795. typedef int ogg_int32_t;
  102796. typedef unsigned int ogg_uint32_t;
  102797. typedef long long ogg_int64_t;
  102798. #elif defined(R5900)
  102799. /* PS2 EE */
  102800. typedef long ogg_int64_t;
  102801. typedef int ogg_int32_t;
  102802. typedef unsigned ogg_uint32_t;
  102803. typedef short ogg_int16_t;
  102804. #elif defined(__SYMBIAN32__)
  102805. /* Symbian GCC */
  102806. typedef signed short ogg_int16_t;
  102807. typedef unsigned short ogg_uint16_t;
  102808. typedef signed int ogg_int32_t;
  102809. typedef unsigned int ogg_uint32_t;
  102810. typedef long long int ogg_int64_t;
  102811. #else
  102812. # include <sys/types.h>
  102813. /********* Start of inlined file: config_types.h *********/
  102814. #ifndef __CONFIG_TYPES_H__
  102815. #define __CONFIG_TYPES_H__
  102816. typedef int16_t ogg_int16_t;
  102817. typedef unsigned short ogg_uint16_t;
  102818. typedef int32_t ogg_int32_t;
  102819. typedef unsigned int ogg_uint32_t;
  102820. typedef int64_t ogg_int64_t;
  102821. #endif
  102822. /********* End of inlined file: config_types.h *********/
  102823. #endif
  102824. #endif /* _OS_TYPES_H */
  102825. /********* End of inlined file: os_types.h *********/
  102826. typedef struct {
  102827. long endbyte;
  102828. int endbit;
  102829. unsigned char *buffer;
  102830. unsigned char *ptr;
  102831. long storage;
  102832. } oggpack_buffer;
  102833. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  102834. typedef struct {
  102835. unsigned char *header;
  102836. long header_len;
  102837. unsigned char *body;
  102838. long body_len;
  102839. } ogg_page;
  102840. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  102841. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  102842. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  102843. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  102844. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  102845. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  102846. }
  102847. /* ogg_stream_state contains the current encode/decode state of a logical
  102848. Ogg bitstream **********************************************************/
  102849. typedef struct {
  102850. unsigned char *body_data; /* bytes from packet bodies */
  102851. long body_storage; /* storage elements allocated */
  102852. long body_fill; /* elements stored; fill mark */
  102853. long body_returned; /* elements of fill returned */
  102854. int *lacing_vals; /* The values that will go to the segment table */
  102855. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  102856. this way, but it is simple coupled to the
  102857. lacing fifo */
  102858. long lacing_storage;
  102859. long lacing_fill;
  102860. long lacing_packet;
  102861. long lacing_returned;
  102862. unsigned char header[282]; /* working space for header encode */
  102863. int header_fill;
  102864. int e_o_s; /* set when we have buffered the last packet in the
  102865. logical bitstream */
  102866. int b_o_s; /* set after we've written the initial page
  102867. of a logical bitstream */
  102868. long serialno;
  102869. long pageno;
  102870. ogg_int64_t packetno; /* sequence number for decode; the framing
  102871. knows where there's a hole in the data,
  102872. but we need coupling so that the codec
  102873. (which is in a seperate abstraction
  102874. layer) also knows about the gap */
  102875. ogg_int64_t granulepos;
  102876. } ogg_stream_state;
  102877. /* ogg_packet is used to encapsulate the data and metadata belonging
  102878. to a single raw Ogg/Vorbis packet *************************************/
  102879. typedef struct {
  102880. unsigned char *packet;
  102881. long bytes;
  102882. long b_o_s;
  102883. long e_o_s;
  102884. ogg_int64_t granulepos;
  102885. ogg_int64_t packetno; /* sequence number for decode; the framing
  102886. knows where there's a hole in the data,
  102887. but we need coupling so that the codec
  102888. (which is in a seperate abstraction
  102889. layer) also knows about the gap */
  102890. } ogg_packet;
  102891. typedef struct {
  102892. unsigned char *data;
  102893. int storage;
  102894. int fill;
  102895. int returned;
  102896. int unsynced;
  102897. int headerbytes;
  102898. int bodybytes;
  102899. } ogg_sync_state;
  102900. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  102901. extern void oggpack_writeinit(oggpack_buffer *b);
  102902. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  102903. extern void oggpack_writealign(oggpack_buffer *b);
  102904. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  102905. extern void oggpack_reset(oggpack_buffer *b);
  102906. extern void oggpack_writeclear(oggpack_buffer *b);
  102907. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102908. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  102909. extern long oggpack_look(oggpack_buffer *b,int bits);
  102910. extern long oggpack_look1(oggpack_buffer *b);
  102911. extern void oggpack_adv(oggpack_buffer *b,int bits);
  102912. extern void oggpack_adv1(oggpack_buffer *b);
  102913. extern long oggpack_read(oggpack_buffer *b,int bits);
  102914. extern long oggpack_read1(oggpack_buffer *b);
  102915. extern long oggpack_bytes(oggpack_buffer *b);
  102916. extern long oggpack_bits(oggpack_buffer *b);
  102917. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  102918. extern void oggpackB_writeinit(oggpack_buffer *b);
  102919. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  102920. extern void oggpackB_writealign(oggpack_buffer *b);
  102921. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  102922. extern void oggpackB_reset(oggpack_buffer *b);
  102923. extern void oggpackB_writeclear(oggpack_buffer *b);
  102924. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  102925. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  102926. extern long oggpackB_look(oggpack_buffer *b,int bits);
  102927. extern long oggpackB_look1(oggpack_buffer *b);
  102928. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  102929. extern void oggpackB_adv1(oggpack_buffer *b);
  102930. extern long oggpackB_read(oggpack_buffer *b,int bits);
  102931. extern long oggpackB_read1(oggpack_buffer *b);
  102932. extern long oggpackB_bytes(oggpack_buffer *b);
  102933. extern long oggpackB_bits(oggpack_buffer *b);
  102934. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  102935. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  102936. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  102937. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  102938. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  102939. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  102940. extern int ogg_sync_init(ogg_sync_state *oy);
  102941. extern int ogg_sync_clear(ogg_sync_state *oy);
  102942. extern int ogg_sync_reset(ogg_sync_state *oy);
  102943. extern int ogg_sync_destroy(ogg_sync_state *oy);
  102944. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  102945. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  102946. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  102947. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  102948. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  102949. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  102950. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  102951. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  102952. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  102953. extern int ogg_stream_clear(ogg_stream_state *os);
  102954. extern int ogg_stream_reset(ogg_stream_state *os);
  102955. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  102956. extern int ogg_stream_destroy(ogg_stream_state *os);
  102957. extern int ogg_stream_eos(ogg_stream_state *os);
  102958. extern void ogg_page_checksum_set(ogg_page *og);
  102959. extern int ogg_page_version(ogg_page *og);
  102960. extern int ogg_page_continued(ogg_page *og);
  102961. extern int ogg_page_bos(ogg_page *og);
  102962. extern int ogg_page_eos(ogg_page *og);
  102963. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  102964. extern int ogg_page_serialno(ogg_page *og);
  102965. extern long ogg_page_pageno(ogg_page *og);
  102966. extern int ogg_page_packets(ogg_page *og);
  102967. extern void ogg_packet_clear(ogg_packet *op);
  102968. #ifdef __cplusplus
  102969. }
  102970. #endif
  102971. #endif /* _OGG_H */
  102972. /********* End of inlined file: ogg.h *********/
  102973. typedef struct vorbis_info{
  102974. int version;
  102975. int channels;
  102976. long rate;
  102977. /* The below bitrate declarations are *hints*.
  102978. Combinations of the three values carry the following implications:
  102979. all three set to the same value:
  102980. implies a fixed rate bitstream
  102981. only nominal set:
  102982. implies a VBR stream that averages the nominal bitrate. No hard
  102983. upper/lower limit
  102984. upper and or lower set:
  102985. implies a VBR bitstream that obeys the bitrate limits. nominal
  102986. may also be set to give a nominal rate.
  102987. none set:
  102988. the coder does not care to speculate.
  102989. */
  102990. long bitrate_upper;
  102991. long bitrate_nominal;
  102992. long bitrate_lower;
  102993. long bitrate_window;
  102994. void *codec_setup;
  102995. } vorbis_info;
  102996. /* vorbis_dsp_state buffers the current vorbis audio
  102997. analysis/synthesis state. The DSP state belongs to a specific
  102998. logical bitstream ****************************************************/
  102999. typedef struct vorbis_dsp_state{
  103000. int analysisp;
  103001. vorbis_info *vi;
  103002. float **pcm;
  103003. float **pcmret;
  103004. int pcm_storage;
  103005. int pcm_current;
  103006. int pcm_returned;
  103007. int preextrapolate;
  103008. int eofflag;
  103009. long lW;
  103010. long W;
  103011. long nW;
  103012. long centerW;
  103013. ogg_int64_t granulepos;
  103014. ogg_int64_t sequence;
  103015. ogg_int64_t glue_bits;
  103016. ogg_int64_t time_bits;
  103017. ogg_int64_t floor_bits;
  103018. ogg_int64_t res_bits;
  103019. void *backend_state;
  103020. } vorbis_dsp_state;
  103021. typedef struct vorbis_block{
  103022. /* necessary stream state for linking to the framing abstraction */
  103023. float **pcm; /* this is a pointer into local storage */
  103024. oggpack_buffer opb;
  103025. long lW;
  103026. long W;
  103027. long nW;
  103028. int pcmend;
  103029. int mode;
  103030. int eofflag;
  103031. ogg_int64_t granulepos;
  103032. ogg_int64_t sequence;
  103033. vorbis_dsp_state *vd; /* For read-only access of configuration */
  103034. /* local storage to avoid remallocing; it's up to the mapping to
  103035. structure it */
  103036. void *localstore;
  103037. long localtop;
  103038. long localalloc;
  103039. long totaluse;
  103040. struct alloc_chain *reap;
  103041. /* bitmetrics for the frame */
  103042. long glue_bits;
  103043. long time_bits;
  103044. long floor_bits;
  103045. long res_bits;
  103046. void *internal;
  103047. } vorbis_block;
  103048. /* vorbis_block is a single block of data to be processed as part of
  103049. the analysis/synthesis stream; it belongs to a specific logical
  103050. bitstream, but is independant from other vorbis_blocks belonging to
  103051. that logical bitstream. *************************************************/
  103052. struct alloc_chain{
  103053. void *ptr;
  103054. struct alloc_chain *next;
  103055. };
  103056. /* vorbis_info contains all the setup information specific to the
  103057. specific compression/decompression mode in progress (eg,
  103058. psychoacoustic settings, channel setup, options, codebook
  103059. etc). vorbis_info and substructures are in backends.h.
  103060. *********************************************************************/
  103061. /* the comments are not part of vorbis_info so that vorbis_info can be
  103062. static storage */
  103063. typedef struct vorbis_comment{
  103064. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  103065. whatever vendor is set to in encode */
  103066. char **user_comments;
  103067. int *comment_lengths;
  103068. int comments;
  103069. char *vendor;
  103070. } vorbis_comment;
  103071. /* libvorbis encodes in two abstraction layers; first we perform DSP
  103072. and produce a packet (see docs/analysis.txt). The packet is then
  103073. coded into a framed OggSquish bitstream by the second layer (see
  103074. docs/framing.txt). Decode is the reverse process; we sync/frame
  103075. the bitstream and extract individual packets, then decode the
  103076. packet back into PCM audio.
  103077. The extra framing/packetizing is used in streaming formats, such as
  103078. files. Over the net (such as with UDP), the framing and
  103079. packetization aren't necessary as they're provided by the transport
  103080. and the streaming layer is not used */
  103081. /* Vorbis PRIMITIVES: general ***************************************/
  103082. extern void vorbis_info_init(vorbis_info *vi);
  103083. extern void vorbis_info_clear(vorbis_info *vi);
  103084. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  103085. extern void vorbis_comment_init(vorbis_comment *vc);
  103086. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  103087. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  103088. const char *tag, char *contents);
  103089. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  103090. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  103091. extern void vorbis_comment_clear(vorbis_comment *vc);
  103092. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  103093. extern int vorbis_block_clear(vorbis_block *vb);
  103094. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  103095. extern double vorbis_granule_time(vorbis_dsp_state *v,
  103096. ogg_int64_t granulepos);
  103097. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  103098. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103099. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  103100. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  103101. vorbis_comment *vc,
  103102. ogg_packet *op,
  103103. ogg_packet *op_comm,
  103104. ogg_packet *op_code);
  103105. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  103106. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  103107. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  103108. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  103109. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103110. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  103111. ogg_packet *op);
  103112. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  103113. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  103114. ogg_packet *op);
  103115. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  103116. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  103117. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  103118. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  103119. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  103120. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  103121. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  103122. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  103123. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  103124. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  103125. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  103126. /* Vorbis ERRORS and return codes ***********************************/
  103127. #define OV_FALSE -1
  103128. #define OV_EOF -2
  103129. #define OV_HOLE -3
  103130. #define OV_EREAD -128
  103131. #define OV_EFAULT -129
  103132. #define OV_EIMPL -130
  103133. #define OV_EINVAL -131
  103134. #define OV_ENOTVORBIS -132
  103135. #define OV_EBADHEADER -133
  103136. #define OV_EVERSION -134
  103137. #define OV_ENOTAUDIO -135
  103138. #define OV_EBADPACKET -136
  103139. #define OV_EBADLINK -137
  103140. #define OV_ENOSEEK -138
  103141. #ifdef __cplusplus
  103142. }
  103143. #endif /* __cplusplus */
  103144. #endif
  103145. /********* End of inlined file: codec.h *********/
  103146. extern int vorbis_encode_init(vorbis_info *vi,
  103147. long channels,
  103148. long rate,
  103149. long max_bitrate,
  103150. long nominal_bitrate,
  103151. long min_bitrate);
  103152. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  103153. long channels,
  103154. long rate,
  103155. long max_bitrate,
  103156. long nominal_bitrate,
  103157. long min_bitrate);
  103158. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  103159. long channels,
  103160. long rate,
  103161. float quality /* quality level from 0. (lo) to 1. (hi) */
  103162. );
  103163. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  103164. long channels,
  103165. long rate,
  103166. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  103167. );
  103168. extern int vorbis_encode_setup_init(vorbis_info *vi);
  103169. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  103170. /* deprecated rate management supported only for compatability */
  103171. #define OV_ECTL_RATEMANAGE_GET 0x10
  103172. #define OV_ECTL_RATEMANAGE_SET 0x11
  103173. #define OV_ECTL_RATEMANAGE_AVG 0x12
  103174. #define OV_ECTL_RATEMANAGE_HARD 0x13
  103175. struct ovectl_ratemanage_arg {
  103176. int management_active;
  103177. long bitrate_hard_min;
  103178. long bitrate_hard_max;
  103179. double bitrate_hard_window;
  103180. long bitrate_av_lo;
  103181. long bitrate_av_hi;
  103182. double bitrate_av_window;
  103183. double bitrate_av_window_center;
  103184. };
  103185. /* new rate setup */
  103186. #define OV_ECTL_RATEMANAGE2_GET 0x14
  103187. #define OV_ECTL_RATEMANAGE2_SET 0x15
  103188. struct ovectl_ratemanage2_arg {
  103189. int management_active;
  103190. long bitrate_limit_min_kbps;
  103191. long bitrate_limit_max_kbps;
  103192. long bitrate_limit_reservoir_bits;
  103193. double bitrate_limit_reservoir_bias;
  103194. long bitrate_average_kbps;
  103195. double bitrate_average_damping;
  103196. };
  103197. #define OV_ECTL_LOWPASS_GET 0x20
  103198. #define OV_ECTL_LOWPASS_SET 0x21
  103199. #define OV_ECTL_IBLOCK_GET 0x30
  103200. #define OV_ECTL_IBLOCK_SET 0x31
  103201. #ifdef __cplusplus
  103202. }
  103203. #endif /* __cplusplus */
  103204. #endif
  103205. /********* End of inlined file: vorbisenc.h *********/
  103206. /********* Start of inlined file: vorbisfile.h *********/
  103207. #ifndef _OV_FILE_H_
  103208. #define _OV_FILE_H_
  103209. #ifdef __cplusplus
  103210. extern "C"
  103211. {
  103212. #endif /* __cplusplus */
  103213. #include <stdio.h>
  103214. /* The function prototypes for the callbacks are basically the same as for
  103215. * the stdio functions fread, fseek, fclose, ftell.
  103216. * The one difference is that the FILE * arguments have been replaced with
  103217. * a void * - this is to be used as a pointer to whatever internal data these
  103218. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  103219. *
  103220. * If you use other functions, check the docs for these functions and return
  103221. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  103222. * unseekable
  103223. */
  103224. typedef struct {
  103225. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  103226. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  103227. int (*close_func) (void *datasource);
  103228. long (*tell_func) (void *datasource);
  103229. } ov_callbacks;
  103230. #define NOTOPEN 0
  103231. #define PARTOPEN 1
  103232. #define OPENED 2
  103233. #define STREAMSET 3
  103234. #define INITSET 4
  103235. typedef struct OggVorbis_File {
  103236. void *datasource; /* Pointer to a FILE *, etc. */
  103237. int seekable;
  103238. ogg_int64_t offset;
  103239. ogg_int64_t end;
  103240. ogg_sync_state oy;
  103241. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  103242. stream appears */
  103243. int links;
  103244. ogg_int64_t *offsets;
  103245. ogg_int64_t *dataoffsets;
  103246. long *serialnos;
  103247. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  103248. compatability; x2 size, stores both
  103249. beginning and end values */
  103250. vorbis_info *vi;
  103251. vorbis_comment *vc;
  103252. /* Decoding working state local storage */
  103253. ogg_int64_t pcm_offset;
  103254. int ready_state;
  103255. long current_serialno;
  103256. int current_link;
  103257. double bittrack;
  103258. double samptrack;
  103259. ogg_stream_state os; /* take physical pages, weld into a logical
  103260. stream of packets */
  103261. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  103262. vorbis_block vb; /* local working space for packet->PCM decode */
  103263. ov_callbacks callbacks;
  103264. } OggVorbis_File;
  103265. extern int ov_clear(OggVorbis_File *vf);
  103266. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103267. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  103268. char *initial, long ibytes, ov_callbacks callbacks);
  103269. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  103270. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  103271. char *initial, long ibytes, ov_callbacks callbacks);
  103272. extern int ov_test_open(OggVorbis_File *vf);
  103273. extern long ov_bitrate(OggVorbis_File *vf,int i);
  103274. extern long ov_bitrate_instant(OggVorbis_File *vf);
  103275. extern long ov_streams(OggVorbis_File *vf);
  103276. extern long ov_seekable(OggVorbis_File *vf);
  103277. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  103278. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  103279. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  103280. extern double ov_time_total(OggVorbis_File *vf,int i);
  103281. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103282. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  103283. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  103284. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  103285. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  103286. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103287. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103288. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  103289. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  103290. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  103291. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  103292. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  103293. extern double ov_time_tell(OggVorbis_File *vf);
  103294. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  103295. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  103296. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  103297. int *bitstream);
  103298. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  103299. int bigendianp,int word,int sgned,int *bitstream);
  103300. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  103301. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  103302. extern int ov_halfrate_p(OggVorbis_File *vf);
  103303. #ifdef __cplusplus
  103304. }
  103305. #endif /* __cplusplus */
  103306. #endif
  103307. /********* End of inlined file: vorbisfile.h *********/
  103308. /********* Start of inlined file: bitwise.c *********/
  103309. /* We're 'LSb' endian; if we write a word but read individual bits,
  103310. then we'll read the lsb first */
  103311. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103312. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103313. // tasks..
  103314. #ifdef _MSC_VER
  103315. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103316. #endif
  103317. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103318. #if JUCE_USE_OGGVORBIS
  103319. #include <string.h>
  103320. #include <stdlib.h>
  103321. #define BUFFER_INCREMENT 256
  103322. static const unsigned long mask[]=
  103323. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  103324. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  103325. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  103326. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  103327. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  103328. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  103329. 0x3fffffff,0x7fffffff,0xffffffff };
  103330. static const unsigned int mask8B[]=
  103331. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  103332. void oggpack_writeinit(oggpack_buffer *b){
  103333. memset(b,0,sizeof(*b));
  103334. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  103335. b->buffer[0]='\0';
  103336. b->storage=BUFFER_INCREMENT;
  103337. }
  103338. void oggpackB_writeinit(oggpack_buffer *b){
  103339. oggpack_writeinit(b);
  103340. }
  103341. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  103342. long bytes=bits>>3;
  103343. bits-=bytes*8;
  103344. b->ptr=b->buffer+bytes;
  103345. b->endbit=bits;
  103346. b->endbyte=bytes;
  103347. *b->ptr&=mask[bits];
  103348. }
  103349. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  103350. long bytes=bits>>3;
  103351. bits-=bytes*8;
  103352. b->ptr=b->buffer+bytes;
  103353. b->endbit=bits;
  103354. b->endbyte=bytes;
  103355. *b->ptr&=mask8B[bits];
  103356. }
  103357. /* Takes only up to 32 bits. */
  103358. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  103359. if(b->endbyte+4>=b->storage){
  103360. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103361. b->storage+=BUFFER_INCREMENT;
  103362. b->ptr=b->buffer+b->endbyte;
  103363. }
  103364. value&=mask[bits];
  103365. bits+=b->endbit;
  103366. b->ptr[0]|=value<<b->endbit;
  103367. if(bits>=8){
  103368. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  103369. if(bits>=16){
  103370. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  103371. if(bits>=24){
  103372. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  103373. if(bits>=32){
  103374. if(b->endbit)
  103375. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  103376. else
  103377. b->ptr[4]=0;
  103378. }
  103379. }
  103380. }
  103381. }
  103382. b->endbyte+=bits/8;
  103383. b->ptr+=bits/8;
  103384. b->endbit=bits&7;
  103385. }
  103386. /* Takes only up to 32 bits. */
  103387. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  103388. if(b->endbyte+4>=b->storage){
  103389. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  103390. b->storage+=BUFFER_INCREMENT;
  103391. b->ptr=b->buffer+b->endbyte;
  103392. }
  103393. value=(value&mask[bits])<<(32-bits);
  103394. bits+=b->endbit;
  103395. b->ptr[0]|=value>>(24+b->endbit);
  103396. if(bits>=8){
  103397. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  103398. if(bits>=16){
  103399. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  103400. if(bits>=24){
  103401. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  103402. if(bits>=32){
  103403. if(b->endbit)
  103404. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  103405. else
  103406. b->ptr[4]=0;
  103407. }
  103408. }
  103409. }
  103410. }
  103411. b->endbyte+=bits/8;
  103412. b->ptr+=bits/8;
  103413. b->endbit=bits&7;
  103414. }
  103415. void oggpack_writealign(oggpack_buffer *b){
  103416. int bits=8-b->endbit;
  103417. if(bits<8)
  103418. oggpack_write(b,0,bits);
  103419. }
  103420. void oggpackB_writealign(oggpack_buffer *b){
  103421. int bits=8-b->endbit;
  103422. if(bits<8)
  103423. oggpackB_write(b,0,bits);
  103424. }
  103425. static void oggpack_writecopy_helper(oggpack_buffer *b,
  103426. void *source,
  103427. long bits,
  103428. void (*w)(oggpack_buffer *,
  103429. unsigned long,
  103430. int),
  103431. int msb){
  103432. unsigned char *ptr=(unsigned char *)source;
  103433. long bytes=bits/8;
  103434. bits-=bytes*8;
  103435. if(b->endbit){
  103436. int i;
  103437. /* unaligned copy. Do it the hard way. */
  103438. for(i=0;i<bytes;i++)
  103439. w(b,(unsigned long)(ptr[i]),8);
  103440. }else{
  103441. /* aligned block copy */
  103442. if(b->endbyte+bytes+1>=b->storage){
  103443. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  103444. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  103445. b->ptr=b->buffer+b->endbyte;
  103446. }
  103447. memmove(b->ptr,source,bytes);
  103448. b->ptr+=bytes;
  103449. b->endbyte+=bytes;
  103450. *b->ptr=0;
  103451. }
  103452. if(bits){
  103453. if(msb)
  103454. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  103455. else
  103456. w(b,(unsigned long)(ptr[bytes]),bits);
  103457. }
  103458. }
  103459. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  103460. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  103461. }
  103462. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  103463. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  103464. }
  103465. void oggpack_reset(oggpack_buffer *b){
  103466. b->ptr=b->buffer;
  103467. b->buffer[0]=0;
  103468. b->endbit=b->endbyte=0;
  103469. }
  103470. void oggpackB_reset(oggpack_buffer *b){
  103471. oggpack_reset(b);
  103472. }
  103473. void oggpack_writeclear(oggpack_buffer *b){
  103474. _ogg_free(b->buffer);
  103475. memset(b,0,sizeof(*b));
  103476. }
  103477. void oggpackB_writeclear(oggpack_buffer *b){
  103478. oggpack_writeclear(b);
  103479. }
  103480. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103481. memset(b,0,sizeof(*b));
  103482. b->buffer=b->ptr=buf;
  103483. b->storage=bytes;
  103484. }
  103485. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  103486. oggpack_readinit(b,buf,bytes);
  103487. }
  103488. /* Read in bits without advancing the bitptr; bits <= 32 */
  103489. long oggpack_look(oggpack_buffer *b,int bits){
  103490. unsigned long ret;
  103491. unsigned long m=mask[bits];
  103492. bits+=b->endbit;
  103493. if(b->endbyte+4>=b->storage){
  103494. /* not the main path */
  103495. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103496. }
  103497. ret=b->ptr[0]>>b->endbit;
  103498. if(bits>8){
  103499. ret|=b->ptr[1]<<(8-b->endbit);
  103500. if(bits>16){
  103501. ret|=b->ptr[2]<<(16-b->endbit);
  103502. if(bits>24){
  103503. ret|=b->ptr[3]<<(24-b->endbit);
  103504. if(bits>32 && b->endbit)
  103505. ret|=b->ptr[4]<<(32-b->endbit);
  103506. }
  103507. }
  103508. }
  103509. return(m&ret);
  103510. }
  103511. /* Read in bits without advancing the bitptr; bits <= 32 */
  103512. long oggpackB_look(oggpack_buffer *b,int bits){
  103513. unsigned long ret;
  103514. int m=32-bits;
  103515. bits+=b->endbit;
  103516. if(b->endbyte+4>=b->storage){
  103517. /* not the main path */
  103518. if(b->endbyte*8+bits>b->storage*8)return(-1);
  103519. }
  103520. ret=b->ptr[0]<<(24+b->endbit);
  103521. if(bits>8){
  103522. ret|=b->ptr[1]<<(16+b->endbit);
  103523. if(bits>16){
  103524. ret|=b->ptr[2]<<(8+b->endbit);
  103525. if(bits>24){
  103526. ret|=b->ptr[3]<<(b->endbit);
  103527. if(bits>32 && b->endbit)
  103528. ret|=b->ptr[4]>>(8-b->endbit);
  103529. }
  103530. }
  103531. }
  103532. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  103533. }
  103534. long oggpack_look1(oggpack_buffer *b){
  103535. if(b->endbyte>=b->storage)return(-1);
  103536. return((b->ptr[0]>>b->endbit)&1);
  103537. }
  103538. long oggpackB_look1(oggpack_buffer *b){
  103539. if(b->endbyte>=b->storage)return(-1);
  103540. return((b->ptr[0]>>(7-b->endbit))&1);
  103541. }
  103542. void oggpack_adv(oggpack_buffer *b,int bits){
  103543. bits+=b->endbit;
  103544. b->ptr+=bits/8;
  103545. b->endbyte+=bits/8;
  103546. b->endbit=bits&7;
  103547. }
  103548. void oggpackB_adv(oggpack_buffer *b,int bits){
  103549. oggpack_adv(b,bits);
  103550. }
  103551. void oggpack_adv1(oggpack_buffer *b){
  103552. if(++(b->endbit)>7){
  103553. b->endbit=0;
  103554. b->ptr++;
  103555. b->endbyte++;
  103556. }
  103557. }
  103558. void oggpackB_adv1(oggpack_buffer *b){
  103559. oggpack_adv1(b);
  103560. }
  103561. /* bits <= 32 */
  103562. long oggpack_read(oggpack_buffer *b,int bits){
  103563. long ret;
  103564. unsigned long m=mask[bits];
  103565. bits+=b->endbit;
  103566. if(b->endbyte+4>=b->storage){
  103567. /* not the main path */
  103568. ret=-1L;
  103569. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103570. }
  103571. ret=b->ptr[0]>>b->endbit;
  103572. if(bits>8){
  103573. ret|=b->ptr[1]<<(8-b->endbit);
  103574. if(bits>16){
  103575. ret|=b->ptr[2]<<(16-b->endbit);
  103576. if(bits>24){
  103577. ret|=b->ptr[3]<<(24-b->endbit);
  103578. if(bits>32 && b->endbit){
  103579. ret|=b->ptr[4]<<(32-b->endbit);
  103580. }
  103581. }
  103582. }
  103583. }
  103584. ret&=m;
  103585. overflow:
  103586. b->ptr+=bits/8;
  103587. b->endbyte+=bits/8;
  103588. b->endbit=bits&7;
  103589. return(ret);
  103590. }
  103591. /* bits <= 32 */
  103592. long oggpackB_read(oggpack_buffer *b,int bits){
  103593. long ret;
  103594. long m=32-bits;
  103595. bits+=b->endbit;
  103596. if(b->endbyte+4>=b->storage){
  103597. /* not the main path */
  103598. ret=-1L;
  103599. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  103600. }
  103601. ret=b->ptr[0]<<(24+b->endbit);
  103602. if(bits>8){
  103603. ret|=b->ptr[1]<<(16+b->endbit);
  103604. if(bits>16){
  103605. ret|=b->ptr[2]<<(8+b->endbit);
  103606. if(bits>24){
  103607. ret|=b->ptr[3]<<(b->endbit);
  103608. if(bits>32 && b->endbit)
  103609. ret|=b->ptr[4]>>(8-b->endbit);
  103610. }
  103611. }
  103612. }
  103613. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  103614. overflow:
  103615. b->ptr+=bits/8;
  103616. b->endbyte+=bits/8;
  103617. b->endbit=bits&7;
  103618. return(ret);
  103619. }
  103620. long oggpack_read1(oggpack_buffer *b){
  103621. long ret;
  103622. if(b->endbyte>=b->storage){
  103623. /* not the main path */
  103624. ret=-1L;
  103625. goto overflow;
  103626. }
  103627. ret=(b->ptr[0]>>b->endbit)&1;
  103628. overflow:
  103629. b->endbit++;
  103630. if(b->endbit>7){
  103631. b->endbit=0;
  103632. b->ptr++;
  103633. b->endbyte++;
  103634. }
  103635. return(ret);
  103636. }
  103637. long oggpackB_read1(oggpack_buffer *b){
  103638. long ret;
  103639. if(b->endbyte>=b->storage){
  103640. /* not the main path */
  103641. ret=-1L;
  103642. goto overflow;
  103643. }
  103644. ret=(b->ptr[0]>>(7-b->endbit))&1;
  103645. overflow:
  103646. b->endbit++;
  103647. if(b->endbit>7){
  103648. b->endbit=0;
  103649. b->ptr++;
  103650. b->endbyte++;
  103651. }
  103652. return(ret);
  103653. }
  103654. long oggpack_bytes(oggpack_buffer *b){
  103655. return(b->endbyte+(b->endbit+7)/8);
  103656. }
  103657. long oggpack_bits(oggpack_buffer *b){
  103658. return(b->endbyte*8+b->endbit);
  103659. }
  103660. long oggpackB_bytes(oggpack_buffer *b){
  103661. return oggpack_bytes(b);
  103662. }
  103663. long oggpackB_bits(oggpack_buffer *b){
  103664. return oggpack_bits(b);
  103665. }
  103666. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  103667. return(b->buffer);
  103668. }
  103669. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  103670. return oggpack_get_buffer(b);
  103671. }
  103672. /* Self test of the bitwise routines; everything else is based on
  103673. them, so they damned well better be solid. */
  103674. #ifdef _V_SELFTEST
  103675. #include <stdio.h>
  103676. static int ilog(unsigned int v){
  103677. int ret=0;
  103678. while(v){
  103679. ret++;
  103680. v>>=1;
  103681. }
  103682. return(ret);
  103683. }
  103684. oggpack_buffer o;
  103685. oggpack_buffer r;
  103686. void report(char *in){
  103687. fprintf(stderr,"%s",in);
  103688. exit(1);
  103689. }
  103690. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103691. long bytes,i;
  103692. unsigned char *buffer;
  103693. oggpack_reset(&o);
  103694. for(i=0;i<vals;i++)
  103695. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  103696. buffer=oggpack_get_buffer(&o);
  103697. bytes=oggpack_bytes(&o);
  103698. if(bytes!=compsize)report("wrong number of bytes!\n");
  103699. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103700. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103701. report("wrote incorrect value!\n");
  103702. }
  103703. oggpack_readinit(&r,buffer,bytes);
  103704. for(i=0;i<vals;i++){
  103705. int tbit=bits?bits:ilog(b[i]);
  103706. if(oggpack_look(&r,tbit)==-1)
  103707. report("out of data!\n");
  103708. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  103709. report("looked at incorrect value!\n");
  103710. if(tbit==1)
  103711. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  103712. report("looked at single bit incorrect value!\n");
  103713. if(tbit==1){
  103714. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  103715. report("read incorrect single bit value!\n");
  103716. }else{
  103717. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  103718. report("read incorrect value!\n");
  103719. }
  103720. }
  103721. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103722. }
  103723. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  103724. long bytes,i;
  103725. unsigned char *buffer;
  103726. oggpackB_reset(&o);
  103727. for(i=0;i<vals;i++)
  103728. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  103729. buffer=oggpackB_get_buffer(&o);
  103730. bytes=oggpackB_bytes(&o);
  103731. if(bytes!=compsize)report("wrong number of bytes!\n");
  103732. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  103733. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  103734. report("wrote incorrect value!\n");
  103735. }
  103736. oggpackB_readinit(&r,buffer,bytes);
  103737. for(i=0;i<vals;i++){
  103738. int tbit=bits?bits:ilog(b[i]);
  103739. if(oggpackB_look(&r,tbit)==-1)
  103740. report("out of data!\n");
  103741. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  103742. report("looked at incorrect value!\n");
  103743. if(tbit==1)
  103744. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  103745. report("looked at single bit incorrect value!\n");
  103746. if(tbit==1){
  103747. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  103748. report("read incorrect single bit value!\n");
  103749. }else{
  103750. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  103751. report("read incorrect value!\n");
  103752. }
  103753. }
  103754. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103755. }
  103756. int main(void){
  103757. unsigned char *buffer;
  103758. long bytes,i;
  103759. static unsigned long testbuffer1[]=
  103760. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  103761. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  103762. int test1size=43;
  103763. static unsigned long testbuffer2[]=
  103764. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  103765. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  103766. 85525151,0,12321,1,349528352};
  103767. int test2size=21;
  103768. static unsigned long testbuffer3[]=
  103769. {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,
  103770. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  103771. int test3size=56;
  103772. static unsigned long large[]=
  103773. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  103774. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  103775. 85525151,0,12321,1,2146528352};
  103776. int onesize=33;
  103777. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  103778. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  103779. 223,4};
  103780. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  103781. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  103782. 245,251,128};
  103783. int twosize=6;
  103784. static int two[6]={61,255,255,251,231,29};
  103785. static int twoB[6]={247,63,255,253,249,120};
  103786. int threesize=54;
  103787. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  103788. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  103789. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  103790. 100,52,4,14,18,86,77,1};
  103791. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  103792. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  103793. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  103794. 200,20,254,4,58,106,176,144,0};
  103795. int foursize=38;
  103796. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  103797. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  103798. 28,2,133,0,1};
  103799. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  103800. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  103801. 129,10,4,32};
  103802. int fivesize=45;
  103803. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  103804. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  103805. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  103806. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  103807. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  103808. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  103809. int sixsize=7;
  103810. static int six[7]={17,177,170,242,169,19,148};
  103811. static int sixB[7]={136,141,85,79,149,200,41};
  103812. /* Test read/write together */
  103813. /* Later we test against pregenerated bitstreams */
  103814. oggpack_writeinit(&o);
  103815. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  103816. cliptest(testbuffer1,test1size,0,one,onesize);
  103817. fprintf(stderr,"ok.");
  103818. fprintf(stderr,"\nNull bit call (LSb): ");
  103819. cliptest(testbuffer3,test3size,0,two,twosize);
  103820. fprintf(stderr,"ok.");
  103821. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  103822. cliptest(testbuffer2,test2size,0,three,threesize);
  103823. fprintf(stderr,"ok.");
  103824. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  103825. oggpack_reset(&o);
  103826. for(i=0;i<test2size;i++)
  103827. oggpack_write(&o,large[i],32);
  103828. buffer=oggpack_get_buffer(&o);
  103829. bytes=oggpack_bytes(&o);
  103830. oggpack_readinit(&r,buffer,bytes);
  103831. for(i=0;i<test2size;i++){
  103832. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  103833. if(oggpack_look(&r,32)!=large[i]){
  103834. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  103835. oggpack_look(&r,32),large[i]);
  103836. report("read incorrect value!\n");
  103837. }
  103838. oggpack_adv(&r,32);
  103839. }
  103840. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103841. fprintf(stderr,"ok.");
  103842. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  103843. cliptest(testbuffer1,test1size,7,four,foursize);
  103844. fprintf(stderr,"ok.");
  103845. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  103846. cliptest(testbuffer2,test2size,17,five,fivesize);
  103847. fprintf(stderr,"ok.");
  103848. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  103849. cliptest(testbuffer3,test3size,1,six,sixsize);
  103850. fprintf(stderr,"ok.");
  103851. fprintf(stderr,"\nTesting read past end (LSb): ");
  103852. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103853. for(i=0;i<64;i++){
  103854. if(oggpack_read(&r,1)!=0){
  103855. fprintf(stderr,"failed; got -1 prematurely.\n");
  103856. exit(1);
  103857. }
  103858. }
  103859. if(oggpack_look(&r,1)!=-1 ||
  103860. oggpack_read(&r,1)!=-1){
  103861. fprintf(stderr,"failed; read past end without -1.\n");
  103862. exit(1);
  103863. }
  103864. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103865. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  103866. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103867. exit(1);
  103868. }
  103869. if(oggpack_look(&r,18)!=0 ||
  103870. oggpack_look(&r,18)!=0){
  103871. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103872. exit(1);
  103873. }
  103874. if(oggpack_look(&r,19)!=-1 ||
  103875. oggpack_look(&r,19)!=-1){
  103876. fprintf(stderr,"failed; read past end without -1.\n");
  103877. exit(1);
  103878. }
  103879. if(oggpack_look(&r,32)!=-1 ||
  103880. oggpack_look(&r,32)!=-1){
  103881. fprintf(stderr,"failed; read past end without -1.\n");
  103882. exit(1);
  103883. }
  103884. oggpack_writeclear(&o);
  103885. fprintf(stderr,"ok.\n");
  103886. /********** lazy, cut-n-paste retest with MSb packing ***********/
  103887. /* Test read/write together */
  103888. /* Later we test against pregenerated bitstreams */
  103889. oggpackB_writeinit(&o);
  103890. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  103891. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  103892. fprintf(stderr,"ok.");
  103893. fprintf(stderr,"\nNull bit call (MSb): ");
  103894. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  103895. fprintf(stderr,"ok.");
  103896. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  103897. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  103898. fprintf(stderr,"ok.");
  103899. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  103900. oggpackB_reset(&o);
  103901. for(i=0;i<test2size;i++)
  103902. oggpackB_write(&o,large[i],32);
  103903. buffer=oggpackB_get_buffer(&o);
  103904. bytes=oggpackB_bytes(&o);
  103905. oggpackB_readinit(&r,buffer,bytes);
  103906. for(i=0;i<test2size;i++){
  103907. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  103908. if(oggpackB_look(&r,32)!=large[i]){
  103909. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  103910. oggpackB_look(&r,32),large[i]);
  103911. report("read incorrect value!\n");
  103912. }
  103913. oggpackB_adv(&r,32);
  103914. }
  103915. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  103916. fprintf(stderr,"ok.");
  103917. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  103918. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  103919. fprintf(stderr,"ok.");
  103920. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  103921. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  103922. fprintf(stderr,"ok.");
  103923. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  103924. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  103925. fprintf(stderr,"ok.");
  103926. fprintf(stderr,"\nTesting read past end (MSb): ");
  103927. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103928. for(i=0;i<64;i++){
  103929. if(oggpackB_read(&r,1)!=0){
  103930. fprintf(stderr,"failed; got -1 prematurely.\n");
  103931. exit(1);
  103932. }
  103933. }
  103934. if(oggpackB_look(&r,1)!=-1 ||
  103935. oggpackB_read(&r,1)!=-1){
  103936. fprintf(stderr,"failed; read past end without -1.\n");
  103937. exit(1);
  103938. }
  103939. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  103940. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  103941. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  103942. exit(1);
  103943. }
  103944. if(oggpackB_look(&r,18)!=0 ||
  103945. oggpackB_look(&r,18)!=0){
  103946. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  103947. exit(1);
  103948. }
  103949. if(oggpackB_look(&r,19)!=-1 ||
  103950. oggpackB_look(&r,19)!=-1){
  103951. fprintf(stderr,"failed; read past end without -1.\n");
  103952. exit(1);
  103953. }
  103954. if(oggpackB_look(&r,32)!=-1 ||
  103955. oggpackB_look(&r,32)!=-1){
  103956. fprintf(stderr,"failed; read past end without -1.\n");
  103957. exit(1);
  103958. }
  103959. oggpackB_writeclear(&o);
  103960. fprintf(stderr,"ok.\n\n");
  103961. return(0);
  103962. }
  103963. #endif /* _V_SELFTEST */
  103964. #undef BUFFER_INCREMENT
  103965. #endif
  103966. /********* End of inlined file: bitwise.c *********/
  103967. /********* Start of inlined file: framing.c *********/
  103968. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103969. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103970. // tasks..
  103971. #ifdef _MSC_VER
  103972. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103973. #endif
  103974. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103975. #if JUCE_USE_OGGVORBIS
  103976. #include <stdlib.h>
  103977. #include <string.h>
  103978. /* A complete description of Ogg framing exists in docs/framing.html */
  103979. int ogg_page_version(ogg_page *og){
  103980. return((int)(og->header[4]));
  103981. }
  103982. int ogg_page_continued(ogg_page *og){
  103983. return((int)(og->header[5]&0x01));
  103984. }
  103985. int ogg_page_bos(ogg_page *og){
  103986. return((int)(og->header[5]&0x02));
  103987. }
  103988. int ogg_page_eos(ogg_page *og){
  103989. return((int)(og->header[5]&0x04));
  103990. }
  103991. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  103992. unsigned char *page=og->header;
  103993. ogg_int64_t granulepos=page[13]&(0xff);
  103994. granulepos= (granulepos<<8)|(page[12]&0xff);
  103995. granulepos= (granulepos<<8)|(page[11]&0xff);
  103996. granulepos= (granulepos<<8)|(page[10]&0xff);
  103997. granulepos= (granulepos<<8)|(page[9]&0xff);
  103998. granulepos= (granulepos<<8)|(page[8]&0xff);
  103999. granulepos= (granulepos<<8)|(page[7]&0xff);
  104000. granulepos= (granulepos<<8)|(page[6]&0xff);
  104001. return(granulepos);
  104002. }
  104003. int ogg_page_serialno(ogg_page *og){
  104004. return(og->header[14] |
  104005. (og->header[15]<<8) |
  104006. (og->header[16]<<16) |
  104007. (og->header[17]<<24));
  104008. }
  104009. long ogg_page_pageno(ogg_page *og){
  104010. return(og->header[18] |
  104011. (og->header[19]<<8) |
  104012. (og->header[20]<<16) |
  104013. (og->header[21]<<24));
  104014. }
  104015. /* returns the number of packets that are completed on this page (if
  104016. the leading packet is begun on a previous page, but ends on this
  104017. page, it's counted */
  104018. /* NOTE:
  104019. If a page consists of a packet begun on a previous page, and a new
  104020. packet begun (but not completed) on this page, the return will be:
  104021. ogg_page_packets(page) ==1,
  104022. ogg_page_continued(page) !=0
  104023. If a page happens to be a single packet that was begun on a
  104024. previous page, and spans to the next page (in the case of a three or
  104025. more page packet), the return will be:
  104026. ogg_page_packets(page) ==0,
  104027. ogg_page_continued(page) !=0
  104028. */
  104029. int ogg_page_packets(ogg_page *og){
  104030. int i,n=og->header[26],count=0;
  104031. for(i=0;i<n;i++)
  104032. if(og->header[27+i]<255)count++;
  104033. return(count);
  104034. }
  104035. #if 0
  104036. /* helper to initialize lookup for direct-table CRC (illustrative; we
  104037. use the static init below) */
  104038. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  104039. int i;
  104040. unsigned long r;
  104041. r = index << 24;
  104042. for (i=0; i<8; i++)
  104043. if (r & 0x80000000UL)
  104044. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  104045. polynomial, although we use an
  104046. unreflected alg and an init/final
  104047. of 0, not 0xffffffff */
  104048. else
  104049. r<<=1;
  104050. return (r & 0xffffffffUL);
  104051. }
  104052. #endif
  104053. static const ogg_uint32_t crc_lookup[256]={
  104054. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  104055. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  104056. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  104057. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  104058. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  104059. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  104060. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  104061. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  104062. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  104063. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  104064. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  104065. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  104066. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  104067. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  104068. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  104069. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  104070. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  104071. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  104072. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  104073. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  104074. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  104075. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  104076. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  104077. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  104078. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  104079. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  104080. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  104081. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  104082. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  104083. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  104084. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  104085. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  104086. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  104087. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  104088. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  104089. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  104090. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  104091. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  104092. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  104093. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  104094. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  104095. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  104096. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  104097. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  104098. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  104099. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  104100. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  104101. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  104102. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  104103. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  104104. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  104105. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  104106. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  104107. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  104108. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  104109. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  104110. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  104111. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  104112. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  104113. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  104114. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  104115. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  104116. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  104117. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  104118. /* init the encode/decode logical stream state */
  104119. int ogg_stream_init(ogg_stream_state *os,int serialno){
  104120. if(os){
  104121. memset(os,0,sizeof(*os));
  104122. os->body_storage=16*1024;
  104123. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  104124. os->lacing_storage=1024;
  104125. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  104126. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  104127. os->serialno=serialno;
  104128. return(0);
  104129. }
  104130. return(-1);
  104131. }
  104132. /* _clear does not free os, only the non-flat storage within */
  104133. int ogg_stream_clear(ogg_stream_state *os){
  104134. if(os){
  104135. if(os->body_data)_ogg_free(os->body_data);
  104136. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  104137. if(os->granule_vals)_ogg_free(os->granule_vals);
  104138. memset(os,0,sizeof(*os));
  104139. }
  104140. return(0);
  104141. }
  104142. int ogg_stream_destroy(ogg_stream_state *os){
  104143. if(os){
  104144. ogg_stream_clear(os);
  104145. _ogg_free(os);
  104146. }
  104147. return(0);
  104148. }
  104149. /* Helpers for ogg_stream_encode; this keeps the structure and
  104150. what's happening fairly clear */
  104151. static void _os_body_expand(ogg_stream_state *os,int needed){
  104152. if(os->body_storage<=os->body_fill+needed){
  104153. os->body_storage+=(needed+1024);
  104154. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  104155. }
  104156. }
  104157. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  104158. if(os->lacing_storage<=os->lacing_fill+needed){
  104159. os->lacing_storage+=(needed+32);
  104160. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  104161. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  104162. }
  104163. }
  104164. /* checksum the page */
  104165. /* Direct table CRC; note that this will be faster in the future if we
  104166. perform the checksum silmultaneously with other copies */
  104167. void ogg_page_checksum_set(ogg_page *og){
  104168. if(og){
  104169. ogg_uint32_t crc_reg=0;
  104170. int i;
  104171. /* safety; needed for API behavior, but not framing code */
  104172. og->header[22]=0;
  104173. og->header[23]=0;
  104174. og->header[24]=0;
  104175. og->header[25]=0;
  104176. for(i=0;i<og->header_len;i++)
  104177. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  104178. for(i=0;i<og->body_len;i++)
  104179. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  104180. og->header[22]=(unsigned char)(crc_reg&0xff);
  104181. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  104182. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  104183. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  104184. }
  104185. }
  104186. /* submit data to the internal buffer of the framing engine */
  104187. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  104188. int lacing_vals=op->bytes/255+1,i;
  104189. if(os->body_returned){
  104190. /* advance packet data according to the body_returned pointer. We
  104191. had to keep it around to return a pointer into the buffer last
  104192. call */
  104193. os->body_fill-=os->body_returned;
  104194. if(os->body_fill)
  104195. memmove(os->body_data,os->body_data+os->body_returned,
  104196. os->body_fill);
  104197. os->body_returned=0;
  104198. }
  104199. /* make sure we have the buffer storage */
  104200. _os_body_expand(os,op->bytes);
  104201. _os_lacing_expand(os,lacing_vals);
  104202. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  104203. the liability of overly clean abstraction for the time being. It
  104204. will actually be fairly easy to eliminate the extra copy in the
  104205. future */
  104206. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  104207. os->body_fill+=op->bytes;
  104208. /* Store lacing vals for this packet */
  104209. for(i=0;i<lacing_vals-1;i++){
  104210. os->lacing_vals[os->lacing_fill+i]=255;
  104211. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  104212. }
  104213. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  104214. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  104215. /* flag the first segment as the beginning of the packet */
  104216. os->lacing_vals[os->lacing_fill]|= 0x100;
  104217. os->lacing_fill+=lacing_vals;
  104218. /* for the sake of completeness */
  104219. os->packetno++;
  104220. if(op->e_o_s)os->e_o_s=1;
  104221. return(0);
  104222. }
  104223. /* This will flush remaining packets into a page (returning nonzero),
  104224. even if there is not enough data to trigger a flush normally
  104225. (undersized page). If there are no packets or partial packets to
  104226. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  104227. try to flush a normal sized page like ogg_stream_pageout; a call to
  104228. ogg_stream_flush does not guarantee that all packets have flushed.
  104229. Only a return value of 0 from ogg_stream_flush indicates all packet
  104230. data is flushed into pages.
  104231. since ogg_stream_flush will flush the last page in a stream even if
  104232. it's undersized, you almost certainly want to use ogg_stream_pageout
  104233. (and *not* ogg_stream_flush) unless you specifically need to flush
  104234. an page regardless of size in the middle of a stream. */
  104235. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  104236. int i;
  104237. int vals=0;
  104238. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  104239. int bytes=0;
  104240. long acc=0;
  104241. ogg_int64_t granule_pos=-1;
  104242. if(maxvals==0)return(0);
  104243. /* construct a page */
  104244. /* decide how many segments to include */
  104245. /* If this is the initial header case, the first page must only include
  104246. the initial header packet */
  104247. if(os->b_o_s==0){ /* 'initial header page' case */
  104248. granule_pos=0;
  104249. for(vals=0;vals<maxvals;vals++){
  104250. if((os->lacing_vals[vals]&0x0ff)<255){
  104251. vals++;
  104252. break;
  104253. }
  104254. }
  104255. }else{
  104256. for(vals=0;vals<maxvals;vals++){
  104257. if(acc>4096)break;
  104258. acc+=os->lacing_vals[vals]&0x0ff;
  104259. if((os->lacing_vals[vals]&0xff)<255)
  104260. granule_pos=os->granule_vals[vals];
  104261. }
  104262. }
  104263. /* construct the header in temp storage */
  104264. memcpy(os->header,"OggS",4);
  104265. /* stream structure version */
  104266. os->header[4]=0x00;
  104267. /* continued packet flag? */
  104268. os->header[5]=0x00;
  104269. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  104270. /* first page flag? */
  104271. if(os->b_o_s==0)os->header[5]|=0x02;
  104272. /* last page flag? */
  104273. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  104274. os->b_o_s=1;
  104275. /* 64 bits of PCM position */
  104276. for(i=6;i<14;i++){
  104277. os->header[i]=(unsigned char)(granule_pos&0xff);
  104278. granule_pos>>=8;
  104279. }
  104280. /* 32 bits of stream serial number */
  104281. {
  104282. long serialno=os->serialno;
  104283. for(i=14;i<18;i++){
  104284. os->header[i]=(unsigned char)(serialno&0xff);
  104285. serialno>>=8;
  104286. }
  104287. }
  104288. /* 32 bits of page counter (we have both counter and page header
  104289. because this val can roll over) */
  104290. if(os->pageno==-1)os->pageno=0; /* because someone called
  104291. stream_reset; this would be a
  104292. strange thing to do in an
  104293. encode stream, but it has
  104294. plausible uses */
  104295. {
  104296. long pageno=os->pageno++;
  104297. for(i=18;i<22;i++){
  104298. os->header[i]=(unsigned char)(pageno&0xff);
  104299. pageno>>=8;
  104300. }
  104301. }
  104302. /* zero for computation; filled in later */
  104303. os->header[22]=0;
  104304. os->header[23]=0;
  104305. os->header[24]=0;
  104306. os->header[25]=0;
  104307. /* segment table */
  104308. os->header[26]=(unsigned char)(vals&0xff);
  104309. for(i=0;i<vals;i++)
  104310. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  104311. /* set pointers in the ogg_page struct */
  104312. og->header=os->header;
  104313. og->header_len=os->header_fill=vals+27;
  104314. og->body=os->body_data+os->body_returned;
  104315. og->body_len=bytes;
  104316. /* advance the lacing data and set the body_returned pointer */
  104317. os->lacing_fill-=vals;
  104318. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  104319. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  104320. os->body_returned+=bytes;
  104321. /* calculate the checksum */
  104322. ogg_page_checksum_set(og);
  104323. /* done */
  104324. return(1);
  104325. }
  104326. /* This constructs pages from buffered packet segments. The pointers
  104327. returned are to static buffers; do not free. The returned buffers are
  104328. good only until the next call (using the same ogg_stream_state) */
  104329. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  104330. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  104331. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  104332. os->lacing_fill>=255 || /* 'segment table full' case */
  104333. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  104334. return(ogg_stream_flush(os,og));
  104335. }
  104336. /* not enough data to construct a page and not end of stream */
  104337. return(0);
  104338. }
  104339. int ogg_stream_eos(ogg_stream_state *os){
  104340. return os->e_o_s;
  104341. }
  104342. /* DECODING PRIMITIVES: packet streaming layer **********************/
  104343. /* This has two layers to place more of the multi-serialno and paging
  104344. control in the application's hands. First, we expose a data buffer
  104345. using ogg_sync_buffer(). The app either copies into the
  104346. buffer, or passes it directly to read(), etc. We then call
  104347. ogg_sync_wrote() to tell how many bytes we just added.
  104348. Pages are returned (pointers into the buffer in ogg_sync_state)
  104349. by ogg_sync_pageout(). The page is then submitted to
  104350. ogg_stream_pagein() along with the appropriate
  104351. ogg_stream_state* (ie, matching serialno). We then get raw
  104352. packets out calling ogg_stream_packetout() with a
  104353. ogg_stream_state. */
  104354. /* initialize the struct to a known state */
  104355. int ogg_sync_init(ogg_sync_state *oy){
  104356. if(oy){
  104357. memset(oy,0,sizeof(*oy));
  104358. }
  104359. return(0);
  104360. }
  104361. /* clear non-flat storage within */
  104362. int ogg_sync_clear(ogg_sync_state *oy){
  104363. if(oy){
  104364. if(oy->data)_ogg_free(oy->data);
  104365. ogg_sync_init(oy);
  104366. }
  104367. return(0);
  104368. }
  104369. int ogg_sync_destroy(ogg_sync_state *oy){
  104370. if(oy){
  104371. ogg_sync_clear(oy);
  104372. _ogg_free(oy);
  104373. }
  104374. return(0);
  104375. }
  104376. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  104377. /* first, clear out any space that has been previously returned */
  104378. if(oy->returned){
  104379. oy->fill-=oy->returned;
  104380. if(oy->fill>0)
  104381. memmove(oy->data,oy->data+oy->returned,oy->fill);
  104382. oy->returned=0;
  104383. }
  104384. if(size>oy->storage-oy->fill){
  104385. /* We need to extend the internal buffer */
  104386. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  104387. if(oy->data)
  104388. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  104389. else
  104390. oy->data=(unsigned char*) _ogg_malloc(newsize);
  104391. oy->storage=newsize;
  104392. }
  104393. /* expose a segment at least as large as requested at the fill mark */
  104394. return((char *)oy->data+oy->fill);
  104395. }
  104396. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  104397. if(oy->fill+bytes>oy->storage)return(-1);
  104398. oy->fill+=bytes;
  104399. return(0);
  104400. }
  104401. /* sync the stream. This is meant to be useful for finding page
  104402. boundaries.
  104403. return values for this:
  104404. -n) skipped n bytes
  104405. 0) page not ready; more data (no bytes skipped)
  104406. n) page synced at current location; page length n bytes
  104407. */
  104408. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  104409. unsigned char *page=oy->data+oy->returned;
  104410. unsigned char *next;
  104411. long bytes=oy->fill-oy->returned;
  104412. if(oy->headerbytes==0){
  104413. int headerbytes,i;
  104414. if(bytes<27)return(0); /* not enough for a header */
  104415. /* verify capture pattern */
  104416. if(memcmp(page,"OggS",4))goto sync_fail;
  104417. headerbytes=page[26]+27;
  104418. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  104419. /* count up body length in the segment table */
  104420. for(i=0;i<page[26];i++)
  104421. oy->bodybytes+=page[27+i];
  104422. oy->headerbytes=headerbytes;
  104423. }
  104424. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  104425. /* The whole test page is buffered. Verify the checksum */
  104426. {
  104427. /* Grab the checksum bytes, set the header field to zero */
  104428. char chksum[4];
  104429. ogg_page log;
  104430. memcpy(chksum,page+22,4);
  104431. memset(page+22,0,4);
  104432. /* set up a temp page struct and recompute the checksum */
  104433. log.header=page;
  104434. log.header_len=oy->headerbytes;
  104435. log.body=page+oy->headerbytes;
  104436. log.body_len=oy->bodybytes;
  104437. ogg_page_checksum_set(&log);
  104438. /* Compare */
  104439. if(memcmp(chksum,page+22,4)){
  104440. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  104441. at all) */
  104442. /* replace the computed checksum with the one actually read in */
  104443. memcpy(page+22,chksum,4);
  104444. /* Bad checksum. Lose sync */
  104445. goto sync_fail;
  104446. }
  104447. }
  104448. /* yes, have a whole page all ready to go */
  104449. {
  104450. unsigned char *page=oy->data+oy->returned;
  104451. long bytes;
  104452. if(og){
  104453. og->header=page;
  104454. og->header_len=oy->headerbytes;
  104455. og->body=page+oy->headerbytes;
  104456. og->body_len=oy->bodybytes;
  104457. }
  104458. oy->unsynced=0;
  104459. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  104460. oy->headerbytes=0;
  104461. oy->bodybytes=0;
  104462. return(bytes);
  104463. }
  104464. sync_fail:
  104465. oy->headerbytes=0;
  104466. oy->bodybytes=0;
  104467. /* search for possible capture */
  104468. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  104469. if(!next)
  104470. next=oy->data+oy->fill;
  104471. oy->returned=next-oy->data;
  104472. return(-(next-page));
  104473. }
  104474. /* sync the stream and get a page. Keep trying until we find a page.
  104475. Supress 'sync errors' after reporting the first.
  104476. return values:
  104477. -1) recapture (hole in data)
  104478. 0) need more data
  104479. 1) page returned
  104480. Returns pointers into buffered data; invalidated by next call to
  104481. _stream, _clear, _init, or _buffer */
  104482. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  104483. /* all we need to do is verify a page at the head of the stream
  104484. buffer. If it doesn't verify, we look for the next potential
  104485. frame */
  104486. for(;;){
  104487. long ret=ogg_sync_pageseek(oy,og);
  104488. if(ret>0){
  104489. /* have a page */
  104490. return(1);
  104491. }
  104492. if(ret==0){
  104493. /* need more data */
  104494. return(0);
  104495. }
  104496. /* head did not start a synced page... skipped some bytes */
  104497. if(!oy->unsynced){
  104498. oy->unsynced=1;
  104499. return(-1);
  104500. }
  104501. /* loop. keep looking */
  104502. }
  104503. }
  104504. /* add the incoming page to the stream state; we decompose the page
  104505. into packet segments here as well. */
  104506. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  104507. unsigned char *header=og->header;
  104508. unsigned char *body=og->body;
  104509. long bodysize=og->body_len;
  104510. int segptr=0;
  104511. int version=ogg_page_version(og);
  104512. int continued=ogg_page_continued(og);
  104513. int bos=ogg_page_bos(og);
  104514. int eos=ogg_page_eos(og);
  104515. ogg_int64_t granulepos=ogg_page_granulepos(og);
  104516. int serialno=ogg_page_serialno(og);
  104517. long pageno=ogg_page_pageno(og);
  104518. int segments=header[26];
  104519. /* clean up 'returned data' */
  104520. {
  104521. long lr=os->lacing_returned;
  104522. long br=os->body_returned;
  104523. /* body data */
  104524. if(br){
  104525. os->body_fill-=br;
  104526. if(os->body_fill)
  104527. memmove(os->body_data,os->body_data+br,os->body_fill);
  104528. os->body_returned=0;
  104529. }
  104530. if(lr){
  104531. /* segment table */
  104532. if(os->lacing_fill-lr){
  104533. memmove(os->lacing_vals,os->lacing_vals+lr,
  104534. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  104535. memmove(os->granule_vals,os->granule_vals+lr,
  104536. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  104537. }
  104538. os->lacing_fill-=lr;
  104539. os->lacing_packet-=lr;
  104540. os->lacing_returned=0;
  104541. }
  104542. }
  104543. /* check the serial number */
  104544. if(serialno!=os->serialno)return(-1);
  104545. if(version>0)return(-1);
  104546. _os_lacing_expand(os,segments+1);
  104547. /* are we in sequence? */
  104548. if(pageno!=os->pageno){
  104549. int i;
  104550. /* unroll previous partial packet (if any) */
  104551. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  104552. os->body_fill-=os->lacing_vals[i]&0xff;
  104553. os->lacing_fill=os->lacing_packet;
  104554. /* make a note of dropped data in segment table */
  104555. if(os->pageno!=-1){
  104556. os->lacing_vals[os->lacing_fill++]=0x400;
  104557. os->lacing_packet++;
  104558. }
  104559. }
  104560. /* are we a 'continued packet' page? If so, we may need to skip
  104561. some segments */
  104562. if(continued){
  104563. if(os->lacing_fill<1 ||
  104564. os->lacing_vals[os->lacing_fill-1]==0x400){
  104565. bos=0;
  104566. for(;segptr<segments;segptr++){
  104567. int val=header[27+segptr];
  104568. body+=val;
  104569. bodysize-=val;
  104570. if(val<255){
  104571. segptr++;
  104572. break;
  104573. }
  104574. }
  104575. }
  104576. }
  104577. if(bodysize){
  104578. _os_body_expand(os,bodysize);
  104579. memcpy(os->body_data+os->body_fill,body,bodysize);
  104580. os->body_fill+=bodysize;
  104581. }
  104582. {
  104583. int saved=-1;
  104584. while(segptr<segments){
  104585. int val=header[27+segptr];
  104586. os->lacing_vals[os->lacing_fill]=val;
  104587. os->granule_vals[os->lacing_fill]=-1;
  104588. if(bos){
  104589. os->lacing_vals[os->lacing_fill]|=0x100;
  104590. bos=0;
  104591. }
  104592. if(val<255)saved=os->lacing_fill;
  104593. os->lacing_fill++;
  104594. segptr++;
  104595. if(val<255)os->lacing_packet=os->lacing_fill;
  104596. }
  104597. /* set the granulepos on the last granuleval of the last full packet */
  104598. if(saved!=-1){
  104599. os->granule_vals[saved]=granulepos;
  104600. }
  104601. }
  104602. if(eos){
  104603. os->e_o_s=1;
  104604. if(os->lacing_fill>0)
  104605. os->lacing_vals[os->lacing_fill-1]|=0x200;
  104606. }
  104607. os->pageno=pageno+1;
  104608. return(0);
  104609. }
  104610. /* clear things to an initial state. Good to call, eg, before seeking */
  104611. int ogg_sync_reset(ogg_sync_state *oy){
  104612. oy->fill=0;
  104613. oy->returned=0;
  104614. oy->unsynced=0;
  104615. oy->headerbytes=0;
  104616. oy->bodybytes=0;
  104617. return(0);
  104618. }
  104619. int ogg_stream_reset(ogg_stream_state *os){
  104620. os->body_fill=0;
  104621. os->body_returned=0;
  104622. os->lacing_fill=0;
  104623. os->lacing_packet=0;
  104624. os->lacing_returned=0;
  104625. os->header_fill=0;
  104626. os->e_o_s=0;
  104627. os->b_o_s=0;
  104628. os->pageno=-1;
  104629. os->packetno=0;
  104630. os->granulepos=0;
  104631. return(0);
  104632. }
  104633. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  104634. ogg_stream_reset(os);
  104635. os->serialno=serialno;
  104636. return(0);
  104637. }
  104638. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  104639. /* The last part of decode. We have the stream broken into packet
  104640. segments. Now we need to group them into packets (or return the
  104641. out of sync markers) */
  104642. int ptr=os->lacing_returned;
  104643. if(os->lacing_packet<=ptr)return(0);
  104644. if(os->lacing_vals[ptr]&0x400){
  104645. /* we need to tell the codec there's a gap; it might need to
  104646. handle previous packet dependencies. */
  104647. os->lacing_returned++;
  104648. os->packetno++;
  104649. return(-1);
  104650. }
  104651. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  104652. to ask if there's a whole packet
  104653. waiting */
  104654. /* Gather the whole packet. We'll have no holes or a partial packet */
  104655. {
  104656. int size=os->lacing_vals[ptr]&0xff;
  104657. int bytes=size;
  104658. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  104659. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  104660. while(size==255){
  104661. int val=os->lacing_vals[++ptr];
  104662. size=val&0xff;
  104663. if(val&0x200)eos=0x200;
  104664. bytes+=size;
  104665. }
  104666. if(op){
  104667. op->e_o_s=eos;
  104668. op->b_o_s=bos;
  104669. op->packet=os->body_data+os->body_returned;
  104670. op->packetno=os->packetno;
  104671. op->granulepos=os->granule_vals[ptr];
  104672. op->bytes=bytes;
  104673. }
  104674. if(adv){
  104675. os->body_returned+=bytes;
  104676. os->lacing_returned=ptr+1;
  104677. os->packetno++;
  104678. }
  104679. }
  104680. return(1);
  104681. }
  104682. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  104683. return _packetout(os,op,1);
  104684. }
  104685. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  104686. return _packetout(os,op,0);
  104687. }
  104688. void ogg_packet_clear(ogg_packet *op) {
  104689. _ogg_free(op->packet);
  104690. memset(op, 0, sizeof(*op));
  104691. }
  104692. #ifdef _V_SELFTEST
  104693. #include <stdio.h>
  104694. ogg_stream_state os_en, os_de;
  104695. ogg_sync_state oy;
  104696. void checkpacket(ogg_packet *op,int len, int no, int pos){
  104697. long j;
  104698. static int sequence=0;
  104699. static int lastno=0;
  104700. if(op->bytes!=len){
  104701. fprintf(stderr,"incorrect packet length!\n");
  104702. exit(1);
  104703. }
  104704. if(op->granulepos!=pos){
  104705. fprintf(stderr,"incorrect packet position!\n");
  104706. exit(1);
  104707. }
  104708. /* packet number just follows sequence/gap; adjust the input number
  104709. for that */
  104710. if(no==0){
  104711. sequence=0;
  104712. }else{
  104713. sequence++;
  104714. if(no>lastno+1)
  104715. sequence++;
  104716. }
  104717. lastno=no;
  104718. if(op->packetno!=sequence){
  104719. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  104720. (long)(op->packetno),sequence);
  104721. exit(1);
  104722. }
  104723. /* Test data */
  104724. for(j=0;j<op->bytes;j++)
  104725. if(op->packet[j]!=((j+no)&0xff)){
  104726. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  104727. j,op->packet[j],(j+no)&0xff);
  104728. exit(1);
  104729. }
  104730. }
  104731. void check_page(unsigned char *data,const int *header,ogg_page *og){
  104732. long j;
  104733. /* Test data */
  104734. for(j=0;j<og->body_len;j++)
  104735. if(og->body[j]!=data[j]){
  104736. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  104737. j,data[j],og->body[j]);
  104738. exit(1);
  104739. }
  104740. /* Test header */
  104741. for(j=0;j<og->header_len;j++){
  104742. if(og->header[j]!=header[j]){
  104743. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  104744. for(j=0;j<header[26]+27;j++)
  104745. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  104746. fprintf(stderr,"\n");
  104747. exit(1);
  104748. }
  104749. }
  104750. if(og->header_len!=header[26]+27){
  104751. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  104752. og->header_len,header[26]+27);
  104753. exit(1);
  104754. }
  104755. }
  104756. void print_header(ogg_page *og){
  104757. int j;
  104758. fprintf(stderr,"\nHEADER:\n");
  104759. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  104760. og->header[0],og->header[1],og->header[2],og->header[3],
  104761. (int)og->header[4],(int)og->header[5]);
  104762. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  104763. (og->header[9]<<24)|(og->header[8]<<16)|
  104764. (og->header[7]<<8)|og->header[6],
  104765. (og->header[17]<<24)|(og->header[16]<<16)|
  104766. (og->header[15]<<8)|og->header[14],
  104767. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  104768. (og->header[19]<<8)|og->header[18]);
  104769. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  104770. (int)og->header[22],(int)og->header[23],
  104771. (int)og->header[24],(int)og->header[25],
  104772. (int)og->header[26]);
  104773. for(j=27;j<og->header_len;j++)
  104774. fprintf(stderr,"%d ",(int)og->header[j]);
  104775. fprintf(stderr,")\n\n");
  104776. }
  104777. void copy_page(ogg_page *og){
  104778. unsigned char *temp=_ogg_malloc(og->header_len);
  104779. memcpy(temp,og->header,og->header_len);
  104780. og->header=temp;
  104781. temp=_ogg_malloc(og->body_len);
  104782. memcpy(temp,og->body,og->body_len);
  104783. og->body=temp;
  104784. }
  104785. void free_page(ogg_page *og){
  104786. _ogg_free (og->header);
  104787. _ogg_free (og->body);
  104788. }
  104789. void error(void){
  104790. fprintf(stderr,"error!\n");
  104791. exit(1);
  104792. }
  104793. /* 17 only */
  104794. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  104795. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104796. 0x01,0x02,0x03,0x04,0,0,0,0,
  104797. 0x15,0xed,0xec,0x91,
  104798. 1,
  104799. 17};
  104800. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  104801. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104802. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104803. 0x01,0x02,0x03,0x04,0,0,0,0,
  104804. 0x59,0x10,0x6c,0x2c,
  104805. 1,
  104806. 17};
  104807. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104808. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  104809. 0x01,0x02,0x03,0x04,1,0,0,0,
  104810. 0x89,0x33,0x85,0xce,
  104811. 13,
  104812. 254,255,0,255,1,255,245,255,255,0,
  104813. 255,255,90};
  104814. /* nil packets; beginning,middle,end */
  104815. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104816. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104817. 0x01,0x02,0x03,0x04,0,0,0,0,
  104818. 0xff,0x7b,0x23,0x17,
  104819. 1,
  104820. 0};
  104821. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104822. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  104823. 0x01,0x02,0x03,0x04,1,0,0,0,
  104824. 0x5c,0x3f,0x66,0xcb,
  104825. 17,
  104826. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  104827. 255,255,90,0};
  104828. /* large initial packet */
  104829. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104830. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104831. 0x01,0x02,0x03,0x04,0,0,0,0,
  104832. 0x01,0x27,0x31,0xaa,
  104833. 18,
  104834. 255,255,255,255,255,255,255,255,
  104835. 255,255,255,255,255,255,255,255,255,10};
  104836. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104837. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104838. 0x01,0x02,0x03,0x04,1,0,0,0,
  104839. 0x7f,0x4e,0x8a,0xd2,
  104840. 4,
  104841. 255,4,255,0};
  104842. /* continuing packet test */
  104843. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104844. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104845. 0x01,0x02,0x03,0x04,0,0,0,0,
  104846. 0xff,0x7b,0x23,0x17,
  104847. 1,
  104848. 0};
  104849. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104850. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104851. 0x01,0x02,0x03,0x04,1,0,0,0,
  104852. 0x54,0x05,0x51,0xc8,
  104853. 17,
  104854. 255,255,255,255,255,255,255,255,
  104855. 255,255,255,255,255,255,255,255,255};
  104856. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104857. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  104858. 0x01,0x02,0x03,0x04,2,0,0,0,
  104859. 0xc8,0xc3,0xcb,0xed,
  104860. 5,
  104861. 10,255,4,255,0};
  104862. /* page with the 255 segment limit */
  104863. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104864. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104865. 0x01,0x02,0x03,0x04,0,0,0,0,
  104866. 0xff,0x7b,0x23,0x17,
  104867. 1,
  104868. 0};
  104869. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104870. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  104871. 0x01,0x02,0x03,0x04,1,0,0,0,
  104872. 0xed,0x2a,0x2e,0xa7,
  104873. 255,
  104874. 10,10,10,10,10,10,10,10,
  104875. 10,10,10,10,10,10,10,10,
  104876. 10,10,10,10,10,10,10,10,
  104877. 10,10,10,10,10,10,10,10,
  104878. 10,10,10,10,10,10,10,10,
  104879. 10,10,10,10,10,10,10,10,
  104880. 10,10,10,10,10,10,10,10,
  104881. 10,10,10,10,10,10,10,10,
  104882. 10,10,10,10,10,10,10,10,
  104883. 10,10,10,10,10,10,10,10,
  104884. 10,10,10,10,10,10,10,10,
  104885. 10,10,10,10,10,10,10,10,
  104886. 10,10,10,10,10,10,10,10,
  104887. 10,10,10,10,10,10,10,10,
  104888. 10,10,10,10,10,10,10,10,
  104889. 10,10,10,10,10,10,10,10,
  104890. 10,10,10,10,10,10,10,10,
  104891. 10,10,10,10,10,10,10,10,
  104892. 10,10,10,10,10,10,10,10,
  104893. 10,10,10,10,10,10,10,10,
  104894. 10,10,10,10,10,10,10,10,
  104895. 10,10,10,10,10,10,10,10,
  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};
  104906. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  104907. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  104908. 0x01,0x02,0x03,0x04,2,0,0,0,
  104909. 0x6c,0x3b,0x82,0x3d,
  104910. 1,
  104911. 50};
  104912. /* packet that overspans over an entire page */
  104913. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104914. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104915. 0x01,0x02,0x03,0x04,0,0,0,0,
  104916. 0xff,0x7b,0x23,0x17,
  104917. 1,
  104918. 0};
  104919. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104920. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104921. 0x01,0x02,0x03,0x04,1,0,0,0,
  104922. 0x3c,0xd9,0x4d,0x3f,
  104923. 17,
  104924. 100,255,255,255,255,255,255,255,255,
  104925. 255,255,255,255,255,255,255,255};
  104926. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  104927. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  104928. 0x01,0x02,0x03,0x04,2,0,0,0,
  104929. 0x01,0xd2,0xe5,0xe5,
  104930. 17,
  104931. 255,255,255,255,255,255,255,255,
  104932. 255,255,255,255,255,255,255,255,255};
  104933. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104934. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  104935. 0x01,0x02,0x03,0x04,3,0,0,0,
  104936. 0xef,0xdd,0x88,0xde,
  104937. 7,
  104938. 255,255,75,255,4,255,0};
  104939. /* packet that overspans over an entire page */
  104940. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  104941. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  104942. 0x01,0x02,0x03,0x04,0,0,0,0,
  104943. 0xff,0x7b,0x23,0x17,
  104944. 1,
  104945. 0};
  104946. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  104947. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  104948. 0x01,0x02,0x03,0x04,1,0,0,0,
  104949. 0x3c,0xd9,0x4d,0x3f,
  104950. 17,
  104951. 100,255,255,255,255,255,255,255,255,
  104952. 255,255,255,255,255,255,255,255};
  104953. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  104954. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  104955. 0x01,0x02,0x03,0x04,2,0,0,0,
  104956. 0xd4,0xe0,0x60,0xe5,
  104957. 1,0};
  104958. void test_pack(const int *pl, const int **headers, int byteskip,
  104959. int pageskip, int packetskip){
  104960. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  104961. long inptr=0;
  104962. long outptr=0;
  104963. long deptr=0;
  104964. long depacket=0;
  104965. long granule_pos=7,pageno=0;
  104966. int i,j,packets,pageout=pageskip;
  104967. int eosflag=0;
  104968. int bosflag=0;
  104969. int byteskipcount=0;
  104970. ogg_stream_reset(&os_en);
  104971. ogg_stream_reset(&os_de);
  104972. ogg_sync_reset(&oy);
  104973. for(packets=0;packets<packetskip;packets++)
  104974. depacket+=pl[packets];
  104975. for(packets=0;;packets++)if(pl[packets]==-1)break;
  104976. for(i=0;i<packets;i++){
  104977. /* construct a test packet */
  104978. ogg_packet op;
  104979. int len=pl[i];
  104980. op.packet=data+inptr;
  104981. op.bytes=len;
  104982. op.e_o_s=(pl[i+1]<0?1:0);
  104983. op.granulepos=granule_pos;
  104984. granule_pos+=1024;
  104985. for(j=0;j<len;j++)data[inptr++]=i+j;
  104986. /* submit the test packet */
  104987. ogg_stream_packetin(&os_en,&op);
  104988. /* retrieve any finished pages */
  104989. {
  104990. ogg_page og;
  104991. while(ogg_stream_pageout(&os_en,&og)){
  104992. /* We have a page. Check it carefully */
  104993. fprintf(stderr,"%ld, ",pageno);
  104994. if(headers[pageno]==NULL){
  104995. fprintf(stderr,"coded too many pages!\n");
  104996. exit(1);
  104997. }
  104998. check_page(data+outptr,headers[pageno],&og);
  104999. outptr+=og.body_len;
  105000. pageno++;
  105001. if(pageskip){
  105002. bosflag=1;
  105003. pageskip--;
  105004. deptr+=og.body_len;
  105005. }
  105006. /* have a complete page; submit it to sync/decode */
  105007. {
  105008. ogg_page og_de;
  105009. ogg_packet op_de,op_de2;
  105010. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  105011. char *next=buf;
  105012. byteskipcount+=og.header_len;
  105013. if(byteskipcount>byteskip){
  105014. memcpy(next,og.header,byteskipcount-byteskip);
  105015. next+=byteskipcount-byteskip;
  105016. byteskipcount=byteskip;
  105017. }
  105018. byteskipcount+=og.body_len;
  105019. if(byteskipcount>byteskip){
  105020. memcpy(next,og.body,byteskipcount-byteskip);
  105021. next+=byteskipcount-byteskip;
  105022. byteskipcount=byteskip;
  105023. }
  105024. ogg_sync_wrote(&oy,next-buf);
  105025. while(1){
  105026. int ret=ogg_sync_pageout(&oy,&og_de);
  105027. if(ret==0)break;
  105028. if(ret<0)continue;
  105029. /* got a page. Happy happy. Verify that it's good. */
  105030. fprintf(stderr,"(%ld), ",pageout);
  105031. check_page(data+deptr,headers[pageout],&og_de);
  105032. deptr+=og_de.body_len;
  105033. pageout++;
  105034. /* submit it to deconstitution */
  105035. ogg_stream_pagein(&os_de,&og_de);
  105036. /* packets out? */
  105037. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  105038. ogg_stream_packetpeek(&os_de,NULL);
  105039. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  105040. /* verify peek and out match */
  105041. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  105042. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  105043. depacket);
  105044. exit(1);
  105045. }
  105046. /* verify the packet! */
  105047. /* check data */
  105048. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  105049. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  105050. depacket);
  105051. exit(1);
  105052. }
  105053. /* check bos flag */
  105054. if(bosflag==0 && op_de.b_o_s==0){
  105055. fprintf(stderr,"b_o_s flag not set on packet!\n");
  105056. exit(1);
  105057. }
  105058. if(bosflag && op_de.b_o_s){
  105059. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  105060. exit(1);
  105061. }
  105062. bosflag=1;
  105063. depacket+=op_de.bytes;
  105064. /* check eos flag */
  105065. if(eosflag){
  105066. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  105067. exit(1);
  105068. }
  105069. if(op_de.e_o_s)eosflag=1;
  105070. /* check granulepos flag */
  105071. if(op_de.granulepos!=-1){
  105072. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  105073. }
  105074. }
  105075. }
  105076. }
  105077. }
  105078. }
  105079. }
  105080. _ogg_free(data);
  105081. if(headers[pageno]!=NULL){
  105082. fprintf(stderr,"did not write last page!\n");
  105083. exit(1);
  105084. }
  105085. if(headers[pageout]!=NULL){
  105086. fprintf(stderr,"did not decode last page!\n");
  105087. exit(1);
  105088. }
  105089. if(inptr!=outptr){
  105090. fprintf(stderr,"encoded page data incomplete!\n");
  105091. exit(1);
  105092. }
  105093. if(inptr!=deptr){
  105094. fprintf(stderr,"decoded page data incomplete!\n");
  105095. exit(1);
  105096. }
  105097. if(inptr!=depacket){
  105098. fprintf(stderr,"decoded packet data incomplete!\n");
  105099. exit(1);
  105100. }
  105101. if(!eosflag){
  105102. fprintf(stderr,"Never got a packet with EOS set!\n");
  105103. exit(1);
  105104. }
  105105. fprintf(stderr,"ok.\n");
  105106. }
  105107. int main(void){
  105108. ogg_stream_init(&os_en,0x04030201);
  105109. ogg_stream_init(&os_de,0x04030201);
  105110. ogg_sync_init(&oy);
  105111. /* Exercise each code path in the framing code. Also verify that
  105112. the checksums are working. */
  105113. {
  105114. /* 17 only */
  105115. const int packets[]={17, -1};
  105116. const int *headret[]={head1_0,NULL};
  105117. fprintf(stderr,"testing single page encoding... ");
  105118. test_pack(packets,headret,0,0,0);
  105119. }
  105120. {
  105121. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  105122. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  105123. const int *headret[]={head1_1,head2_1,NULL};
  105124. fprintf(stderr,"testing basic page encoding... ");
  105125. test_pack(packets,headret,0,0,0);
  105126. }
  105127. {
  105128. /* nil packets; beginning,middle,end */
  105129. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  105130. const int *headret[]={head1_2,head2_2,NULL};
  105131. fprintf(stderr,"testing basic nil packets... ");
  105132. test_pack(packets,headret,0,0,0);
  105133. }
  105134. {
  105135. /* large initial packet */
  105136. const int packets[]={4345,259,255,-1};
  105137. const int *headret[]={head1_3,head2_3,NULL};
  105138. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  105139. test_pack(packets,headret,0,0,0);
  105140. }
  105141. {
  105142. /* continuing packet test */
  105143. const int packets[]={0,4345,259,255,-1};
  105144. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  105145. fprintf(stderr,"testing single packet page span... ");
  105146. test_pack(packets,headret,0,0,0);
  105147. }
  105148. /* page with the 255 segment limit */
  105149. {
  105150. const int packets[]={0,10,10,10,10,10,10,10,10,
  105151. 10,10,10,10,10,10,10,10,
  105152. 10,10,10,10,10,10,10,10,
  105153. 10,10,10,10,10,10,10,10,
  105154. 10,10,10,10,10,10,10,10,
  105155. 10,10,10,10,10,10,10,10,
  105156. 10,10,10,10,10,10,10,10,
  105157. 10,10,10,10,10,10,10,10,
  105158. 10,10,10,10,10,10,10,10,
  105159. 10,10,10,10,10,10,10,10,
  105160. 10,10,10,10,10,10,10,10,
  105161. 10,10,10,10,10,10,10,10,
  105162. 10,10,10,10,10,10,10,10,
  105163. 10,10,10,10,10,10,10,10,
  105164. 10,10,10,10,10,10,10,10,
  105165. 10,10,10,10,10,10,10,10,
  105166. 10,10,10,10,10,10,10,10,
  105167. 10,10,10,10,10,10,10,10,
  105168. 10,10,10,10,10,10,10,10,
  105169. 10,10,10,10,10,10,10,10,
  105170. 10,10,10,10,10,10,10,10,
  105171. 10,10,10,10,10,10,10,10,
  105172. 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,50,-1};
  105182. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  105183. fprintf(stderr,"testing max packet segments... ");
  105184. test_pack(packets,headret,0,0,0);
  105185. }
  105186. {
  105187. /* packet that overspans over an entire page */
  105188. const int packets[]={0,100,9000,259,255,-1};
  105189. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105190. fprintf(stderr,"testing very large packets... ");
  105191. test_pack(packets,headret,0,0,0);
  105192. }
  105193. {
  105194. /* test for the libogg 1.1.1 resync in large continuation bug
  105195. found by Josh Coalson) */
  105196. const int packets[]={0,100,9000,259,255,-1};
  105197. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  105198. fprintf(stderr,"testing continuation resync in very large packets... ");
  105199. test_pack(packets,headret,100,2,3);
  105200. }
  105201. {
  105202. /* term only page. why not? */
  105203. const int packets[]={0,100,4080,-1};
  105204. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  105205. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  105206. test_pack(packets,headret,0,0,0);
  105207. }
  105208. {
  105209. /* build a bunch of pages for testing */
  105210. unsigned char *data=_ogg_malloc(1024*1024);
  105211. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  105212. int inptr=0,i,j;
  105213. ogg_page og[5];
  105214. ogg_stream_reset(&os_en);
  105215. for(i=0;pl[i]!=-1;i++){
  105216. ogg_packet op;
  105217. int len=pl[i];
  105218. op.packet=data+inptr;
  105219. op.bytes=len;
  105220. op.e_o_s=(pl[i+1]<0?1:0);
  105221. op.granulepos=(i+1)*1000;
  105222. for(j=0;j<len;j++)data[inptr++]=i+j;
  105223. ogg_stream_packetin(&os_en,&op);
  105224. }
  105225. _ogg_free(data);
  105226. /* retrieve finished pages */
  105227. for(i=0;i<5;i++){
  105228. if(ogg_stream_pageout(&os_en,&og[i])==0){
  105229. fprintf(stderr,"Too few pages output building sync tests!\n");
  105230. exit(1);
  105231. }
  105232. copy_page(&og[i]);
  105233. }
  105234. /* Test lost pages on pagein/packetout: no rollback */
  105235. {
  105236. ogg_page temp;
  105237. ogg_packet test;
  105238. fprintf(stderr,"Testing loss of pages... ");
  105239. ogg_sync_reset(&oy);
  105240. ogg_stream_reset(&os_de);
  105241. for(i=0;i<5;i++){
  105242. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105243. og[i].header_len);
  105244. ogg_sync_wrote(&oy,og[i].header_len);
  105245. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105246. ogg_sync_wrote(&oy,og[i].body_len);
  105247. }
  105248. ogg_sync_pageout(&oy,&temp);
  105249. ogg_stream_pagein(&os_de,&temp);
  105250. ogg_sync_pageout(&oy,&temp);
  105251. ogg_stream_pagein(&os_de,&temp);
  105252. ogg_sync_pageout(&oy,&temp);
  105253. /* skip */
  105254. ogg_sync_pageout(&oy,&temp);
  105255. ogg_stream_pagein(&os_de,&temp);
  105256. /* do we get the expected results/packets? */
  105257. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105258. checkpacket(&test,0,0,0);
  105259. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105260. checkpacket(&test,100,1,-1);
  105261. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105262. checkpacket(&test,4079,2,3000);
  105263. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105264. fprintf(stderr,"Error: loss of page did not return error\n");
  105265. exit(1);
  105266. }
  105267. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105268. checkpacket(&test,76,5,-1);
  105269. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105270. checkpacket(&test,34,6,-1);
  105271. fprintf(stderr,"ok.\n");
  105272. }
  105273. /* Test lost pages on pagein/packetout: rollback with continuation */
  105274. {
  105275. ogg_page temp;
  105276. ogg_packet test;
  105277. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  105278. ogg_sync_reset(&oy);
  105279. ogg_stream_reset(&os_de);
  105280. for(i=0;i<5;i++){
  105281. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  105282. og[i].header_len);
  105283. ogg_sync_wrote(&oy,og[i].header_len);
  105284. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  105285. ogg_sync_wrote(&oy,og[i].body_len);
  105286. }
  105287. ogg_sync_pageout(&oy,&temp);
  105288. ogg_stream_pagein(&os_de,&temp);
  105289. ogg_sync_pageout(&oy,&temp);
  105290. ogg_stream_pagein(&os_de,&temp);
  105291. ogg_sync_pageout(&oy,&temp);
  105292. ogg_stream_pagein(&os_de,&temp);
  105293. ogg_sync_pageout(&oy,&temp);
  105294. /* skip */
  105295. ogg_sync_pageout(&oy,&temp);
  105296. ogg_stream_pagein(&os_de,&temp);
  105297. /* do we get the expected results/packets? */
  105298. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105299. checkpacket(&test,0,0,0);
  105300. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105301. checkpacket(&test,100,1,-1);
  105302. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105303. checkpacket(&test,4079,2,3000);
  105304. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105305. checkpacket(&test,2956,3,4000);
  105306. if(ogg_stream_packetout(&os_de,&test)!=-1){
  105307. fprintf(stderr,"Error: loss of page did not return error\n");
  105308. exit(1);
  105309. }
  105310. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  105311. checkpacket(&test,300,13,14000);
  105312. fprintf(stderr,"ok.\n");
  105313. }
  105314. /* the rest only test sync */
  105315. {
  105316. ogg_page og_de;
  105317. /* Test fractional page inputs: incomplete capture */
  105318. fprintf(stderr,"Testing sync on partial inputs... ");
  105319. ogg_sync_reset(&oy);
  105320. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105321. 3);
  105322. ogg_sync_wrote(&oy,3);
  105323. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105324. /* Test fractional page inputs: incomplete fixed header */
  105325. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  105326. 20);
  105327. ogg_sync_wrote(&oy,20);
  105328. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105329. /* Test fractional page inputs: incomplete header */
  105330. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  105331. 5);
  105332. ogg_sync_wrote(&oy,5);
  105333. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105334. /* Test fractional page inputs: incomplete body */
  105335. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  105336. og[1].header_len-28);
  105337. ogg_sync_wrote(&oy,og[1].header_len-28);
  105338. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105339. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  105340. ogg_sync_wrote(&oy,1000);
  105341. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105342. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  105343. og[1].body_len-1000);
  105344. ogg_sync_wrote(&oy,og[1].body_len-1000);
  105345. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105346. fprintf(stderr,"ok.\n");
  105347. }
  105348. /* Test fractional page inputs: page + incomplete capture */
  105349. {
  105350. ogg_page og_de;
  105351. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  105352. ogg_sync_reset(&oy);
  105353. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105354. og[1].header_len);
  105355. ogg_sync_wrote(&oy,og[1].header_len);
  105356. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105357. og[1].body_len);
  105358. ogg_sync_wrote(&oy,og[1].body_len);
  105359. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105360. 20);
  105361. ogg_sync_wrote(&oy,20);
  105362. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105363. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105364. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  105365. og[1].header_len-20);
  105366. ogg_sync_wrote(&oy,og[1].header_len-20);
  105367. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105368. og[1].body_len);
  105369. ogg_sync_wrote(&oy,og[1].body_len);
  105370. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105371. fprintf(stderr,"ok.\n");
  105372. }
  105373. /* Test recapture: garbage + page */
  105374. {
  105375. ogg_page og_de;
  105376. fprintf(stderr,"Testing search for capture... ");
  105377. ogg_sync_reset(&oy);
  105378. /* 'garbage' */
  105379. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105380. og[1].body_len);
  105381. ogg_sync_wrote(&oy,og[1].body_len);
  105382. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105383. og[1].header_len);
  105384. ogg_sync_wrote(&oy,og[1].header_len);
  105385. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105386. og[1].body_len);
  105387. ogg_sync_wrote(&oy,og[1].body_len);
  105388. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105389. 20);
  105390. ogg_sync_wrote(&oy,20);
  105391. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105392. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105393. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105394. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  105395. og[2].header_len-20);
  105396. ogg_sync_wrote(&oy,og[2].header_len-20);
  105397. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105398. og[2].body_len);
  105399. ogg_sync_wrote(&oy,og[2].body_len);
  105400. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105401. fprintf(stderr,"ok.\n");
  105402. }
  105403. /* Test recapture: page + garbage + page */
  105404. {
  105405. ogg_page og_de;
  105406. fprintf(stderr,"Testing recapture... ");
  105407. ogg_sync_reset(&oy);
  105408. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  105409. og[1].header_len);
  105410. ogg_sync_wrote(&oy,og[1].header_len);
  105411. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  105412. og[1].body_len);
  105413. ogg_sync_wrote(&oy,og[1].body_len);
  105414. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105415. og[2].header_len);
  105416. ogg_sync_wrote(&oy,og[2].header_len);
  105417. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  105418. og[2].header_len);
  105419. ogg_sync_wrote(&oy,og[2].header_len);
  105420. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105421. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  105422. og[2].body_len-5);
  105423. ogg_sync_wrote(&oy,og[2].body_len-5);
  105424. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  105425. og[3].header_len);
  105426. ogg_sync_wrote(&oy,og[3].header_len);
  105427. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  105428. og[3].body_len);
  105429. ogg_sync_wrote(&oy,og[3].body_len);
  105430. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  105431. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  105432. fprintf(stderr,"ok.\n");
  105433. }
  105434. /* Free page data that was previously copied */
  105435. {
  105436. for(i=0;i<5;i++){
  105437. free_page(&og[i]);
  105438. }
  105439. }
  105440. }
  105441. return(0);
  105442. }
  105443. #endif
  105444. #endif
  105445. /********* End of inlined file: framing.c *********/
  105446. /********* Start of inlined file: analysis.c *********/
  105447. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105448. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105449. // tasks..
  105450. #ifdef _MSC_VER
  105451. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105452. #endif
  105453. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105454. #if JUCE_USE_OGGVORBIS
  105455. #include <stdio.h>
  105456. #include <string.h>
  105457. #include <math.h>
  105458. /********* Start of inlined file: codec_internal.h *********/
  105459. #ifndef _V_CODECI_H_
  105460. #define _V_CODECI_H_
  105461. /********* Start of inlined file: envelope.h *********/
  105462. #ifndef _V_ENVELOPE_
  105463. #define _V_ENVELOPE_
  105464. /********* Start of inlined file: mdct.h *********/
  105465. #ifndef _OGG_mdct_H_
  105466. #define _OGG_mdct_H_
  105467. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  105468. #ifdef MDCT_INTEGERIZED
  105469. #define DATA_TYPE int
  105470. #define REG_TYPE register int
  105471. #define TRIGBITS 14
  105472. #define cPI3_8 6270
  105473. #define cPI2_8 11585
  105474. #define cPI1_8 15137
  105475. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  105476. #define MULT_NORM(x) ((x)>>TRIGBITS)
  105477. #define HALVE(x) ((x)>>1)
  105478. #else
  105479. #define DATA_TYPE float
  105480. #define REG_TYPE float
  105481. #define cPI3_8 .38268343236508977175F
  105482. #define cPI2_8 .70710678118654752441F
  105483. #define cPI1_8 .92387953251128675613F
  105484. #define FLOAT_CONV(x) (x)
  105485. #define MULT_NORM(x) (x)
  105486. #define HALVE(x) ((x)*.5f)
  105487. #endif
  105488. typedef struct {
  105489. int n;
  105490. int log2n;
  105491. DATA_TYPE *trig;
  105492. int *bitrev;
  105493. DATA_TYPE scale;
  105494. } mdct_lookup;
  105495. extern void mdct_init(mdct_lookup *lookup,int n);
  105496. extern void mdct_clear(mdct_lookup *l);
  105497. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105498. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  105499. #endif
  105500. /********* End of inlined file: mdct.h *********/
  105501. #define VE_PRE 16
  105502. #define VE_WIN 4
  105503. #define VE_POST 2
  105504. #define VE_AMP (VE_PRE+VE_POST-1)
  105505. #define VE_BANDS 7
  105506. #define VE_NEARDC 15
  105507. #define VE_MINSTRETCH 2 /* a bit less than short block */
  105508. #define VE_MAXSTRETCH 12 /* one-third full block */
  105509. typedef struct {
  105510. float ampbuf[VE_AMP];
  105511. int ampptr;
  105512. float nearDC[VE_NEARDC];
  105513. float nearDC_acc;
  105514. float nearDC_partialacc;
  105515. int nearptr;
  105516. } envelope_filter_state;
  105517. typedef struct {
  105518. int begin;
  105519. int end;
  105520. float *window;
  105521. float total;
  105522. } envelope_band;
  105523. typedef struct {
  105524. int ch;
  105525. int winlength;
  105526. int searchstep;
  105527. float minenergy;
  105528. mdct_lookup mdct;
  105529. float *mdct_win;
  105530. envelope_band band[VE_BANDS];
  105531. envelope_filter_state *filter;
  105532. int stretch;
  105533. int *mark;
  105534. long storage;
  105535. long current;
  105536. long curmark;
  105537. long cursor;
  105538. } envelope_lookup;
  105539. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  105540. extern void _ve_envelope_clear(envelope_lookup *e);
  105541. extern long _ve_envelope_search(vorbis_dsp_state *v);
  105542. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  105543. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  105544. #endif
  105545. /********* End of inlined file: envelope.h *********/
  105546. /********* Start of inlined file: codebook.h *********/
  105547. #ifndef _V_CODEBOOK_H_
  105548. #define _V_CODEBOOK_H_
  105549. /* This structure encapsulates huffman and VQ style encoding books; it
  105550. doesn't do anything specific to either.
  105551. valuelist/quantlist are nonNULL (and q_* significant) only if
  105552. there's entry->value mapping to be done.
  105553. If encode-side mapping must be done (and thus the entry needs to be
  105554. hunted), the auxiliary encode pointer will point to a decision
  105555. tree. This is true of both VQ and huffman, but is mostly useful
  105556. with VQ.
  105557. */
  105558. typedef struct static_codebook{
  105559. long dim; /* codebook dimensions (elements per vector) */
  105560. long entries; /* codebook entries */
  105561. long *lengthlist; /* codeword lengths in bits */
  105562. /* mapping ***************************************************************/
  105563. int maptype; /* 0=none
  105564. 1=implicitly populated values from map column
  105565. 2=listed arbitrary values */
  105566. /* The below does a linear, single monotonic sequence mapping. */
  105567. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  105568. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  105569. int q_quant; /* bits: 0 < quant <= 16 */
  105570. int q_sequencep; /* bitflag */
  105571. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  105572. map == 2: list of dim*entries quantized entry vals
  105573. */
  105574. /* encode helpers ********************************************************/
  105575. struct encode_aux_nearestmatch *nearest_tree;
  105576. struct encode_aux_threshmatch *thresh_tree;
  105577. struct encode_aux_pigeonhole *pigeon_tree;
  105578. int allocedp;
  105579. } static_codebook;
  105580. /* this structures an arbitrary trained book to quickly find the
  105581. nearest cell match */
  105582. typedef struct encode_aux_nearestmatch{
  105583. /* pre-calculated partitioning tree */
  105584. long *ptr0;
  105585. long *ptr1;
  105586. long *p; /* decision points (each is an entry) */
  105587. long *q; /* decision points (each is an entry) */
  105588. long aux; /* number of tree entries */
  105589. long alloc;
  105590. } encode_aux_nearestmatch;
  105591. /* assumes a maptype of 1; encode side only, so that's OK */
  105592. typedef struct encode_aux_threshmatch{
  105593. float *quantthresh;
  105594. long *quantmap;
  105595. int quantvals;
  105596. int threshvals;
  105597. } encode_aux_threshmatch;
  105598. typedef struct encode_aux_pigeonhole{
  105599. float min;
  105600. float del;
  105601. int mapentries;
  105602. int quantvals;
  105603. long *pigeonmap;
  105604. long fittotal;
  105605. long *fitlist;
  105606. long *fitmap;
  105607. long *fitlength;
  105608. } encode_aux_pigeonhole;
  105609. typedef struct codebook{
  105610. long dim; /* codebook dimensions (elements per vector) */
  105611. long entries; /* codebook entries */
  105612. long used_entries; /* populated codebook entries */
  105613. const static_codebook *c;
  105614. /* for encode, the below are entry-ordered, fully populated */
  105615. /* for decode, the below are ordered by bitreversed codeword and only
  105616. used entries are populated */
  105617. float *valuelist; /* list of dim*entries actual entry values */
  105618. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  105619. int *dec_index; /* only used if sparseness collapsed */
  105620. char *dec_codelengths;
  105621. ogg_uint32_t *dec_firsttable;
  105622. int dec_firsttablen;
  105623. int dec_maxlength;
  105624. } codebook;
  105625. extern void vorbis_staticbook_clear(static_codebook *b);
  105626. extern void vorbis_staticbook_destroy(static_codebook *b);
  105627. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  105628. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  105629. extern void vorbis_book_clear(codebook *b);
  105630. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  105631. extern float *_book_logdist(const static_codebook *b,float *vals);
  105632. extern float _float32_unpack(long val);
  105633. extern long _float32_pack(float val);
  105634. extern int _best(codebook *book, float *a, int step);
  105635. extern int _ilog(unsigned int v);
  105636. extern long _book_maptype1_quantvals(const static_codebook *b);
  105637. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  105638. extern long vorbis_book_codeword(codebook *book,int entry);
  105639. extern long vorbis_book_codelen(codebook *book,int entry);
  105640. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  105641. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  105642. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  105643. extern int vorbis_book_errorv(codebook *book, float *a);
  105644. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  105645. oggpack_buffer *b);
  105646. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  105647. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  105648. oggpack_buffer *b,int n);
  105649. extern long vorbis_book_decodev_set(codebook *book, float *a,
  105650. oggpack_buffer *b,int n);
  105651. extern long vorbis_book_decodev_add(codebook *book, float *a,
  105652. oggpack_buffer *b,int n);
  105653. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  105654. long off,int ch,
  105655. oggpack_buffer *b,int n);
  105656. #endif
  105657. /********* End of inlined file: codebook.h *********/
  105658. #define BLOCKTYPE_IMPULSE 0
  105659. #define BLOCKTYPE_PADDING 1
  105660. #define BLOCKTYPE_TRANSITION 0
  105661. #define BLOCKTYPE_LONG 1
  105662. #define PACKETBLOBS 15
  105663. typedef struct vorbis_block_internal{
  105664. float **pcmdelay; /* this is a pointer into local storage */
  105665. float ampmax;
  105666. int blocktype;
  105667. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  105668. blob [PACKETBLOBS/2] points to
  105669. the oggpack_buffer in the
  105670. main vorbis_block */
  105671. } vorbis_block_internal;
  105672. typedef void vorbis_look_floor;
  105673. typedef void vorbis_look_residue;
  105674. typedef void vorbis_look_transform;
  105675. /* mode ************************************************************/
  105676. typedef struct {
  105677. int blockflag;
  105678. int windowtype;
  105679. int transformtype;
  105680. int mapping;
  105681. } vorbis_info_mode;
  105682. typedef void vorbis_info_floor;
  105683. typedef void vorbis_info_residue;
  105684. typedef void vorbis_info_mapping;
  105685. /********* Start of inlined file: psy.h *********/
  105686. #ifndef _V_PSY_H_
  105687. #define _V_PSY_H_
  105688. /********* Start of inlined file: smallft.h *********/
  105689. #ifndef _V_SMFT_H_
  105690. #define _V_SMFT_H_
  105691. typedef struct {
  105692. int n;
  105693. float *trigcache;
  105694. int *splitcache;
  105695. } drft_lookup;
  105696. extern void drft_forward(drft_lookup *l,float *data);
  105697. extern void drft_backward(drft_lookup *l,float *data);
  105698. extern void drft_init(drft_lookup *l,int n);
  105699. extern void drft_clear(drft_lookup *l);
  105700. #endif
  105701. /********* End of inlined file: smallft.h *********/
  105702. /********* Start of inlined file: backends.h *********/
  105703. /* this is exposed up here because we need it for static modes.
  105704. Lookups for each backend aren't exposed because there's no reason
  105705. to do so */
  105706. #ifndef _vorbis_backend_h_
  105707. #define _vorbis_backend_h_
  105708. /* this would all be simpler/shorter with templates, but.... */
  105709. /* Floor backend generic *****************************************/
  105710. typedef struct{
  105711. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  105712. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  105713. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  105714. void (*free_info) (vorbis_info_floor *);
  105715. void (*free_look) (vorbis_look_floor *);
  105716. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  105717. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  105718. void *buffer,float *);
  105719. } vorbis_func_floor;
  105720. typedef struct{
  105721. int order;
  105722. long rate;
  105723. long barkmap;
  105724. int ampbits;
  105725. int ampdB;
  105726. int numbooks; /* <= 16 */
  105727. int books[16];
  105728. float lessthan; /* encode-only config setting hacks for libvorbis */
  105729. float greaterthan; /* encode-only config setting hacks for libvorbis */
  105730. } vorbis_info_floor0;
  105731. #define VIF_POSIT 63
  105732. #define VIF_CLASS 16
  105733. #define VIF_PARTS 31
  105734. typedef struct{
  105735. int partitions; /* 0 to 31 */
  105736. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  105737. int class_dim[VIF_CLASS]; /* 1 to 8 */
  105738. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  105739. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  105740. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  105741. int mult; /* 1 2 3 or 4 */
  105742. int postlist[VIF_POSIT+2]; /* first two implicit */
  105743. /* encode side analysis parameters */
  105744. float maxover;
  105745. float maxunder;
  105746. float maxerr;
  105747. float twofitweight;
  105748. float twofitatten;
  105749. int n;
  105750. } vorbis_info_floor1;
  105751. /* Residue backend generic *****************************************/
  105752. typedef struct{
  105753. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  105754. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  105755. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  105756. vorbis_info_residue *);
  105757. void (*free_info) (vorbis_info_residue *);
  105758. void (*free_look) (vorbis_look_residue *);
  105759. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  105760. float **,int *,int);
  105761. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  105762. vorbis_look_residue *,
  105763. float **,float **,int *,int,long **);
  105764. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  105765. float **,int *,int);
  105766. } vorbis_func_residue;
  105767. typedef struct vorbis_info_residue0{
  105768. /* block-partitioned VQ coded straight residue */
  105769. long begin;
  105770. long end;
  105771. /* first stage (lossless partitioning) */
  105772. int grouping; /* group n vectors per partition */
  105773. int partitions; /* possible codebooks for a partition */
  105774. int groupbook; /* huffbook for partitioning */
  105775. int secondstages[64]; /* expanded out to pointers in lookup */
  105776. int booklist[256]; /* list of second stage books */
  105777. float classmetric1[64];
  105778. float classmetric2[64];
  105779. } vorbis_info_residue0;
  105780. /* Mapping backend generic *****************************************/
  105781. typedef struct{
  105782. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  105783. oggpack_buffer *);
  105784. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  105785. void (*free_info) (vorbis_info_mapping *);
  105786. int (*forward) (struct vorbis_block *vb);
  105787. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  105788. } vorbis_func_mapping;
  105789. typedef struct vorbis_info_mapping0{
  105790. int submaps; /* <= 16 */
  105791. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  105792. int floorsubmap[16]; /* [mux] submap to floors */
  105793. int residuesubmap[16]; /* [mux] submap to residue */
  105794. int coupling_steps;
  105795. int coupling_mag[256];
  105796. int coupling_ang[256];
  105797. } vorbis_info_mapping0;
  105798. #endif
  105799. /********* End of inlined file: backends.h *********/
  105800. #ifndef EHMER_MAX
  105801. #define EHMER_MAX 56
  105802. #endif
  105803. /* psychoacoustic setup ********************************************/
  105804. #define P_BANDS 17 /* 62Hz to 16kHz */
  105805. #define P_LEVELS 8 /* 30dB to 100dB */
  105806. #define P_LEVEL_0 30. /* 30 dB */
  105807. #define P_NOISECURVES 3
  105808. #define NOISE_COMPAND_LEVELS 40
  105809. typedef struct vorbis_info_psy{
  105810. int blockflag;
  105811. float ath_adjatt;
  105812. float ath_maxatt;
  105813. float tone_masteratt[P_NOISECURVES];
  105814. float tone_centerboost;
  105815. float tone_decay;
  105816. float tone_abs_limit;
  105817. float toneatt[P_BANDS];
  105818. int noisemaskp;
  105819. float noisemaxsupp;
  105820. float noisewindowlo;
  105821. float noisewindowhi;
  105822. int noisewindowlomin;
  105823. int noisewindowhimin;
  105824. int noisewindowfixed;
  105825. float noiseoff[P_NOISECURVES][P_BANDS];
  105826. float noisecompand[NOISE_COMPAND_LEVELS];
  105827. float max_curve_dB;
  105828. int normal_channel_p;
  105829. int normal_point_p;
  105830. int normal_start;
  105831. int normal_partition;
  105832. double normal_thresh;
  105833. } vorbis_info_psy;
  105834. typedef struct{
  105835. int eighth_octave_lines;
  105836. /* for block long/short tuning; encode only */
  105837. float preecho_thresh[VE_BANDS];
  105838. float postecho_thresh[VE_BANDS];
  105839. float stretch_penalty;
  105840. float preecho_minenergy;
  105841. float ampmax_att_per_sec;
  105842. /* channel coupling config */
  105843. int coupling_pkHz[PACKETBLOBS];
  105844. int coupling_pointlimit[2][PACKETBLOBS];
  105845. int coupling_prepointamp[PACKETBLOBS];
  105846. int coupling_postpointamp[PACKETBLOBS];
  105847. int sliding_lowpass[2][PACKETBLOBS];
  105848. } vorbis_info_psy_global;
  105849. typedef struct {
  105850. float ampmax;
  105851. int channels;
  105852. vorbis_info_psy_global *gi;
  105853. int coupling_pointlimit[2][P_NOISECURVES];
  105854. } vorbis_look_psy_global;
  105855. typedef struct {
  105856. int n;
  105857. struct vorbis_info_psy *vi;
  105858. float ***tonecurves;
  105859. float **noiseoffset;
  105860. float *ath;
  105861. long *octave; /* in n.ocshift format */
  105862. long *bark;
  105863. long firstoc;
  105864. long shiftoc;
  105865. int eighth_octave_lines; /* power of two, please */
  105866. int total_octave_lines;
  105867. long rate; /* cache it */
  105868. float m_val; /* Masking compensation value */
  105869. } vorbis_look_psy;
  105870. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  105871. vorbis_info_psy_global *gi,int n,long rate);
  105872. extern void _vp_psy_clear(vorbis_look_psy *p);
  105873. extern void *_vi_psy_dup(void *source);
  105874. extern void _vi_psy_free(vorbis_info_psy *i);
  105875. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  105876. extern void _vp_remove_floor(vorbis_look_psy *p,
  105877. float *mdct,
  105878. int *icodedflr,
  105879. float *residue,
  105880. int sliding_lowpass);
  105881. extern void _vp_noisemask(vorbis_look_psy *p,
  105882. float *logmdct,
  105883. float *logmask);
  105884. extern void _vp_tonemask(vorbis_look_psy *p,
  105885. float *logfft,
  105886. float *logmask,
  105887. float global_specmax,
  105888. float local_specmax);
  105889. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  105890. float *noise,
  105891. float *tone,
  105892. int offset_select,
  105893. float *logmask,
  105894. float *mdct,
  105895. float *logmdct);
  105896. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  105897. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  105898. vorbis_info_psy_global *g,
  105899. vorbis_look_psy *p,
  105900. vorbis_info_mapping0 *vi,
  105901. float **mdct);
  105902. extern void _vp_couple(int blobno,
  105903. vorbis_info_psy_global *g,
  105904. vorbis_look_psy *p,
  105905. vorbis_info_mapping0 *vi,
  105906. float **res,
  105907. float **mag_memo,
  105908. int **mag_sort,
  105909. int **ifloor,
  105910. int *nonzero,
  105911. int sliding_lowpass);
  105912. extern void _vp_noise_normalize(vorbis_look_psy *p,
  105913. float *in,float *out,int *sortedindex);
  105914. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  105915. float *magnitudes,int *sortedindex);
  105916. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  105917. vorbis_look_psy *p,
  105918. vorbis_info_mapping0 *vi,
  105919. float **mags);
  105920. extern void hf_reduction(vorbis_info_psy_global *g,
  105921. vorbis_look_psy *p,
  105922. vorbis_info_mapping0 *vi,
  105923. float **mdct);
  105924. #endif
  105925. /********* End of inlined file: psy.h *********/
  105926. /********* Start of inlined file: bitrate.h *********/
  105927. #ifndef _V_BITRATE_H_
  105928. #define _V_BITRATE_H_
  105929. /********* Start of inlined file: os.h *********/
  105930. #ifndef _OS_H
  105931. #define _OS_H
  105932. /********************************************************************
  105933. * *
  105934. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  105935. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  105936. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  105937. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  105938. * *
  105939. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  105940. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  105941. * *
  105942. ********************************************************************
  105943. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  105944. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  105945. ********************************************************************/
  105946. #ifdef HAVE_CONFIG_H
  105947. #include "config.h"
  105948. #endif
  105949. #include <math.h>
  105950. /********* Start of inlined file: misc.h *********/
  105951. #ifndef _V_RANDOM_H_
  105952. #define _V_RANDOM_H_
  105953. extern int analysis_noisy;
  105954. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  105955. extern void _vorbis_block_ripcord(vorbis_block *vb);
  105956. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  105957. ogg_int64_t off);
  105958. #ifdef DEBUG_MALLOC
  105959. #define _VDBG_GRAPHFILE "malloc.m"
  105960. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  105961. extern void _VDBG_free(void *ptr,char *file,long line);
  105962. #ifndef MISC_C
  105963. #undef _ogg_malloc
  105964. #undef _ogg_calloc
  105965. #undef _ogg_realloc
  105966. #undef _ogg_free
  105967. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  105968. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  105969. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  105970. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  105971. #endif
  105972. #endif
  105973. #endif
  105974. /********* End of inlined file: misc.h *********/
  105975. #ifndef _V_IFDEFJAIL_H_
  105976. # define _V_IFDEFJAIL_H_
  105977. # ifdef __GNUC__
  105978. # define STIN static __inline__
  105979. # elif _WIN32
  105980. # define STIN static __inline
  105981. # else
  105982. # define STIN static
  105983. # endif
  105984. #ifdef DJGPP
  105985. # define rint(x) (floor((x)+0.5f))
  105986. #endif
  105987. #ifndef M_PI
  105988. # define M_PI (3.1415926536f)
  105989. #endif
  105990. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  105991. # include <malloc.h>
  105992. # define rint(x) (floor((x)+0.5f))
  105993. # define NO_FLOAT_MATH_LIB
  105994. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  105995. #endif
  105996. #if defined(__SYMBIAN32__) && defined(__WINS__)
  105997. void *_alloca(size_t size);
  105998. # define alloca _alloca
  105999. #endif
  106000. #ifndef FAST_HYPOT
  106001. # define FAST_HYPOT hypot
  106002. #endif
  106003. #endif
  106004. #ifdef HAVE_ALLOCA_H
  106005. # include <alloca.h>
  106006. #endif
  106007. #ifdef USE_MEMORY_H
  106008. # include <memory.h>
  106009. #endif
  106010. #ifndef min
  106011. # define min(x,y) ((x)>(y)?(y):(x))
  106012. #endif
  106013. #ifndef max
  106014. # define max(x,y) ((x)<(y)?(y):(x))
  106015. #endif
  106016. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  106017. # define VORBIS_FPU_CONTROL
  106018. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  106019. Because of encapsulation constraints (GCC can't see inside the asm
  106020. block and so we end up doing stupid things like a store/load that
  106021. is collectively a noop), we do it this way */
  106022. /* we must set up the fpu before this works!! */
  106023. typedef ogg_int16_t vorbis_fpu_control;
  106024. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106025. ogg_int16_t ret;
  106026. ogg_int16_t temp;
  106027. __asm__ __volatile__("fnstcw %0\n\t"
  106028. "movw %0,%%dx\n\t"
  106029. "orw $62463,%%dx\n\t"
  106030. "movw %%dx,%1\n\t"
  106031. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  106032. *fpu=ret;
  106033. }
  106034. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106035. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  106036. }
  106037. /* assumes the FPU is in round mode! */
  106038. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  106039. we get extra fst/fld to
  106040. truncate precision */
  106041. int i;
  106042. __asm__("fistl %0": "=m"(i) : "t"(f));
  106043. return(i);
  106044. }
  106045. #endif
  106046. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  106047. # define VORBIS_FPU_CONTROL
  106048. typedef ogg_int16_t vorbis_fpu_control;
  106049. static __inline int vorbis_ftoi(double f){
  106050. int i;
  106051. __asm{
  106052. fld f
  106053. fistp i
  106054. }
  106055. return i;
  106056. }
  106057. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  106058. }
  106059. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  106060. }
  106061. #endif
  106062. #ifndef VORBIS_FPU_CONTROL
  106063. typedef int vorbis_fpu_control;
  106064. static int vorbis_ftoi(double f){
  106065. return (int)(f+.5);
  106066. }
  106067. /* We don't have special code for this compiler/arch, so do it the slow way */
  106068. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  106069. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  106070. #endif
  106071. #endif /* _OS_H */
  106072. /********* End of inlined file: os.h *********/
  106073. /* encode side bitrate tracking */
  106074. typedef struct bitrate_manager_state {
  106075. int managed;
  106076. long avg_reservoir;
  106077. long minmax_reservoir;
  106078. long avg_bitsper;
  106079. long min_bitsper;
  106080. long max_bitsper;
  106081. long short_per_long;
  106082. double avgfloat;
  106083. vorbis_block *vb;
  106084. int choice;
  106085. } bitrate_manager_state;
  106086. typedef struct bitrate_manager_info{
  106087. long avg_rate;
  106088. long min_rate;
  106089. long max_rate;
  106090. long reservoir_bits;
  106091. double reservoir_bias;
  106092. double slew_damp;
  106093. } bitrate_manager_info;
  106094. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  106095. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  106096. extern int vorbis_bitrate_managed(vorbis_block *vb);
  106097. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  106098. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  106099. #endif
  106100. /********* End of inlined file: bitrate.h *********/
  106101. static int ilog(unsigned int v){
  106102. int ret=0;
  106103. while(v){
  106104. ret++;
  106105. v>>=1;
  106106. }
  106107. return(ret);
  106108. }
  106109. static int ilog2(unsigned int v){
  106110. int ret=0;
  106111. if(v)--v;
  106112. while(v){
  106113. ret++;
  106114. v>>=1;
  106115. }
  106116. return(ret);
  106117. }
  106118. typedef struct private_state {
  106119. /* local lookup storage */
  106120. envelope_lookup *ve; /* envelope lookup */
  106121. int window[2];
  106122. vorbis_look_transform **transform[2]; /* block, type */
  106123. drft_lookup fft_look[2];
  106124. int modebits;
  106125. vorbis_look_floor **flr;
  106126. vorbis_look_residue **residue;
  106127. vorbis_look_psy *psy;
  106128. vorbis_look_psy_global *psy_g_look;
  106129. /* local storage, only used on the encoding side. This way the
  106130. application does not need to worry about freeing some packets'
  106131. memory and not others'; packet storage is always tracked.
  106132. Cleared next call to a _dsp_ function */
  106133. unsigned char *header;
  106134. unsigned char *header1;
  106135. unsigned char *header2;
  106136. bitrate_manager_state bms;
  106137. ogg_int64_t sample_count;
  106138. } private_state;
  106139. /* codec_setup_info contains all the setup information specific to the
  106140. specific compression/decompression mode in progress (eg,
  106141. psychoacoustic settings, channel setup, options, codebook
  106142. etc).
  106143. *********************************************************************/
  106144. /********* Start of inlined file: highlevel.h *********/
  106145. typedef struct highlevel_byblocktype {
  106146. double tone_mask_setting;
  106147. double tone_peaklimit_setting;
  106148. double noise_bias_setting;
  106149. double noise_compand_setting;
  106150. } highlevel_byblocktype;
  106151. typedef struct highlevel_encode_setup {
  106152. void *setup;
  106153. int set_in_stone;
  106154. double base_setting;
  106155. double long_setting;
  106156. double short_setting;
  106157. double impulse_noisetune;
  106158. int managed;
  106159. long bitrate_min;
  106160. long bitrate_av;
  106161. double bitrate_av_damp;
  106162. long bitrate_max;
  106163. long bitrate_reservoir;
  106164. double bitrate_reservoir_bias;
  106165. int impulse_block_p;
  106166. int noise_normalize_p;
  106167. double stereo_point_setting;
  106168. double lowpass_kHz;
  106169. double ath_floating_dB;
  106170. double ath_absolute_dB;
  106171. double amplitude_track_dBpersec;
  106172. double trigger_setting;
  106173. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  106174. } highlevel_encode_setup;
  106175. /********* End of inlined file: highlevel.h *********/
  106176. typedef struct codec_setup_info {
  106177. /* Vorbis supports only short and long blocks, but allows the
  106178. encoder to choose the sizes */
  106179. long blocksizes[2];
  106180. /* modes are the primary means of supporting on-the-fly different
  106181. blocksizes, different channel mappings (LR or M/A),
  106182. different residue backends, etc. Each mode consists of a
  106183. blocksize flag and a mapping (along with the mapping setup */
  106184. int modes;
  106185. int maps;
  106186. int floors;
  106187. int residues;
  106188. int books;
  106189. int psys; /* encode only */
  106190. vorbis_info_mode *mode_param[64];
  106191. int map_type[64];
  106192. vorbis_info_mapping *map_param[64];
  106193. int floor_type[64];
  106194. vorbis_info_floor *floor_param[64];
  106195. int residue_type[64];
  106196. vorbis_info_residue *residue_param[64];
  106197. static_codebook *book_param[256];
  106198. codebook *fullbooks;
  106199. vorbis_info_psy *psy_param[4]; /* encode only */
  106200. vorbis_info_psy_global psy_g_param;
  106201. bitrate_manager_info bi;
  106202. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  106203. highly redundant structure, but
  106204. improves clarity of program flow. */
  106205. int halfrate_flag; /* painless downsample for decode */
  106206. } codec_setup_info;
  106207. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  106208. extern void _vp_global_free(vorbis_look_psy_global *look);
  106209. #endif
  106210. /********* End of inlined file: codec_internal.h *********/
  106211. /********* Start of inlined file: registry.h *********/
  106212. #ifndef _V_REG_H_
  106213. #define _V_REG_H_
  106214. #define VI_TRANSFORMB 1
  106215. #define VI_WINDOWB 1
  106216. #define VI_TIMEB 1
  106217. #define VI_FLOORB 2
  106218. #define VI_RESB 3
  106219. #define VI_MAPB 1
  106220. extern vorbis_func_floor *_floor_P[];
  106221. extern vorbis_func_residue *_residue_P[];
  106222. extern vorbis_func_mapping *_mapping_P[];
  106223. #endif
  106224. /********* End of inlined file: registry.h *********/
  106225. /********* Start of inlined file: scales.h *********/
  106226. #ifndef _V_SCALES_H_
  106227. #define _V_SCALES_H_
  106228. #include <math.h>
  106229. /* 20log10(x) */
  106230. #define VORBIS_IEEE_FLOAT32 1
  106231. #ifdef VORBIS_IEEE_FLOAT32
  106232. static float unitnorm(float x){
  106233. union {
  106234. ogg_uint32_t i;
  106235. float f;
  106236. } ix;
  106237. ix.f = x;
  106238. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  106239. return ix.f;
  106240. }
  106241. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  106242. static float todB(const float *x){
  106243. union {
  106244. ogg_uint32_t i;
  106245. float f;
  106246. } ix;
  106247. ix.f = *x;
  106248. ix.i = ix.i&0x7fffffff;
  106249. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  106250. }
  106251. #define todB_nn(x) todB(x)
  106252. #else
  106253. static float unitnorm(float x){
  106254. if(x<0)return(-1.f);
  106255. return(1.f);
  106256. }
  106257. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  106258. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  106259. #endif
  106260. #define fromdB(x) (exp((x)*.11512925f))
  106261. /* The bark scale equations are approximations, since the original
  106262. table was somewhat hand rolled. The below are chosen to have the
  106263. best possible fit to the rolled tables, thus their somewhat odd
  106264. appearance (these are more accurate and over a longer range than
  106265. the oft-quoted bark equations found in the texts I have). The
  106266. approximations are valid from 0 - 30kHz (nyquist) or so.
  106267. all f in Hz, z in Bark */
  106268. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  106269. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  106270. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  106271. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  106272. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  106273. 0.0 */
  106274. #define toOC(n) (log(n)*1.442695f-5.965784f)
  106275. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  106276. #endif
  106277. /********* End of inlined file: scales.h *********/
  106278. int analysis_noisy=1;
  106279. /* decides between modes, dispatches to the appropriate mapping. */
  106280. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  106281. int ret,i;
  106282. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106283. vb->glue_bits=0;
  106284. vb->time_bits=0;
  106285. vb->floor_bits=0;
  106286. vb->res_bits=0;
  106287. /* first things first. Make sure encode is ready */
  106288. for(i=0;i<PACKETBLOBS;i++)
  106289. oggpack_reset(vbi->packetblob[i]);
  106290. /* we only have one mapping type (0), and we let the mapping code
  106291. itself figure out what soft mode to use. This allows easier
  106292. bitrate management */
  106293. if((ret=_mapping_P[0]->forward(vb)))
  106294. return(ret);
  106295. if(op){
  106296. if(vorbis_bitrate_managed(vb))
  106297. /* The app is using a bitmanaged mode... but not using the
  106298. bitrate management interface. */
  106299. return(OV_EINVAL);
  106300. op->packet=oggpack_get_buffer(&vb->opb);
  106301. op->bytes=oggpack_bytes(&vb->opb);
  106302. op->b_o_s=0;
  106303. op->e_o_s=vb->eofflag;
  106304. op->granulepos=vb->granulepos;
  106305. op->packetno=vb->sequence; /* for sake of completeness */
  106306. }
  106307. return(0);
  106308. }
  106309. /* there was no great place to put this.... */
  106310. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  106311. int j;
  106312. FILE *of;
  106313. char buffer[80];
  106314. /* if(i==5870){*/
  106315. sprintf(buffer,"%s_%d.m",base,i);
  106316. of=fopen(buffer,"w");
  106317. if(!of)perror("failed to open data dump file");
  106318. for(j=0;j<n;j++){
  106319. if(bark){
  106320. float b=toBARK((4000.f*j/n)+.25);
  106321. fprintf(of,"%f ",b);
  106322. }else
  106323. if(off!=0)
  106324. fprintf(of,"%f ",(double)(j+off)/8000.);
  106325. else
  106326. fprintf(of,"%f ",(double)j);
  106327. if(dB){
  106328. float val;
  106329. if(v[j]==0.)
  106330. val=-140.;
  106331. else
  106332. val=todB(v+j);
  106333. fprintf(of,"%f\n",val);
  106334. }else{
  106335. fprintf(of,"%f\n",v[j]);
  106336. }
  106337. }
  106338. fclose(of);
  106339. /* } */
  106340. }
  106341. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  106342. ogg_int64_t off){
  106343. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  106344. }
  106345. #endif
  106346. /********* End of inlined file: analysis.c *********/
  106347. /********* Start of inlined file: bitrate.c *********/
  106348. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106349. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106350. // tasks..
  106351. #ifdef _MSC_VER
  106352. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106353. #endif
  106354. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106355. #if JUCE_USE_OGGVORBIS
  106356. #include <stdlib.h>
  106357. #include <string.h>
  106358. #include <math.h>
  106359. /* compute bitrate tracking setup */
  106360. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  106361. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  106362. bitrate_manager_info *bi=&ci->bi;
  106363. memset(bm,0,sizeof(*bm));
  106364. if(bi && (bi->reservoir_bits>0)){
  106365. long ratesamples=vi->rate;
  106366. int halfsamples=ci->blocksizes[0]>>1;
  106367. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  106368. bm->managed=1;
  106369. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  106370. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  106371. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  106372. bm->avgfloat=PACKETBLOBS/2;
  106373. /* not a necessary fix, but one that leads to a more balanced
  106374. typical initialization */
  106375. {
  106376. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106377. bm->minmax_reservoir=desired_fill;
  106378. bm->avg_reservoir=desired_fill;
  106379. }
  106380. }
  106381. }
  106382. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  106383. memset(bm,0,sizeof(*bm));
  106384. return;
  106385. }
  106386. int vorbis_bitrate_managed(vorbis_block *vb){
  106387. vorbis_dsp_state *vd=vb->vd;
  106388. private_state *b=(private_state*)vd->backend_state;
  106389. bitrate_manager_state *bm=&b->bms;
  106390. if(bm && bm->managed)return(1);
  106391. return(0);
  106392. }
  106393. /* finish taking in the block we just processed */
  106394. int vorbis_bitrate_addblock(vorbis_block *vb){
  106395. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106396. vorbis_dsp_state *vd=vb->vd;
  106397. private_state *b=(private_state*)vd->backend_state;
  106398. bitrate_manager_state *bm=&b->bms;
  106399. vorbis_info *vi=vd->vi;
  106400. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106401. bitrate_manager_info *bi=&ci->bi;
  106402. int choice=rint(bm->avgfloat);
  106403. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106404. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  106405. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  106406. int samples=ci->blocksizes[vb->W]>>1;
  106407. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  106408. if(!bm->managed){
  106409. /* not a bitrate managed stream, but for API simplicity, we'll
  106410. buffer the packet to keep the code path clean */
  106411. if(bm->vb)return(-1); /* one has been submitted without
  106412. being claimed */
  106413. bm->vb=vb;
  106414. return(0);
  106415. }
  106416. bm->vb=vb;
  106417. /* look ahead for avg floater */
  106418. if(bm->avg_bitsper>0){
  106419. double slew=0.;
  106420. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106421. double slewlimit= 15./bi->slew_damp;
  106422. /* choosing a new floater:
  106423. if we're over target, we slew down
  106424. if we're under target, we slew up
  106425. choose slew as follows: look through packetblobs of this frame
  106426. and set slew as the first in the appropriate direction that
  106427. gives us the slew we want. This may mean no slew if delta is
  106428. already favorable.
  106429. Then limit slew to slew max */
  106430. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106431. while(choice>0 && this_bits>avg_target_bits &&
  106432. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  106433. choice--;
  106434. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106435. }
  106436. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106437. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  106438. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  106439. choice++;
  106440. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106441. }
  106442. }
  106443. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  106444. if(slew<-slewlimit)slew=-slewlimit;
  106445. if(slew>slewlimit)slew=slewlimit;
  106446. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  106447. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106448. }
  106449. /* enforce min(if used) on the current floater (if used) */
  106450. if(bm->min_bitsper>0){
  106451. /* do we need to force the bitrate up? */
  106452. if(this_bits<min_target_bits){
  106453. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  106454. choice++;
  106455. if(choice>=PACKETBLOBS)break;
  106456. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106457. }
  106458. }
  106459. }
  106460. /* enforce max (if used) on the current floater (if used) */
  106461. if(bm->max_bitsper>0){
  106462. /* do we need to force the bitrate down? */
  106463. if(this_bits>max_target_bits){
  106464. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  106465. choice--;
  106466. if(choice<0)break;
  106467. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106468. }
  106469. }
  106470. }
  106471. /* Choice of packetblobs now made based on floater, and min/max
  106472. requirements. Now boundary check extreme choices */
  106473. if(choice<0){
  106474. /* choosing a smaller packetblob is insufficient to trim bitrate.
  106475. frame will need to be truncated */
  106476. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  106477. bm->choice=choice=0;
  106478. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  106479. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  106480. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106481. }
  106482. }else{
  106483. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  106484. if(choice>=PACKETBLOBS)
  106485. choice=PACKETBLOBS-1;
  106486. bm->choice=choice;
  106487. /* prop up bitrate according to demand. pad this frame out with zeroes */
  106488. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  106489. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  106490. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  106491. }
  106492. /* now we have the final packet and the final packet size. Update statistics */
  106493. /* min and max reservoir */
  106494. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  106495. if(max_target_bits>0 && this_bits>max_target_bits){
  106496. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106497. }else if(min_target_bits>0 && this_bits<min_target_bits){
  106498. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106499. }else{
  106500. /* inbetween; we want to take reservoir toward but not past desired_fill */
  106501. if(bm->minmax_reservoir>desired_fill){
  106502. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  106503. bm->minmax_reservoir+=(this_bits-max_target_bits);
  106504. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  106505. }else{
  106506. bm->minmax_reservoir=desired_fill;
  106507. }
  106508. }else{
  106509. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  106510. bm->minmax_reservoir+=(this_bits-min_target_bits);
  106511. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  106512. }else{
  106513. bm->minmax_reservoir=desired_fill;
  106514. }
  106515. }
  106516. }
  106517. }
  106518. /* avg reservoir */
  106519. if(bm->avg_bitsper>0){
  106520. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  106521. bm->avg_reservoir+=this_bits-avg_target_bits;
  106522. }
  106523. return(0);
  106524. }
  106525. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  106526. private_state *b=(private_state*)vd->backend_state;
  106527. bitrate_manager_state *bm=&b->bms;
  106528. vorbis_block *vb=bm->vb;
  106529. int choice=PACKETBLOBS/2;
  106530. if(!vb)return 0;
  106531. if(op){
  106532. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106533. if(vorbis_bitrate_managed(vb))
  106534. choice=bm->choice;
  106535. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  106536. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  106537. op->b_o_s=0;
  106538. op->e_o_s=vb->eofflag;
  106539. op->granulepos=vb->granulepos;
  106540. op->packetno=vb->sequence; /* for sake of completeness */
  106541. }
  106542. bm->vb=0;
  106543. return(1);
  106544. }
  106545. #endif
  106546. /********* End of inlined file: bitrate.c *********/
  106547. /********* Start of inlined file: block.c *********/
  106548. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106549. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106550. // tasks..
  106551. #ifdef _MSC_VER
  106552. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106553. #endif
  106554. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106555. #if JUCE_USE_OGGVORBIS
  106556. #include <stdio.h>
  106557. #include <stdlib.h>
  106558. #include <string.h>
  106559. /********* Start of inlined file: window.h *********/
  106560. #ifndef _V_WINDOW_
  106561. #define _V_WINDOW_
  106562. extern float *_vorbis_window_get(int n);
  106563. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  106564. int lW,int W,int nW);
  106565. #endif
  106566. /********* End of inlined file: window.h *********/
  106567. /********* Start of inlined file: lpc.h *********/
  106568. #ifndef _V_LPC_H_
  106569. #define _V_LPC_H_
  106570. /* simple linear scale LPC code */
  106571. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  106572. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  106573. float *data,long n);
  106574. #endif
  106575. /********* End of inlined file: lpc.h *********/
  106576. /* pcm accumulator examples (not exhaustive):
  106577. <-------------- lW ---------------->
  106578. <--------------- W ---------------->
  106579. : .....|..... _______________ |
  106580. : .''' | '''_--- | |\ |
  106581. :.....''' |_____--- '''......| | \_______|
  106582. :.................|__________________|_______|__|______|
  106583. |<------ Sl ------>| > Sr < |endW
  106584. |beginSl |endSl | |endSr
  106585. |beginW |endlW |beginSr
  106586. |< lW >|
  106587. <--------------- W ---------------->
  106588. | | .. ______________ |
  106589. | | ' `/ | ---_ |
  106590. |___.'___/`. | ---_____|
  106591. |_______|__|_______|_________________|
  106592. | >|Sl|< |<------ Sr ----->|endW
  106593. | | |endSl |beginSr |endSr
  106594. |beginW | |endlW
  106595. mult[0] |beginSl mult[n]
  106596. <-------------- lW ----------------->
  106597. |<--W-->|
  106598. : .............. ___ | |
  106599. : .''' |`/ \ | |
  106600. :.....''' |/`....\|...|
  106601. :.........................|___|___|___|
  106602. |Sl |Sr |endW
  106603. | | |endSr
  106604. | |beginSr
  106605. | |endSl
  106606. |beginSl
  106607. |beginW
  106608. */
  106609. /* block abstraction setup *********************************************/
  106610. #ifndef WORD_ALIGN
  106611. #define WORD_ALIGN 8
  106612. #endif
  106613. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  106614. int i;
  106615. memset(vb,0,sizeof(*vb));
  106616. vb->vd=v;
  106617. vb->localalloc=0;
  106618. vb->localstore=NULL;
  106619. if(v->analysisp){
  106620. vorbis_block_internal *vbi=(vorbis_block_internal*)
  106621. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  106622. vbi->ampmax=-9999;
  106623. for(i=0;i<PACKETBLOBS;i++){
  106624. if(i==PACKETBLOBS/2){
  106625. vbi->packetblob[i]=&vb->opb;
  106626. }else{
  106627. vbi->packetblob[i]=
  106628. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  106629. }
  106630. oggpack_writeinit(vbi->packetblob[i]);
  106631. }
  106632. }
  106633. return(0);
  106634. }
  106635. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  106636. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  106637. if(bytes+vb->localtop>vb->localalloc){
  106638. /* can't just _ogg_realloc... there are outstanding pointers */
  106639. if(vb->localstore){
  106640. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  106641. vb->totaluse+=vb->localtop;
  106642. link->next=vb->reap;
  106643. link->ptr=vb->localstore;
  106644. vb->reap=link;
  106645. }
  106646. /* highly conservative */
  106647. vb->localalloc=bytes;
  106648. vb->localstore=_ogg_malloc(vb->localalloc);
  106649. vb->localtop=0;
  106650. }
  106651. {
  106652. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  106653. vb->localtop+=bytes;
  106654. return ret;
  106655. }
  106656. }
  106657. /* reap the chain, pull the ripcord */
  106658. void _vorbis_block_ripcord(vorbis_block *vb){
  106659. /* reap the chain */
  106660. struct alloc_chain *reap=vb->reap;
  106661. while(reap){
  106662. struct alloc_chain *next=reap->next;
  106663. _ogg_free(reap->ptr);
  106664. memset(reap,0,sizeof(*reap));
  106665. _ogg_free(reap);
  106666. reap=next;
  106667. }
  106668. /* consolidate storage */
  106669. if(vb->totaluse){
  106670. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  106671. vb->localalloc+=vb->totaluse;
  106672. vb->totaluse=0;
  106673. }
  106674. /* pull the ripcord */
  106675. vb->localtop=0;
  106676. vb->reap=NULL;
  106677. }
  106678. int vorbis_block_clear(vorbis_block *vb){
  106679. int i;
  106680. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  106681. _vorbis_block_ripcord(vb);
  106682. if(vb->localstore)_ogg_free(vb->localstore);
  106683. if(vbi){
  106684. for(i=0;i<PACKETBLOBS;i++){
  106685. oggpack_writeclear(vbi->packetblob[i]);
  106686. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  106687. }
  106688. _ogg_free(vbi);
  106689. }
  106690. memset(vb,0,sizeof(*vb));
  106691. return(0);
  106692. }
  106693. /* Analysis side code, but directly related to blocking. Thus it's
  106694. here and not in analysis.c (which is for analysis transforms only).
  106695. The init is here because some of it is shared */
  106696. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  106697. int i;
  106698. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106699. private_state *b=NULL;
  106700. int hs;
  106701. if(ci==NULL) return 1;
  106702. hs=ci->halfrate_flag;
  106703. memset(v,0,sizeof(*v));
  106704. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  106705. v->vi=vi;
  106706. b->modebits=ilog2(ci->modes);
  106707. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  106708. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  106709. /* MDCT is tranform 0 */
  106710. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106711. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  106712. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  106713. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  106714. /* Vorbis I uses only window type 0 */
  106715. b->window[0]=ilog2(ci->blocksizes[0])-6;
  106716. b->window[1]=ilog2(ci->blocksizes[1])-6;
  106717. if(encp){ /* encode/decode differ here */
  106718. /* analysis always needs an fft */
  106719. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  106720. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  106721. /* finish the codebooks */
  106722. if(!ci->fullbooks){
  106723. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106724. for(i=0;i<ci->books;i++)
  106725. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  106726. }
  106727. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  106728. for(i=0;i<ci->psys;i++){
  106729. _vp_psy_init(b->psy+i,
  106730. ci->psy_param[i],
  106731. &ci->psy_g_param,
  106732. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  106733. vi->rate);
  106734. }
  106735. v->analysisp=1;
  106736. }else{
  106737. /* finish the codebooks */
  106738. if(!ci->fullbooks){
  106739. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  106740. for(i=0;i<ci->books;i++){
  106741. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  106742. /* decode codebooks are now standalone after init */
  106743. vorbis_staticbook_destroy(ci->book_param[i]);
  106744. ci->book_param[i]=NULL;
  106745. }
  106746. }
  106747. }
  106748. /* initialize the storage vectors. blocksize[1] is small for encode,
  106749. but the correct size for decode */
  106750. v->pcm_storage=ci->blocksizes[1];
  106751. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  106752. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  106753. {
  106754. int i;
  106755. for(i=0;i<vi->channels;i++)
  106756. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  106757. }
  106758. /* all 1 (large block) or 0 (small block) */
  106759. /* explicitly set for the sake of clarity */
  106760. v->lW=0; /* previous window size */
  106761. v->W=0; /* current window size */
  106762. /* all vector indexes */
  106763. v->centerW=ci->blocksizes[1]/2;
  106764. v->pcm_current=v->centerW;
  106765. /* initialize all the backend lookups */
  106766. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  106767. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  106768. for(i=0;i<ci->floors;i++)
  106769. b->flr[i]=_floor_P[ci->floor_type[i]]->
  106770. look(v,ci->floor_param[i]);
  106771. for(i=0;i<ci->residues;i++)
  106772. b->residue[i]=_residue_P[ci->residue_type[i]]->
  106773. look(v,ci->residue_param[i]);
  106774. return 0;
  106775. }
  106776. /* arbitrary settings and spec-mandated numbers get filled in here */
  106777. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  106778. private_state *b=NULL;
  106779. if(_vds_shared_init(v,vi,1))return 1;
  106780. b=(private_state*)v->backend_state;
  106781. b->psy_g_look=_vp_global_look(vi);
  106782. /* Initialize the envelope state storage */
  106783. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  106784. _ve_envelope_init(b->ve,vi);
  106785. vorbis_bitrate_init(vi,&b->bms);
  106786. /* compressed audio packets start after the headers
  106787. with sequence number 3 */
  106788. v->sequence=3;
  106789. return(0);
  106790. }
  106791. void vorbis_dsp_clear(vorbis_dsp_state *v){
  106792. int i;
  106793. if(v){
  106794. vorbis_info *vi=v->vi;
  106795. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  106796. private_state *b=(private_state*)v->backend_state;
  106797. if(b){
  106798. if(b->ve){
  106799. _ve_envelope_clear(b->ve);
  106800. _ogg_free(b->ve);
  106801. }
  106802. if(b->transform[0]){
  106803. mdct_clear((mdct_lookup*) b->transform[0][0]);
  106804. _ogg_free(b->transform[0][0]);
  106805. _ogg_free(b->transform[0]);
  106806. }
  106807. if(b->transform[1]){
  106808. mdct_clear((mdct_lookup*) b->transform[1][0]);
  106809. _ogg_free(b->transform[1][0]);
  106810. _ogg_free(b->transform[1]);
  106811. }
  106812. if(b->flr){
  106813. for(i=0;i<ci->floors;i++)
  106814. _floor_P[ci->floor_type[i]]->
  106815. free_look(b->flr[i]);
  106816. _ogg_free(b->flr);
  106817. }
  106818. if(b->residue){
  106819. for(i=0;i<ci->residues;i++)
  106820. _residue_P[ci->residue_type[i]]->
  106821. free_look(b->residue[i]);
  106822. _ogg_free(b->residue);
  106823. }
  106824. if(b->psy){
  106825. for(i=0;i<ci->psys;i++)
  106826. _vp_psy_clear(b->psy+i);
  106827. _ogg_free(b->psy);
  106828. }
  106829. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  106830. vorbis_bitrate_clear(&b->bms);
  106831. drft_clear(&b->fft_look[0]);
  106832. drft_clear(&b->fft_look[1]);
  106833. }
  106834. if(v->pcm){
  106835. for(i=0;i<vi->channels;i++)
  106836. if(v->pcm[i])_ogg_free(v->pcm[i]);
  106837. _ogg_free(v->pcm);
  106838. if(v->pcmret)_ogg_free(v->pcmret);
  106839. }
  106840. if(b){
  106841. /* free header, header1, header2 */
  106842. if(b->header)_ogg_free(b->header);
  106843. if(b->header1)_ogg_free(b->header1);
  106844. if(b->header2)_ogg_free(b->header2);
  106845. _ogg_free(b);
  106846. }
  106847. memset(v,0,sizeof(*v));
  106848. }
  106849. }
  106850. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  106851. int i;
  106852. vorbis_info *vi=v->vi;
  106853. private_state *b=(private_state*)v->backend_state;
  106854. /* free header, header1, header2 */
  106855. if(b->header)_ogg_free(b->header);b->header=NULL;
  106856. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  106857. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  106858. /* Do we have enough storage space for the requested buffer? If not,
  106859. expand the PCM (and envelope) storage */
  106860. if(v->pcm_current+vals>=v->pcm_storage){
  106861. v->pcm_storage=v->pcm_current+vals*2;
  106862. for(i=0;i<vi->channels;i++){
  106863. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  106864. }
  106865. }
  106866. for(i=0;i<vi->channels;i++)
  106867. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  106868. return(v->pcmret);
  106869. }
  106870. static void _preextrapolate_helper(vorbis_dsp_state *v){
  106871. int i;
  106872. int order=32;
  106873. float *lpc=(float*)alloca(order*sizeof(*lpc));
  106874. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  106875. long j;
  106876. v->preextrapolate=1;
  106877. if(v->pcm_current-v->centerW>order*2){ /* safety */
  106878. for(i=0;i<v->vi->channels;i++){
  106879. /* need to run the extrapolation in reverse! */
  106880. for(j=0;j<v->pcm_current;j++)
  106881. work[j]=v->pcm[i][v->pcm_current-j-1];
  106882. /* prime as above */
  106883. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  106884. /* run the predictor filter */
  106885. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  106886. order,
  106887. work+v->pcm_current-v->centerW,
  106888. v->centerW);
  106889. for(j=0;j<v->pcm_current;j++)
  106890. v->pcm[i][v->pcm_current-j-1]=work[j];
  106891. }
  106892. }
  106893. }
  106894. /* call with val<=0 to set eof */
  106895. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  106896. vorbis_info *vi=v->vi;
  106897. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106898. if(vals<=0){
  106899. int order=32;
  106900. int i;
  106901. float *lpc=(float*) alloca(order*sizeof(*lpc));
  106902. /* if it wasn't done earlier (very short sample) */
  106903. if(!v->preextrapolate)
  106904. _preextrapolate_helper(v);
  106905. /* We're encoding the end of the stream. Just make sure we have
  106906. [at least] a few full blocks of zeroes at the end. */
  106907. /* actually, we don't want zeroes; that could drop a large
  106908. amplitude off a cliff, creating spread spectrum noise that will
  106909. suck to encode. Extrapolate for the sake of cleanliness. */
  106910. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  106911. v->eofflag=v->pcm_current;
  106912. v->pcm_current+=ci->blocksizes[1]*3;
  106913. for(i=0;i<vi->channels;i++){
  106914. if(v->eofflag>order*2){
  106915. /* extrapolate with LPC to fill in */
  106916. long n;
  106917. /* make a predictor filter */
  106918. n=v->eofflag;
  106919. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  106920. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  106921. /* run the predictor filter */
  106922. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  106923. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  106924. }else{
  106925. /* not enough data to extrapolate (unlikely to happen due to
  106926. guarding the overlap, but bulletproof in case that
  106927. assumtion goes away). zeroes will do. */
  106928. memset(v->pcm[i]+v->eofflag,0,
  106929. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  106930. }
  106931. }
  106932. }else{
  106933. if(v->pcm_current+vals>v->pcm_storage)
  106934. return(OV_EINVAL);
  106935. v->pcm_current+=vals;
  106936. /* we may want to reverse extrapolate the beginning of a stream
  106937. too... in case we're beginning on a cliff! */
  106938. /* clumsy, but simple. It only runs once, so simple is good. */
  106939. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  106940. _preextrapolate_helper(v);
  106941. }
  106942. return(0);
  106943. }
  106944. /* do the deltas, envelope shaping, pre-echo and determine the size of
  106945. the next block on which to continue analysis */
  106946. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  106947. int i;
  106948. vorbis_info *vi=v->vi;
  106949. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106950. private_state *b=(private_state*)v->backend_state;
  106951. vorbis_look_psy_global *g=b->psy_g_look;
  106952. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  106953. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  106954. /* check to see if we're started... */
  106955. if(!v->preextrapolate)return(0);
  106956. /* check to see if we're done... */
  106957. if(v->eofflag==-1)return(0);
  106958. /* By our invariant, we have lW, W and centerW set. Search for
  106959. the next boundary so we can determine nW (the next window size)
  106960. which lets us compute the shape of the current block's window */
  106961. /* we do an envelope search even on a single blocksize; we may still
  106962. be throwing more bits at impulses, and envelope search handles
  106963. marking impulses too. */
  106964. {
  106965. long bp=_ve_envelope_search(v);
  106966. if(bp==-1){
  106967. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  106968. full long block */
  106969. v->nW=0;
  106970. }else{
  106971. if(ci->blocksizes[0]==ci->blocksizes[1])
  106972. v->nW=0;
  106973. else
  106974. v->nW=bp;
  106975. }
  106976. }
  106977. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  106978. {
  106979. /* center of next block + next block maximum right side. */
  106980. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  106981. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  106982. although this check is
  106983. less strict that the
  106984. _ve_envelope_search,
  106985. the search is not run
  106986. if we only use one
  106987. block size */
  106988. }
  106989. /* fill in the block. Note that for a short window, lW and nW are *short*
  106990. regardless of actual settings in the stream */
  106991. _vorbis_block_ripcord(vb);
  106992. vb->lW=v->lW;
  106993. vb->W=v->W;
  106994. vb->nW=v->nW;
  106995. if(v->W){
  106996. if(!v->lW || !v->nW){
  106997. vbi->blocktype=BLOCKTYPE_TRANSITION;
  106998. /*fprintf(stderr,"-");*/
  106999. }else{
  107000. vbi->blocktype=BLOCKTYPE_LONG;
  107001. /*fprintf(stderr,"_");*/
  107002. }
  107003. }else{
  107004. if(_ve_envelope_mark(v)){
  107005. vbi->blocktype=BLOCKTYPE_IMPULSE;
  107006. /*fprintf(stderr,"|");*/
  107007. }else{
  107008. vbi->blocktype=BLOCKTYPE_PADDING;
  107009. /*fprintf(stderr,".");*/
  107010. }
  107011. }
  107012. vb->vd=v;
  107013. vb->sequence=v->sequence++;
  107014. vb->granulepos=v->granulepos;
  107015. vb->pcmend=ci->blocksizes[v->W];
  107016. /* copy the vectors; this uses the local storage in vb */
  107017. /* this tracks 'strongest peak' for later psychoacoustics */
  107018. /* moved to the global psy state; clean this mess up */
  107019. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  107020. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  107021. vbi->ampmax=g->ampmax;
  107022. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  107023. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  107024. for(i=0;i<vi->channels;i++){
  107025. vbi->pcmdelay[i]=
  107026. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107027. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  107028. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  107029. /* before we added the delay
  107030. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  107031. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  107032. */
  107033. }
  107034. /* handle eof detection: eof==0 means that we've not yet received EOF
  107035. eof>0 marks the last 'real' sample in pcm[]
  107036. eof<0 'no more to do'; doesn't get here */
  107037. if(v->eofflag){
  107038. if(v->centerW>=v->eofflag){
  107039. v->eofflag=-1;
  107040. vb->eofflag=1;
  107041. return(1);
  107042. }
  107043. }
  107044. /* advance storage vectors and clean up */
  107045. {
  107046. int new_centerNext=ci->blocksizes[1]/2;
  107047. int movementW=centerNext-new_centerNext;
  107048. if(movementW>0){
  107049. _ve_envelope_shift(b->ve,movementW);
  107050. v->pcm_current-=movementW;
  107051. for(i=0;i<vi->channels;i++)
  107052. memmove(v->pcm[i],v->pcm[i]+movementW,
  107053. v->pcm_current*sizeof(*v->pcm[i]));
  107054. v->lW=v->W;
  107055. v->W=v->nW;
  107056. v->centerW=new_centerNext;
  107057. if(v->eofflag){
  107058. v->eofflag-=movementW;
  107059. if(v->eofflag<=0)v->eofflag=-1;
  107060. /* do not add padding to end of stream! */
  107061. if(v->centerW>=v->eofflag){
  107062. v->granulepos+=movementW-(v->centerW-v->eofflag);
  107063. }else{
  107064. v->granulepos+=movementW;
  107065. }
  107066. }else{
  107067. v->granulepos+=movementW;
  107068. }
  107069. }
  107070. }
  107071. /* done */
  107072. return(1);
  107073. }
  107074. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  107075. vorbis_info *vi=v->vi;
  107076. codec_setup_info *ci;
  107077. int hs;
  107078. if(!v->backend_state)return -1;
  107079. if(!vi)return -1;
  107080. ci=(codec_setup_info*) vi->codec_setup;
  107081. if(!ci)return -1;
  107082. hs=ci->halfrate_flag;
  107083. v->centerW=ci->blocksizes[1]>>(hs+1);
  107084. v->pcm_current=v->centerW>>hs;
  107085. v->pcm_returned=-1;
  107086. v->granulepos=-1;
  107087. v->sequence=-1;
  107088. v->eofflag=0;
  107089. ((private_state *)(v->backend_state))->sample_count=-1;
  107090. return(0);
  107091. }
  107092. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  107093. if(_vds_shared_init(v,vi,0)) return 1;
  107094. vorbis_synthesis_restart(v);
  107095. return 0;
  107096. }
  107097. /* Unlike in analysis, the window is only partially applied for each
  107098. block. The time domain envelope is not yet handled at the point of
  107099. calling (as it relies on the previous block). */
  107100. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  107101. vorbis_info *vi=v->vi;
  107102. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107103. private_state *b=(private_state*)v->backend_state;
  107104. int hs=ci->halfrate_flag;
  107105. int i,j;
  107106. if(!vb)return(OV_EINVAL);
  107107. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  107108. v->lW=v->W;
  107109. v->W=vb->W;
  107110. v->nW=-1;
  107111. if((v->sequence==-1)||
  107112. (v->sequence+1 != vb->sequence)){
  107113. v->granulepos=-1; /* out of sequence; lose count */
  107114. b->sample_count=-1;
  107115. }
  107116. v->sequence=vb->sequence;
  107117. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  107118. was called on block */
  107119. int n=ci->blocksizes[v->W]>>(hs+1);
  107120. int n0=ci->blocksizes[0]>>(hs+1);
  107121. int n1=ci->blocksizes[1]>>(hs+1);
  107122. int thisCenter;
  107123. int prevCenter;
  107124. v->glue_bits+=vb->glue_bits;
  107125. v->time_bits+=vb->time_bits;
  107126. v->floor_bits+=vb->floor_bits;
  107127. v->res_bits+=vb->res_bits;
  107128. if(v->centerW){
  107129. thisCenter=n1;
  107130. prevCenter=0;
  107131. }else{
  107132. thisCenter=0;
  107133. prevCenter=n1;
  107134. }
  107135. /* v->pcm is now used like a two-stage double buffer. We don't want
  107136. to have to constantly shift *or* adjust memory usage. Don't
  107137. accept a new block until the old is shifted out */
  107138. for(j=0;j<vi->channels;j++){
  107139. /* the overlap/add section */
  107140. if(v->lW){
  107141. if(v->W){
  107142. /* large/large */
  107143. float *w=_vorbis_window_get(b->window[1]-hs);
  107144. float *pcm=v->pcm[j]+prevCenter;
  107145. float *p=vb->pcm[j];
  107146. for(i=0;i<n1;i++)
  107147. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  107148. }else{
  107149. /* large/small */
  107150. float *w=_vorbis_window_get(b->window[0]-hs);
  107151. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  107152. float *p=vb->pcm[j];
  107153. for(i=0;i<n0;i++)
  107154. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107155. }
  107156. }else{
  107157. if(v->W){
  107158. /* small/large */
  107159. float *w=_vorbis_window_get(b->window[0]-hs);
  107160. float *pcm=v->pcm[j]+prevCenter;
  107161. float *p=vb->pcm[j]+n1/2-n0/2;
  107162. for(i=0;i<n0;i++)
  107163. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107164. for(;i<n1/2+n0/2;i++)
  107165. pcm[i]=p[i];
  107166. }else{
  107167. /* small/small */
  107168. float *w=_vorbis_window_get(b->window[0]-hs);
  107169. float *pcm=v->pcm[j]+prevCenter;
  107170. float *p=vb->pcm[j];
  107171. for(i=0;i<n0;i++)
  107172. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  107173. }
  107174. }
  107175. /* the copy section */
  107176. {
  107177. float *pcm=v->pcm[j]+thisCenter;
  107178. float *p=vb->pcm[j]+n;
  107179. for(i=0;i<n;i++)
  107180. pcm[i]=p[i];
  107181. }
  107182. }
  107183. if(v->centerW)
  107184. v->centerW=0;
  107185. else
  107186. v->centerW=n1;
  107187. /* deal with initial packet state; we do this using the explicit
  107188. pcm_returned==-1 flag otherwise we're sensitive to first block
  107189. being short or long */
  107190. if(v->pcm_returned==-1){
  107191. v->pcm_returned=thisCenter;
  107192. v->pcm_current=thisCenter;
  107193. }else{
  107194. v->pcm_returned=prevCenter;
  107195. v->pcm_current=prevCenter+
  107196. ((ci->blocksizes[v->lW]/4+
  107197. ci->blocksizes[v->W]/4)>>hs);
  107198. }
  107199. }
  107200. /* track the frame number... This is for convenience, but also
  107201. making sure our last packet doesn't end with added padding. If
  107202. the last packet is partial, the number of samples we'll have to
  107203. return will be past the vb->granulepos.
  107204. This is not foolproof! It will be confused if we begin
  107205. decoding at the last page after a seek or hole. In that case,
  107206. we don't have a starting point to judge where the last frame
  107207. is. For this reason, vorbisfile will always try to make sure
  107208. it reads the last two marked pages in proper sequence */
  107209. if(b->sample_count==-1){
  107210. b->sample_count=0;
  107211. }else{
  107212. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107213. }
  107214. if(v->granulepos==-1){
  107215. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  107216. v->granulepos=vb->granulepos;
  107217. /* is this a short page? */
  107218. if(b->sample_count>v->granulepos){
  107219. /* corner case; if this is both the first and last audio page,
  107220. then spec says the end is cut, not beginning */
  107221. if(vb->eofflag){
  107222. /* trim the end */
  107223. /* no preceeding granulepos; assume we started at zero (we'd
  107224. have to in a short single-page stream) */
  107225. /* granulepos could be -1 due to a seek, but that would result
  107226. in a long count, not short count */
  107227. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  107228. }else{
  107229. /* trim the beginning */
  107230. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  107231. if(v->pcm_returned>v->pcm_current)
  107232. v->pcm_returned=v->pcm_current;
  107233. }
  107234. }
  107235. }
  107236. }else{
  107237. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  107238. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  107239. if(v->granulepos>vb->granulepos){
  107240. long extra=v->granulepos-vb->granulepos;
  107241. if(extra)
  107242. if(vb->eofflag){
  107243. /* partial last frame. Strip the extra samples off */
  107244. v->pcm_current-=extra>>hs;
  107245. } /* else {Shouldn't happen *unless* the bitstream is out of
  107246. spec. Either way, believe the bitstream } */
  107247. } /* else {Shouldn't happen *unless* the bitstream is out of
  107248. spec. Either way, believe the bitstream } */
  107249. v->granulepos=vb->granulepos;
  107250. }
  107251. }
  107252. /* Update, cleanup */
  107253. if(vb->eofflag)v->eofflag=1;
  107254. return(0);
  107255. }
  107256. /* pcm==NULL indicates we just want the pending samples, no more */
  107257. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  107258. vorbis_info *vi=v->vi;
  107259. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  107260. if(pcm){
  107261. int i;
  107262. for(i=0;i<vi->channels;i++)
  107263. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107264. *pcm=v->pcmret;
  107265. }
  107266. return(v->pcm_current-v->pcm_returned);
  107267. }
  107268. return(0);
  107269. }
  107270. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  107271. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  107272. v->pcm_returned+=n;
  107273. return(0);
  107274. }
  107275. /* intended for use with a specific vorbisfile feature; we want access
  107276. to the [usually synthetic/postextrapolated] buffer and lapping at
  107277. the end of a decode cycle, specifically, a half-short-block worth.
  107278. This funtion works like pcmout above, except it will also expose
  107279. this implicit buffer data not normally decoded. */
  107280. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  107281. vorbis_info *vi=v->vi;
  107282. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  107283. int hs=ci->halfrate_flag;
  107284. int n=ci->blocksizes[v->W]>>(hs+1);
  107285. int n0=ci->blocksizes[0]>>(hs+1);
  107286. int n1=ci->blocksizes[1]>>(hs+1);
  107287. int i,j;
  107288. if(v->pcm_returned<0)return 0;
  107289. /* our returned data ends at pcm_returned; because the synthesis pcm
  107290. buffer is a two-fragment ring, that means our data block may be
  107291. fragmented by buffering, wrapping or a short block not filling
  107292. out a buffer. To simplify things, we unfragment if it's at all
  107293. possibly needed. Otherwise, we'd need to call lapout more than
  107294. once as well as hold additional dsp state. Opt for
  107295. simplicity. */
  107296. /* centerW was advanced by blockin; it would be the center of the
  107297. *next* block */
  107298. if(v->centerW==n1){
  107299. /* the data buffer wraps; swap the halves */
  107300. /* slow, sure, small */
  107301. for(j=0;j<vi->channels;j++){
  107302. float *p=v->pcm[j];
  107303. for(i=0;i<n1;i++){
  107304. float temp=p[i];
  107305. p[i]=p[i+n1];
  107306. p[i+n1]=temp;
  107307. }
  107308. }
  107309. v->pcm_current-=n1;
  107310. v->pcm_returned-=n1;
  107311. v->centerW=0;
  107312. }
  107313. /* solidify buffer into contiguous space */
  107314. if((v->lW^v->W)==1){
  107315. /* long/short or short/long */
  107316. for(j=0;j<vi->channels;j++){
  107317. float *s=v->pcm[j];
  107318. float *d=v->pcm[j]+(n1-n0)/2;
  107319. for(i=(n1+n0)/2-1;i>=0;--i)
  107320. d[i]=s[i];
  107321. }
  107322. v->pcm_returned+=(n1-n0)/2;
  107323. v->pcm_current+=(n1-n0)/2;
  107324. }else{
  107325. if(v->lW==0){
  107326. /* short/short */
  107327. for(j=0;j<vi->channels;j++){
  107328. float *s=v->pcm[j];
  107329. float *d=v->pcm[j]+n1-n0;
  107330. for(i=n0-1;i>=0;--i)
  107331. d[i]=s[i];
  107332. }
  107333. v->pcm_returned+=n1-n0;
  107334. v->pcm_current+=n1-n0;
  107335. }
  107336. }
  107337. if(pcm){
  107338. int i;
  107339. for(i=0;i<vi->channels;i++)
  107340. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  107341. *pcm=v->pcmret;
  107342. }
  107343. return(n1+n-v->pcm_returned);
  107344. }
  107345. float *vorbis_window(vorbis_dsp_state *v,int W){
  107346. vorbis_info *vi=v->vi;
  107347. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  107348. int hs=ci->halfrate_flag;
  107349. private_state *b=(private_state*)v->backend_state;
  107350. if(b->window[W]-1<0)return NULL;
  107351. return _vorbis_window_get(b->window[W]-hs);
  107352. }
  107353. #endif
  107354. /********* End of inlined file: block.c *********/
  107355. /********* Start of inlined file: codebook.c *********/
  107356. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107357. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107358. // tasks..
  107359. #ifdef _MSC_VER
  107360. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107361. #endif
  107362. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107363. #if JUCE_USE_OGGVORBIS
  107364. #include <stdlib.h>
  107365. #include <string.h>
  107366. #include <math.h>
  107367. /* packs the given codebook into the bitstream **************************/
  107368. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  107369. long i,j;
  107370. int ordered=0;
  107371. /* first the basic parameters */
  107372. oggpack_write(opb,0x564342,24);
  107373. oggpack_write(opb,c->dim,16);
  107374. oggpack_write(opb,c->entries,24);
  107375. /* pack the codewords. There are two packings; length ordered and
  107376. length random. Decide between the two now. */
  107377. for(i=1;i<c->entries;i++)
  107378. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  107379. if(i==c->entries)ordered=1;
  107380. if(ordered){
  107381. /* length ordered. We only need to say how many codewords of
  107382. each length. The actual codewords are generated
  107383. deterministically */
  107384. long count=0;
  107385. oggpack_write(opb,1,1); /* ordered */
  107386. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  107387. for(i=1;i<c->entries;i++){
  107388. long thisx=c->lengthlist[i];
  107389. long last=c->lengthlist[i-1];
  107390. if(thisx>last){
  107391. for(j=last;j<thisx;j++){
  107392. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107393. count=i;
  107394. }
  107395. }
  107396. }
  107397. oggpack_write(opb,i-count,_ilog(c->entries-count));
  107398. }else{
  107399. /* length random. Again, we don't code the codeword itself, just
  107400. the length. This time, though, we have to encode each length */
  107401. oggpack_write(opb,0,1); /* unordered */
  107402. /* algortihmic mapping has use for 'unused entries', which we tag
  107403. here. The algorithmic mapping happens as usual, but the unused
  107404. entry has no codeword. */
  107405. for(i=0;i<c->entries;i++)
  107406. if(c->lengthlist[i]==0)break;
  107407. if(i==c->entries){
  107408. oggpack_write(opb,0,1); /* no unused entries */
  107409. for(i=0;i<c->entries;i++)
  107410. oggpack_write(opb,c->lengthlist[i]-1,5);
  107411. }else{
  107412. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  107413. for(i=0;i<c->entries;i++){
  107414. if(c->lengthlist[i]==0){
  107415. oggpack_write(opb,0,1);
  107416. }else{
  107417. oggpack_write(opb,1,1);
  107418. oggpack_write(opb,c->lengthlist[i]-1,5);
  107419. }
  107420. }
  107421. }
  107422. }
  107423. /* is the entry number the desired return value, or do we have a
  107424. mapping? If we have a mapping, what type? */
  107425. oggpack_write(opb,c->maptype,4);
  107426. switch(c->maptype){
  107427. case 0:
  107428. /* no mapping */
  107429. break;
  107430. case 1:case 2:
  107431. /* implicitly populated value mapping */
  107432. /* explicitly populated value mapping */
  107433. if(!c->quantlist){
  107434. /* no quantlist? error */
  107435. return(-1);
  107436. }
  107437. /* values that define the dequantization */
  107438. oggpack_write(opb,c->q_min,32);
  107439. oggpack_write(opb,c->q_delta,32);
  107440. oggpack_write(opb,c->q_quant-1,4);
  107441. oggpack_write(opb,c->q_sequencep,1);
  107442. {
  107443. int quantvals;
  107444. switch(c->maptype){
  107445. case 1:
  107446. /* a single column of (c->entries/c->dim) quantized values for
  107447. building a full value list algorithmically (square lattice) */
  107448. quantvals=_book_maptype1_quantvals(c);
  107449. break;
  107450. case 2:
  107451. /* every value (c->entries*c->dim total) specified explicitly */
  107452. quantvals=c->entries*c->dim;
  107453. break;
  107454. default: /* NOT_REACHABLE */
  107455. quantvals=-1;
  107456. }
  107457. /* quantized values */
  107458. for(i=0;i<quantvals;i++)
  107459. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  107460. }
  107461. break;
  107462. default:
  107463. /* error case; we don't have any other map types now */
  107464. return(-1);
  107465. }
  107466. return(0);
  107467. }
  107468. /* unpacks a codebook from the packet buffer into the codebook struct,
  107469. readies the codebook auxiliary structures for decode *************/
  107470. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  107471. long i,j;
  107472. memset(s,0,sizeof(*s));
  107473. s->allocedp=1;
  107474. /* make sure alignment is correct */
  107475. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  107476. /* first the basic parameters */
  107477. s->dim=oggpack_read(opb,16);
  107478. s->entries=oggpack_read(opb,24);
  107479. if(s->entries==-1)goto _eofout;
  107480. /* codeword ordering.... length ordered or unordered? */
  107481. switch((int)oggpack_read(opb,1)){
  107482. case 0:
  107483. /* unordered */
  107484. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107485. /* allocated but unused entries? */
  107486. if(oggpack_read(opb,1)){
  107487. /* yes, unused entries */
  107488. for(i=0;i<s->entries;i++){
  107489. if(oggpack_read(opb,1)){
  107490. long num=oggpack_read(opb,5);
  107491. if(num==-1)goto _eofout;
  107492. s->lengthlist[i]=num+1;
  107493. }else
  107494. s->lengthlist[i]=0;
  107495. }
  107496. }else{
  107497. /* all entries used; no tagging */
  107498. for(i=0;i<s->entries;i++){
  107499. long num=oggpack_read(opb,5);
  107500. if(num==-1)goto _eofout;
  107501. s->lengthlist[i]=num+1;
  107502. }
  107503. }
  107504. break;
  107505. case 1:
  107506. /* ordered */
  107507. {
  107508. long length=oggpack_read(opb,5)+1;
  107509. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  107510. for(i=0;i<s->entries;){
  107511. long num=oggpack_read(opb,_ilog(s->entries-i));
  107512. if(num==-1)goto _eofout;
  107513. for(j=0;j<num && i<s->entries;j++,i++)
  107514. s->lengthlist[i]=length;
  107515. length++;
  107516. }
  107517. }
  107518. break;
  107519. default:
  107520. /* EOF */
  107521. return(-1);
  107522. }
  107523. /* Do we have a mapping to unpack? */
  107524. switch((s->maptype=oggpack_read(opb,4))){
  107525. case 0:
  107526. /* no mapping */
  107527. break;
  107528. case 1: case 2:
  107529. /* implicitly populated value mapping */
  107530. /* explicitly populated value mapping */
  107531. s->q_min=oggpack_read(opb,32);
  107532. s->q_delta=oggpack_read(opb,32);
  107533. s->q_quant=oggpack_read(opb,4)+1;
  107534. s->q_sequencep=oggpack_read(opb,1);
  107535. {
  107536. int quantvals=0;
  107537. switch(s->maptype){
  107538. case 1:
  107539. quantvals=_book_maptype1_quantvals(s);
  107540. break;
  107541. case 2:
  107542. quantvals=s->entries*s->dim;
  107543. break;
  107544. }
  107545. /* quantized values */
  107546. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  107547. for(i=0;i<quantvals;i++)
  107548. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  107549. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  107550. }
  107551. break;
  107552. default:
  107553. goto _errout;
  107554. }
  107555. /* all set */
  107556. return(0);
  107557. _errout:
  107558. _eofout:
  107559. vorbis_staticbook_clear(s);
  107560. return(-1);
  107561. }
  107562. /* returns the number of bits ************************************************/
  107563. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  107564. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  107565. return(book->c->lengthlist[a]);
  107566. }
  107567. /* One the encode side, our vector writers are each designed for a
  107568. specific purpose, and the encoder is not flexible without modification:
  107569. The LSP vector coder uses a single stage nearest-match with no
  107570. interleave, so no step and no error return. This is specced by floor0
  107571. and doesn't change.
  107572. Residue0 encoding interleaves, uses multiple stages, and each stage
  107573. peels of a specific amount of resolution from a lattice (thus we want
  107574. to match by threshold, not nearest match). Residue doesn't *have* to
  107575. be encoded that way, but to change it, one will need to add more
  107576. infrastructure on the encode side (decode side is specced and simpler) */
  107577. /* floor0 LSP (single stage, non interleaved, nearest match) */
  107578. /* returns entry number and *modifies a* to the quantization value *****/
  107579. int vorbis_book_errorv(codebook *book,float *a){
  107580. int dim=book->dim,k;
  107581. int best=_best(book,a,1);
  107582. for(k=0;k<dim;k++)
  107583. a[k]=(book->valuelist+best*dim)[k];
  107584. return(best);
  107585. }
  107586. /* returns the number of bits and *modifies a* to the quantization value *****/
  107587. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  107588. int k,dim=book->dim;
  107589. for(k=0;k<dim;k++)
  107590. a[k]=(book->valuelist+best*dim)[k];
  107591. return(vorbis_book_encode(book,best,b));
  107592. }
  107593. /* the 'eliminate the decode tree' optimization actually requires the
  107594. codewords to be MSb first, not LSb. This is an annoying inelegancy
  107595. (and one of the first places where carefully thought out design
  107596. turned out to be wrong; Vorbis II and future Ogg codecs should go
  107597. to an MSb bitpacker), but not actually the huge hit it appears to
  107598. be. The first-stage decode table catches most words so that
  107599. bitreverse is not in the main execution path. */
  107600. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  107601. int read=book->dec_maxlength;
  107602. long lo,hi;
  107603. long lok = oggpack_look(b,book->dec_firsttablen);
  107604. if (lok >= 0) {
  107605. long entry = book->dec_firsttable[lok];
  107606. if(entry&0x80000000UL){
  107607. lo=(entry>>15)&0x7fff;
  107608. hi=book->used_entries-(entry&0x7fff);
  107609. }else{
  107610. oggpack_adv(b, book->dec_codelengths[entry-1]);
  107611. return(entry-1);
  107612. }
  107613. }else{
  107614. lo=0;
  107615. hi=book->used_entries;
  107616. }
  107617. lok = oggpack_look(b, read);
  107618. while(lok<0 && read>1)
  107619. lok = oggpack_look(b, --read);
  107620. if(lok<0)return -1;
  107621. /* bisect search for the codeword in the ordered list */
  107622. {
  107623. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  107624. while(hi-lo>1){
  107625. long p=(hi-lo)>>1;
  107626. long test=book->codelist[lo+p]>testword;
  107627. lo+=p&(test-1);
  107628. hi-=p&(-test);
  107629. }
  107630. if(book->dec_codelengths[lo]<=read){
  107631. oggpack_adv(b, book->dec_codelengths[lo]);
  107632. return(lo);
  107633. }
  107634. }
  107635. oggpack_adv(b, read);
  107636. return(-1);
  107637. }
  107638. /* Decode side is specced and easier, because we don't need to find
  107639. matches using different criteria; we simply read and map. There are
  107640. two things we need to do 'depending':
  107641. We may need to support interleave. We don't really, but it's
  107642. convenient to do it here rather than rebuild the vector later.
  107643. Cascades may be additive or multiplicitive; this is not inherent in
  107644. the codebook, but set in the code using the codebook. Like
  107645. interleaving, it's easiest to do it here.
  107646. addmul==0 -> declarative (set the value)
  107647. addmul==1 -> additive
  107648. addmul==2 -> multiplicitive */
  107649. /* returns the [original, not compacted] entry number or -1 on eof *********/
  107650. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  107651. long packed_entry=decode_packed_entry_number(book,b);
  107652. if(packed_entry>=0)
  107653. return(book->dec_index[packed_entry]);
  107654. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  107655. return(packed_entry);
  107656. }
  107657. /* returns 0 on OK or -1 on eof *************************************/
  107658. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107659. int step=n/book->dim;
  107660. long *entry = (long*)alloca(sizeof(*entry)*step);
  107661. float **t = (float**)alloca(sizeof(*t)*step);
  107662. int i,j,o;
  107663. for (i = 0; i < step; i++) {
  107664. entry[i]=decode_packed_entry_number(book,b);
  107665. if(entry[i]==-1)return(-1);
  107666. t[i] = book->valuelist+entry[i]*book->dim;
  107667. }
  107668. for(i=0,o=0;i<book->dim;i++,o+=step)
  107669. for (j=0;j<step;j++)
  107670. a[o+j]+=t[j][i];
  107671. return(0);
  107672. }
  107673. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  107674. int i,j,entry;
  107675. float *t;
  107676. if(book->dim>8){
  107677. for(i=0;i<n;){
  107678. entry = decode_packed_entry_number(book,b);
  107679. if(entry==-1)return(-1);
  107680. t = book->valuelist+entry*book->dim;
  107681. for (j=0;j<book->dim;)
  107682. a[i++]+=t[j++];
  107683. }
  107684. }else{
  107685. for(i=0;i<n;){
  107686. entry = decode_packed_entry_number(book,b);
  107687. if(entry==-1)return(-1);
  107688. t = book->valuelist+entry*book->dim;
  107689. j=0;
  107690. switch((int)book->dim){
  107691. case 8:
  107692. a[i++]+=t[j++];
  107693. case 7:
  107694. a[i++]+=t[j++];
  107695. case 6:
  107696. a[i++]+=t[j++];
  107697. case 5:
  107698. a[i++]+=t[j++];
  107699. case 4:
  107700. a[i++]+=t[j++];
  107701. case 3:
  107702. a[i++]+=t[j++];
  107703. case 2:
  107704. a[i++]+=t[j++];
  107705. case 1:
  107706. a[i++]+=t[j++];
  107707. case 0:
  107708. break;
  107709. }
  107710. }
  107711. }
  107712. return(0);
  107713. }
  107714. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  107715. int i,j,entry;
  107716. float *t;
  107717. for(i=0;i<n;){
  107718. entry = decode_packed_entry_number(book,b);
  107719. if(entry==-1)return(-1);
  107720. t = book->valuelist+entry*book->dim;
  107721. for (j=0;j<book->dim;)
  107722. a[i++]=t[j++];
  107723. }
  107724. return(0);
  107725. }
  107726. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  107727. oggpack_buffer *b,int n){
  107728. long i,j,entry;
  107729. int chptr=0;
  107730. for(i=offset/ch;i<(offset+n)/ch;){
  107731. entry = decode_packed_entry_number(book,b);
  107732. if(entry==-1)return(-1);
  107733. {
  107734. const float *t = book->valuelist+entry*book->dim;
  107735. for (j=0;j<book->dim;j++){
  107736. a[chptr++][i]+=t[j];
  107737. if(chptr==ch){
  107738. chptr=0;
  107739. i++;
  107740. }
  107741. }
  107742. }
  107743. }
  107744. return(0);
  107745. }
  107746. #ifdef _V_SELFTEST
  107747. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  107748. number of vectors through (keeping track of the quantized values),
  107749. and decode using the unpacked book. quantized version of in should
  107750. exactly equal out */
  107751. #include <stdio.h>
  107752. #include "vorbis/book/lsp20_0.vqh"
  107753. #include "vorbis/book/res0a_13.vqh"
  107754. #define TESTSIZE 40
  107755. float test1[TESTSIZE]={
  107756. 0.105939f,
  107757. 0.215373f,
  107758. 0.429117f,
  107759. 0.587974f,
  107760. 0.181173f,
  107761. 0.296583f,
  107762. 0.515707f,
  107763. 0.715261f,
  107764. 0.162327f,
  107765. 0.263834f,
  107766. 0.342876f,
  107767. 0.406025f,
  107768. 0.103571f,
  107769. 0.223561f,
  107770. 0.368513f,
  107771. 0.540313f,
  107772. 0.136672f,
  107773. 0.395882f,
  107774. 0.587183f,
  107775. 0.652476f,
  107776. 0.114338f,
  107777. 0.417300f,
  107778. 0.525486f,
  107779. 0.698679f,
  107780. 0.147492f,
  107781. 0.324481f,
  107782. 0.643089f,
  107783. 0.757582f,
  107784. 0.139556f,
  107785. 0.215795f,
  107786. 0.324559f,
  107787. 0.399387f,
  107788. 0.120236f,
  107789. 0.267420f,
  107790. 0.446940f,
  107791. 0.608760f,
  107792. 0.115587f,
  107793. 0.287234f,
  107794. 0.571081f,
  107795. 0.708603f,
  107796. };
  107797. float test3[TESTSIZE]={
  107798. 0,1,-2,3,4,-5,6,7,8,9,
  107799. 8,-2,7,-1,4,6,8,3,1,-9,
  107800. 10,11,12,13,14,15,26,17,18,19,
  107801. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  107802. static_codebook *testlist[]={&_vq_book_lsp20_0,
  107803. &_vq_book_res0a_13,NULL};
  107804. float *testvec[]={test1,test3};
  107805. int main(){
  107806. oggpack_buffer write;
  107807. oggpack_buffer read;
  107808. long ptr=0,i;
  107809. oggpack_writeinit(&write);
  107810. fprintf(stderr,"Testing codebook abstraction...:\n");
  107811. while(testlist[ptr]){
  107812. codebook c;
  107813. static_codebook s;
  107814. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  107815. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  107816. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  107817. memset(iv,0,sizeof(*iv)*TESTSIZE);
  107818. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  107819. /* pack the codebook, write the testvector */
  107820. oggpack_reset(&write);
  107821. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  107822. we can write */
  107823. vorbis_staticbook_pack(testlist[ptr],&write);
  107824. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  107825. for(i=0;i<TESTSIZE;i+=c.dim){
  107826. int best=_best(&c,qv+i,1);
  107827. vorbis_book_encodev(&c,best,qv+i,&write);
  107828. }
  107829. vorbis_book_clear(&c);
  107830. fprintf(stderr,"OK.\n");
  107831. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  107832. /* transfer the write data to a read buffer and unpack/read */
  107833. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  107834. if(vorbis_staticbook_unpack(&read,&s)){
  107835. fprintf(stderr,"Error unpacking codebook.\n");
  107836. exit(1);
  107837. }
  107838. if(vorbis_book_init_decode(&c,&s)){
  107839. fprintf(stderr,"Error initializing codebook.\n");
  107840. exit(1);
  107841. }
  107842. for(i=0;i<TESTSIZE;i+=c.dim)
  107843. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  107844. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  107845. exit(1);
  107846. }
  107847. for(i=0;i<TESTSIZE;i++)
  107848. if(fabs(qv[i]-iv[i])>.000001){
  107849. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  107850. iv[i],qv[i],i);
  107851. exit(1);
  107852. }
  107853. fprintf(stderr,"OK\n");
  107854. ptr++;
  107855. }
  107856. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  107857. exit(0);
  107858. }
  107859. #endif
  107860. #endif
  107861. /********* End of inlined file: codebook.c *********/
  107862. /********* Start of inlined file: envelope.c *********/
  107863. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107864. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107865. // tasks..
  107866. #ifdef _MSC_VER
  107867. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107868. #endif
  107869. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107870. #if JUCE_USE_OGGVORBIS
  107871. #include <stdlib.h>
  107872. #include <string.h>
  107873. #include <stdio.h>
  107874. #include <math.h>
  107875. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  107876. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107877. vorbis_info_psy_global *gi=&ci->psy_g_param;
  107878. int ch=vi->channels;
  107879. int i,j;
  107880. int n=e->winlength=128;
  107881. e->searchstep=64; /* not random */
  107882. e->minenergy=gi->preecho_minenergy;
  107883. e->ch=ch;
  107884. e->storage=128;
  107885. e->cursor=ci->blocksizes[1]/2;
  107886. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  107887. mdct_init(&e->mdct,n);
  107888. for(i=0;i<n;i++){
  107889. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  107890. e->mdct_win[i]*=e->mdct_win[i];
  107891. }
  107892. /* magic follows */
  107893. e->band[0].begin=2; e->band[0].end=4;
  107894. e->band[1].begin=4; e->band[1].end=5;
  107895. e->band[2].begin=6; e->band[2].end=6;
  107896. e->band[3].begin=9; e->band[3].end=8;
  107897. e->band[4].begin=13; e->band[4].end=8;
  107898. e->band[5].begin=17; e->band[5].end=8;
  107899. e->band[6].begin=22; e->band[6].end=8;
  107900. for(j=0;j<VE_BANDS;j++){
  107901. n=e->band[j].end;
  107902. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  107903. for(i=0;i<n;i++){
  107904. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  107905. e->band[j].total+=e->band[j].window[i];
  107906. }
  107907. e->band[j].total=1./e->band[j].total;
  107908. }
  107909. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  107910. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  107911. }
  107912. void _ve_envelope_clear(envelope_lookup *e){
  107913. int i;
  107914. mdct_clear(&e->mdct);
  107915. for(i=0;i<VE_BANDS;i++)
  107916. _ogg_free(e->band[i].window);
  107917. _ogg_free(e->mdct_win);
  107918. _ogg_free(e->filter);
  107919. _ogg_free(e->mark);
  107920. memset(e,0,sizeof(*e));
  107921. }
  107922. /* fairly straight threshhold-by-band based until we find something
  107923. that works better and isn't patented. */
  107924. static int _ve_amp(envelope_lookup *ve,
  107925. vorbis_info_psy_global *gi,
  107926. float *data,
  107927. envelope_band *bands,
  107928. envelope_filter_state *filters,
  107929. long pos){
  107930. long n=ve->winlength;
  107931. int ret=0;
  107932. long i,j;
  107933. float decay;
  107934. /* we want to have a 'minimum bar' for energy, else we're just
  107935. basing blocks on quantization noise that outweighs the signal
  107936. itself (for low power signals) */
  107937. float minV=ve->minenergy;
  107938. float *vec=(float*) alloca(n*sizeof(*vec));
  107939. /* stretch is used to gradually lengthen the number of windows
  107940. considered prevoius-to-potential-trigger */
  107941. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  107942. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  107943. if(penalty<0.f)penalty=0.f;
  107944. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  107945. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  107946. totalshift+pos*ve->searchstep);*/
  107947. /* window and transform */
  107948. for(i=0;i<n;i++)
  107949. vec[i]=data[i]*ve->mdct_win[i];
  107950. mdct_forward(&ve->mdct,vec,vec);
  107951. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  107952. /* near-DC spreading function; this has nothing to do with
  107953. psychoacoustics, just sidelobe leakage and window size */
  107954. {
  107955. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  107956. int ptr=filters->nearptr;
  107957. /* the accumulation is regularly refreshed from scratch to avoid
  107958. floating point creep */
  107959. if(ptr==0){
  107960. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  107961. filters->nearDC_partialacc=temp;
  107962. }else{
  107963. decay=filters->nearDC_acc+=temp;
  107964. filters->nearDC_partialacc+=temp;
  107965. }
  107966. filters->nearDC_acc-=filters->nearDC[ptr];
  107967. filters->nearDC[ptr]=temp;
  107968. decay*=(1./(VE_NEARDC+1));
  107969. filters->nearptr++;
  107970. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  107971. decay=todB(&decay)*.5-15.f;
  107972. }
  107973. /* perform spreading and limiting, also smooth the spectrum. yes,
  107974. the MDCT results in all real coefficients, but it still *behaves*
  107975. like real/imaginary pairs */
  107976. for(i=0;i<n/2;i+=2){
  107977. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  107978. val=todB(&val)*.5f;
  107979. if(val<decay)val=decay;
  107980. if(val<minV)val=minV;
  107981. vec[i>>1]=val;
  107982. decay-=8.;
  107983. }
  107984. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  107985. /* perform preecho/postecho triggering by band */
  107986. for(j=0;j<VE_BANDS;j++){
  107987. float acc=0.;
  107988. float valmax,valmin;
  107989. /* accumulate amplitude */
  107990. for(i=0;i<bands[j].end;i++)
  107991. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  107992. acc*=bands[j].total;
  107993. /* convert amplitude to delta */
  107994. {
  107995. int p,thisx=filters[j].ampptr;
  107996. float postmax,postmin,premax=-99999.f,premin=99999.f;
  107997. p=thisx;
  107998. p--;
  107999. if(p<0)p+=VE_AMP;
  108000. postmax=max(acc,filters[j].ampbuf[p]);
  108001. postmin=min(acc,filters[j].ampbuf[p]);
  108002. for(i=0;i<stretch;i++){
  108003. p--;
  108004. if(p<0)p+=VE_AMP;
  108005. premax=max(premax,filters[j].ampbuf[p]);
  108006. premin=min(premin,filters[j].ampbuf[p]);
  108007. }
  108008. valmin=postmin-premin;
  108009. valmax=postmax-premax;
  108010. /*filters[j].markers[pos]=valmax;*/
  108011. filters[j].ampbuf[thisx]=acc;
  108012. filters[j].ampptr++;
  108013. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  108014. }
  108015. /* look at min/max, decide trigger */
  108016. if(valmax>gi->preecho_thresh[j]+penalty){
  108017. ret|=1;
  108018. ret|=4;
  108019. }
  108020. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  108021. }
  108022. return(ret);
  108023. }
  108024. #if 0
  108025. static int seq=0;
  108026. static ogg_int64_t totalshift=-1024;
  108027. #endif
  108028. long _ve_envelope_search(vorbis_dsp_state *v){
  108029. vorbis_info *vi=v->vi;
  108030. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108031. vorbis_info_psy_global *gi=&ci->psy_g_param;
  108032. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108033. long i,j;
  108034. int first=ve->current/ve->searchstep;
  108035. int last=v->pcm_current/ve->searchstep-VE_WIN;
  108036. if(first<0)first=0;
  108037. /* make sure we have enough storage to match the PCM */
  108038. if(last+VE_WIN+VE_POST>ve->storage){
  108039. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  108040. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  108041. }
  108042. for(j=first;j<last;j++){
  108043. int ret=0;
  108044. ve->stretch++;
  108045. if(ve->stretch>VE_MAXSTRETCH*2)
  108046. ve->stretch=VE_MAXSTRETCH*2;
  108047. for(i=0;i<ve->ch;i++){
  108048. float *pcm=v->pcm[i]+ve->searchstep*(j);
  108049. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  108050. }
  108051. ve->mark[j+VE_POST]=0;
  108052. if(ret&1){
  108053. ve->mark[j]=1;
  108054. ve->mark[j+1]=1;
  108055. }
  108056. if(ret&2){
  108057. ve->mark[j]=1;
  108058. if(j>0)ve->mark[j-1]=1;
  108059. }
  108060. if(ret&4)ve->stretch=-1;
  108061. }
  108062. ve->current=last*ve->searchstep;
  108063. {
  108064. long centerW=v->centerW;
  108065. long testW=
  108066. centerW+
  108067. ci->blocksizes[v->W]/4+
  108068. ci->blocksizes[1]/2+
  108069. ci->blocksizes[0]/4;
  108070. j=ve->cursor;
  108071. while(j<ve->current-(ve->searchstep)){/* account for postecho
  108072. working back one window */
  108073. if(j>=testW)return(1);
  108074. ve->cursor=j;
  108075. if(ve->mark[j/ve->searchstep]){
  108076. if(j>centerW){
  108077. #if 0
  108078. if(j>ve->curmark){
  108079. float *marker=alloca(v->pcm_current*sizeof(*marker));
  108080. int l,m;
  108081. memset(marker,0,sizeof(*marker)*v->pcm_current);
  108082. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  108083. seq,
  108084. (totalshift+ve->cursor)/44100.,
  108085. (totalshift+j)/44100.);
  108086. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  108087. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  108088. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  108089. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  108090. for(m=0;m<VE_BANDS;m++){
  108091. char buf[80];
  108092. sprintf(buf,"delL%d",m);
  108093. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  108094. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108095. }
  108096. for(m=0;m<VE_BANDS;m++){
  108097. char buf[80];
  108098. sprintf(buf,"delR%d",m);
  108099. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  108100. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  108101. }
  108102. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  108103. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  108104. seq++;
  108105. }
  108106. #endif
  108107. ve->curmark=j;
  108108. if(j>=testW)return(1);
  108109. return(0);
  108110. }
  108111. }
  108112. j+=ve->searchstep;
  108113. }
  108114. }
  108115. return(-1);
  108116. }
  108117. int _ve_envelope_mark(vorbis_dsp_state *v){
  108118. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  108119. vorbis_info *vi=v->vi;
  108120. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108121. long centerW=v->centerW;
  108122. long beginW=centerW-ci->blocksizes[v->W]/4;
  108123. long endW=centerW+ci->blocksizes[v->W]/4;
  108124. if(v->W){
  108125. beginW-=ci->blocksizes[v->lW]/4;
  108126. endW+=ci->blocksizes[v->nW]/4;
  108127. }else{
  108128. beginW-=ci->blocksizes[0]/4;
  108129. endW+=ci->blocksizes[0]/4;
  108130. }
  108131. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  108132. {
  108133. long first=beginW/ve->searchstep;
  108134. long last=endW/ve->searchstep;
  108135. long i;
  108136. for(i=first;i<last;i++)
  108137. if(ve->mark[i])return(1);
  108138. }
  108139. return(0);
  108140. }
  108141. void _ve_envelope_shift(envelope_lookup *e,long shift){
  108142. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  108143. ahead of ve->current */
  108144. int smallshift=shift/e->searchstep;
  108145. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  108146. #if 0
  108147. for(i=0;i<VE_BANDS*e->ch;i++)
  108148. memmove(e->filter[i].markers,
  108149. e->filter[i].markers+smallshift,
  108150. (1024-smallshift)*sizeof(*(*e->filter).markers));
  108151. totalshift+=shift;
  108152. #endif
  108153. e->current-=shift;
  108154. if(e->curmark>=0)
  108155. e->curmark-=shift;
  108156. e->cursor-=shift;
  108157. }
  108158. #endif
  108159. /********* End of inlined file: envelope.c *********/
  108160. /********* Start of inlined file: floor0.c *********/
  108161. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108162. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108163. // tasks..
  108164. #ifdef _MSC_VER
  108165. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108166. #endif
  108167. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108168. #if JUCE_USE_OGGVORBIS
  108169. #include <stdlib.h>
  108170. #include <string.h>
  108171. #include <math.h>
  108172. /********* Start of inlined file: lsp.h *********/
  108173. #ifndef _V_LSP_H_
  108174. #define _V_LSP_H_
  108175. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  108176. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  108177. float *lsp,int m,
  108178. float amp,float ampoffset);
  108179. #endif
  108180. /********* End of inlined file: lsp.h *********/
  108181. #include <stdio.h>
  108182. typedef struct {
  108183. int ln;
  108184. int m;
  108185. int **linearmap;
  108186. int n[2];
  108187. vorbis_info_floor0 *vi;
  108188. long bits;
  108189. long frames;
  108190. } vorbis_look_floor0;
  108191. /***********************************************/
  108192. static void floor0_free_info(vorbis_info_floor *i){
  108193. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  108194. if(info){
  108195. memset(info,0,sizeof(*info));
  108196. _ogg_free(info);
  108197. }
  108198. }
  108199. static void floor0_free_look(vorbis_look_floor *i){
  108200. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108201. if(look){
  108202. if(look->linearmap){
  108203. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  108204. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  108205. _ogg_free(look->linearmap);
  108206. }
  108207. memset(look,0,sizeof(*look));
  108208. _ogg_free(look);
  108209. }
  108210. }
  108211. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108212. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108213. int j;
  108214. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  108215. info->order=oggpack_read(opb,8);
  108216. info->rate=oggpack_read(opb,16);
  108217. info->barkmap=oggpack_read(opb,16);
  108218. info->ampbits=oggpack_read(opb,6);
  108219. info->ampdB=oggpack_read(opb,8);
  108220. info->numbooks=oggpack_read(opb,4)+1;
  108221. if(info->order<1)goto err_out;
  108222. if(info->rate<1)goto err_out;
  108223. if(info->barkmap<1)goto err_out;
  108224. if(info->numbooks<1)goto err_out;
  108225. for(j=0;j<info->numbooks;j++){
  108226. info->books[j]=oggpack_read(opb,8);
  108227. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  108228. }
  108229. return(info);
  108230. err_out:
  108231. floor0_free_info(info);
  108232. return(NULL);
  108233. }
  108234. /* initialize Bark scale and normalization lookups. We could do this
  108235. with static tables, but Vorbis allows a number of possible
  108236. combinations, so it's best to do it computationally.
  108237. The below is authoritative in terms of defining scale mapping.
  108238. Note that the scale depends on the sampling rate as well as the
  108239. linear block and mapping sizes */
  108240. static void floor0_map_lazy_init(vorbis_block *vb,
  108241. vorbis_info_floor *infoX,
  108242. vorbis_look_floor0 *look){
  108243. if(!look->linearmap[vb->W]){
  108244. vorbis_dsp_state *vd=vb->vd;
  108245. vorbis_info *vi=vd->vi;
  108246. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108247. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  108248. int W=vb->W;
  108249. int n=ci->blocksizes[W]/2,j;
  108250. /* we choose a scaling constant so that:
  108251. floor(bark(rate/2-1)*C)=mapped-1
  108252. floor(bark(rate/2)*C)=mapped */
  108253. float scale=look->ln/toBARK(info->rate/2.f);
  108254. /* the mapping from a linear scale to a smaller bark scale is
  108255. straightforward. We do *not* make sure that the linear mapping
  108256. does not skip bark-scale bins; the decoder simply skips them and
  108257. the encoder may do what it wishes in filling them. They're
  108258. necessary in some mapping combinations to keep the scale spacing
  108259. accurate */
  108260. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  108261. for(j=0;j<n;j++){
  108262. int val=floor( toBARK((info->rate/2.f)/n*j)
  108263. *scale); /* bark numbers represent band edges */
  108264. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  108265. look->linearmap[W][j]=val;
  108266. }
  108267. look->linearmap[W][j]=-1;
  108268. look->n[W]=n;
  108269. }
  108270. }
  108271. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  108272. vorbis_info_floor *i){
  108273. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  108274. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  108275. look->m=info->order;
  108276. look->ln=info->barkmap;
  108277. look->vi=info;
  108278. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  108279. return look;
  108280. }
  108281. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  108282. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108283. vorbis_info_floor0 *info=look->vi;
  108284. int j,k;
  108285. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  108286. if(ampraw>0){ /* also handles the -1 out of data case */
  108287. long maxval=(1<<info->ampbits)-1;
  108288. float amp=(float)ampraw/maxval*info->ampdB;
  108289. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  108290. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  108291. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  108292. codebook *b=ci->fullbooks+info->books[booknum];
  108293. float last=0.f;
  108294. /* the additional b->dim is a guard against any possible stack
  108295. smash; b->dim is provably more than we can overflow the
  108296. vector */
  108297. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  108298. for(j=0;j<look->m;j+=b->dim)
  108299. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  108300. for(j=0;j<look->m;){
  108301. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  108302. last=lsp[j-1];
  108303. }
  108304. lsp[look->m]=amp;
  108305. return(lsp);
  108306. }
  108307. }
  108308. eop:
  108309. return(NULL);
  108310. }
  108311. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  108312. void *memo,float *out){
  108313. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  108314. vorbis_info_floor0 *info=look->vi;
  108315. floor0_map_lazy_init(vb,info,look);
  108316. if(memo){
  108317. float *lsp=(float *)memo;
  108318. float amp=lsp[look->m];
  108319. /* take the coefficients back to a spectral envelope curve */
  108320. vorbis_lsp_to_curve(out,
  108321. look->linearmap[vb->W],
  108322. look->n[vb->W],
  108323. look->ln,
  108324. lsp,look->m,amp,(float)info->ampdB);
  108325. return(1);
  108326. }
  108327. memset(out,0,sizeof(*out)*look->n[vb->W]);
  108328. return(0);
  108329. }
  108330. /* export hooks */
  108331. vorbis_func_floor floor0_exportbundle={
  108332. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  108333. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  108334. };
  108335. #endif
  108336. /********* End of inlined file: floor0.c *********/
  108337. /********* Start of inlined file: floor1.c *********/
  108338. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108339. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108340. // tasks..
  108341. #ifdef _MSC_VER
  108342. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108343. #endif
  108344. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108345. #if JUCE_USE_OGGVORBIS
  108346. #include <stdlib.h>
  108347. #include <string.h>
  108348. #include <math.h>
  108349. #include <stdio.h>
  108350. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  108351. typedef struct {
  108352. int sorted_index[VIF_POSIT+2];
  108353. int forward_index[VIF_POSIT+2];
  108354. int reverse_index[VIF_POSIT+2];
  108355. int hineighbor[VIF_POSIT];
  108356. int loneighbor[VIF_POSIT];
  108357. int posts;
  108358. int n;
  108359. int quant_q;
  108360. vorbis_info_floor1 *vi;
  108361. long phrasebits;
  108362. long postbits;
  108363. long frames;
  108364. } vorbis_look_floor1;
  108365. typedef struct lsfit_acc{
  108366. long x0;
  108367. long x1;
  108368. long xa;
  108369. long ya;
  108370. long x2a;
  108371. long y2a;
  108372. long xya;
  108373. long an;
  108374. } lsfit_acc;
  108375. /***********************************************/
  108376. static void floor1_free_info(vorbis_info_floor *i){
  108377. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108378. if(info){
  108379. memset(info,0,sizeof(*info));
  108380. _ogg_free(info);
  108381. }
  108382. }
  108383. static void floor1_free_look(vorbis_look_floor *i){
  108384. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  108385. if(look){
  108386. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  108387. (float)look->phrasebits/look->frames,
  108388. (float)look->postbits/look->frames,
  108389. (float)(look->postbits+look->phrasebits)/look->frames);*/
  108390. memset(look,0,sizeof(*look));
  108391. _ogg_free(look);
  108392. }
  108393. }
  108394. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  108395. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  108396. int j,k;
  108397. int count=0;
  108398. int rangebits;
  108399. int maxposit=info->postlist[1];
  108400. int maxclass=-1;
  108401. /* save out partitions */
  108402. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  108403. for(j=0;j<info->partitions;j++){
  108404. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  108405. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108406. }
  108407. /* save out partition classes */
  108408. for(j=0;j<maxclass+1;j++){
  108409. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  108410. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  108411. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  108412. for(k=0;k<(1<<info->class_subs[j]);k++)
  108413. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  108414. }
  108415. /* save out the post list */
  108416. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  108417. oggpack_write(opb,ilog2(maxposit),4);
  108418. rangebits=ilog2(maxposit);
  108419. for(j=0,k=0;j<info->partitions;j++){
  108420. count+=info->class_dim[info->partitionclass[j]];
  108421. for(;k<count;k++)
  108422. oggpack_write(opb,info->postlist[k+2],rangebits);
  108423. }
  108424. }
  108425. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  108426. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108427. int j,k,count=0,maxclass=-1,rangebits;
  108428. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  108429. /* read partitions */
  108430. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  108431. for(j=0;j<info->partitions;j++){
  108432. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  108433. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  108434. }
  108435. /* read partition classes */
  108436. for(j=0;j<maxclass+1;j++){
  108437. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  108438. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  108439. if(info->class_subs[j]<0)
  108440. goto err_out;
  108441. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  108442. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  108443. goto err_out;
  108444. for(k=0;k<(1<<info->class_subs[j]);k++){
  108445. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  108446. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  108447. goto err_out;
  108448. }
  108449. }
  108450. /* read the post list */
  108451. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  108452. rangebits=oggpack_read(opb,4);
  108453. for(j=0,k=0;j<info->partitions;j++){
  108454. count+=info->class_dim[info->partitionclass[j]];
  108455. for(;k<count;k++){
  108456. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  108457. if(t<0 || t>=(1<<rangebits))
  108458. goto err_out;
  108459. }
  108460. }
  108461. info->postlist[0]=0;
  108462. info->postlist[1]=1<<rangebits;
  108463. return(info);
  108464. err_out:
  108465. floor1_free_info(info);
  108466. return(NULL);
  108467. }
  108468. static int icomp(const void *a,const void *b){
  108469. return(**(int **)a-**(int **)b);
  108470. }
  108471. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  108472. vorbis_info_floor *in){
  108473. int *sortpointer[VIF_POSIT+2];
  108474. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  108475. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  108476. int i,j,n=0;
  108477. look->vi=info;
  108478. look->n=info->postlist[1];
  108479. /* we drop each position value in-between already decoded values,
  108480. and use linear interpolation to predict each new value past the
  108481. edges. The positions are read in the order of the position
  108482. list... we precompute the bounding positions in the lookup. Of
  108483. course, the neighbors can change (if a position is declined), but
  108484. this is an initial mapping */
  108485. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  108486. n+=2;
  108487. look->posts=n;
  108488. /* also store a sorted position index */
  108489. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  108490. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  108491. /* points from sort order back to range number */
  108492. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  108493. /* points from range order to sorted position */
  108494. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  108495. /* we actually need the post values too */
  108496. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  108497. /* quantize values to multiplier spec */
  108498. switch(info->mult){
  108499. case 1: /* 1024 -> 256 */
  108500. look->quant_q=256;
  108501. break;
  108502. case 2: /* 1024 -> 128 */
  108503. look->quant_q=128;
  108504. break;
  108505. case 3: /* 1024 -> 86 */
  108506. look->quant_q=86;
  108507. break;
  108508. case 4: /* 1024 -> 64 */
  108509. look->quant_q=64;
  108510. break;
  108511. }
  108512. /* discover our neighbors for decode where we don't use fit flags
  108513. (that would push the neighbors outward) */
  108514. for(i=0;i<n-2;i++){
  108515. int lo=0;
  108516. int hi=1;
  108517. int lx=0;
  108518. int hx=look->n;
  108519. int currentx=info->postlist[i+2];
  108520. for(j=0;j<i+2;j++){
  108521. int x=info->postlist[j];
  108522. if(x>lx && x<currentx){
  108523. lo=j;
  108524. lx=x;
  108525. }
  108526. if(x<hx && x>currentx){
  108527. hi=j;
  108528. hx=x;
  108529. }
  108530. }
  108531. look->loneighbor[i]=lo;
  108532. look->hineighbor[i]=hi;
  108533. }
  108534. return(look);
  108535. }
  108536. static int render_point(int x0,int x1,int y0,int y1,int x){
  108537. y0&=0x7fff; /* mask off flag */
  108538. y1&=0x7fff;
  108539. {
  108540. int dy=y1-y0;
  108541. int adx=x1-x0;
  108542. int ady=abs(dy);
  108543. int err=ady*(x-x0);
  108544. int off=err/adx;
  108545. if(dy<0)return(y0-off);
  108546. return(y0+off);
  108547. }
  108548. }
  108549. static int vorbis_dBquant(const float *x){
  108550. int i= *x*7.3142857f+1023.5f;
  108551. if(i>1023)return(1023);
  108552. if(i<0)return(0);
  108553. return i;
  108554. }
  108555. static float FLOOR1_fromdB_LOOKUP[256]={
  108556. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108557. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108558. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108559. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108560. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108561. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108562. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108563. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108564. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108565. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108566. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108567. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108568. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108569. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108570. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108571. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108572. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108573. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108574. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108575. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108576. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108577. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108578. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108579. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108580. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108581. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108582. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108583. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108584. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108585. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108586. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108587. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108588. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108589. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108590. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108591. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108592. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108593. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108594. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108595. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108596. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108597. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108598. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108599. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108600. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108601. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108602. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108603. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108604. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108605. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108606. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108607. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108608. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108609. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108610. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108611. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108612. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108613. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108614. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108615. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108616. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108617. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108618. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108619. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108620. };
  108621. static void render_line(int x0,int x1,int y0,int y1,float *d){
  108622. int dy=y1-y0;
  108623. int adx=x1-x0;
  108624. int ady=abs(dy);
  108625. int base=dy/adx;
  108626. int sy=(dy<0?base-1:base+1);
  108627. int x=x0;
  108628. int y=y0;
  108629. int err=0;
  108630. ady-=abs(base*adx);
  108631. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108632. while(++x<x1){
  108633. err=err+ady;
  108634. if(err>=adx){
  108635. err-=adx;
  108636. y+=sy;
  108637. }else{
  108638. y+=base;
  108639. }
  108640. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  108641. }
  108642. }
  108643. static void render_line0(int x0,int x1,int y0,int y1,int *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]=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]=y;
  108663. }
  108664. }
  108665. /* the floor has already been filtered to only include relevant sections */
  108666. static int accumulate_fit(const float *flr,const float *mdct,
  108667. int x0, int x1,lsfit_acc *a,
  108668. int n,vorbis_info_floor1 *info){
  108669. long i;
  108670. 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;
  108671. memset(a,0,sizeof(*a));
  108672. a->x0=x0;
  108673. a->x1=x1;
  108674. if(x1>=n)x1=n-1;
  108675. for(i=x0;i<=x1;i++){
  108676. int quantized=vorbis_dBquant(flr+i);
  108677. if(quantized){
  108678. if(mdct[i]+info->twofitatten>=flr[i]){
  108679. xa += i;
  108680. ya += quantized;
  108681. x2a += i*i;
  108682. y2a += quantized*quantized;
  108683. xya += i*quantized;
  108684. na++;
  108685. }else{
  108686. xb += i;
  108687. yb += quantized;
  108688. x2b += i*i;
  108689. y2b += quantized*quantized;
  108690. xyb += i*quantized;
  108691. nb++;
  108692. }
  108693. }
  108694. }
  108695. xb+=xa;
  108696. yb+=ya;
  108697. x2b+=x2a;
  108698. y2b+=y2a;
  108699. xyb+=xya;
  108700. nb+=na;
  108701. /* weight toward the actually used frequencies if we meet the threshhold */
  108702. {
  108703. int weight=nb*info->twofitweight/(na+1);
  108704. a->xa=xa*weight+xb;
  108705. a->ya=ya*weight+yb;
  108706. a->x2a=x2a*weight+x2b;
  108707. a->y2a=y2a*weight+y2b;
  108708. a->xya=xya*weight+xyb;
  108709. a->an=na*weight+nb;
  108710. }
  108711. return(na);
  108712. }
  108713. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  108714. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  108715. long x0=a[0].x0;
  108716. long x1=a[fits-1].x1;
  108717. for(i=0;i<fits;i++){
  108718. x+=a[i].xa;
  108719. y+=a[i].ya;
  108720. x2+=a[i].x2a;
  108721. y2+=a[i].y2a;
  108722. xy+=a[i].xya;
  108723. an+=a[i].an;
  108724. }
  108725. if(*y0>=0){
  108726. x+= x0;
  108727. y+= *y0;
  108728. x2+= x0 * x0;
  108729. y2+= *y0 * *y0;
  108730. xy+= *y0 * x0;
  108731. an++;
  108732. }
  108733. if(*y1>=0){
  108734. x+= x1;
  108735. y+= *y1;
  108736. x2+= x1 * x1;
  108737. y2+= *y1 * *y1;
  108738. xy+= *y1 * x1;
  108739. an++;
  108740. }
  108741. if(an){
  108742. /* need 64 bit multiplies, which C doesn't give portably as int */
  108743. double fx=x;
  108744. double fy=y;
  108745. double fx2=x2;
  108746. double fxy=xy;
  108747. double denom=1./(an*fx2-fx*fx);
  108748. double a=(fy*fx2-fxy*fx)*denom;
  108749. double b=(an*fxy-fx*fy)*denom;
  108750. *y0=rint(a+b*x0);
  108751. *y1=rint(a+b*x1);
  108752. /* limit to our range! */
  108753. if(*y0>1023)*y0=1023;
  108754. if(*y1>1023)*y1=1023;
  108755. if(*y0<0)*y0=0;
  108756. if(*y1<0)*y1=0;
  108757. }else{
  108758. *y0=0;
  108759. *y1=0;
  108760. }
  108761. }
  108762. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  108763. long y=0;
  108764. int i;
  108765. for(i=0;i<fits && y==0;i++)
  108766. y+=a[i].ya;
  108767. *y0=*y1=y;
  108768. }*/
  108769. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  108770. const float *mdct,
  108771. vorbis_info_floor1 *info){
  108772. int dy=y1-y0;
  108773. int adx=x1-x0;
  108774. int ady=abs(dy);
  108775. int base=dy/adx;
  108776. int sy=(dy<0?base-1:base+1);
  108777. int x=x0;
  108778. int y=y0;
  108779. int err=0;
  108780. int val=vorbis_dBquant(mask+x);
  108781. int mse=0;
  108782. int n=0;
  108783. ady-=abs(base*adx);
  108784. mse=(y-val);
  108785. mse*=mse;
  108786. n++;
  108787. if(mdct[x]+info->twofitatten>=mask[x]){
  108788. if(y+info->maxover<val)return(1);
  108789. if(y-info->maxunder>val)return(1);
  108790. }
  108791. while(++x<x1){
  108792. err=err+ady;
  108793. if(err>=adx){
  108794. err-=adx;
  108795. y+=sy;
  108796. }else{
  108797. y+=base;
  108798. }
  108799. val=vorbis_dBquant(mask+x);
  108800. mse+=((y-val)*(y-val));
  108801. n++;
  108802. if(mdct[x]+info->twofitatten>=mask[x]){
  108803. if(val){
  108804. if(y+info->maxover<val)return(1);
  108805. if(y-info->maxunder>val)return(1);
  108806. }
  108807. }
  108808. }
  108809. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  108810. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  108811. if(mse/n>info->maxerr)return(1);
  108812. return(0);
  108813. }
  108814. static int post_Y(int *A,int *B,int pos){
  108815. if(A[pos]<0)
  108816. return B[pos];
  108817. if(B[pos]<0)
  108818. return A[pos];
  108819. return (A[pos]+B[pos])>>1;
  108820. }
  108821. int *floor1_fit(vorbis_block *vb,void *look_,
  108822. const float *logmdct, /* in */
  108823. const float *logmask){
  108824. long i,j;
  108825. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  108826. vorbis_info_floor1 *info=look->vi;
  108827. long n=look->n;
  108828. long posts=look->posts;
  108829. long nonzero=0;
  108830. lsfit_acc fits[VIF_POSIT+1];
  108831. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  108832. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  108833. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  108834. int hineighbor[VIF_POSIT+2];
  108835. int *output=NULL;
  108836. int memo[VIF_POSIT+2];
  108837. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  108838. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  108839. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  108840. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  108841. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  108842. /* quantize the relevant floor points and collect them into line fit
  108843. structures (one per minimal division) at the same time */
  108844. if(posts==0){
  108845. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  108846. }else{
  108847. for(i=0;i<posts-1;i++)
  108848. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  108849. look->sorted_index[i+1],fits+i,
  108850. n,info);
  108851. }
  108852. if(nonzero){
  108853. /* start by fitting the implicit base case.... */
  108854. int y0=-200;
  108855. int y1=-200;
  108856. fit_line(fits,posts-1,&y0,&y1);
  108857. fit_valueA[0]=y0;
  108858. fit_valueB[0]=y0;
  108859. fit_valueB[1]=y1;
  108860. fit_valueA[1]=y1;
  108861. /* Non degenerate case */
  108862. /* start progressive splitting. This is a greedy, non-optimal
  108863. algorithm, but simple and close enough to the best
  108864. answer. */
  108865. for(i=2;i<posts;i++){
  108866. int sortpos=look->reverse_index[i];
  108867. int ln=loneighbor[sortpos];
  108868. int hn=hineighbor[sortpos];
  108869. /* eliminate repeat searches of a particular range with a memo */
  108870. if(memo[ln]!=hn){
  108871. /* haven't performed this error search yet */
  108872. int lsortpos=look->reverse_index[ln];
  108873. int hsortpos=look->reverse_index[hn];
  108874. memo[ln]=hn;
  108875. {
  108876. /* A note: we want to bound/minimize *local*, not global, error */
  108877. int lx=info->postlist[ln];
  108878. int hx=info->postlist[hn];
  108879. int ly=post_Y(fit_valueA,fit_valueB,ln);
  108880. int hy=post_Y(fit_valueA,fit_valueB,hn);
  108881. if(ly==-1 || hy==-1){
  108882. exit(1);
  108883. }
  108884. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  108885. /* outside error bounds/begin search area. Split it. */
  108886. int ly0=-200;
  108887. int ly1=-200;
  108888. int hy0=-200;
  108889. int hy1=-200;
  108890. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  108891. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  108892. /* store new edge values */
  108893. fit_valueB[ln]=ly0;
  108894. if(ln==0)fit_valueA[ln]=ly0;
  108895. fit_valueA[i]=ly1;
  108896. fit_valueB[i]=hy0;
  108897. fit_valueA[hn]=hy1;
  108898. if(hn==1)fit_valueB[hn]=hy1;
  108899. if(ly1>=0 || hy0>=0){
  108900. /* store new neighbor values */
  108901. for(j=sortpos-1;j>=0;j--)
  108902. if(hineighbor[j]==hn)
  108903. hineighbor[j]=i;
  108904. else
  108905. break;
  108906. for(j=sortpos+1;j<posts;j++)
  108907. if(loneighbor[j]==ln)
  108908. loneighbor[j]=i;
  108909. else
  108910. break;
  108911. }
  108912. }else{
  108913. fit_valueA[i]=-200;
  108914. fit_valueB[i]=-200;
  108915. }
  108916. }
  108917. }
  108918. }
  108919. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108920. output[0]=post_Y(fit_valueA,fit_valueB,0);
  108921. output[1]=post_Y(fit_valueA,fit_valueB,1);
  108922. /* fill in posts marked as not using a fit; we will zero
  108923. back out to 'unused' when encoding them so long as curve
  108924. interpolation doesn't force them into use */
  108925. for(i=2;i<posts;i++){
  108926. int ln=look->loneighbor[i-2];
  108927. int hn=look->hineighbor[i-2];
  108928. int x0=info->postlist[ln];
  108929. int x1=info->postlist[hn];
  108930. int y0=output[ln];
  108931. int y1=output[hn];
  108932. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  108933. int vx=post_Y(fit_valueA,fit_valueB,i);
  108934. if(vx>=0 && predicted!=vx){
  108935. output[i]=vx;
  108936. }else{
  108937. output[i]= predicted|0x8000;
  108938. }
  108939. }
  108940. }
  108941. return(output);
  108942. }
  108943. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  108944. int *A,int *B,
  108945. int del){
  108946. long i;
  108947. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  108948. long posts=look->posts;
  108949. int *output=NULL;
  108950. if(A && B){
  108951. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  108952. for(i=0;i<posts;i++){
  108953. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  108954. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  108955. }
  108956. }
  108957. return(output);
  108958. }
  108959. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108960. void*look_,
  108961. int *post,int *ilogmask){
  108962. long i,j;
  108963. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  108964. vorbis_info_floor1 *info=look->vi;
  108965. long posts=look->posts;
  108966. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  108967. int out[VIF_POSIT+2];
  108968. static_codebook **sbooks=ci->book_param;
  108969. codebook *books=ci->fullbooks;
  108970. static long seq=0;
  108971. /* quantize values to multiplier spec */
  108972. if(post){
  108973. for(i=0;i<posts;i++){
  108974. int val=post[i]&0x7fff;
  108975. switch(info->mult){
  108976. case 1: /* 1024 -> 256 */
  108977. val>>=2;
  108978. break;
  108979. case 2: /* 1024 -> 128 */
  108980. val>>=3;
  108981. break;
  108982. case 3: /* 1024 -> 86 */
  108983. val/=12;
  108984. break;
  108985. case 4: /* 1024 -> 64 */
  108986. val>>=4;
  108987. break;
  108988. }
  108989. post[i]=val | (post[i]&0x8000);
  108990. }
  108991. out[0]=post[0];
  108992. out[1]=post[1];
  108993. /* find prediction values for each post and subtract them */
  108994. for(i=2;i<posts;i++){
  108995. int ln=look->loneighbor[i-2];
  108996. int hn=look->hineighbor[i-2];
  108997. int x0=info->postlist[ln];
  108998. int x1=info->postlist[hn];
  108999. int y0=post[ln];
  109000. int y1=post[hn];
  109001. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  109002. if((post[i]&0x8000) || (predicted==post[i])){
  109003. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  109004. in interpolation */
  109005. out[i]=0;
  109006. }else{
  109007. int headroom=(look->quant_q-predicted<predicted?
  109008. look->quant_q-predicted:predicted);
  109009. int val=post[i]-predicted;
  109010. /* at this point the 'deviation' value is in the range +/- max
  109011. range, but the real, unique range can always be mapped to
  109012. only [0-maxrange). So we want to wrap the deviation into
  109013. this limited range, but do it in the way that least screws
  109014. an essentially gaussian probability distribution. */
  109015. if(val<0)
  109016. if(val<-headroom)
  109017. val=headroom-val-1;
  109018. else
  109019. val=-1-(val<<1);
  109020. else
  109021. if(val>=headroom)
  109022. val= val+headroom;
  109023. else
  109024. val<<=1;
  109025. out[i]=val;
  109026. post[ln]&=0x7fff;
  109027. post[hn]&=0x7fff;
  109028. }
  109029. }
  109030. /* we have everything we need. pack it out */
  109031. /* mark nontrivial floor */
  109032. oggpack_write(opb,1,1);
  109033. /* beginning/end post */
  109034. look->frames++;
  109035. look->postbits+=ilog(look->quant_q-1)*2;
  109036. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  109037. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  109038. /* partition by partition */
  109039. for(i=0,j=2;i<info->partitions;i++){
  109040. int classx=info->partitionclass[i];
  109041. int cdim=info->class_dim[classx];
  109042. int csubbits=info->class_subs[classx];
  109043. int csub=1<<csubbits;
  109044. int bookas[8]={0,0,0,0,0,0,0,0};
  109045. int cval=0;
  109046. int cshift=0;
  109047. int k,l;
  109048. /* generate the partition's first stage cascade value */
  109049. if(csubbits){
  109050. int maxval[8];
  109051. for(k=0;k<csub;k++){
  109052. int booknum=info->class_subbook[classx][k];
  109053. if(booknum<0){
  109054. maxval[k]=1;
  109055. }else{
  109056. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  109057. }
  109058. }
  109059. for(k=0;k<cdim;k++){
  109060. for(l=0;l<csub;l++){
  109061. int val=out[j+k];
  109062. if(val<maxval[l]){
  109063. bookas[k]=l;
  109064. break;
  109065. }
  109066. }
  109067. cval|= bookas[k]<<cshift;
  109068. cshift+=csubbits;
  109069. }
  109070. /* write it */
  109071. look->phrasebits+=
  109072. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  109073. #ifdef TRAIN_FLOOR1
  109074. {
  109075. FILE *of;
  109076. char buffer[80];
  109077. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  109078. vb->pcmend/2,posts-2,class);
  109079. of=fopen(buffer,"a");
  109080. fprintf(of,"%d\n",cval);
  109081. fclose(of);
  109082. }
  109083. #endif
  109084. }
  109085. /* write post values */
  109086. for(k=0;k<cdim;k++){
  109087. int book=info->class_subbook[classx][bookas[k]];
  109088. if(book>=0){
  109089. /* hack to allow training with 'bad' books */
  109090. if(out[j+k]<(books+book)->entries)
  109091. look->postbits+=vorbis_book_encode(books+book,
  109092. out[j+k],opb);
  109093. /*else
  109094. fprintf(stderr,"+!");*/
  109095. #ifdef TRAIN_FLOOR1
  109096. {
  109097. FILE *of;
  109098. char buffer[80];
  109099. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  109100. vb->pcmend/2,posts-2,class,bookas[k]);
  109101. of=fopen(buffer,"a");
  109102. fprintf(of,"%d\n",out[j+k]);
  109103. fclose(of);
  109104. }
  109105. #endif
  109106. }
  109107. }
  109108. j+=cdim;
  109109. }
  109110. {
  109111. /* generate quantized floor equivalent to what we'd unpack in decode */
  109112. /* render the lines */
  109113. int hx=0;
  109114. int lx=0;
  109115. int ly=post[0]*info->mult;
  109116. for(j=1;j<look->posts;j++){
  109117. int current=look->forward_index[j];
  109118. int hy=post[current]&0x7fff;
  109119. if(hy==post[current]){
  109120. hy*=info->mult;
  109121. hx=info->postlist[current];
  109122. render_line0(lx,hx,ly,hy,ilogmask);
  109123. lx=hx;
  109124. ly=hy;
  109125. }
  109126. }
  109127. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  109128. seq++;
  109129. return(1);
  109130. }
  109131. }else{
  109132. oggpack_write(opb,0,1);
  109133. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  109134. seq++;
  109135. return(0);
  109136. }
  109137. }
  109138. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  109139. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109140. vorbis_info_floor1 *info=look->vi;
  109141. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109142. int i,j,k;
  109143. codebook *books=ci->fullbooks;
  109144. /* unpack wrapped/predicted values from stream */
  109145. if(oggpack_read(&vb->opb,1)==1){
  109146. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  109147. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109148. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  109149. /* partition by partition */
  109150. for(i=0,j=2;i<info->partitions;i++){
  109151. int classx=info->partitionclass[i];
  109152. int cdim=info->class_dim[classx];
  109153. int csubbits=info->class_subs[classx];
  109154. int csub=1<<csubbits;
  109155. int cval=0;
  109156. /* decode the partition's first stage cascade value */
  109157. if(csubbits){
  109158. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  109159. if(cval==-1)goto eop;
  109160. }
  109161. for(k=0;k<cdim;k++){
  109162. int book=info->class_subbook[classx][cval&(csub-1)];
  109163. cval>>=csubbits;
  109164. if(book>=0){
  109165. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  109166. goto eop;
  109167. }else{
  109168. fit_value[j+k]=0;
  109169. }
  109170. }
  109171. j+=cdim;
  109172. }
  109173. /* unwrap positive values and reconsitute via linear interpolation */
  109174. for(i=2;i<look->posts;i++){
  109175. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  109176. info->postlist[look->hineighbor[i-2]],
  109177. fit_value[look->loneighbor[i-2]],
  109178. fit_value[look->hineighbor[i-2]],
  109179. info->postlist[i]);
  109180. int hiroom=look->quant_q-predicted;
  109181. int loroom=predicted;
  109182. int room=(hiroom<loroom?hiroom:loroom)<<1;
  109183. int val=fit_value[i];
  109184. if(val){
  109185. if(val>=room){
  109186. if(hiroom>loroom){
  109187. val = val-loroom;
  109188. }else{
  109189. val = -1-(val-hiroom);
  109190. }
  109191. }else{
  109192. if(val&1){
  109193. val= -((val+1)>>1);
  109194. }else{
  109195. val>>=1;
  109196. }
  109197. }
  109198. fit_value[i]=val+predicted;
  109199. fit_value[look->loneighbor[i-2]]&=0x7fff;
  109200. fit_value[look->hineighbor[i-2]]&=0x7fff;
  109201. }else{
  109202. fit_value[i]=predicted|0x8000;
  109203. }
  109204. }
  109205. return(fit_value);
  109206. }
  109207. eop:
  109208. return(NULL);
  109209. }
  109210. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  109211. float *out){
  109212. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  109213. vorbis_info_floor1 *info=look->vi;
  109214. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  109215. int n=ci->blocksizes[vb->W]/2;
  109216. int j;
  109217. if(memo){
  109218. /* render the lines */
  109219. int *fit_value=(int *)memo;
  109220. int hx=0;
  109221. int lx=0;
  109222. int ly=fit_value[0]*info->mult;
  109223. for(j=1;j<look->posts;j++){
  109224. int current=look->forward_index[j];
  109225. int hy=fit_value[current]&0x7fff;
  109226. if(hy==fit_value[current]){
  109227. hy*=info->mult;
  109228. hx=info->postlist[current];
  109229. render_line(lx,hx,ly,hy,out);
  109230. lx=hx;
  109231. ly=hy;
  109232. }
  109233. }
  109234. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  109235. return(1);
  109236. }
  109237. memset(out,0,sizeof(*out)*n);
  109238. return(0);
  109239. }
  109240. /* export hooks */
  109241. vorbis_func_floor floor1_exportbundle={
  109242. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  109243. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  109244. };
  109245. #endif
  109246. /********* End of inlined file: floor1.c *********/
  109247. /********* Start of inlined file: info.c *********/
  109248. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109249. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109250. // tasks..
  109251. #ifdef _MSC_VER
  109252. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109253. #endif
  109254. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109255. #if JUCE_USE_OGGVORBIS
  109256. /* general handling of the header and the vorbis_info structure (and
  109257. substructures) */
  109258. #include <stdlib.h>
  109259. #include <string.h>
  109260. #include <ctype.h>
  109261. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  109262. while(bytes--){
  109263. oggpack_write(o,*s++,8);
  109264. }
  109265. }
  109266. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  109267. while(bytes--){
  109268. *buf++=oggpack_read(o,8);
  109269. }
  109270. }
  109271. void vorbis_comment_init(vorbis_comment *vc){
  109272. memset(vc,0,sizeof(*vc));
  109273. }
  109274. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  109275. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  109276. (vc->comments+2)*sizeof(*vc->user_comments));
  109277. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  109278. (vc->comments+2)*sizeof(*vc->comment_lengths));
  109279. vc->comment_lengths[vc->comments]=strlen(comment);
  109280. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  109281. strcpy(vc->user_comments[vc->comments], comment);
  109282. vc->comments++;
  109283. vc->user_comments[vc->comments]=NULL;
  109284. }
  109285. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  109286. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  109287. strcpy(comment, tag);
  109288. strcat(comment, "=");
  109289. strcat(comment, contents);
  109290. vorbis_comment_add(vc, comment);
  109291. }
  109292. /* This is more or less the same as strncasecmp - but that doesn't exist
  109293. * everywhere, and this is a fairly trivial function, so we include it */
  109294. static int tagcompare(const char *s1, const char *s2, int n){
  109295. int c=0;
  109296. while(c < n){
  109297. if(toupper(s1[c]) != toupper(s2[c]))
  109298. return !0;
  109299. c++;
  109300. }
  109301. return 0;
  109302. }
  109303. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  109304. long i;
  109305. int found = 0;
  109306. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109307. char *fulltag = (char*)alloca(taglen+ 1);
  109308. strcpy(fulltag, tag);
  109309. strcat(fulltag, "=");
  109310. for(i=0;i<vc->comments;i++){
  109311. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  109312. if(count == found)
  109313. /* We return a pointer to the data, not a copy */
  109314. return vc->user_comments[i] + taglen;
  109315. else
  109316. found++;
  109317. }
  109318. }
  109319. return NULL; /* didn't find anything */
  109320. }
  109321. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  109322. int i,count=0;
  109323. int taglen = strlen(tag)+1; /* +1 for the = we append */
  109324. char *fulltag = (char*)alloca(taglen+1);
  109325. strcpy(fulltag,tag);
  109326. strcat(fulltag, "=");
  109327. for(i=0;i<vc->comments;i++){
  109328. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  109329. count++;
  109330. }
  109331. return count;
  109332. }
  109333. void vorbis_comment_clear(vorbis_comment *vc){
  109334. if(vc){
  109335. long i;
  109336. for(i=0;i<vc->comments;i++)
  109337. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  109338. if(vc->user_comments)_ogg_free(vc->user_comments);
  109339. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  109340. if(vc->vendor)_ogg_free(vc->vendor);
  109341. }
  109342. memset(vc,0,sizeof(*vc));
  109343. }
  109344. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  109345. They may be equal, but short will never ge greater than long */
  109346. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  109347. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  109348. return ci ? ci->blocksizes[zo] : -1;
  109349. }
  109350. /* used by synthesis, which has a full, alloced vi */
  109351. void vorbis_info_init(vorbis_info *vi){
  109352. memset(vi,0,sizeof(*vi));
  109353. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  109354. }
  109355. void vorbis_info_clear(vorbis_info *vi){
  109356. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109357. int i;
  109358. if(ci){
  109359. for(i=0;i<ci->modes;i++)
  109360. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  109361. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  109362. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  109363. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  109364. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  109365. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  109366. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  109367. for(i=0;i<ci->books;i++){
  109368. if(ci->book_param[i]){
  109369. /* knows if the book was not alloced */
  109370. vorbis_staticbook_destroy(ci->book_param[i]);
  109371. }
  109372. if(ci->fullbooks)
  109373. vorbis_book_clear(ci->fullbooks+i);
  109374. }
  109375. if(ci->fullbooks)
  109376. _ogg_free(ci->fullbooks);
  109377. for(i=0;i<ci->psys;i++)
  109378. _vi_psy_free(ci->psy_param[i]);
  109379. _ogg_free(ci);
  109380. }
  109381. memset(vi,0,sizeof(*vi));
  109382. }
  109383. /* Header packing/unpacking ********************************************/
  109384. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  109385. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109386. if(!ci)return(OV_EFAULT);
  109387. vi->version=oggpack_read(opb,32);
  109388. if(vi->version!=0)return(OV_EVERSION);
  109389. vi->channels=oggpack_read(opb,8);
  109390. vi->rate=oggpack_read(opb,32);
  109391. vi->bitrate_upper=oggpack_read(opb,32);
  109392. vi->bitrate_nominal=oggpack_read(opb,32);
  109393. vi->bitrate_lower=oggpack_read(opb,32);
  109394. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  109395. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  109396. if(vi->rate<1)goto err_out;
  109397. if(vi->channels<1)goto err_out;
  109398. if(ci->blocksizes[0]<8)goto err_out;
  109399. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  109400. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109401. return(0);
  109402. err_out:
  109403. vorbis_info_clear(vi);
  109404. return(OV_EBADHEADER);
  109405. }
  109406. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  109407. int i;
  109408. int vendorlen=oggpack_read(opb,32);
  109409. if(vendorlen<0)goto err_out;
  109410. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  109411. _v_readstring(opb,vc->vendor,vendorlen);
  109412. vc->comments=oggpack_read(opb,32);
  109413. if(vc->comments<0)goto err_out;
  109414. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  109415. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  109416. for(i=0;i<vc->comments;i++){
  109417. int len=oggpack_read(opb,32);
  109418. if(len<0)goto err_out;
  109419. vc->comment_lengths[i]=len;
  109420. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  109421. _v_readstring(opb,vc->user_comments[i],len);
  109422. }
  109423. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  109424. return(0);
  109425. err_out:
  109426. vorbis_comment_clear(vc);
  109427. return(OV_EBADHEADER);
  109428. }
  109429. /* all of the real encoding details are here. The modes, books,
  109430. everything */
  109431. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  109432. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109433. int i;
  109434. if(!ci)return(OV_EFAULT);
  109435. /* codebooks */
  109436. ci->books=oggpack_read(opb,8)+1;
  109437. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  109438. for(i=0;i<ci->books;i++){
  109439. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  109440. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  109441. }
  109442. /* time backend settings; hooks are unused */
  109443. {
  109444. int times=oggpack_read(opb,6)+1;
  109445. for(i=0;i<times;i++){
  109446. int test=oggpack_read(opb,16);
  109447. if(test<0 || test>=VI_TIMEB)goto err_out;
  109448. }
  109449. }
  109450. /* floor backend settings */
  109451. ci->floors=oggpack_read(opb,6)+1;
  109452. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  109453. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  109454. for(i=0;i<ci->floors;i++){
  109455. ci->floor_type[i]=oggpack_read(opb,16);
  109456. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  109457. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  109458. if(!ci->floor_param[i])goto err_out;
  109459. }
  109460. /* residue backend settings */
  109461. ci->residues=oggpack_read(opb,6)+1;
  109462. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  109463. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  109464. for(i=0;i<ci->residues;i++){
  109465. ci->residue_type[i]=oggpack_read(opb,16);
  109466. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  109467. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  109468. if(!ci->residue_param[i])goto err_out;
  109469. }
  109470. /* map backend settings */
  109471. ci->maps=oggpack_read(opb,6)+1;
  109472. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  109473. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  109474. for(i=0;i<ci->maps;i++){
  109475. ci->map_type[i]=oggpack_read(opb,16);
  109476. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  109477. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  109478. if(!ci->map_param[i])goto err_out;
  109479. }
  109480. /* mode settings */
  109481. ci->modes=oggpack_read(opb,6)+1;
  109482. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  109483. for(i=0;i<ci->modes;i++){
  109484. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  109485. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  109486. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  109487. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  109488. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  109489. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  109490. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  109491. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  109492. }
  109493. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  109494. return(0);
  109495. err_out:
  109496. vorbis_info_clear(vi);
  109497. return(OV_EBADHEADER);
  109498. }
  109499. /* The Vorbis header is in three packets; the initial small packet in
  109500. the first page that identifies basic parameters, a second packet
  109501. with bitstream comments and a third packet that holds the
  109502. codebook. */
  109503. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  109504. oggpack_buffer opb;
  109505. if(op){
  109506. oggpack_readinit(&opb,op->packet,op->bytes);
  109507. /* Which of the three types of header is this? */
  109508. /* Also verify header-ness, vorbis */
  109509. {
  109510. char buffer[6];
  109511. int packtype=oggpack_read(&opb,8);
  109512. memset(buffer,0,6);
  109513. _v_readstring(&opb,buffer,6);
  109514. if(memcmp(buffer,"vorbis",6)){
  109515. /* not a vorbis header */
  109516. return(OV_ENOTVORBIS);
  109517. }
  109518. switch(packtype){
  109519. case 0x01: /* least significant *bit* is read first */
  109520. if(!op->b_o_s){
  109521. /* Not the initial packet */
  109522. return(OV_EBADHEADER);
  109523. }
  109524. if(vi->rate!=0){
  109525. /* previously initialized info header */
  109526. return(OV_EBADHEADER);
  109527. }
  109528. return(_vorbis_unpack_info(vi,&opb));
  109529. case 0x03: /* least significant *bit* is read first */
  109530. if(vi->rate==0){
  109531. /* um... we didn't get the initial header */
  109532. return(OV_EBADHEADER);
  109533. }
  109534. return(_vorbis_unpack_comment(vc,&opb));
  109535. case 0x05: /* least significant *bit* is read first */
  109536. if(vi->rate==0 || vc->vendor==NULL){
  109537. /* um... we didn;t get the initial header or comments yet */
  109538. return(OV_EBADHEADER);
  109539. }
  109540. return(_vorbis_unpack_books(vi,&opb));
  109541. default:
  109542. /* Not a valid vorbis header type */
  109543. return(OV_EBADHEADER);
  109544. break;
  109545. }
  109546. }
  109547. }
  109548. return(OV_EBADHEADER);
  109549. }
  109550. /* pack side **********************************************************/
  109551. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  109552. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109553. if(!ci)return(OV_EFAULT);
  109554. /* preamble */
  109555. oggpack_write(opb,0x01,8);
  109556. _v_writestring(opb,"vorbis", 6);
  109557. /* basic information about the stream */
  109558. oggpack_write(opb,0x00,32);
  109559. oggpack_write(opb,vi->channels,8);
  109560. oggpack_write(opb,vi->rate,32);
  109561. oggpack_write(opb,vi->bitrate_upper,32);
  109562. oggpack_write(opb,vi->bitrate_nominal,32);
  109563. oggpack_write(opb,vi->bitrate_lower,32);
  109564. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  109565. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  109566. oggpack_write(opb,1,1);
  109567. return(0);
  109568. }
  109569. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  109570. char temp[]="Xiph.Org libVorbis I 20050304";
  109571. int bytes = strlen(temp);
  109572. /* preamble */
  109573. oggpack_write(opb,0x03,8);
  109574. _v_writestring(opb,"vorbis", 6);
  109575. /* vendor */
  109576. oggpack_write(opb,bytes,32);
  109577. _v_writestring(opb,temp, bytes);
  109578. /* comments */
  109579. oggpack_write(opb,vc->comments,32);
  109580. if(vc->comments){
  109581. int i;
  109582. for(i=0;i<vc->comments;i++){
  109583. if(vc->user_comments[i]){
  109584. oggpack_write(opb,vc->comment_lengths[i],32);
  109585. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  109586. }else{
  109587. oggpack_write(opb,0,32);
  109588. }
  109589. }
  109590. }
  109591. oggpack_write(opb,1,1);
  109592. return(0);
  109593. }
  109594. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  109595. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109596. int i;
  109597. if(!ci)return(OV_EFAULT);
  109598. oggpack_write(opb,0x05,8);
  109599. _v_writestring(opb,"vorbis", 6);
  109600. /* books */
  109601. oggpack_write(opb,ci->books-1,8);
  109602. for(i=0;i<ci->books;i++)
  109603. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  109604. /* times; hook placeholders */
  109605. oggpack_write(opb,0,6);
  109606. oggpack_write(opb,0,16);
  109607. /* floors */
  109608. oggpack_write(opb,ci->floors-1,6);
  109609. for(i=0;i<ci->floors;i++){
  109610. oggpack_write(opb,ci->floor_type[i],16);
  109611. if(_floor_P[ci->floor_type[i]]->pack)
  109612. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  109613. else
  109614. goto err_out;
  109615. }
  109616. /* residues */
  109617. oggpack_write(opb,ci->residues-1,6);
  109618. for(i=0;i<ci->residues;i++){
  109619. oggpack_write(opb,ci->residue_type[i],16);
  109620. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  109621. }
  109622. /* maps */
  109623. oggpack_write(opb,ci->maps-1,6);
  109624. for(i=0;i<ci->maps;i++){
  109625. oggpack_write(opb,ci->map_type[i],16);
  109626. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  109627. }
  109628. /* modes */
  109629. oggpack_write(opb,ci->modes-1,6);
  109630. for(i=0;i<ci->modes;i++){
  109631. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  109632. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  109633. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  109634. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  109635. }
  109636. oggpack_write(opb,1,1);
  109637. return(0);
  109638. err_out:
  109639. return(-1);
  109640. }
  109641. int vorbis_commentheader_out(vorbis_comment *vc,
  109642. ogg_packet *op){
  109643. oggpack_buffer opb;
  109644. oggpack_writeinit(&opb);
  109645. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  109646. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109647. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  109648. op->bytes=oggpack_bytes(&opb);
  109649. op->b_o_s=0;
  109650. op->e_o_s=0;
  109651. op->granulepos=0;
  109652. op->packetno=1;
  109653. return 0;
  109654. }
  109655. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  109656. vorbis_comment *vc,
  109657. ogg_packet *op,
  109658. ogg_packet *op_comm,
  109659. ogg_packet *op_code){
  109660. int ret=OV_EIMPL;
  109661. vorbis_info *vi=v->vi;
  109662. oggpack_buffer opb;
  109663. private_state *b=(private_state*)v->backend_state;
  109664. if(!b){
  109665. ret=OV_EFAULT;
  109666. goto err_out;
  109667. }
  109668. /* first header packet **********************************************/
  109669. oggpack_writeinit(&opb);
  109670. if(_vorbis_pack_info(&opb,vi))goto err_out;
  109671. /* build the packet */
  109672. if(b->header)_ogg_free(b->header);
  109673. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109674. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  109675. op->packet=b->header;
  109676. op->bytes=oggpack_bytes(&opb);
  109677. op->b_o_s=1;
  109678. op->e_o_s=0;
  109679. op->granulepos=0;
  109680. op->packetno=0;
  109681. /* second header packet (comments) **********************************/
  109682. oggpack_reset(&opb);
  109683. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  109684. if(b->header1)_ogg_free(b->header1);
  109685. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109686. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  109687. op_comm->packet=b->header1;
  109688. op_comm->bytes=oggpack_bytes(&opb);
  109689. op_comm->b_o_s=0;
  109690. op_comm->e_o_s=0;
  109691. op_comm->granulepos=0;
  109692. op_comm->packetno=1;
  109693. /* third header packet (modes/codebooks) ****************************/
  109694. oggpack_reset(&opb);
  109695. if(_vorbis_pack_books(&opb,vi))goto err_out;
  109696. if(b->header2)_ogg_free(b->header2);
  109697. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  109698. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  109699. op_code->packet=b->header2;
  109700. op_code->bytes=oggpack_bytes(&opb);
  109701. op_code->b_o_s=0;
  109702. op_code->e_o_s=0;
  109703. op_code->granulepos=0;
  109704. op_code->packetno=2;
  109705. oggpack_writeclear(&opb);
  109706. return(0);
  109707. err_out:
  109708. oggpack_writeclear(&opb);
  109709. memset(op,0,sizeof(*op));
  109710. memset(op_comm,0,sizeof(*op_comm));
  109711. memset(op_code,0,sizeof(*op_code));
  109712. if(b->header)_ogg_free(b->header);
  109713. if(b->header1)_ogg_free(b->header1);
  109714. if(b->header2)_ogg_free(b->header2);
  109715. b->header=NULL;
  109716. b->header1=NULL;
  109717. b->header2=NULL;
  109718. return(ret);
  109719. }
  109720. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  109721. if(granulepos>=0)
  109722. return((double)granulepos/v->vi->rate);
  109723. return(-1);
  109724. }
  109725. #endif
  109726. /********* End of inlined file: info.c *********/
  109727. /********* Start of inlined file: lpc.c *********/
  109728. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  109729. are derived from code written by Jutta Degener and Carsten Bormann;
  109730. thus we include their copyright below. The entirety of this file
  109731. is freely redistributable on the condition that both of these
  109732. copyright notices are preserved without modification. */
  109733. /* Preserved Copyright: *********************************************/
  109734. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  109735. Technische Universita"t Berlin
  109736. Any use of this software is permitted provided that this notice is not
  109737. removed and that neither the authors nor the Technische Universita"t
  109738. Berlin are deemed to have made any representations as to the
  109739. suitability of this software for any purpose nor are held responsible
  109740. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  109741. THIS SOFTWARE.
  109742. As a matter of courtesy, the authors request to be informed about uses
  109743. this software has found, about bugs in this software, and about any
  109744. improvements that may be of general interest.
  109745. Berlin, 28.11.1994
  109746. Jutta Degener
  109747. Carsten Bormann
  109748. *********************************************************************/
  109749. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109750. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109751. // tasks..
  109752. #ifdef _MSC_VER
  109753. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109754. #endif
  109755. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109756. #if JUCE_USE_OGGVORBIS
  109757. #include <stdlib.h>
  109758. #include <string.h>
  109759. #include <math.h>
  109760. /* Autocorrelation LPC coeff generation algorithm invented by
  109761. N. Levinson in 1947, modified by J. Durbin in 1959. */
  109762. /* Input : n elements of time doamin data
  109763. Output: m lpc coefficients, excitation energy */
  109764. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  109765. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  109766. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  109767. double error;
  109768. int i,j;
  109769. /* autocorrelation, p+1 lag coefficients */
  109770. j=m+1;
  109771. while(j--){
  109772. double d=0; /* double needed for accumulator depth */
  109773. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  109774. aut[j]=d;
  109775. }
  109776. /* Generate lpc coefficients from autocorr values */
  109777. error=aut[0];
  109778. for(i=0;i<m;i++){
  109779. double r= -aut[i+1];
  109780. if(error==0){
  109781. memset(lpci,0,m*sizeof(*lpci));
  109782. return 0;
  109783. }
  109784. /* Sum up this iteration's reflection coefficient; note that in
  109785. Vorbis we don't save it. If anyone wants to recycle this code
  109786. and needs reflection coefficients, save the results of 'r' from
  109787. each iteration. */
  109788. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  109789. r/=error;
  109790. /* Update LPC coefficients and total error */
  109791. lpc[i]=r;
  109792. for(j=0;j<i/2;j++){
  109793. double tmp=lpc[j];
  109794. lpc[j]+=r*lpc[i-1-j];
  109795. lpc[i-1-j]+=r*tmp;
  109796. }
  109797. if(i%2)lpc[j]+=lpc[j]*r;
  109798. error*=1.f-r*r;
  109799. }
  109800. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  109801. /* we need the error value to know how big an impulse to hit the
  109802. filter with later */
  109803. return error;
  109804. }
  109805. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  109806. float *data,long n){
  109807. /* in: coeff[0...m-1] LPC coefficients
  109808. prime[0...m-1] initial values (allocated size of n+m-1)
  109809. out: data[0...n-1] data samples */
  109810. long i,j,o,p;
  109811. float y;
  109812. float *work=(float*)alloca(sizeof(*work)*(m+n));
  109813. if(!prime)
  109814. for(i=0;i<m;i++)
  109815. work[i]=0.f;
  109816. else
  109817. for(i=0;i<m;i++)
  109818. work[i]=prime[i];
  109819. for(i=0;i<n;i++){
  109820. y=0;
  109821. o=i;
  109822. p=m;
  109823. for(j=0;j<m;j++)
  109824. y-=work[o++]*coeff[--p];
  109825. data[i]=work[o]=y;
  109826. }
  109827. }
  109828. #endif
  109829. /********* End of inlined file: lpc.c *********/
  109830. /********* Start of inlined file: lsp.c *********/
  109831. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  109832. an iterative root polisher (CACM algorithm 283). It *is* possible
  109833. to confuse this algorithm into not converging; that should only
  109834. happen with absurdly closely spaced roots (very sharp peaks in the
  109835. LPC f response) which in turn should be impossible in our use of
  109836. the code. If this *does* happen anyway, it's a bug in the floor
  109837. finder; find the cause of the confusion (probably a single bin
  109838. spike or accidental near-float-limit resolution problems) and
  109839. correct it. */
  109840. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109841. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109842. // tasks..
  109843. #ifdef _MSC_VER
  109844. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109845. #endif
  109846. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109847. #if JUCE_USE_OGGVORBIS
  109848. #include <math.h>
  109849. #include <string.h>
  109850. #include <stdlib.h>
  109851. /********* Start of inlined file: lookup.h *********/
  109852. #ifndef _V_LOOKUP_H_
  109853. #ifdef FLOAT_LOOKUP
  109854. extern float vorbis_coslook(float a);
  109855. extern float vorbis_invsqlook(float a);
  109856. extern float vorbis_invsq2explook(int a);
  109857. extern float vorbis_fromdBlook(float a);
  109858. #endif
  109859. #ifdef INT_LOOKUP
  109860. extern long vorbis_invsqlook_i(long a,long e);
  109861. extern long vorbis_coslook_i(long a);
  109862. extern float vorbis_fromdBlook_i(long a);
  109863. #endif
  109864. #endif
  109865. /********* End of inlined file: lookup.h *********/
  109866. /* three possible LSP to f curve functions; the exact computation
  109867. (float), a lookup based float implementation, and an integer
  109868. implementation. The float lookup is likely the optimal choice on
  109869. any machine with an FPU. The integer implementation is *not* fixed
  109870. point (due to the need for a large dynamic range and thus a
  109871. seperately tracked exponent) and thus much more complex than the
  109872. relatively simple float implementations. It's mostly for future
  109873. work on a fully fixed point implementation for processors like the
  109874. ARM family. */
  109875. /* undefine both for the 'old' but more precise implementation */
  109876. #define FLOAT_LOOKUP
  109877. #undef INT_LOOKUP
  109878. #ifdef FLOAT_LOOKUP
  109879. /********* Start of inlined file: lookup.c *********/
  109880. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109881. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109882. // tasks..
  109883. #ifdef _MSC_VER
  109884. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109885. #endif
  109886. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109887. #if JUCE_USE_OGGVORBIS
  109888. #include <math.h>
  109889. /********* Start of inlined file: lookup.h *********/
  109890. #ifndef _V_LOOKUP_H_
  109891. #ifdef FLOAT_LOOKUP
  109892. extern float vorbis_coslook(float a);
  109893. extern float vorbis_invsqlook(float a);
  109894. extern float vorbis_invsq2explook(int a);
  109895. extern float vorbis_fromdBlook(float a);
  109896. #endif
  109897. #ifdef INT_LOOKUP
  109898. extern long vorbis_invsqlook_i(long a,long e);
  109899. extern long vorbis_coslook_i(long a);
  109900. extern float vorbis_fromdBlook_i(long a);
  109901. #endif
  109902. #endif
  109903. /********* End of inlined file: lookup.h *********/
  109904. /********* Start of inlined file: lookup_data.h *********/
  109905. #ifndef _V_LOOKUP_DATA_H_
  109906. #ifdef FLOAT_LOOKUP
  109907. #define COS_LOOKUP_SZ 128
  109908. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  109909. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  109910. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  109911. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  109912. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  109913. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  109914. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  109915. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  109916. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  109917. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  109918. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  109919. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  109920. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  109921. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  109922. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  109923. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  109924. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  109925. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  109926. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  109927. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  109928. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  109929. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  109930. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  109931. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  109932. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  109933. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  109934. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  109935. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  109936. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  109937. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  109938. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  109939. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  109940. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  109941. -1.0000000000000f,
  109942. };
  109943. #define INVSQ_LOOKUP_SZ 32
  109944. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  109945. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  109946. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  109947. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  109948. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  109949. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  109950. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  109951. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  109952. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  109953. 1.000000000000f,
  109954. };
  109955. #define INVSQ2EXP_LOOKUP_MIN (-32)
  109956. #define INVSQ2EXP_LOOKUP_MAX 32
  109957. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  109958. INVSQ2EXP_LOOKUP_MIN+1]={
  109959. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  109960. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  109961. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  109962. 1024.f, 724.0773439f, 512.f, 362.038672f,
  109963. 256.f, 181.019336f, 128.f, 90.50966799f,
  109964. 64.f, 45.254834f, 32.f, 22.627417f,
  109965. 16.f, 11.3137085f, 8.f, 5.656854249f,
  109966. 4.f, 2.828427125f, 2.f, 1.414213562f,
  109967. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  109968. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  109969. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  109970. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  109971. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  109972. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  109973. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  109974. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  109975. 1.525878906e-05f,
  109976. };
  109977. #endif
  109978. #define FROMdB_LOOKUP_SZ 35
  109979. #define FROMdB2_LOOKUP_SZ 32
  109980. #define FROMdB_SHIFT 5
  109981. #define FROMdB2_SHIFT 3
  109982. #define FROMdB2_MASK 31
  109983. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  109984. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  109985. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  109986. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  109987. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  109988. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  109989. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  109990. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  109991. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  109992. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  109993. };
  109994. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  109995. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  109996. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  109997. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  109998. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  109999. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110000. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110001. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110002. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110003. };
  110004. #ifdef INT_LOOKUP
  110005. #define INVSQ_LOOKUP_I_SHIFT 10
  110006. #define INVSQ_LOOKUP_I_MASK 1023
  110007. static long INVSQ_LOOKUP_I[64+1]={
  110008. 92682l, 91966l, 91267l, 90583l,
  110009. 89915l, 89261l, 88621l, 87995l,
  110010. 87381l, 86781l, 86192l, 85616l,
  110011. 85051l, 84497l, 83953l, 83420l,
  110012. 82897l, 82384l, 81880l, 81385l,
  110013. 80899l, 80422l, 79953l, 79492l,
  110014. 79039l, 78594l, 78156l, 77726l,
  110015. 77302l, 76885l, 76475l, 76072l,
  110016. 75674l, 75283l, 74898l, 74519l,
  110017. 74146l, 73778l, 73415l, 73058l,
  110018. 72706l, 72359l, 72016l, 71679l,
  110019. 71347l, 71019l, 70695l, 70376l,
  110020. 70061l, 69750l, 69444l, 69141l,
  110021. 68842l, 68548l, 68256l, 67969l,
  110022. 67685l, 67405l, 67128l, 66855l,
  110023. 66585l, 66318l, 66054l, 65794l,
  110024. 65536l,
  110025. };
  110026. #define COS_LOOKUP_I_SHIFT 9
  110027. #define COS_LOOKUP_I_MASK 511
  110028. #define COS_LOOKUP_I_SZ 128
  110029. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110030. 16384l, 16379l, 16364l, 16340l,
  110031. 16305l, 16261l, 16207l, 16143l,
  110032. 16069l, 15986l, 15893l, 15791l,
  110033. 15679l, 15557l, 15426l, 15286l,
  110034. 15137l, 14978l, 14811l, 14635l,
  110035. 14449l, 14256l, 14053l, 13842l,
  110036. 13623l, 13395l, 13160l, 12916l,
  110037. 12665l, 12406l, 12140l, 11866l,
  110038. 11585l, 11297l, 11003l, 10702l,
  110039. 10394l, 10080l, 9760l, 9434l,
  110040. 9102l, 8765l, 8423l, 8076l,
  110041. 7723l, 7366l, 7005l, 6639l,
  110042. 6270l, 5897l, 5520l, 5139l,
  110043. 4756l, 4370l, 3981l, 3590l,
  110044. 3196l, 2801l, 2404l, 2006l,
  110045. 1606l, 1205l, 804l, 402l,
  110046. 0l, -401l, -803l, -1204l,
  110047. -1605l, -2005l, -2403l, -2800l,
  110048. -3195l, -3589l, -3980l, -4369l,
  110049. -4755l, -5138l, -5519l, -5896l,
  110050. -6269l, -6638l, -7004l, -7365l,
  110051. -7722l, -8075l, -8422l, -8764l,
  110052. -9101l, -9433l, -9759l, -10079l,
  110053. -10393l, -10701l, -11002l, -11296l,
  110054. -11584l, -11865l, -12139l, -12405l,
  110055. -12664l, -12915l, -13159l, -13394l,
  110056. -13622l, -13841l, -14052l, -14255l,
  110057. -14448l, -14634l, -14810l, -14977l,
  110058. -15136l, -15285l, -15425l, -15556l,
  110059. -15678l, -15790l, -15892l, -15985l,
  110060. -16068l, -16142l, -16206l, -16260l,
  110061. -16304l, -16339l, -16363l, -16378l,
  110062. -16383l,
  110063. };
  110064. #endif
  110065. #endif
  110066. /********* End of inlined file: lookup_data.h *********/
  110067. #ifdef FLOAT_LOOKUP
  110068. /* interpolated lookup based cos function, domain 0 to PI only */
  110069. float vorbis_coslook(float a){
  110070. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110071. int i=vorbis_ftoi(d-.5);
  110072. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110073. }
  110074. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110075. float vorbis_invsqlook(float a){
  110076. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110077. int i=vorbis_ftoi(d-.5f);
  110078. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110079. }
  110080. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110081. float vorbis_invsq2explook(int a){
  110082. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110083. }
  110084. #include <stdio.h>
  110085. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110086. float vorbis_fromdBlook(float a){
  110087. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110088. return (i<0)?1.f:
  110089. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110090. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110091. }
  110092. #endif
  110093. #ifdef INT_LOOKUP
  110094. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110095. 16.16 format
  110096. returns in m.8 format */
  110097. long vorbis_invsqlook_i(long a,long e){
  110098. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110099. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110100. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110101. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110102. d)>>16); /* result 1.16 */
  110103. e+=32;
  110104. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110105. e=(e>>1)-8;
  110106. return(val>>e);
  110107. }
  110108. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110109. /* a is in n.12 format */
  110110. float vorbis_fromdBlook_i(long a){
  110111. int i=(-a)>>(12-FROMdB2_SHIFT);
  110112. return (i<0)?1.f:
  110113. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110114. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110115. }
  110116. /* interpolated lookup based cos function, domain 0 to PI only */
  110117. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110118. long vorbis_coslook_i(long a){
  110119. int i=a>>COS_LOOKUP_I_SHIFT;
  110120. int d=a&COS_LOOKUP_I_MASK;
  110121. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110122. COS_LOOKUP_I_SHIFT);
  110123. }
  110124. #endif
  110125. #endif
  110126. /********* End of inlined file: lookup.c *********/
  110127. /* catch this in the build system; we #include for
  110128. compilers (like gcc) that can't inline across
  110129. modules */
  110130. /* side effect: changes *lsp to cosines of lsp */
  110131. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110132. float amp,float ampoffset){
  110133. int i;
  110134. float wdel=M_PI/ln;
  110135. vorbis_fpu_control fpu;
  110136. (void) fpu; // to avoid an unused variable warning
  110137. vorbis_fpu_setround(&fpu);
  110138. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  110139. i=0;
  110140. while(i<n){
  110141. int k=map[i];
  110142. int qexp;
  110143. float p=.7071067812f;
  110144. float q=.7071067812f;
  110145. float w=vorbis_coslook(wdel*k);
  110146. float *ftmp=lsp;
  110147. int c=m>>1;
  110148. do{
  110149. q*=ftmp[0]-w;
  110150. p*=ftmp[1]-w;
  110151. ftmp+=2;
  110152. }while(--c);
  110153. if(m&1){
  110154. /* odd order filter; slightly assymetric */
  110155. /* the last coefficient */
  110156. q*=ftmp[0]-w;
  110157. q*=q;
  110158. p*=p*(1.f-w*w);
  110159. }else{
  110160. /* even order filter; still symmetric */
  110161. q*=q*(1.f+w);
  110162. p*=p*(1.f-w);
  110163. }
  110164. q=frexp(p+q,&qexp);
  110165. q=vorbis_fromdBlook(amp*
  110166. vorbis_invsqlook(q)*
  110167. vorbis_invsq2explook(qexp+m)-
  110168. ampoffset);
  110169. do{
  110170. curve[i++]*=q;
  110171. }while(map[i]==k);
  110172. }
  110173. vorbis_fpu_restore(fpu);
  110174. }
  110175. #else
  110176. #ifdef INT_LOOKUP
  110177. /********* Start of inlined file: lookup.c *********/
  110178. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110179. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110180. // tasks..
  110181. #ifdef _MSC_VER
  110182. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110183. #endif
  110184. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110185. #if JUCE_USE_OGGVORBIS
  110186. #include <math.h>
  110187. /********* Start of inlined file: lookup.h *********/
  110188. #ifndef _V_LOOKUP_H_
  110189. #ifdef FLOAT_LOOKUP
  110190. extern float vorbis_coslook(float a);
  110191. extern float vorbis_invsqlook(float a);
  110192. extern float vorbis_invsq2explook(int a);
  110193. extern float vorbis_fromdBlook(float a);
  110194. #endif
  110195. #ifdef INT_LOOKUP
  110196. extern long vorbis_invsqlook_i(long a,long e);
  110197. extern long vorbis_coslook_i(long a);
  110198. extern float vorbis_fromdBlook_i(long a);
  110199. #endif
  110200. #endif
  110201. /********* End of inlined file: lookup.h *********/
  110202. /********* Start of inlined file: lookup_data.h *********/
  110203. #ifndef _V_LOOKUP_DATA_H_
  110204. #ifdef FLOAT_LOOKUP
  110205. #define COS_LOOKUP_SZ 128
  110206. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  110207. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  110208. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  110209. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  110210. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  110211. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  110212. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  110213. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  110214. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  110215. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  110216. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  110217. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  110218. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  110219. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  110220. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  110221. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  110222. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  110223. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  110224. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  110225. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  110226. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  110227. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  110228. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  110229. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  110230. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  110231. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  110232. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  110233. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  110234. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  110235. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  110236. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  110237. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  110238. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  110239. -1.0000000000000f,
  110240. };
  110241. #define INVSQ_LOOKUP_SZ 32
  110242. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  110243. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  110244. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  110245. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  110246. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  110247. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  110248. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  110249. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  110250. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  110251. 1.000000000000f,
  110252. };
  110253. #define INVSQ2EXP_LOOKUP_MIN (-32)
  110254. #define INVSQ2EXP_LOOKUP_MAX 32
  110255. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  110256. INVSQ2EXP_LOOKUP_MIN+1]={
  110257. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  110258. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  110259. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  110260. 1024.f, 724.0773439f, 512.f, 362.038672f,
  110261. 256.f, 181.019336f, 128.f, 90.50966799f,
  110262. 64.f, 45.254834f, 32.f, 22.627417f,
  110263. 16.f, 11.3137085f, 8.f, 5.656854249f,
  110264. 4.f, 2.828427125f, 2.f, 1.414213562f,
  110265. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  110266. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  110267. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  110268. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  110269. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  110270. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  110271. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  110272. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  110273. 1.525878906e-05f,
  110274. };
  110275. #endif
  110276. #define FROMdB_LOOKUP_SZ 35
  110277. #define FROMdB2_LOOKUP_SZ 32
  110278. #define FROMdB_SHIFT 5
  110279. #define FROMdB2_SHIFT 3
  110280. #define FROMdB2_MASK 31
  110281. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  110282. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  110283. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  110284. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  110285. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  110286. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  110287. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  110288. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  110289. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  110290. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  110291. };
  110292. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  110293. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  110294. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  110295. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  110296. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  110297. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  110298. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  110299. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  110300. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  110301. };
  110302. #ifdef INT_LOOKUP
  110303. #define INVSQ_LOOKUP_I_SHIFT 10
  110304. #define INVSQ_LOOKUP_I_MASK 1023
  110305. static long INVSQ_LOOKUP_I[64+1]={
  110306. 92682l, 91966l, 91267l, 90583l,
  110307. 89915l, 89261l, 88621l, 87995l,
  110308. 87381l, 86781l, 86192l, 85616l,
  110309. 85051l, 84497l, 83953l, 83420l,
  110310. 82897l, 82384l, 81880l, 81385l,
  110311. 80899l, 80422l, 79953l, 79492l,
  110312. 79039l, 78594l, 78156l, 77726l,
  110313. 77302l, 76885l, 76475l, 76072l,
  110314. 75674l, 75283l, 74898l, 74519l,
  110315. 74146l, 73778l, 73415l, 73058l,
  110316. 72706l, 72359l, 72016l, 71679l,
  110317. 71347l, 71019l, 70695l, 70376l,
  110318. 70061l, 69750l, 69444l, 69141l,
  110319. 68842l, 68548l, 68256l, 67969l,
  110320. 67685l, 67405l, 67128l, 66855l,
  110321. 66585l, 66318l, 66054l, 65794l,
  110322. 65536l,
  110323. };
  110324. #define COS_LOOKUP_I_SHIFT 9
  110325. #define COS_LOOKUP_I_MASK 511
  110326. #define COS_LOOKUP_I_SZ 128
  110327. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  110328. 16384l, 16379l, 16364l, 16340l,
  110329. 16305l, 16261l, 16207l, 16143l,
  110330. 16069l, 15986l, 15893l, 15791l,
  110331. 15679l, 15557l, 15426l, 15286l,
  110332. 15137l, 14978l, 14811l, 14635l,
  110333. 14449l, 14256l, 14053l, 13842l,
  110334. 13623l, 13395l, 13160l, 12916l,
  110335. 12665l, 12406l, 12140l, 11866l,
  110336. 11585l, 11297l, 11003l, 10702l,
  110337. 10394l, 10080l, 9760l, 9434l,
  110338. 9102l, 8765l, 8423l, 8076l,
  110339. 7723l, 7366l, 7005l, 6639l,
  110340. 6270l, 5897l, 5520l, 5139l,
  110341. 4756l, 4370l, 3981l, 3590l,
  110342. 3196l, 2801l, 2404l, 2006l,
  110343. 1606l, 1205l, 804l, 402l,
  110344. 0l, -401l, -803l, -1204l,
  110345. -1605l, -2005l, -2403l, -2800l,
  110346. -3195l, -3589l, -3980l, -4369l,
  110347. -4755l, -5138l, -5519l, -5896l,
  110348. -6269l, -6638l, -7004l, -7365l,
  110349. -7722l, -8075l, -8422l, -8764l,
  110350. -9101l, -9433l, -9759l, -10079l,
  110351. -10393l, -10701l, -11002l, -11296l,
  110352. -11584l, -11865l, -12139l, -12405l,
  110353. -12664l, -12915l, -13159l, -13394l,
  110354. -13622l, -13841l, -14052l, -14255l,
  110355. -14448l, -14634l, -14810l, -14977l,
  110356. -15136l, -15285l, -15425l, -15556l,
  110357. -15678l, -15790l, -15892l, -15985l,
  110358. -16068l, -16142l, -16206l, -16260l,
  110359. -16304l, -16339l, -16363l, -16378l,
  110360. -16383l,
  110361. };
  110362. #endif
  110363. #endif
  110364. /********* End of inlined file: lookup_data.h *********/
  110365. #ifdef FLOAT_LOOKUP
  110366. /* interpolated lookup based cos function, domain 0 to PI only */
  110367. float vorbis_coslook(float a){
  110368. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  110369. int i=vorbis_ftoi(d-.5);
  110370. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  110371. }
  110372. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110373. float vorbis_invsqlook(float a){
  110374. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  110375. int i=vorbis_ftoi(d-.5f);
  110376. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  110377. }
  110378. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  110379. float vorbis_invsq2explook(int a){
  110380. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  110381. }
  110382. #include <stdio.h>
  110383. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110384. float vorbis_fromdBlook(float a){
  110385. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  110386. return (i<0)?1.f:
  110387. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110388. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110389. }
  110390. #endif
  110391. #ifdef INT_LOOKUP
  110392. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  110393. 16.16 format
  110394. returns in m.8 format */
  110395. long vorbis_invsqlook_i(long a,long e){
  110396. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  110397. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  110398. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  110399. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  110400. d)>>16); /* result 1.16 */
  110401. e+=32;
  110402. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  110403. e=(e>>1)-8;
  110404. return(val>>e);
  110405. }
  110406. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  110407. /* a is in n.12 format */
  110408. float vorbis_fromdBlook_i(long a){
  110409. int i=(-a)>>(12-FROMdB2_SHIFT);
  110410. return (i<0)?1.f:
  110411. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  110412. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  110413. }
  110414. /* interpolated lookup based cos function, domain 0 to PI only */
  110415. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  110416. long vorbis_coslook_i(long a){
  110417. int i=a>>COS_LOOKUP_I_SHIFT;
  110418. int d=a&COS_LOOKUP_I_MASK;
  110419. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  110420. COS_LOOKUP_I_SHIFT);
  110421. }
  110422. #endif
  110423. #endif
  110424. /********* End of inlined file: lookup.c *********/
  110425. /* catch this in the build system; we #include for
  110426. compilers (like gcc) that can't inline across
  110427. modules */
  110428. static int MLOOP_1[64]={
  110429. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  110430. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  110431. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110432. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  110433. };
  110434. static int MLOOP_2[64]={
  110435. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  110436. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  110437. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110438. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  110439. };
  110440. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  110441. /* side effect: changes *lsp to cosines of lsp */
  110442. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110443. float amp,float ampoffset){
  110444. /* 0 <= m < 256 */
  110445. /* set up for using all int later */
  110446. int i;
  110447. int ampoffseti=rint(ampoffset*4096.f);
  110448. int ampi=rint(amp*16.f);
  110449. long *ilsp=alloca(m*sizeof(*ilsp));
  110450. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  110451. i=0;
  110452. while(i<n){
  110453. int j,k=map[i];
  110454. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  110455. unsigned long qi=46341;
  110456. int qexp=0,shift;
  110457. long wi=vorbis_coslook_i(k*65536/ln);
  110458. qi*=labs(ilsp[0]-wi);
  110459. pi*=labs(ilsp[1]-wi);
  110460. for(j=3;j<m;j+=2){
  110461. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110462. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110463. shift=MLOOP_3[(pi|qi)>>16];
  110464. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110465. pi=(pi>>shift)*labs(ilsp[j]-wi);
  110466. qexp+=shift;
  110467. }
  110468. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110469. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110470. shift=MLOOP_3[(pi|qi)>>16];
  110471. /* pi,qi normalized collectively, both tracked using qexp */
  110472. if(m&1){
  110473. /* odd order filter; slightly assymetric */
  110474. /* the last coefficient */
  110475. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  110476. pi=(pi>>shift)<<14;
  110477. qexp+=shift;
  110478. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  110479. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  110480. shift=MLOOP_3[(pi|qi)>>16];
  110481. pi>>=shift;
  110482. qi>>=shift;
  110483. qexp+=shift-14*((m+1)>>1);
  110484. pi=((pi*pi)>>16);
  110485. qi=((qi*qi)>>16);
  110486. qexp=qexp*2+m;
  110487. pi*=(1<<14)-((wi*wi)>>14);
  110488. qi+=pi>>14;
  110489. }else{
  110490. /* even order filter; still symmetric */
  110491. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  110492. worth tracking step by step */
  110493. pi>>=shift;
  110494. qi>>=shift;
  110495. qexp+=shift-7*m;
  110496. pi=((pi*pi)>>16);
  110497. qi=((qi*qi)>>16);
  110498. qexp=qexp*2+m;
  110499. pi*=(1<<14)-wi;
  110500. qi*=(1<<14)+wi;
  110501. qi=(qi+pi)>>14;
  110502. }
  110503. /* we've let the normalization drift because it wasn't important;
  110504. however, for the lookup, things must be normalized again. We
  110505. need at most one right shift or a number of left shifts */
  110506. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  110507. qi>>=1; qexp++;
  110508. }else
  110509. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  110510. qi<<=1; qexp--;
  110511. }
  110512. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  110513. vorbis_invsqlook_i(qi,qexp)-
  110514. /* m.8, m+n<=8 */
  110515. ampoffseti); /* 8.12[0] */
  110516. curve[i]*=amp;
  110517. while(map[++i]==k)curve[i]*=amp;
  110518. }
  110519. }
  110520. #else
  110521. /* old, nonoptimized but simple version for any poor sap who needs to
  110522. figure out what the hell this code does, or wants the other
  110523. fraction of a dB precision */
  110524. /* side effect: changes *lsp to cosines of lsp */
  110525. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  110526. float amp,float ampoffset){
  110527. int i;
  110528. float wdel=M_PI/ln;
  110529. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  110530. i=0;
  110531. while(i<n){
  110532. int j,k=map[i];
  110533. float p=.5f;
  110534. float q=.5f;
  110535. float w=2.f*cos(wdel*k);
  110536. for(j=1;j<m;j+=2){
  110537. q *= w-lsp[j-1];
  110538. p *= w-lsp[j];
  110539. }
  110540. if(j==m){
  110541. /* odd order filter; slightly assymetric */
  110542. /* the last coefficient */
  110543. q*=w-lsp[j-1];
  110544. p*=p*(4.f-w*w);
  110545. q*=q;
  110546. }else{
  110547. /* even order filter; still symmetric */
  110548. p*=p*(2.f-w);
  110549. q*=q*(2.f+w);
  110550. }
  110551. q=fromdB(amp/sqrt(p+q)-ampoffset);
  110552. curve[i]*=q;
  110553. while(map[++i]==k)curve[i]*=q;
  110554. }
  110555. }
  110556. #endif
  110557. #endif
  110558. static void cheby(float *g, int ord) {
  110559. int i, j;
  110560. g[0] *= .5f;
  110561. for(i=2; i<= ord; i++) {
  110562. for(j=ord; j >= i; j--) {
  110563. g[j-2] -= g[j];
  110564. g[j] += g[j];
  110565. }
  110566. }
  110567. }
  110568. static int comp(const void *a,const void *b){
  110569. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  110570. }
  110571. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  110572. but there are root sets for which it gets into limit cycles
  110573. (exacerbated by zero suppression) and fails. We can't afford to
  110574. fail, even if the failure is 1 in 100,000,000, so we now use
  110575. Laguerre and later polish with Newton-Raphson (which can then
  110576. afford to fail) */
  110577. #define EPSILON 10e-7
  110578. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  110579. int i,m;
  110580. double lastdelta=0.f;
  110581. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  110582. for(i=0;i<=ord;i++)defl[i]=a[i];
  110583. for(m=ord;m>0;m--){
  110584. double newx=0.f,delta;
  110585. /* iterate a root */
  110586. while(1){
  110587. double p=defl[m],pp=0.f,ppp=0.f,denom;
  110588. /* eval the polynomial and its first two derivatives */
  110589. for(i=m;i>0;i--){
  110590. ppp = newx*ppp + pp;
  110591. pp = newx*pp + p;
  110592. p = newx*p + defl[i-1];
  110593. }
  110594. /* Laguerre's method */
  110595. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  110596. if(denom<0)
  110597. return(-1); /* complex root! The LPC generator handed us a bad filter */
  110598. if(pp>0){
  110599. denom = pp + sqrt(denom);
  110600. if(denom<EPSILON)denom=EPSILON;
  110601. }else{
  110602. denom = pp - sqrt(denom);
  110603. if(denom>-(EPSILON))denom=-(EPSILON);
  110604. }
  110605. delta = m*p/denom;
  110606. newx -= delta;
  110607. if(delta<0.f)delta*=-1;
  110608. if(fabs(delta/newx)<10e-12)break;
  110609. lastdelta=delta;
  110610. }
  110611. r[m-1]=newx;
  110612. /* forward deflation */
  110613. for(i=m;i>0;i--)
  110614. defl[i-1]+=newx*defl[i];
  110615. defl++;
  110616. }
  110617. return(0);
  110618. }
  110619. /* for spit-and-polish only */
  110620. static int Newton_Raphson(float *a,int ord,float *r){
  110621. int i, k, count=0;
  110622. double error=1.f;
  110623. double *root=(double*)alloca(ord*sizeof(*root));
  110624. for(i=0; i<ord;i++) root[i] = r[i];
  110625. while(error>1e-20){
  110626. error=0;
  110627. for(i=0; i<ord; i++) { /* Update each point. */
  110628. double pp=0.,delta;
  110629. double rooti=root[i];
  110630. double p=a[ord];
  110631. for(k=ord-1; k>= 0; k--) {
  110632. pp= pp* rooti + p;
  110633. p = p * rooti + a[k];
  110634. }
  110635. delta = p/pp;
  110636. root[i] -= delta;
  110637. error+= delta*delta;
  110638. }
  110639. if(count>40)return(-1);
  110640. count++;
  110641. }
  110642. /* Replaced the original bubble sort with a real sort. With your
  110643. help, we can eliminate the bubble sort in our lifetime. --Monty */
  110644. for(i=0; i<ord;i++) r[i] = root[i];
  110645. return(0);
  110646. }
  110647. /* Convert lpc coefficients to lsp coefficients */
  110648. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  110649. int order2=(m+1)>>1;
  110650. int g1_order,g2_order;
  110651. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  110652. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  110653. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  110654. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  110655. int i;
  110656. /* even and odd are slightly different base cases */
  110657. g1_order=(m+1)>>1;
  110658. g2_order=(m) >>1;
  110659. /* Compute the lengths of the x polynomials. */
  110660. /* Compute the first half of K & R F1 & F2 polynomials. */
  110661. /* Compute half of the symmetric and antisymmetric polynomials. */
  110662. /* Remove the roots at +1 and -1. */
  110663. g1[g1_order] = 1.f;
  110664. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  110665. g2[g2_order] = 1.f;
  110666. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  110667. if(g1_order>g2_order){
  110668. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  110669. }else{
  110670. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  110671. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  110672. }
  110673. /* Convert into polynomials in cos(alpha) */
  110674. cheby(g1,g1_order);
  110675. cheby(g2,g2_order);
  110676. /* Find the roots of the 2 even polynomials.*/
  110677. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  110678. Laguerre_With_Deflation(g2,g2_order,g2r))
  110679. return(-1);
  110680. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  110681. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  110682. qsort(g1r,g1_order,sizeof(*g1r),comp);
  110683. qsort(g2r,g2_order,sizeof(*g2r),comp);
  110684. for(i=0;i<g1_order;i++)
  110685. lsp[i*2] = acos(g1r[i]);
  110686. for(i=0;i<g2_order;i++)
  110687. lsp[i*2+1] = acos(g2r[i]);
  110688. return(0);
  110689. }
  110690. #endif
  110691. /********* End of inlined file: lsp.c *********/
  110692. /********* Start of inlined file: mapping0.c *********/
  110693. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110694. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110695. // tasks..
  110696. #ifdef _MSC_VER
  110697. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110698. #endif
  110699. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110700. #if JUCE_USE_OGGVORBIS
  110701. #include <stdlib.h>
  110702. #include <stdio.h>
  110703. #include <string.h>
  110704. #include <math.h>
  110705. /* simplistic, wasteful way of doing this (unique lookup for each
  110706. mode/submapping); there should be a central repository for
  110707. identical lookups. That will require minor work, so I'm putting it
  110708. off as low priority.
  110709. Why a lookup for each backend in a given mode? Because the
  110710. blocksize is set by the mode, and low backend lookups may require
  110711. parameters from other areas of the mode/mapping */
  110712. static void mapping0_free_info(vorbis_info_mapping *i){
  110713. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  110714. if(info){
  110715. memset(info,0,sizeof(*info));
  110716. _ogg_free(info);
  110717. }
  110718. }
  110719. static int ilog3(unsigned int v){
  110720. int ret=0;
  110721. if(v)--v;
  110722. while(v){
  110723. ret++;
  110724. v>>=1;
  110725. }
  110726. return(ret);
  110727. }
  110728. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  110729. oggpack_buffer *opb){
  110730. int i;
  110731. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  110732. /* another 'we meant to do it this way' hack... up to beta 4, we
  110733. packed 4 binary zeros here to signify one submapping in use. We
  110734. now redefine that to mean four bitflags that indicate use of
  110735. deeper features; bit0:submappings, bit1:coupling,
  110736. bit2,3:reserved. This is backward compatable with all actual uses
  110737. of the beta code. */
  110738. if(info->submaps>1){
  110739. oggpack_write(opb,1,1);
  110740. oggpack_write(opb,info->submaps-1,4);
  110741. }else
  110742. oggpack_write(opb,0,1);
  110743. if(info->coupling_steps>0){
  110744. oggpack_write(opb,1,1);
  110745. oggpack_write(opb,info->coupling_steps-1,8);
  110746. for(i=0;i<info->coupling_steps;i++){
  110747. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  110748. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  110749. }
  110750. }else
  110751. oggpack_write(opb,0,1);
  110752. oggpack_write(opb,0,2); /* 2,3:reserved */
  110753. /* we don't write the channel submappings if we only have one... */
  110754. if(info->submaps>1){
  110755. for(i=0;i<vi->channels;i++)
  110756. oggpack_write(opb,info->chmuxlist[i],4);
  110757. }
  110758. for(i=0;i<info->submaps;i++){
  110759. oggpack_write(opb,0,8); /* time submap unused */
  110760. oggpack_write(opb,info->floorsubmap[i],8);
  110761. oggpack_write(opb,info->residuesubmap[i],8);
  110762. }
  110763. }
  110764. /* also responsible for range checking */
  110765. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  110766. int i;
  110767. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  110768. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110769. memset(info,0,sizeof(*info));
  110770. if(oggpack_read(opb,1))
  110771. info->submaps=oggpack_read(opb,4)+1;
  110772. else
  110773. info->submaps=1;
  110774. if(oggpack_read(opb,1)){
  110775. info->coupling_steps=oggpack_read(opb,8)+1;
  110776. for(i=0;i<info->coupling_steps;i++){
  110777. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  110778. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  110779. if(testM<0 ||
  110780. testA<0 ||
  110781. testM==testA ||
  110782. testM>=vi->channels ||
  110783. testA>=vi->channels) goto err_out;
  110784. }
  110785. }
  110786. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  110787. if(info->submaps>1){
  110788. for(i=0;i<vi->channels;i++){
  110789. info->chmuxlist[i]=oggpack_read(opb,4);
  110790. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  110791. }
  110792. }
  110793. for(i=0;i<info->submaps;i++){
  110794. oggpack_read(opb,8); /* time submap unused */
  110795. info->floorsubmap[i]=oggpack_read(opb,8);
  110796. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  110797. info->residuesubmap[i]=oggpack_read(opb,8);
  110798. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  110799. }
  110800. return info;
  110801. err_out:
  110802. mapping0_free_info(info);
  110803. return(NULL);
  110804. }
  110805. #if 0
  110806. static long seq=0;
  110807. static ogg_int64_t total=0;
  110808. static float FLOOR1_fromdB_LOOKUP[256]={
  110809. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  110810. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  110811. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  110812. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  110813. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  110814. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  110815. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  110816. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  110817. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  110818. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  110819. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  110820. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  110821. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  110822. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  110823. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  110824. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  110825. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  110826. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  110827. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  110828. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  110829. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  110830. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  110831. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  110832. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  110833. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  110834. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  110835. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  110836. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  110837. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  110838. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  110839. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  110840. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  110841. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  110842. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  110843. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  110844. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  110845. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  110846. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  110847. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  110848. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  110849. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  110850. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  110851. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  110852. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  110853. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  110854. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  110855. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  110856. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  110857. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  110858. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  110859. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  110860. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  110861. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  110862. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  110863. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  110864. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  110865. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  110866. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  110867. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  110868. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  110869. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  110870. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  110871. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  110872. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  110873. };
  110874. #endif
  110875. extern int *floor1_fit(vorbis_block *vb,void *look,
  110876. const float *logmdct, /* in */
  110877. const float *logmask);
  110878. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  110879. int *A,int *B,
  110880. int del);
  110881. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  110882. void*look,
  110883. int *post,int *ilogmask);
  110884. static int mapping0_forward(vorbis_block *vb){
  110885. vorbis_dsp_state *vd=vb->vd;
  110886. vorbis_info *vi=vd->vi;
  110887. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110888. private_state *b=(private_state*)vb->vd->backend_state;
  110889. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110890. int n=vb->pcmend;
  110891. int i,j,k;
  110892. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  110893. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  110894. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  110895. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  110896. float global_ampmax=vbi->ampmax;
  110897. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  110898. int blocktype=vbi->blocktype;
  110899. int modenumber=vb->W;
  110900. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  110901. vorbis_look_psy *psy_look=
  110902. b->psy+blocktype+(vb->W?2:0);
  110903. vb->mode=modenumber;
  110904. for(i=0;i<vi->channels;i++){
  110905. float scale=4.f/n;
  110906. float scale_dB;
  110907. float *pcm =vb->pcm[i];
  110908. float *logfft =pcm;
  110909. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  110910. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  110911. todB estimation used on IEEE 754
  110912. compliant machines had a bug that
  110913. returned dB values about a third
  110914. of a decibel too high. The bug
  110915. was harmless because tunings
  110916. implicitly took that into
  110917. account. However, fixing the bug
  110918. in the estimator requires
  110919. changing all the tunings as well.
  110920. For now, it's easier to sync
  110921. things back up here, and
  110922. recalibrate the tunings in the
  110923. next major model upgrade. */
  110924. #if 0
  110925. if(vi->channels==2)
  110926. if(i==0)
  110927. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  110928. else
  110929. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  110930. #endif
  110931. /* window the PCM data */
  110932. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  110933. #if 0
  110934. if(vi->channels==2)
  110935. if(i==0)
  110936. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  110937. else
  110938. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  110939. #endif
  110940. /* transform the PCM data */
  110941. /* only MDCT right now.... */
  110942. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  110943. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  110944. drft_forward(&b->fft_look[vb->W],pcm);
  110945. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  110946. original todB estimation used on
  110947. IEEE 754 compliant machines had a
  110948. bug that returned dB values about
  110949. a third of a decibel too high.
  110950. The bug was harmless because
  110951. tunings implicitly took that into
  110952. account. However, fixing the bug
  110953. in the estimator requires
  110954. changing all the tunings as well.
  110955. For now, it's easier to sync
  110956. things back up here, and
  110957. recalibrate the tunings in the
  110958. next major model upgrade. */
  110959. local_ampmax[i]=logfft[0];
  110960. for(j=1;j<n-1;j+=2){
  110961. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  110962. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  110963. .345 is a hack; the original todB
  110964. estimation used on IEEE 754
  110965. compliant machines had a bug that
  110966. returned dB values about a third
  110967. of a decibel too high. The bug
  110968. was harmless because tunings
  110969. implicitly took that into
  110970. account. However, fixing the bug
  110971. in the estimator requires
  110972. changing all the tunings as well.
  110973. For now, it's easier to sync
  110974. things back up here, and
  110975. recalibrate the tunings in the
  110976. next major model upgrade. */
  110977. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  110978. }
  110979. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  110980. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  110981. #if 0
  110982. if(vi->channels==2){
  110983. if(i==0){
  110984. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  110985. }else{
  110986. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  110987. }
  110988. }
  110989. #endif
  110990. }
  110991. {
  110992. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  110993. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  110994. for(i=0;i<vi->channels;i++){
  110995. /* the encoder setup assumes that all the modes used by any
  110996. specific bitrate tweaking use the same floor */
  110997. int submap=info->chmuxlist[i];
  110998. /* the following makes things clearer to *me* anyway */
  110999. float *mdct =gmdct[i];
  111000. float *logfft =vb->pcm[i];
  111001. float *logmdct =logfft+n/2;
  111002. float *logmask =logfft;
  111003. vb->mode=modenumber;
  111004. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  111005. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  111006. for(j=0;j<n/2;j++)
  111007. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  111008. todB estimation used on IEEE 754
  111009. compliant machines had a bug that
  111010. returned dB values about a third
  111011. of a decibel too high. The bug
  111012. was harmless because tunings
  111013. implicitly took that into
  111014. account. However, fixing the bug
  111015. in the estimator requires
  111016. changing all the tunings as well.
  111017. For now, it's easier to sync
  111018. things back up here, and
  111019. recalibrate the tunings in the
  111020. next major model upgrade. */
  111021. #if 0
  111022. if(vi->channels==2){
  111023. if(i==0)
  111024. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  111025. else
  111026. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  111027. }else{
  111028. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  111029. }
  111030. #endif
  111031. /* first step; noise masking. Not only does 'noise masking'
  111032. give us curves from which we can decide how much resolution
  111033. to give noise parts of the spectrum, it also implicitly hands
  111034. us a tonality estimate (the larger the value in the
  111035. 'noise_depth' vector, the more tonal that area is) */
  111036. _vp_noisemask(psy_look,
  111037. logmdct,
  111038. noise); /* noise does not have by-frequency offset
  111039. bias applied yet */
  111040. #if 0
  111041. if(vi->channels==2){
  111042. if(i==0)
  111043. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  111044. else
  111045. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  111046. }
  111047. #endif
  111048. /* second step: 'all the other crap'; all the stuff that isn't
  111049. computed/fit for bitrate management goes in the second psy
  111050. vector. This includes tone masking, peak limiting and ATH */
  111051. _vp_tonemask(psy_look,
  111052. logfft,
  111053. tone,
  111054. global_ampmax,
  111055. local_ampmax[i]);
  111056. #if 0
  111057. if(vi->channels==2){
  111058. if(i==0)
  111059. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  111060. else
  111061. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  111062. }
  111063. #endif
  111064. /* third step; we offset the noise vectors, overlay tone
  111065. masking. We then do a floor1-specific line fit. If we're
  111066. performing bitrate management, the line fit is performed
  111067. multiple times for up/down tweakage on demand. */
  111068. #if 0
  111069. {
  111070. float aotuv[psy_look->n];
  111071. #endif
  111072. _vp_offset_and_mix(psy_look,
  111073. noise,
  111074. tone,
  111075. 1,
  111076. logmask,
  111077. mdct,
  111078. logmdct);
  111079. #if 0
  111080. if(vi->channels==2){
  111081. if(i==0)
  111082. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  111083. else
  111084. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  111085. }
  111086. }
  111087. #endif
  111088. #if 0
  111089. if(vi->channels==2){
  111090. if(i==0)
  111091. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  111092. else
  111093. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  111094. }
  111095. #endif
  111096. /* this algorithm is hardwired to floor 1 for now; abort out if
  111097. we're *not* floor1. This won't happen unless someone has
  111098. broken the encode setup lib. Guard it anyway. */
  111099. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  111100. floor_posts[i][PACKETBLOBS/2]=
  111101. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111102. logmdct,
  111103. logmask);
  111104. /* are we managing bitrate? If so, perform two more fits for
  111105. later rate tweaking (fits represent hi/lo) */
  111106. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  111107. /* higher rate by way of lower noise curve */
  111108. _vp_offset_and_mix(psy_look,
  111109. noise,
  111110. tone,
  111111. 2,
  111112. logmask,
  111113. mdct,
  111114. logmdct);
  111115. #if 0
  111116. if(vi->channels==2){
  111117. if(i==0)
  111118. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  111119. else
  111120. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  111121. }
  111122. #endif
  111123. floor_posts[i][PACKETBLOBS-1]=
  111124. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111125. logmdct,
  111126. logmask);
  111127. /* lower rate by way of higher noise curve */
  111128. _vp_offset_and_mix(psy_look,
  111129. noise,
  111130. tone,
  111131. 0,
  111132. logmask,
  111133. mdct,
  111134. logmdct);
  111135. #if 0
  111136. if(vi->channels==2)
  111137. if(i==0)
  111138. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  111139. else
  111140. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  111141. #endif
  111142. floor_posts[i][0]=
  111143. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  111144. logmdct,
  111145. logmask);
  111146. /* we also interpolate a range of intermediate curves for
  111147. intermediate rates */
  111148. for(k=1;k<PACKETBLOBS/2;k++)
  111149. floor_posts[i][k]=
  111150. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111151. floor_posts[i][0],
  111152. floor_posts[i][PACKETBLOBS/2],
  111153. k*65536/(PACKETBLOBS/2));
  111154. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  111155. floor_posts[i][k]=
  111156. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  111157. floor_posts[i][PACKETBLOBS/2],
  111158. floor_posts[i][PACKETBLOBS-1],
  111159. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  111160. }
  111161. }
  111162. }
  111163. vbi->ampmax=global_ampmax;
  111164. /*
  111165. the next phases are performed once for vbr-only and PACKETBLOB
  111166. times for bitrate managed modes.
  111167. 1) encode actual mode being used
  111168. 2) encode the floor for each channel, compute coded mask curve/res
  111169. 3) normalize and couple.
  111170. 4) encode residue
  111171. 5) save packet bytes to the packetblob vector
  111172. */
  111173. /* iterate over the many masking curve fits we've created */
  111174. {
  111175. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  111176. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  111177. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111178. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  111179. float **mag_memo;
  111180. int **mag_sort;
  111181. if(info->coupling_steps){
  111182. mag_memo=_vp_quantize_couple_memo(vb,
  111183. &ci->psy_g_param,
  111184. psy_look,
  111185. info,
  111186. gmdct);
  111187. mag_sort=_vp_quantize_couple_sort(vb,
  111188. psy_look,
  111189. info,
  111190. mag_memo);
  111191. hf_reduction(&ci->psy_g_param,
  111192. psy_look,
  111193. info,
  111194. mag_memo);
  111195. }
  111196. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  111197. if(psy_look->vi->normal_channel_p){
  111198. for(i=0;i<vi->channels;i++){
  111199. float *mdct =gmdct[i];
  111200. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  111201. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  111202. }
  111203. }
  111204. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  111205. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  111206. k++){
  111207. oggpack_buffer *opb=vbi->packetblob[k];
  111208. /* start out our new packet blob with packet type and mode */
  111209. /* Encode the packet type */
  111210. oggpack_write(opb,0,1);
  111211. /* Encode the modenumber */
  111212. /* Encode frame mode, pre,post windowsize, then dispatch */
  111213. oggpack_write(opb,modenumber,b->modebits);
  111214. if(vb->W){
  111215. oggpack_write(opb,vb->lW,1);
  111216. oggpack_write(opb,vb->nW,1);
  111217. }
  111218. /* encode floor, compute masking curve, sep out residue */
  111219. for(i=0;i<vi->channels;i++){
  111220. int submap=info->chmuxlist[i];
  111221. float *mdct =gmdct[i];
  111222. float *res =vb->pcm[i];
  111223. int *ilogmask=ilogmaskch[i]=
  111224. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  111225. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  111226. floor_posts[i][k],
  111227. ilogmask);
  111228. #if 0
  111229. {
  111230. char buf[80];
  111231. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  111232. float work[n/2];
  111233. for(j=0;j<n/2;j++)
  111234. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  111235. _analysis_output(buf,seq,work,n/2,1,1,0);
  111236. }
  111237. #endif
  111238. _vp_remove_floor(psy_look,
  111239. mdct,
  111240. ilogmask,
  111241. res,
  111242. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111243. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  111244. #if 0
  111245. {
  111246. char buf[80];
  111247. float work[n/2];
  111248. for(j=0;j<n/2;j++)
  111249. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  111250. sprintf(buf,"resI%c%d",i?'R':'L',k);
  111251. _analysis_output(buf,seq,work,n/2,1,1,0);
  111252. }
  111253. #endif
  111254. }
  111255. /* our iteration is now based on masking curve, not prequant and
  111256. coupling. Only one prequant/coupling step */
  111257. /* quantize/couple */
  111258. /* incomplete implementation that assumes the tree is all depth
  111259. one, or no tree at all */
  111260. if(info->coupling_steps){
  111261. _vp_couple(k,
  111262. &ci->psy_g_param,
  111263. psy_look,
  111264. info,
  111265. vb->pcm,
  111266. mag_memo,
  111267. mag_sort,
  111268. ilogmaskch,
  111269. nonzero,
  111270. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  111271. }
  111272. /* classify and encode by submap */
  111273. for(i=0;i<info->submaps;i++){
  111274. int ch_in_bundle=0;
  111275. long **classifications;
  111276. int resnum=info->residuesubmap[i];
  111277. for(j=0;j<vi->channels;j++){
  111278. if(info->chmuxlist[j]==i){
  111279. zerobundle[ch_in_bundle]=0;
  111280. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  111281. res_bundle[ch_in_bundle]=vb->pcm[j];
  111282. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  111283. }
  111284. }
  111285. classifications=_residue_P[ci->residue_type[resnum]]->
  111286. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  111287. _residue_P[ci->residue_type[resnum]]->
  111288. forward(opb,vb,b->residue[resnum],
  111289. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  111290. }
  111291. /* ok, done encoding. Next protopacket. */
  111292. }
  111293. }
  111294. #if 0
  111295. seq++;
  111296. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  111297. #endif
  111298. return(0);
  111299. }
  111300. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  111301. vorbis_dsp_state *vd=vb->vd;
  111302. vorbis_info *vi=vd->vi;
  111303. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111304. private_state *b=(private_state*)vd->backend_state;
  111305. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  111306. int i,j;
  111307. long n=vb->pcmend=ci->blocksizes[vb->W];
  111308. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  111309. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  111310. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  111311. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  111312. /* recover the spectral envelope; store it in the PCM vector for now */
  111313. for(i=0;i<vi->channels;i++){
  111314. int submap=info->chmuxlist[i];
  111315. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111316. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  111317. if(floormemo[i])
  111318. nonzero[i]=1;
  111319. else
  111320. nonzero[i]=0;
  111321. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  111322. }
  111323. /* channel coupling can 'dirty' the nonzero listing */
  111324. for(i=0;i<info->coupling_steps;i++){
  111325. if(nonzero[info->coupling_mag[i]] ||
  111326. nonzero[info->coupling_ang[i]]){
  111327. nonzero[info->coupling_mag[i]]=1;
  111328. nonzero[info->coupling_ang[i]]=1;
  111329. }
  111330. }
  111331. /* recover the residue into our working vectors */
  111332. for(i=0;i<info->submaps;i++){
  111333. int ch_in_bundle=0;
  111334. for(j=0;j<vi->channels;j++){
  111335. if(info->chmuxlist[j]==i){
  111336. if(nonzero[j])
  111337. zerobundle[ch_in_bundle]=1;
  111338. else
  111339. zerobundle[ch_in_bundle]=0;
  111340. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  111341. }
  111342. }
  111343. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  111344. inverse(vb,b->residue[info->residuesubmap[i]],
  111345. pcmbundle,zerobundle,ch_in_bundle);
  111346. }
  111347. /* channel coupling */
  111348. for(i=info->coupling_steps-1;i>=0;i--){
  111349. float *pcmM=vb->pcm[info->coupling_mag[i]];
  111350. float *pcmA=vb->pcm[info->coupling_ang[i]];
  111351. for(j=0;j<n/2;j++){
  111352. float mag=pcmM[j];
  111353. float ang=pcmA[j];
  111354. if(mag>0)
  111355. if(ang>0){
  111356. pcmM[j]=mag;
  111357. pcmA[j]=mag-ang;
  111358. }else{
  111359. pcmA[j]=mag;
  111360. pcmM[j]=mag+ang;
  111361. }
  111362. else
  111363. if(ang>0){
  111364. pcmM[j]=mag;
  111365. pcmA[j]=mag+ang;
  111366. }else{
  111367. pcmA[j]=mag;
  111368. pcmM[j]=mag-ang;
  111369. }
  111370. }
  111371. }
  111372. /* compute and apply spectral envelope */
  111373. for(i=0;i<vi->channels;i++){
  111374. float *pcm=vb->pcm[i];
  111375. int submap=info->chmuxlist[i];
  111376. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  111377. inverse2(vb,b->flr[info->floorsubmap[submap]],
  111378. floormemo[i],pcm);
  111379. }
  111380. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  111381. /* only MDCT right now.... */
  111382. for(i=0;i<vi->channels;i++){
  111383. float *pcm=vb->pcm[i];
  111384. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  111385. }
  111386. /* all done! */
  111387. return(0);
  111388. }
  111389. /* export hooks */
  111390. vorbis_func_mapping mapping0_exportbundle={
  111391. &mapping0_pack,
  111392. &mapping0_unpack,
  111393. &mapping0_free_info,
  111394. &mapping0_forward,
  111395. &mapping0_inverse
  111396. };
  111397. #endif
  111398. /********* End of inlined file: mapping0.c *********/
  111399. /********* Start of inlined file: mdct.c *********/
  111400. /* this can also be run as an integer transform by uncommenting a
  111401. define in mdct.h; the integerization is a first pass and although
  111402. it's likely stable for Vorbis, the dynamic range is constrained and
  111403. roundoff isn't done (so it's noisy). Consider it functional, but
  111404. only a starting point. There's no point on a machine with an FPU */
  111405. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111406. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111407. // tasks..
  111408. #ifdef _MSC_VER
  111409. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111410. #endif
  111411. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111412. #if JUCE_USE_OGGVORBIS
  111413. #include <stdio.h>
  111414. #include <stdlib.h>
  111415. #include <string.h>
  111416. #include <math.h>
  111417. /* build lookups for trig functions; also pre-figure scaling and
  111418. some window function algebra. */
  111419. void mdct_init(mdct_lookup *lookup,int n){
  111420. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  111421. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  111422. int i;
  111423. int n2=n>>1;
  111424. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  111425. lookup->n=n;
  111426. lookup->trig=T;
  111427. lookup->bitrev=bitrev;
  111428. /* trig lookups... */
  111429. for(i=0;i<n/4;i++){
  111430. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  111431. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  111432. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  111433. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  111434. }
  111435. for(i=0;i<n/8;i++){
  111436. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  111437. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  111438. }
  111439. /* bitreverse lookup... */
  111440. {
  111441. int mask=(1<<(log2n-1))-1,i,j;
  111442. int msb=1<<(log2n-2);
  111443. for(i=0;i<n/8;i++){
  111444. int acc=0;
  111445. for(j=0;msb>>j;j++)
  111446. if((msb>>j)&i)acc|=1<<j;
  111447. bitrev[i*2]=((~acc)&mask)-1;
  111448. bitrev[i*2+1]=acc;
  111449. }
  111450. }
  111451. lookup->scale=FLOAT_CONV(4.f/n);
  111452. }
  111453. /* 8 point butterfly (in place, 4 register) */
  111454. STIN void mdct_butterfly_8(DATA_TYPE *x){
  111455. REG_TYPE r0 = x[6] + x[2];
  111456. REG_TYPE r1 = x[6] - x[2];
  111457. REG_TYPE r2 = x[4] + x[0];
  111458. REG_TYPE r3 = x[4] - x[0];
  111459. x[6] = r0 + r2;
  111460. x[4] = r0 - r2;
  111461. r0 = x[5] - x[1];
  111462. r2 = x[7] - x[3];
  111463. x[0] = r1 + r0;
  111464. x[2] = r1 - r0;
  111465. r0 = x[5] + x[1];
  111466. r1 = x[7] + x[3];
  111467. x[3] = r2 + r3;
  111468. x[1] = r2 - r3;
  111469. x[7] = r1 + r0;
  111470. x[5] = r1 - r0;
  111471. }
  111472. /* 16 point butterfly (in place, 4 register) */
  111473. STIN void mdct_butterfly_16(DATA_TYPE *x){
  111474. REG_TYPE r0 = x[1] - x[9];
  111475. REG_TYPE r1 = x[0] - x[8];
  111476. x[8] += x[0];
  111477. x[9] += x[1];
  111478. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  111479. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  111480. r0 = x[3] - x[11];
  111481. r1 = x[10] - x[2];
  111482. x[10] += x[2];
  111483. x[11] += x[3];
  111484. x[2] = r0;
  111485. x[3] = r1;
  111486. r0 = x[12] - x[4];
  111487. r1 = x[13] - x[5];
  111488. x[12] += x[4];
  111489. x[13] += x[5];
  111490. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  111491. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  111492. r0 = x[14] - x[6];
  111493. r1 = x[15] - x[7];
  111494. x[14] += x[6];
  111495. x[15] += x[7];
  111496. x[6] = r0;
  111497. x[7] = r1;
  111498. mdct_butterfly_8(x);
  111499. mdct_butterfly_8(x+8);
  111500. }
  111501. /* 32 point butterfly (in place, 4 register) */
  111502. STIN void mdct_butterfly_32(DATA_TYPE *x){
  111503. REG_TYPE r0 = x[30] - x[14];
  111504. REG_TYPE r1 = x[31] - x[15];
  111505. x[30] += x[14];
  111506. x[31] += x[15];
  111507. x[14] = r0;
  111508. x[15] = r1;
  111509. r0 = x[28] - x[12];
  111510. r1 = x[29] - x[13];
  111511. x[28] += x[12];
  111512. x[29] += x[13];
  111513. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  111514. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  111515. r0 = x[26] - x[10];
  111516. r1 = x[27] - x[11];
  111517. x[26] += x[10];
  111518. x[27] += x[11];
  111519. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  111520. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  111521. r0 = x[24] - x[8];
  111522. r1 = x[25] - x[9];
  111523. x[24] += x[8];
  111524. x[25] += x[9];
  111525. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  111526. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111527. r0 = x[22] - x[6];
  111528. r1 = x[7] - x[23];
  111529. x[22] += x[6];
  111530. x[23] += x[7];
  111531. x[6] = r1;
  111532. x[7] = r0;
  111533. r0 = x[4] - x[20];
  111534. r1 = x[5] - x[21];
  111535. x[20] += x[4];
  111536. x[21] += x[5];
  111537. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  111538. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  111539. r0 = x[2] - x[18];
  111540. r1 = x[3] - x[19];
  111541. x[18] += x[2];
  111542. x[19] += x[3];
  111543. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  111544. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  111545. r0 = x[0] - x[16];
  111546. r1 = x[1] - x[17];
  111547. x[16] += x[0];
  111548. x[17] += x[1];
  111549. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  111550. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  111551. mdct_butterfly_16(x);
  111552. mdct_butterfly_16(x+16);
  111553. }
  111554. /* N point first stage butterfly (in place, 2 register) */
  111555. STIN void mdct_butterfly_first(DATA_TYPE *T,
  111556. DATA_TYPE *x,
  111557. int points){
  111558. DATA_TYPE *x1 = x + points - 8;
  111559. DATA_TYPE *x2 = x + (points>>1) - 8;
  111560. REG_TYPE r0;
  111561. REG_TYPE r1;
  111562. do{
  111563. r0 = x1[6] - x2[6];
  111564. r1 = x1[7] - x2[7];
  111565. x1[6] += x2[6];
  111566. x1[7] += x2[7];
  111567. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111568. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111569. r0 = x1[4] - x2[4];
  111570. r1 = x1[5] - x2[5];
  111571. x1[4] += x2[4];
  111572. x1[5] += x2[5];
  111573. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  111574. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  111575. r0 = x1[2] - x2[2];
  111576. r1 = x1[3] - x2[3];
  111577. x1[2] += x2[2];
  111578. x1[3] += x2[3];
  111579. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  111580. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  111581. r0 = x1[0] - x2[0];
  111582. r1 = x1[1] - x2[1];
  111583. x1[0] += x2[0];
  111584. x1[1] += x2[1];
  111585. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  111586. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  111587. x1-=8;
  111588. x2-=8;
  111589. T+=16;
  111590. }while(x2>=x);
  111591. }
  111592. /* N/stage point generic N stage butterfly (in place, 2 register) */
  111593. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  111594. DATA_TYPE *x,
  111595. int points,
  111596. int trigint){
  111597. DATA_TYPE *x1 = x + points - 8;
  111598. DATA_TYPE *x2 = x + (points>>1) - 8;
  111599. REG_TYPE r0;
  111600. REG_TYPE r1;
  111601. do{
  111602. r0 = x1[6] - x2[6];
  111603. r1 = x1[7] - x2[7];
  111604. x1[6] += x2[6];
  111605. x1[7] += x2[7];
  111606. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111607. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111608. T+=trigint;
  111609. r0 = x1[4] - x2[4];
  111610. r1 = x1[5] - x2[5];
  111611. x1[4] += x2[4];
  111612. x1[5] += x2[5];
  111613. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111614. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111615. T+=trigint;
  111616. r0 = x1[2] - x2[2];
  111617. r1 = x1[3] - x2[3];
  111618. x1[2] += x2[2];
  111619. x1[3] += x2[3];
  111620. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111621. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111622. T+=trigint;
  111623. r0 = x1[0] - x2[0];
  111624. r1 = x1[1] - x2[1];
  111625. x1[0] += x2[0];
  111626. x1[1] += x2[1];
  111627. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  111628. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  111629. T+=trigint;
  111630. x1-=8;
  111631. x2-=8;
  111632. }while(x2>=x);
  111633. }
  111634. STIN void mdct_butterflies(mdct_lookup *init,
  111635. DATA_TYPE *x,
  111636. int points){
  111637. DATA_TYPE *T=init->trig;
  111638. int stages=init->log2n-5;
  111639. int i,j;
  111640. if(--stages>0){
  111641. mdct_butterfly_first(T,x,points);
  111642. }
  111643. for(i=1;--stages>0;i++){
  111644. for(j=0;j<(1<<i);j++)
  111645. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  111646. }
  111647. for(j=0;j<points;j+=32)
  111648. mdct_butterfly_32(x+j);
  111649. }
  111650. void mdct_clear(mdct_lookup *l){
  111651. if(l){
  111652. if(l->trig)_ogg_free(l->trig);
  111653. if(l->bitrev)_ogg_free(l->bitrev);
  111654. memset(l,0,sizeof(*l));
  111655. }
  111656. }
  111657. STIN void mdct_bitreverse(mdct_lookup *init,
  111658. DATA_TYPE *x){
  111659. int n = init->n;
  111660. int *bit = init->bitrev;
  111661. DATA_TYPE *w0 = x;
  111662. DATA_TYPE *w1 = x = w0+(n>>1);
  111663. DATA_TYPE *T = init->trig+n;
  111664. do{
  111665. DATA_TYPE *x0 = x+bit[0];
  111666. DATA_TYPE *x1 = x+bit[1];
  111667. REG_TYPE r0 = x0[1] - x1[1];
  111668. REG_TYPE r1 = x0[0] + x1[0];
  111669. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  111670. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  111671. w1 -= 4;
  111672. r0 = HALVE(x0[1] + x1[1]);
  111673. r1 = HALVE(x0[0] - x1[0]);
  111674. w0[0] = r0 + r2;
  111675. w1[2] = r0 - r2;
  111676. w0[1] = r1 + r3;
  111677. w1[3] = r3 - r1;
  111678. x0 = x+bit[2];
  111679. x1 = x+bit[3];
  111680. r0 = x0[1] - x1[1];
  111681. r1 = x0[0] + x1[0];
  111682. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  111683. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  111684. r0 = HALVE(x0[1] + x1[1]);
  111685. r1 = HALVE(x0[0] - x1[0]);
  111686. w0[2] = r0 + r2;
  111687. w1[0] = r0 - r2;
  111688. w0[3] = r1 + r3;
  111689. w1[1] = r3 - r1;
  111690. T += 4;
  111691. bit += 4;
  111692. w0 += 4;
  111693. }while(w0<w1);
  111694. }
  111695. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111696. int n=init->n;
  111697. int n2=n>>1;
  111698. int n4=n>>2;
  111699. /* rotate */
  111700. DATA_TYPE *iX = in+n2-7;
  111701. DATA_TYPE *oX = out+n2+n4;
  111702. DATA_TYPE *T = init->trig+n4;
  111703. do{
  111704. oX -= 4;
  111705. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  111706. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  111707. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  111708. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  111709. iX -= 8;
  111710. T += 4;
  111711. }while(iX>=in);
  111712. iX = in+n2-8;
  111713. oX = out+n2+n4;
  111714. T = init->trig+n4;
  111715. do{
  111716. T -= 4;
  111717. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  111718. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  111719. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  111720. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  111721. iX -= 8;
  111722. oX += 4;
  111723. }while(iX>=in);
  111724. mdct_butterflies(init,out+n2,n2);
  111725. mdct_bitreverse(init,out);
  111726. /* roatate + window */
  111727. {
  111728. DATA_TYPE *oX1=out+n2+n4;
  111729. DATA_TYPE *oX2=out+n2+n4;
  111730. DATA_TYPE *iX =out;
  111731. T =init->trig+n2;
  111732. do{
  111733. oX1-=4;
  111734. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  111735. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  111736. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  111737. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  111738. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  111739. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  111740. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  111741. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  111742. oX2+=4;
  111743. iX += 8;
  111744. T += 8;
  111745. }while(iX<oX1);
  111746. iX=out+n2+n4;
  111747. oX1=out+n4;
  111748. oX2=oX1;
  111749. do{
  111750. oX1-=4;
  111751. iX-=4;
  111752. oX2[0] = -(oX1[3] = iX[3]);
  111753. oX2[1] = -(oX1[2] = iX[2]);
  111754. oX2[2] = -(oX1[1] = iX[1]);
  111755. oX2[3] = -(oX1[0] = iX[0]);
  111756. oX2+=4;
  111757. }while(oX2<iX);
  111758. iX=out+n2+n4;
  111759. oX1=out+n2+n4;
  111760. oX2=out+n2;
  111761. do{
  111762. oX1-=4;
  111763. oX1[0]= iX[3];
  111764. oX1[1]= iX[2];
  111765. oX1[2]= iX[1];
  111766. oX1[3]= iX[0];
  111767. iX+=4;
  111768. }while(oX1>oX2);
  111769. }
  111770. }
  111771. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  111772. int n=init->n;
  111773. int n2=n>>1;
  111774. int n4=n>>2;
  111775. int n8=n>>3;
  111776. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  111777. DATA_TYPE *w2=w+n2;
  111778. /* rotate */
  111779. /* window + rotate + step 1 */
  111780. REG_TYPE r0;
  111781. REG_TYPE r1;
  111782. DATA_TYPE *x0=in+n2+n4;
  111783. DATA_TYPE *x1=x0+1;
  111784. DATA_TYPE *T=init->trig+n2;
  111785. int i=0;
  111786. for(i=0;i<n8;i+=2){
  111787. x0 -=4;
  111788. T-=2;
  111789. r0= x0[2] + x1[0];
  111790. r1= x0[0] + x1[2];
  111791. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111792. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111793. x1 +=4;
  111794. }
  111795. x1=in+1;
  111796. for(;i<n2-n8;i+=2){
  111797. T-=2;
  111798. x0 -=4;
  111799. r0= x0[2] - x1[0];
  111800. r1= x0[0] - x1[2];
  111801. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111802. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111803. x1 +=4;
  111804. }
  111805. x0=in+n;
  111806. for(;i<n2;i+=2){
  111807. T-=2;
  111808. x0 -=4;
  111809. r0= -x0[2] - x1[0];
  111810. r1= -x0[0] - x1[2];
  111811. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  111812. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  111813. x1 +=4;
  111814. }
  111815. mdct_butterflies(init,w+n2,n2);
  111816. mdct_bitreverse(init,w);
  111817. /* roatate + window */
  111818. T=init->trig+n2;
  111819. x0=out+n2;
  111820. for(i=0;i<n4;i++){
  111821. x0--;
  111822. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  111823. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  111824. w+=2;
  111825. T+=2;
  111826. }
  111827. }
  111828. #endif
  111829. /********* End of inlined file: mdct.c *********/
  111830. /********* Start of inlined file: psy.c *********/
  111831. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111832. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111833. // tasks..
  111834. #ifdef _MSC_VER
  111835. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111836. #endif
  111837. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111838. #if JUCE_USE_OGGVORBIS
  111839. #include <stdlib.h>
  111840. #include <math.h>
  111841. #include <string.h>
  111842. /********* Start of inlined file: masking.h *********/
  111843. #ifndef _V_MASKING_H_
  111844. #define _V_MASKING_H_
  111845. /* more detailed ATH; the bass if flat to save stressing the floor
  111846. overly for only a bin or two of savings. */
  111847. #define MAX_ATH 88
  111848. static float ATH[]={
  111849. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  111850. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  111851. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  111852. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  111853. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  111854. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  111855. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  111856. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  111857. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  111858. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  111859. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  111860. };
  111861. /* The tone masking curves from Ehmer's and Fielder's papers have been
  111862. replaced by an empirically collected data set. The previously
  111863. published values were, far too often, simply on crack. */
  111864. #define EHMER_OFFSET 16
  111865. #define EHMER_MAX 56
  111866. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  111867. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  111868. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  111869. for collection of these curves) */
  111870. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  111871. /* 62.5 Hz */
  111872. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  111873. -60, -60, -60, -60, -62, -62, -65, -73,
  111874. -69, -68, -68, -67, -70, -70, -72, -74,
  111875. -75, -79, -79, -80, -83, -88, -93, -100,
  111876. -110, -999, -999, -999, -999, -999, -999, -999,
  111877. -999, -999, -999, -999, -999, -999, -999, -999,
  111878. -999, -999, -999, -999, -999, -999, -999, -999},
  111879. { -48, -48, -48, -48, -48, -48, -48, -48,
  111880. -48, -48, -48, -48, -48, -53, -61, -66,
  111881. -66, -68, -67, -70, -76, -76, -72, -73,
  111882. -75, -76, -78, -79, -83, -88, -93, -100,
  111883. -110, -999, -999, -999, -999, -999, -999, -999,
  111884. -999, -999, -999, -999, -999, -999, -999, -999,
  111885. -999, -999, -999, -999, -999, -999, -999, -999},
  111886. { -37, -37, -37, -37, -37, -37, -37, -37,
  111887. -38, -40, -42, -46, -48, -53, -55, -62,
  111888. -65, -58, -56, -56, -61, -60, -65, -67,
  111889. -69, -71, -77, -77, -78, -80, -82, -84,
  111890. -88, -93, -98, -106, -112, -999, -999, -999,
  111891. -999, -999, -999, -999, -999, -999, -999, -999,
  111892. -999, -999, -999, -999, -999, -999, -999, -999},
  111893. { -25, -25, -25, -25, -25, -25, -25, -25,
  111894. -25, -26, -27, -29, -32, -38, -48, -52,
  111895. -52, -50, -48, -48, -51, -52, -54, -60,
  111896. -67, -67, -66, -68, -69, -73, -73, -76,
  111897. -80, -81, -81, -85, -85, -86, -88, -93,
  111898. -100, -110, -999, -999, -999, -999, -999, -999,
  111899. -999, -999, -999, -999, -999, -999, -999, -999},
  111900. { -16, -16, -16, -16, -16, -16, -16, -16,
  111901. -17, -19, -20, -22, -26, -28, -31, -40,
  111902. -47, -39, -39, -40, -42, -43, -47, -51,
  111903. -57, -52, -55, -55, -60, -58, -62, -63,
  111904. -70, -67, -69, -72, -73, -77, -80, -82,
  111905. -83, -87, -90, -94, -98, -104, -115, -999,
  111906. -999, -999, -999, -999, -999, -999, -999, -999},
  111907. { -8, -8, -8, -8, -8, -8, -8, -8,
  111908. -8, -8, -10, -11, -15, -19, -25, -30,
  111909. -34, -31, -30, -31, -29, -32, -35, -42,
  111910. -48, -42, -44, -46, -50, -50, -51, -52,
  111911. -59, -54, -55, -55, -58, -62, -63, -66,
  111912. -72, -73, -76, -75, -78, -80, -80, -81,
  111913. -84, -88, -90, -94, -98, -101, -106, -110}},
  111914. /* 88Hz */
  111915. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  111916. -66, -66, -66, -66, -66, -67, -67, -67,
  111917. -76, -72, -71, -74, -76, -76, -75, -78,
  111918. -79, -79, -81, -83, -86, -89, -93, -97,
  111919. -100, -105, -110, -999, -999, -999, -999, -999,
  111920. -999, -999, -999, -999, -999, -999, -999, -999,
  111921. -999, -999, -999, -999, -999, -999, -999, -999},
  111922. { -47, -47, -47, -47, -47, -47, -47, -47,
  111923. -47, -47, -47, -48, -51, -55, -59, -66,
  111924. -66, -66, -67, -66, -68, -69, -70, -74,
  111925. -79, -77, -77, -78, -80, -81, -82, -84,
  111926. -86, -88, -91, -95, -100, -108, -116, -999,
  111927. -999, -999, -999, -999, -999, -999, -999, -999,
  111928. -999, -999, -999, -999, -999, -999, -999, -999},
  111929. { -36, -36, -36, -36, -36, -36, -36, -36,
  111930. -36, -37, -37, -41, -44, -48, -51, -58,
  111931. -62, -60, -57, -59, -59, -60, -63, -65,
  111932. -72, -71, -70, -72, -74, -77, -76, -78,
  111933. -81, -81, -80, -83, -86, -91, -96, -100,
  111934. -105, -110, -999, -999, -999, -999, -999, -999,
  111935. -999, -999, -999, -999, -999, -999, -999, -999},
  111936. { -28, -28, -28, -28, -28, -28, -28, -28,
  111937. -28, -30, -32, -32, -33, -35, -41, -49,
  111938. -50, -49, -47, -48, -48, -52, -51, -57,
  111939. -65, -61, -59, -61, -64, -69, -70, -74,
  111940. -77, -77, -78, -81, -84, -85, -87, -90,
  111941. -92, -96, -100, -107, -112, -999, -999, -999,
  111942. -999, -999, -999, -999, -999, -999, -999, -999},
  111943. { -19, -19, -19, -19, -19, -19, -19, -19,
  111944. -20, -21, -23, -27, -30, -35, -36, -41,
  111945. -46, -44, -42, -40, -41, -41, -43, -48,
  111946. -55, -53, -52, -53, -56, -59, -58, -60,
  111947. -67, -66, -69, -71, -72, -75, -79, -81,
  111948. -84, -87, -90, -93, -97, -101, -107, -114,
  111949. -999, -999, -999, -999, -999, -999, -999, -999},
  111950. { -9, -9, -9, -9, -9, -9, -9, -9,
  111951. -11, -12, -12, -15, -16, -20, -23, -30,
  111952. -37, -34, -33, -34, -31, -32, -32, -38,
  111953. -47, -44, -41, -40, -47, -49, -46, -46,
  111954. -58, -50, -50, -54, -58, -62, -64, -67,
  111955. -67, -70, -72, -76, -79, -83, -87, -91,
  111956. -96, -100, -104, -110, -999, -999, -999, -999}},
  111957. /* 125 Hz */
  111958. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  111959. -62, -62, -63, -64, -66, -67, -66, -68,
  111960. -75, -72, -76, -75, -76, -78, -79, -82,
  111961. -84, -85, -90, -94, -101, -110, -999, -999,
  111962. -999, -999, -999, -999, -999, -999, -999, -999,
  111963. -999, -999, -999, -999, -999, -999, -999, -999,
  111964. -999, -999, -999, -999, -999, -999, -999, -999},
  111965. { -59, -59, -59, -59, -59, -59, -59, -59,
  111966. -59, -59, -59, -60, -60, -61, -63, -66,
  111967. -71, -68, -70, -70, -71, -72, -72, -75,
  111968. -81, -78, -79, -82, -83, -86, -90, -97,
  111969. -103, -113, -999, -999, -999, -999, -999, -999,
  111970. -999, -999, -999, -999, -999, -999, -999, -999,
  111971. -999, -999, -999, -999, -999, -999, -999, -999},
  111972. { -53, -53, -53, -53, -53, -53, -53, -53,
  111973. -53, -54, -55, -57, -56, -57, -55, -61,
  111974. -65, -60, -60, -62, -63, -63, -66, -68,
  111975. -74, -73, -75, -75, -78, -80, -80, -82,
  111976. -85, -90, -96, -101, -108, -999, -999, -999,
  111977. -999, -999, -999, -999, -999, -999, -999, -999,
  111978. -999, -999, -999, -999, -999, -999, -999, -999},
  111979. { -46, -46, -46, -46, -46, -46, -46, -46,
  111980. -46, -46, -47, -47, -47, -47, -48, -51,
  111981. -57, -51, -49, -50, -51, -53, -54, -59,
  111982. -66, -60, -62, -67, -67, -70, -72, -75,
  111983. -76, -78, -81, -85, -88, -94, -97, -104,
  111984. -112, -999, -999, -999, -999, -999, -999, -999,
  111985. -999, -999, -999, -999, -999, -999, -999, -999},
  111986. { -36, -36, -36, -36, -36, -36, -36, -36,
  111987. -39, -41, -42, -42, -39, -38, -41, -43,
  111988. -52, -44, -40, -39, -37, -37, -40, -47,
  111989. -54, -50, -48, -50, -55, -61, -59, -62,
  111990. -66, -66, -66, -69, -69, -73, -74, -74,
  111991. -75, -77, -79, -82, -87, -91, -95, -100,
  111992. -108, -115, -999, -999, -999, -999, -999, -999},
  111993. { -28, -26, -24, -22, -20, -20, -23, -29,
  111994. -30, -31, -28, -27, -28, -28, -28, -35,
  111995. -40, -33, -32, -29, -30, -30, -30, -37,
  111996. -45, -41, -37, -38, -45, -47, -47, -48,
  111997. -53, -49, -48, -50, -49, -49, -51, -52,
  111998. -58, -56, -57, -56, -60, -61, -62, -70,
  111999. -72, -74, -78, -83, -88, -93, -100, -106}},
  112000. /* 177 Hz */
  112001. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112002. -999, -110, -105, -100, -95, -91, -87, -83,
  112003. -80, -78, -76, -78, -78, -81, -83, -85,
  112004. -86, -85, -86, -87, -90, -97, -107, -999,
  112005. -999, -999, -999, -999, -999, -999, -999, -999,
  112006. -999, -999, -999, -999, -999, -999, -999, -999,
  112007. -999, -999, -999, -999, -999, -999, -999, -999},
  112008. {-999, -999, -999, -110, -105, -100, -95, -90,
  112009. -85, -81, -77, -73, -70, -67, -67, -68,
  112010. -75, -73, -70, -69, -70, -72, -75, -79,
  112011. -84, -83, -84, -86, -88, -89, -89, -93,
  112012. -98, -105, -112, -999, -999, -999, -999, -999,
  112013. -999, -999, -999, -999, -999, -999, -999, -999,
  112014. -999, -999, -999, -999, -999, -999, -999, -999},
  112015. {-105, -100, -95, -90, -85, -80, -76, -71,
  112016. -68, -68, -65, -63, -63, -62, -62, -64,
  112017. -65, -64, -61, -62, -63, -64, -66, -68,
  112018. -73, -73, -74, -75, -76, -81, -83, -85,
  112019. -88, -89, -92, -95, -100, -108, -999, -999,
  112020. -999, -999, -999, -999, -999, -999, -999, -999,
  112021. -999, -999, -999, -999, -999, -999, -999, -999},
  112022. { -80, -75, -71, -68, -65, -63, -62, -61,
  112023. -61, -61, -61, -59, -56, -57, -53, -50,
  112024. -58, -52, -50, -50, -52, -53, -54, -58,
  112025. -67, -63, -67, -68, -72, -75, -78, -80,
  112026. -81, -81, -82, -85, -89, -90, -93, -97,
  112027. -101, -107, -114, -999, -999, -999, -999, -999,
  112028. -999, -999, -999, -999, -999, -999, -999, -999},
  112029. { -65, -61, -59, -57, -56, -55, -55, -56,
  112030. -56, -57, -55, -53, -52, -47, -44, -44,
  112031. -50, -44, -41, -39, -39, -42, -40, -46,
  112032. -51, -49, -50, -53, -54, -63, -60, -61,
  112033. -62, -66, -66, -66, -70, -73, -74, -75,
  112034. -76, -75, -79, -85, -89, -91, -96, -102,
  112035. -110, -999, -999, -999, -999, -999, -999, -999},
  112036. { -52, -50, -49, -49, -48, -48, -48, -49,
  112037. -50, -50, -49, -46, -43, -39, -35, -33,
  112038. -38, -36, -32, -29, -32, -32, -32, -35,
  112039. -44, -39, -38, -38, -46, -50, -45, -46,
  112040. -53, -50, -50, -50, -54, -54, -53, -53,
  112041. -56, -57, -59, -66, -70, -72, -74, -79,
  112042. -83, -85, -90, -97, -114, -999, -999, -999}},
  112043. /* 250 Hz */
  112044. {{-999, -999, -999, -999, -999, -999, -110, -105,
  112045. -100, -95, -90, -86, -80, -75, -75, -79,
  112046. -80, -79, -80, -81, -82, -88, -95, -103,
  112047. -110, -999, -999, -999, -999, -999, -999, -999,
  112048. -999, -999, -999, -999, -999, -999, -999, -999,
  112049. -999, -999, -999, -999, -999, -999, -999, -999,
  112050. -999, -999, -999, -999, -999, -999, -999, -999},
  112051. {-999, -999, -999, -999, -108, -103, -98, -93,
  112052. -88, -83, -79, -78, -75, -71, -67, -68,
  112053. -73, -73, -72, -73, -75, -77, -80, -82,
  112054. -88, -93, -100, -107, -114, -999, -999, -999,
  112055. -999, -999, -999, -999, -999, -999, -999, -999,
  112056. -999, -999, -999, -999, -999, -999, -999, -999,
  112057. -999, -999, -999, -999, -999, -999, -999, -999},
  112058. {-999, -999, -999, -110, -105, -101, -96, -90,
  112059. -86, -81, -77, -73, -69, -66, -61, -62,
  112060. -66, -64, -62, -65, -66, -70, -72, -76,
  112061. -81, -80, -84, -90, -95, -102, -110, -999,
  112062. -999, -999, -999, -999, -999, -999, -999, -999,
  112063. -999, -999, -999, -999, -999, -999, -999, -999,
  112064. -999, -999, -999, -999, -999, -999, -999, -999},
  112065. {-999, -999, -999, -107, -103, -97, -92, -88,
  112066. -83, -79, -74, -70, -66, -59, -53, -58,
  112067. -62, -55, -54, -54, -54, -58, -61, -62,
  112068. -72, -70, -72, -75, -78, -80, -81, -80,
  112069. -83, -83, -88, -93, -100, -107, -115, -999,
  112070. -999, -999, -999, -999, -999, -999, -999, -999,
  112071. -999, -999, -999, -999, -999, -999, -999, -999},
  112072. {-999, -999, -999, -105, -100, -95, -90, -85,
  112073. -80, -75, -70, -66, -62, -56, -48, -44,
  112074. -48, -46, -46, -43, -46, -48, -48, -51,
  112075. -58, -58, -59, -60, -62, -62, -61, -61,
  112076. -65, -64, -65, -68, -70, -74, -75, -78,
  112077. -81, -86, -95, -110, -999, -999, -999, -999,
  112078. -999, -999, -999, -999, -999, -999, -999, -999},
  112079. {-999, -999, -105, -100, -95, -90, -85, -80,
  112080. -75, -70, -65, -61, -55, -49, -39, -33,
  112081. -40, -35, -32, -38, -40, -33, -35, -37,
  112082. -46, -41, -45, -44, -46, -42, -45, -46,
  112083. -52, -50, -50, -50, -54, -54, -55, -57,
  112084. -62, -64, -66, -68, -70, -76, -81, -90,
  112085. -100, -110, -999, -999, -999, -999, -999, -999}},
  112086. /* 354 hz */
  112087. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112088. -105, -98, -90, -85, -82, -83, -80, -78,
  112089. -84, -79, -80, -83, -87, -89, -91, -93,
  112090. -99, -106, -117, -999, -999, -999, -999, -999,
  112091. -999, -999, -999, -999, -999, -999, -999, -999,
  112092. -999, -999, -999, -999, -999, -999, -999, -999,
  112093. -999, -999, -999, -999, -999, -999, -999, -999},
  112094. {-999, -999, -999, -999, -999, -999, -999, -999,
  112095. -105, -98, -90, -85, -80, -75, -70, -68,
  112096. -74, -72, -74, -77, -80, -82, -85, -87,
  112097. -92, -89, -91, -95, -100, -106, -112, -999,
  112098. -999, -999, -999, -999, -999, -999, -999, -999,
  112099. -999, -999, -999, -999, -999, -999, -999, -999,
  112100. -999, -999, -999, -999, -999, -999, -999, -999},
  112101. {-999, -999, -999, -999, -999, -999, -999, -999,
  112102. -105, -98, -90, -83, -75, -71, -63, -64,
  112103. -67, -62, -64, -67, -70, -73, -77, -81,
  112104. -84, -83, -85, -89, -90, -93, -98, -104,
  112105. -109, -114, -999, -999, -999, -999, -999, -999,
  112106. -999, -999, -999, -999, -999, -999, -999, -999,
  112107. -999, -999, -999, -999, -999, -999, -999, -999},
  112108. {-999, -999, -999, -999, -999, -999, -999, -999,
  112109. -103, -96, -88, -81, -75, -68, -58, -54,
  112110. -56, -54, -56, -56, -58, -60, -63, -66,
  112111. -74, -69, -72, -72, -75, -74, -77, -81,
  112112. -81, -82, -84, -87, -93, -96, -99, -104,
  112113. -110, -999, -999, -999, -999, -999, -999, -999,
  112114. -999, -999, -999, -999, -999, -999, -999, -999},
  112115. {-999, -999, -999, -999, -999, -108, -102, -96,
  112116. -91, -85, -80, -74, -68, -60, -51, -46,
  112117. -48, -46, -43, -45, -47, -47, -49, -48,
  112118. -56, -53, -55, -58, -57, -63, -58, -60,
  112119. -66, -64, -67, -70, -70, -74, -77, -84,
  112120. -86, -89, -91, -93, -94, -101, -109, -118,
  112121. -999, -999, -999, -999, -999, -999, -999, -999},
  112122. {-999, -999, -999, -108, -103, -98, -93, -88,
  112123. -83, -78, -73, -68, -60, -53, -44, -35,
  112124. -38, -38, -34, -34, -36, -40, -41, -44,
  112125. -51, -45, -46, -47, -46, -54, -50, -49,
  112126. -50, -50, -50, -51, -54, -57, -58, -60,
  112127. -66, -66, -66, -64, -65, -68, -77, -82,
  112128. -87, -95, -110, -999, -999, -999, -999, -999}},
  112129. /* 500 Hz */
  112130. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112131. -107, -102, -97, -92, -87, -83, -78, -75,
  112132. -82, -79, -83, -85, -89, -92, -95, -98,
  112133. -101, -105, -109, -113, -999, -999, -999, -999,
  112134. -999, -999, -999, -999, -999, -999, -999, -999,
  112135. -999, -999, -999, -999, -999, -999, -999, -999,
  112136. -999, -999, -999, -999, -999, -999, -999, -999},
  112137. {-999, -999, -999, -999, -999, -999, -999, -106,
  112138. -100, -95, -90, -86, -81, -78, -74, -69,
  112139. -74, -74, -76, -79, -83, -84, -86, -89,
  112140. -92, -97, -93, -100, -103, -107, -110, -999,
  112141. -999, -999, -999, -999, -999, -999, -999, -999,
  112142. -999, -999, -999, -999, -999, -999, -999, -999,
  112143. -999, -999, -999, -999, -999, -999, -999, -999},
  112144. {-999, -999, -999, -999, -999, -999, -106, -100,
  112145. -95, -90, -87, -83, -80, -75, -69, -60,
  112146. -66, -66, -68, -70, -74, -78, -79, -81,
  112147. -81, -83, -84, -87, -93, -96, -99, -103,
  112148. -107, -110, -999, -999, -999, -999, -999, -999,
  112149. -999, -999, -999, -999, -999, -999, -999, -999,
  112150. -999, -999, -999, -999, -999, -999, -999, -999},
  112151. {-999, -999, -999, -999, -999, -108, -103, -98,
  112152. -93, -89, -85, -82, -78, -71, -62, -55,
  112153. -58, -58, -54, -54, -55, -59, -61, -62,
  112154. -70, -66, -66, -67, -70, -72, -75, -78,
  112155. -84, -84, -84, -88, -91, -90, -95, -98,
  112156. -102, -103, -106, -110, -999, -999, -999, -999,
  112157. -999, -999, -999, -999, -999, -999, -999, -999},
  112158. {-999, -999, -999, -999, -108, -103, -98, -94,
  112159. -90, -87, -82, -79, -73, -67, -58, -47,
  112160. -50, -45, -41, -45, -48, -44, -44, -49,
  112161. -54, -51, -48, -47, -49, -50, -51, -57,
  112162. -58, -60, -63, -69, -70, -69, -71, -74,
  112163. -78, -82, -90, -95, -101, -105, -110, -999,
  112164. -999, -999, -999, -999, -999, -999, -999, -999},
  112165. {-999, -999, -999, -105, -101, -97, -93, -90,
  112166. -85, -80, -77, -72, -65, -56, -48, -37,
  112167. -40, -36, -34, -40, -50, -47, -38, -41,
  112168. -47, -38, -35, -39, -38, -43, -40, -45,
  112169. -50, -45, -44, -47, -50, -55, -48, -48,
  112170. -52, -66, -70, -76, -82, -90, -97, -105,
  112171. -110, -999, -999, -999, -999, -999, -999, -999}},
  112172. /* 707 Hz */
  112173. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112174. -999, -108, -103, -98, -93, -86, -79, -76,
  112175. -83, -81, -85, -87, -89, -93, -98, -102,
  112176. -107, -112, -999, -999, -999, -999, -999, -999,
  112177. -999, -999, -999, -999, -999, -999, -999, -999,
  112178. -999, -999, -999, -999, -999, -999, -999, -999,
  112179. -999, -999, -999, -999, -999, -999, -999, -999},
  112180. {-999, -999, -999, -999, -999, -999, -999, -999,
  112181. -999, -108, -103, -98, -93, -86, -79, -71,
  112182. -77, -74, -77, -79, -81, -84, -85, -90,
  112183. -92, -93, -92, -98, -101, -108, -112, -999,
  112184. -999, -999, -999, -999, -999, -999, -999, -999,
  112185. -999, -999, -999, -999, -999, -999, -999, -999,
  112186. -999, -999, -999, -999, -999, -999, -999, -999},
  112187. {-999, -999, -999, -999, -999, -999, -999, -999,
  112188. -108, -103, -98, -93, -87, -78, -68, -65,
  112189. -66, -62, -65, -67, -70, -73, -75, -78,
  112190. -82, -82, -83, -84, -91, -93, -98, -102,
  112191. -106, -110, -999, -999, -999, -999, -999, -999,
  112192. -999, -999, -999, -999, -999, -999, -999, -999,
  112193. -999, -999, -999, -999, -999, -999, -999, -999},
  112194. {-999, -999, -999, -999, -999, -999, -999, -999,
  112195. -105, -100, -95, -90, -82, -74, -62, -57,
  112196. -58, -56, -51, -52, -52, -54, -54, -58,
  112197. -66, -59, -60, -63, -66, -69, -73, -79,
  112198. -83, -84, -80, -81, -81, -82, -88, -92,
  112199. -98, -105, -113, -999, -999, -999, -999, -999,
  112200. -999, -999, -999, -999, -999, -999, -999, -999},
  112201. {-999, -999, -999, -999, -999, -999, -999, -107,
  112202. -102, -97, -92, -84, -79, -69, -57, -47,
  112203. -52, -47, -44, -45, -50, -52, -42, -42,
  112204. -53, -43, -43, -48, -51, -56, -55, -52,
  112205. -57, -59, -61, -62, -67, -71, -78, -83,
  112206. -86, -94, -98, -103, -110, -999, -999, -999,
  112207. -999, -999, -999, -999, -999, -999, -999, -999},
  112208. {-999, -999, -999, -999, -999, -999, -105, -100,
  112209. -95, -90, -84, -78, -70, -61, -51, -41,
  112210. -40, -38, -40, -46, -52, -51, -41, -40,
  112211. -46, -40, -38, -38, -41, -46, -41, -46,
  112212. -47, -43, -43, -45, -41, -45, -56, -67,
  112213. -68, -83, -87, -90, -95, -102, -107, -113,
  112214. -999, -999, -999, -999, -999, -999, -999, -999}},
  112215. /* 1000 Hz */
  112216. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112217. -999, -109, -105, -101, -96, -91, -84, -77,
  112218. -82, -82, -85, -89, -94, -100, -106, -110,
  112219. -999, -999, -999, -999, -999, -999, -999, -999,
  112220. -999, -999, -999, -999, -999, -999, -999, -999,
  112221. -999, -999, -999, -999, -999, -999, -999, -999,
  112222. -999, -999, -999, -999, -999, -999, -999, -999},
  112223. {-999, -999, -999, -999, -999, -999, -999, -999,
  112224. -999, -106, -103, -98, -92, -85, -80, -71,
  112225. -75, -72, -76, -80, -84, -86, -89, -93,
  112226. -100, -107, -113, -999, -999, -999, -999, -999,
  112227. -999, -999, -999, -999, -999, -999, -999, -999,
  112228. -999, -999, -999, -999, -999, -999, -999, -999,
  112229. -999, -999, -999, -999, -999, -999, -999, -999},
  112230. {-999, -999, -999, -999, -999, -999, -999, -107,
  112231. -104, -101, -97, -92, -88, -84, -80, -64,
  112232. -66, -63, -64, -66, -69, -73, -77, -83,
  112233. -83, -86, -91, -98, -104, -111, -999, -999,
  112234. -999, -999, -999, -999, -999, -999, -999, -999,
  112235. -999, -999, -999, -999, -999, -999, -999, -999,
  112236. -999, -999, -999, -999, -999, -999, -999, -999},
  112237. {-999, -999, -999, -999, -999, -999, -999, -107,
  112238. -104, -101, -97, -92, -90, -84, -74, -57,
  112239. -58, -52, -55, -54, -50, -52, -50, -52,
  112240. -63, -62, -69, -76, -77, -78, -78, -79,
  112241. -82, -88, -94, -100, -106, -111, -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, -106, -102,
  112245. -98, -95, -90, -85, -83, -78, -70, -50,
  112246. -50, -41, -44, -49, -47, -50, -50, -44,
  112247. -55, -46, -47, -48, -48, -54, -49, -49,
  112248. -58, -62, -71, -81, -87, -92, -97, -102,
  112249. -108, -114, -999, -999, -999, -999, -999, -999,
  112250. -999, -999, -999, -999, -999, -999, -999, -999},
  112251. {-999, -999, -999, -999, -999, -999, -106, -102,
  112252. -98, -95, -90, -85, -83, -78, -70, -45,
  112253. -43, -41, -47, -50, -51, -50, -49, -45,
  112254. -47, -41, -44, -41, -39, -43, -38, -37,
  112255. -40, -41, -44, -50, -58, -65, -73, -79,
  112256. -85, -92, -97, -101, -105, -109, -113, -999,
  112257. -999, -999, -999, -999, -999, -999, -999, -999}},
  112258. /* 1414 Hz */
  112259. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112260. -999, -999, -999, -107, -100, -95, -87, -81,
  112261. -85, -83, -88, -93, -100, -107, -114, -999,
  112262. -999, -999, -999, -999, -999, -999, -999, -999,
  112263. -999, -999, -999, -999, -999, -999, -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, -999, -999,
  112267. -999, -999, -107, -101, -95, -88, -83, -76,
  112268. -73, -72, -79, -84, -90, -95, -100, -105,
  112269. -110, -115, -999, -999, -999, -999, -999, -999,
  112270. -999, -999, -999, -999, -999, -999, -999, -999,
  112271. -999, -999, -999, -999, -999, -999, -999, -999,
  112272. -999, -999, -999, -999, -999, -999, -999, -999},
  112273. {-999, -999, -999, -999, -999, -999, -999, -999,
  112274. -999, -999, -104, -98, -92, -87, -81, -70,
  112275. -65, -62, -67, -71, -74, -80, -85, -91,
  112276. -95, -99, -103, -108, -111, -114, -999, -999,
  112277. -999, -999, -999, -999, -999, -999, -999, -999,
  112278. -999, -999, -999, -999, -999, -999, -999, -999,
  112279. -999, -999, -999, -999, -999, -999, -999, -999},
  112280. {-999, -999, -999, -999, -999, -999, -999, -999,
  112281. -999, -999, -103, -97, -90, -85, -76, -60,
  112282. -56, -54, -60, -62, -61, -56, -63, -65,
  112283. -73, -74, -77, -75, -78, -81, -86, -87,
  112284. -88, -91, -94, -98, -103, -110, -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, -105,
  112288. -100, -97, -92, -86, -81, -79, -70, -57,
  112289. -51, -47, -51, -58, -60, -56, -53, -50,
  112290. -58, -52, -50, -50, -53, -55, -64, -69,
  112291. -71, -85, -82, -78, -81, -85, -95, -102,
  112292. -112, -999, -999, -999, -999, -999, -999, -999,
  112293. -999, -999, -999, -999, -999, -999, -999, -999},
  112294. {-999, -999, -999, -999, -999, -999, -999, -105,
  112295. -100, -97, -92, -85, -83, -79, -72, -49,
  112296. -40, -43, -43, -54, -56, -51, -50, -40,
  112297. -43, -38, -36, -35, -37, -38, -37, -44,
  112298. -54, -60, -57, -60, -70, -75, -84, -92,
  112299. -103, -112, -999, -999, -999, -999, -999, -999,
  112300. -999, -999, -999, -999, -999, -999, -999, -999}},
  112301. /* 2000 Hz */
  112302. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112303. -999, -999, -999, -110, -102, -95, -89, -82,
  112304. -83, -84, -90, -92, -99, -107, -113, -999,
  112305. -999, -999, -999, -999, -999, -999, -999, -999,
  112306. -999, -999, -999, -999, -999, -999, -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, -999,
  112310. -999, -999, -107, -101, -95, -89, -83, -72,
  112311. -74, -78, -85, -88, -88, -90, -92, -98,
  112312. -105, -111, -999, -999, -999, -999, -999, -999,
  112313. -999, -999, -999, -999, -999, -999, -999, -999,
  112314. -999, -999, -999, -999, -999, -999, -999, -999,
  112315. -999, -999, -999, -999, -999, -999, -999, -999},
  112316. {-999, -999, -999, -999, -999, -999, -999, -999,
  112317. -999, -109, -103, -97, -93, -87, -81, -70,
  112318. -70, -67, -75, -73, -76, -79, -81, -83,
  112319. -88, -89, -97, -103, -110, -999, -999, -999,
  112320. -999, -999, -999, -999, -999, -999, -999, -999,
  112321. -999, -999, -999, -999, -999, -999, -999, -999,
  112322. -999, -999, -999, -999, -999, -999, -999, -999},
  112323. {-999, -999, -999, -999, -999, -999, -999, -999,
  112324. -999, -107, -100, -94, -88, -83, -75, -63,
  112325. -59, -59, -63, -66, -60, -62, -67, -67,
  112326. -77, -76, -81, -88, -86, -92, -96, -102,
  112327. -109, -116, -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, -105, -98, -92, -86, -81, -73, -56,
  112332. -52, -47, -55, -60, -58, -52, -51, -45,
  112333. -49, -50, -53, -54, -61, -71, -70, -69,
  112334. -78, -79, -87, -90, -96, -104, -112, -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, -103, -96, -90, -86, -78, -70, -51,
  112339. -42, -47, -48, -55, -54, -54, -53, -42,
  112340. -35, -28, -33, -38, -37, -44, -47, -49,
  112341. -54, -63, -68, -78, -82, -89, -94, -99,
  112342. -104, -109, -114, -999, -999, -999, -999, -999,
  112343. -999, -999, -999, -999, -999, -999, -999, -999}},
  112344. /* 2828 Hz */
  112345. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112346. -999, -999, -999, -999, -110, -100, -90, -79,
  112347. -85, -81, -82, -82, -89, -94, -99, -103,
  112348. -109, -115, -999, -999, -999, -999, -999, -999,
  112349. -999, -999, -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, -999, -999, -999, -105, -97, -85, -72,
  112354. -74, -70, -70, -70, -76, -85, -91, -93,
  112355. -97, -103, -109, -115, -999, -999, -999, -999,
  112356. -999, -999, -999, -999, -999, -999, -999, -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, -999, -999, -999, -112, -93, -81, -68,
  112361. -62, -60, -60, -57, -63, -70, -77, -82,
  112362. -90, -93, -98, -104, -109, -113, -999, -999,
  112363. -999, -999, -999, -999, -999, -999, -999, -999,
  112364. -999, -999, -999, -999, -999, -999, -999, -999,
  112365. -999, -999, -999, -999, -999, -999, -999, -999},
  112366. {-999, -999, -999, -999, -999, -999, -999, -999,
  112367. -999, -999, -999, -113, -100, -93, -84, -63,
  112368. -58, -48, -53, -54, -52, -52, -57, -64,
  112369. -66, -76, -83, -81, -85, -85, -90, -95,
  112370. -98, -101, -103, -106, -108, -111, -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, -105, -95, -86, -74, -53,
  112375. -50, -38, -43, -49, -43, -42, -39, -39,
  112376. -46, -52, -57, -56, -72, -69, -74, -81,
  112377. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  112382. -43, -41, -44, -47, -43, -47, -40, -30,
  112383. -31, -31, -39, -33, -40, -41, -43, -53,
  112384. -59, -70, -73, -77, -79, -82, -84, -87,
  112385. -999, -999, -999, -999, -999, -999, -999, -999,
  112386. -999, -999, -999, -999, -999, -999, -999, -999}},
  112387. /* 4000 Hz */
  112388. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112389. -999, -999, -999, -999, -999, -110, -91, -76,
  112390. -75, -85, -93, -98, -104, -110, -999, -999,
  112391. -999, -999, -999, -999, -999, -999, -999, -999,
  112392. -999, -999, -999, -999, -999, -999, -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, -999, -999, -110, -91, -70,
  112397. -70, -75, -86, -89, -94, -98, -101, -106,
  112398. -110, -999, -999, -999, -999, -999, -999, -999,
  112399. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -999, -999, -110, -95, -80, -60,
  112404. -65, -64, -74, -83, -88, -91, -95, -99,
  112405. -103, -107, -110, -999, -999, -999, -999, -999,
  112406. -999, -999, -999, -999, -999, -999, -999, -999,
  112407. -999, -999, -999, -999, -999, -999, -999, -999,
  112408. -999, -999, -999, -999, -999, -999, -999, -999},
  112409. {-999, -999, -999, -999, -999, -999, -999, -999,
  112410. -999, -999, -999, -999, -110, -95, -80, -58,
  112411. -55, -49, -66, -68, -71, -78, -78, -80,
  112412. -88, -85, -89, -97, -100, -105, -110, -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, -110, -95, -80, -53,
  112418. -52, -41, -59, -59, -49, -58, -56, -63,
  112419. -86, -79, -90, -93, -98, -103, -107, -112,
  112420. -999, -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, -110, -97, -91, -73, -45,
  112425. -40, -33, -53, -61, -49, -54, -50, -50,
  112426. -60, -52, -67, -74, -81, -92, -96, -100,
  112427. -105, -110, -999, -999, -999, -999, -999, -999,
  112428. -999, -999, -999, -999, -999, -999, -999, -999,
  112429. -999, -999, -999, -999, -999, -999, -999, -999}},
  112430. /* 5657 Hz */
  112431. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112432. -999, -999, -999, -113, -106, -99, -92, -77,
  112433. -80, -88, -97, -106, -115, -999, -999, -999,
  112434. -999, -999, -999, -999, -999, -999, -999, -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, -116, -109, -102, -95, -89, -74,
  112440. -72, -88, -87, -95, -102, -109, -116, -999,
  112441. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -116, -109, -102, -95, -89, -75,
  112447. -66, -74, -77, -78, -86, -87, -90, -96,
  112448. -105, -115, -999, -999, -999, -999, -999, -999,
  112449. -999, -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  112453. -999, -999, -115, -108, -101, -94, -88, -66,
  112454. -56, -61, -70, -65, -78, -72, -83, -84,
  112455. -93, -98, -105, -110, -999, -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, -110, -105, -95, -89, -82, -57,
  112461. -52, -52, -59, -56, -59, -58, -69, -67,
  112462. -88, -82, -82, -89, -94, -100, -108, -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, -110, -101, -96, -90, -83, -77, -54,
  112468. -43, -38, -50, -48, -52, -48, -42, -42,
  112469. -51, -52, -53, -59, -65, -71, -78, -85,
  112470. -95, -999, -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. /* 8000 Hz */
  112474. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112475. -999, -999, -999, -999, -120, -105, -86, -68,
  112476. -78, -79, -90, -100, -110, -999, -999, -999,
  112477. -999, -999, -999, -999, -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, -999, -999, -120, -105, -86, -66,
  112483. -73, -77, -88, -96, -105, -115, -999, -999,
  112484. -999, -999, -999, -999, -999, -999, -999, -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, -999, -999, -120, -105, -92, -80, -61,
  112490. -64, -68, -80, -87, -92, -100, -110, -999,
  112491. -999, -999, -999, -999, -999, -999, -999, -999,
  112492. -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  112496. -999, -999, -999, -120, -104, -91, -79, -52,
  112497. -60, -54, -64, -69, -77, -80, -82, -84,
  112498. -85, -87, -88, -90, -999, -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, -118, -100, -87, -77, -49,
  112504. -50, -44, -58, -61, -61, -67, -65, -62,
  112505. -62, -62, -65, -68, -999, -999, -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, -115, -98, -84, -62, -49,
  112511. -44, -38, -46, -49, -49, -46, -39, -37,
  112512. -39, -40, -42, -43, -999, -999, -999, -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. /* 11314 Hz */
  112517. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112518. -999, -999, -999, -999, -999, -110, -88, -74,
  112519. -77, -82, -82, -85, -90, -94, -99, -104,
  112520. -999, -999, -999, -999, -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, -999, -999, -110, -88, -66,
  112526. -70, -81, -80, -81, -84, -88, -91, -93,
  112527. -999, -999, -999, -999, -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, -999, -999, -110, -88, -61,
  112533. -63, -70, -71, -74, -77, -80, -83, -85,
  112534. -999, -999, -999, -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  112539. -999, -999, -999, -999, -999, -110, -86, -62,
  112540. -63, -62, -62, -58, -52, -50, -50, -52,
  112541. -54, -999, -999, -999, -999, -999, -999, -999,
  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, -118, -108, -84, -53,
  112547. -50, -50, -50, -55, -47, -45, -40, -40,
  112548. -40, -999, -999, -999, -999, -999, -999, -999,
  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, -118, -100, -73, -43,
  112554. -37, -42, -43, -53, -38, -37, -35, -35,
  112555. -38, -999, -999, -999, -999, -999, -999, -999,
  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. /* 16000 Hz */
  112560. {{-999, -999, -999, -999, -999, -999, -999, -999,
  112561. -999, -999, -999, -110, -100, -91, -84, -74,
  112562. -80, -80, -80, -80, -80, -999, -999, -999,
  112563. -999, -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, -110, -100, -91, -84, -74,
  112569. -68, -68, -68, -68, -68, -999, -999, -999,
  112570. -999, -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, -110, -100, -86, -78, -70,
  112576. -60, -45, -30, -21, -999, -999, -999, -999,
  112577. -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  112582. -999, -999, -999, -110, -100, -87, -78, -67,
  112583. -48, -38, -29, -21, -999, -999, -999, -999,
  112584. -999, -999, -999, -999, -999, -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, -110, -100, -86, -69, -56,
  112590. -45, -35, -33, -29, -999, -999, -999, -999,
  112591. -999, -999, -999, -999, -999, -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, -110, -100, -83, -71, -48,
  112597. -27, -38, -37, -34, -999, -999, -999, -999,
  112598. -999, -999, -999, -999, -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. };
  112603. #endif
  112604. /********* End of inlined file: masking.h *********/
  112605. #define NEGINF -9999.f
  112606. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  112607. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  112608. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  112609. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112610. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112611. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  112612. look->channels=vi->channels;
  112613. look->ampmax=-9999.;
  112614. look->gi=gi;
  112615. return(look);
  112616. }
  112617. void _vp_global_free(vorbis_look_psy_global *look){
  112618. if(look){
  112619. memset(look,0,sizeof(*look));
  112620. _ogg_free(look);
  112621. }
  112622. }
  112623. void _vi_gpsy_free(vorbis_info_psy_global *i){
  112624. if(i){
  112625. memset(i,0,sizeof(*i));
  112626. _ogg_free(i);
  112627. }
  112628. }
  112629. void _vi_psy_free(vorbis_info_psy *i){
  112630. if(i){
  112631. memset(i,0,sizeof(*i));
  112632. _ogg_free(i);
  112633. }
  112634. }
  112635. static void min_curve(float *c,
  112636. float *c2){
  112637. int i;
  112638. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  112639. }
  112640. static void max_curve(float *c,
  112641. float *c2){
  112642. int i;
  112643. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  112644. }
  112645. static void attenuate_curve(float *c,float att){
  112646. int i;
  112647. for(i=0;i<EHMER_MAX;i++)
  112648. c[i]+=att;
  112649. }
  112650. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  112651. float center_boost, float center_decay_rate){
  112652. int i,j,k,m;
  112653. float ath[EHMER_MAX];
  112654. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  112655. float athc[P_LEVELS][EHMER_MAX];
  112656. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  112657. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  112658. memset(workc,0,sizeof(workc));
  112659. for(i=0;i<P_BANDS;i++){
  112660. /* we add back in the ATH to avoid low level curves falling off to
  112661. -infinity and unnecessarily cutting off high level curves in the
  112662. curve limiting (last step). */
  112663. /* A half-band's settings must be valid over the whole band, and
  112664. it's better to mask too little than too much */
  112665. int ath_offset=i*4;
  112666. for(j=0;j<EHMER_MAX;j++){
  112667. float min=999.;
  112668. for(k=0;k<4;k++)
  112669. if(j+k+ath_offset<MAX_ATH){
  112670. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  112671. }else{
  112672. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  112673. }
  112674. ath[j]=min;
  112675. }
  112676. /* copy curves into working space, replicate the 50dB curve to 30
  112677. and 40, replicate the 100dB curve to 110 */
  112678. for(j=0;j<6;j++)
  112679. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  112680. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112681. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  112682. /* apply centered curve boost/decay */
  112683. for(j=0;j<P_LEVELS;j++){
  112684. for(k=0;k<EHMER_MAX;k++){
  112685. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  112686. if(adj<0. && center_boost>0)adj=0.;
  112687. if(adj>0. && center_boost<0)adj=0.;
  112688. workc[i][j][k]+=adj;
  112689. }
  112690. }
  112691. /* normalize curves so the driving amplitude is 0dB */
  112692. /* make temp curves with the ATH overlayed */
  112693. for(j=0;j<P_LEVELS;j++){
  112694. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  112695. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  112696. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  112697. max_curve(athc[j],workc[i][j]);
  112698. }
  112699. /* Now limit the louder curves.
  112700. the idea is this: We don't know what the playback attenuation
  112701. will be; 0dB SL moves every time the user twiddles the volume
  112702. knob. So that means we have to use a single 'most pessimal' curve
  112703. for all masking amplitudes, right? Wrong. The *loudest* sound
  112704. can be in (we assume) a range of ...+100dB] SL. However, sounds
  112705. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  112706. etc... */
  112707. for(j=1;j<P_LEVELS;j++){
  112708. min_curve(athc[j],athc[j-1]);
  112709. min_curve(workc[i][j],athc[j]);
  112710. }
  112711. }
  112712. for(i=0;i<P_BANDS;i++){
  112713. int hi_curve,lo_curve,bin;
  112714. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  112715. /* low frequency curves are measured with greater resolution than
  112716. the MDCT/FFT will actually give us; we want the curve applied
  112717. to the tone data to be pessimistic and thus apply the minimum
  112718. masking possible for a given bin. That means that a single bin
  112719. could span more than one octave and that the curve will be a
  112720. composite of multiple octaves. It also may mean that a single
  112721. bin may span > an eighth of an octave and that the eighth
  112722. octave values may also be composited. */
  112723. /* which octave curves will we be compositing? */
  112724. bin=floor(fromOC(i*.5)/binHz);
  112725. lo_curve= ceil(toOC(bin*binHz+1)*2);
  112726. hi_curve= floor(toOC((bin+1)*binHz)*2);
  112727. if(lo_curve>i)lo_curve=i;
  112728. if(lo_curve<0)lo_curve=0;
  112729. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  112730. for(m=0;m<P_LEVELS;m++){
  112731. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  112732. for(j=0;j<n;j++)brute_buffer[j]=999.;
  112733. /* render the curve into bins, then pull values back into curve.
  112734. The point is that any inherent subsampling aliasing results in
  112735. a safe minimum */
  112736. for(k=lo_curve;k<=hi_curve;k++){
  112737. int l=0;
  112738. for(j=0;j<EHMER_MAX;j++){
  112739. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  112740. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  112741. if(lo_bin<0)lo_bin=0;
  112742. if(lo_bin>n)lo_bin=n;
  112743. if(lo_bin<l)l=lo_bin;
  112744. if(hi_bin<0)hi_bin=0;
  112745. if(hi_bin>n)hi_bin=n;
  112746. for(;l<hi_bin && l<n;l++)
  112747. if(brute_buffer[l]>workc[k][m][j])
  112748. brute_buffer[l]=workc[k][m][j];
  112749. }
  112750. for(;l<n;l++)
  112751. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112752. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112753. }
  112754. /* be equally paranoid about being valid up to next half ocatve */
  112755. if(i+1<P_BANDS){
  112756. int l=0;
  112757. k=i+1;
  112758. for(j=0;j<EHMER_MAX;j++){
  112759. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  112760. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  112761. if(lo_bin<0)lo_bin=0;
  112762. if(lo_bin>n)lo_bin=n;
  112763. if(lo_bin<l)l=lo_bin;
  112764. if(hi_bin<0)hi_bin=0;
  112765. if(hi_bin>n)hi_bin=n;
  112766. for(;l<hi_bin && l<n;l++)
  112767. if(brute_buffer[l]>workc[k][m][j])
  112768. brute_buffer[l]=workc[k][m][j];
  112769. }
  112770. for(;l<n;l++)
  112771. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  112772. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  112773. }
  112774. for(j=0;j<EHMER_MAX;j++){
  112775. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  112776. if(bin<0){
  112777. ret[i][m][j+2]=-999.;
  112778. }else{
  112779. if(bin>=n){
  112780. ret[i][m][j+2]=-999.;
  112781. }else{
  112782. ret[i][m][j+2]=brute_buffer[bin];
  112783. }
  112784. }
  112785. }
  112786. /* add fenceposts */
  112787. for(j=0;j<EHMER_OFFSET;j++)
  112788. if(ret[i][m][j+2]>-200.f)break;
  112789. ret[i][m][0]=j;
  112790. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  112791. if(ret[i][m][j+2]>-200.f)
  112792. break;
  112793. ret[i][m][1]=j;
  112794. }
  112795. }
  112796. return(ret);
  112797. }
  112798. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  112799. vorbis_info_psy_global *gi,int n,long rate){
  112800. long i,j,lo=-99,hi=1;
  112801. long maxoc;
  112802. memset(p,0,sizeof(*p));
  112803. p->eighth_octave_lines=gi->eighth_octave_lines;
  112804. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  112805. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  112806. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  112807. p->total_octave_lines=maxoc-p->firstoc+1;
  112808. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  112809. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  112810. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  112811. p->vi=vi;
  112812. p->n=n;
  112813. p->rate=rate;
  112814. /* AoTuV HF weighting */
  112815. p->m_val = 1.;
  112816. if(rate < 26000) p->m_val = 0;
  112817. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  112818. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  112819. /* set up the lookups for a given blocksize and sample rate */
  112820. for(i=0,j=0;i<MAX_ATH-1;i++){
  112821. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  112822. float base=ATH[i];
  112823. if(j<endpos){
  112824. float delta=(ATH[i+1]-base)/(endpos-j);
  112825. for(;j<endpos && j<n;j++){
  112826. p->ath[j]=base+100.;
  112827. base+=delta;
  112828. }
  112829. }
  112830. }
  112831. for(i=0;i<n;i++){
  112832. float bark=toBARK(rate/(2*n)*i);
  112833. for(;lo+vi->noisewindowlomin<i &&
  112834. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  112835. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  112836. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  112837. p->bark[i]=((lo-1)<<16)+(hi-1);
  112838. }
  112839. for(i=0;i<n;i++)
  112840. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  112841. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  112842. vi->tone_centerboost,vi->tone_decay);
  112843. /* set up rolling noise median */
  112844. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  112845. for(i=0;i<P_NOISECURVES;i++)
  112846. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  112847. for(i=0;i<n;i++){
  112848. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  112849. int inthalfoc;
  112850. float del;
  112851. if(halfoc<0)halfoc=0;
  112852. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  112853. inthalfoc=(int)halfoc;
  112854. del=halfoc-inthalfoc;
  112855. for(j=0;j<P_NOISECURVES;j++)
  112856. p->noiseoffset[j][i]=
  112857. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  112858. p->vi->noiseoff[j][inthalfoc+1]*del;
  112859. }
  112860. #if 0
  112861. {
  112862. static int ls=0;
  112863. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  112864. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  112865. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  112866. }
  112867. #endif
  112868. }
  112869. void _vp_psy_clear(vorbis_look_psy *p){
  112870. int i,j;
  112871. if(p){
  112872. if(p->ath)_ogg_free(p->ath);
  112873. if(p->octave)_ogg_free(p->octave);
  112874. if(p->bark)_ogg_free(p->bark);
  112875. if(p->tonecurves){
  112876. for(i=0;i<P_BANDS;i++){
  112877. for(j=0;j<P_LEVELS;j++){
  112878. _ogg_free(p->tonecurves[i][j]);
  112879. }
  112880. _ogg_free(p->tonecurves[i]);
  112881. }
  112882. _ogg_free(p->tonecurves);
  112883. }
  112884. if(p->noiseoffset){
  112885. for(i=0;i<P_NOISECURVES;i++){
  112886. _ogg_free(p->noiseoffset[i]);
  112887. }
  112888. _ogg_free(p->noiseoffset);
  112889. }
  112890. memset(p,0,sizeof(*p));
  112891. }
  112892. }
  112893. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  112894. static void seed_curve(float *seed,
  112895. const float **curves,
  112896. float amp,
  112897. int oc, int n,
  112898. int linesper,float dBoffset){
  112899. int i,post1;
  112900. int seedptr;
  112901. const float *posts,*curve;
  112902. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  112903. choice=max(choice,0);
  112904. choice=min(choice,P_LEVELS-1);
  112905. posts=curves[choice];
  112906. curve=posts+2;
  112907. post1=(int)posts[1];
  112908. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  112909. for(i=posts[0];i<post1;i++){
  112910. if(seedptr>0){
  112911. float lin=amp+curve[i];
  112912. if(seed[seedptr]<lin)seed[seedptr]=lin;
  112913. }
  112914. seedptr+=linesper;
  112915. if(seedptr>=n)break;
  112916. }
  112917. }
  112918. static void seed_loop(vorbis_look_psy *p,
  112919. const float ***curves,
  112920. const float *f,
  112921. const float *flr,
  112922. float *seed,
  112923. float specmax){
  112924. vorbis_info_psy *vi=p->vi;
  112925. long n=p->n,i;
  112926. float dBoffset=vi->max_curve_dB-specmax;
  112927. /* prime the working vector with peak values */
  112928. for(i=0;i<n;i++){
  112929. float max=f[i];
  112930. long oc=p->octave[i];
  112931. while(i+1<n && p->octave[i+1]==oc){
  112932. i++;
  112933. if(f[i]>max)max=f[i];
  112934. }
  112935. if(max+6.f>flr[i]){
  112936. oc=oc>>p->shiftoc;
  112937. if(oc>=P_BANDS)oc=P_BANDS-1;
  112938. if(oc<0)oc=0;
  112939. seed_curve(seed,
  112940. curves[oc],
  112941. max,
  112942. p->octave[i]-p->firstoc,
  112943. p->total_octave_lines,
  112944. p->eighth_octave_lines,
  112945. dBoffset);
  112946. }
  112947. }
  112948. }
  112949. static void seed_chase(float *seeds, int linesper, long n){
  112950. long *posstack=(long*)alloca(n*sizeof(*posstack));
  112951. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  112952. long stack=0;
  112953. long pos=0;
  112954. long i;
  112955. for(i=0;i<n;i++){
  112956. if(stack<2){
  112957. posstack[stack]=i;
  112958. ampstack[stack++]=seeds[i];
  112959. }else{
  112960. while(1){
  112961. if(seeds[i]<ampstack[stack-1]){
  112962. posstack[stack]=i;
  112963. ampstack[stack++]=seeds[i];
  112964. break;
  112965. }else{
  112966. if(i<posstack[stack-1]+linesper){
  112967. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  112968. i<posstack[stack-2]+linesper){
  112969. /* we completely overlap, making stack-1 irrelevant. pop it */
  112970. stack--;
  112971. continue;
  112972. }
  112973. }
  112974. posstack[stack]=i;
  112975. ampstack[stack++]=seeds[i];
  112976. break;
  112977. }
  112978. }
  112979. }
  112980. }
  112981. /* the stack now contains only the positions that are relevant. Scan
  112982. 'em straight through */
  112983. for(i=0;i<stack;i++){
  112984. long endpos;
  112985. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  112986. endpos=posstack[i+1];
  112987. }else{
  112988. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  112989. discarded in short frames */
  112990. }
  112991. if(endpos>n)endpos=n;
  112992. for(;pos<endpos;pos++)
  112993. seeds[pos]=ampstack[i];
  112994. }
  112995. /* there. Linear time. I now remember this was on a problem set I
  112996. had in Grad Skool... I didn't solve it at the time ;-) */
  112997. }
  112998. /* bleaugh, this is more complicated than it needs to be */
  112999. #include<stdio.h>
  113000. static void max_seeds(vorbis_look_psy *p,
  113001. float *seed,
  113002. float *flr){
  113003. long n=p->total_octave_lines;
  113004. int linesper=p->eighth_octave_lines;
  113005. long linpos=0;
  113006. long pos;
  113007. seed_chase(seed,linesper,n); /* for masking */
  113008. pos=p->octave[0]-p->firstoc-(linesper>>1);
  113009. while(linpos+1<p->n){
  113010. float minV=seed[pos];
  113011. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  113012. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  113013. while(pos+1<=end){
  113014. pos++;
  113015. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  113016. minV=seed[pos];
  113017. }
  113018. end=pos+p->firstoc;
  113019. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  113020. if(flr[linpos]<minV)flr[linpos]=minV;
  113021. }
  113022. {
  113023. float minV=seed[p->total_octave_lines-1];
  113024. for(;linpos<p->n;linpos++)
  113025. if(flr[linpos]<minV)flr[linpos]=minV;
  113026. }
  113027. }
  113028. static void bark_noise_hybridmp(int n,const long *b,
  113029. const float *f,
  113030. float *noise,
  113031. const float offset,
  113032. const int fixed){
  113033. float *N=(float*) alloca(n*sizeof(*N));
  113034. float *X=(float*) alloca(n*sizeof(*N));
  113035. float *XX=(float*) alloca(n*sizeof(*N));
  113036. float *Y=(float*) alloca(n*sizeof(*N));
  113037. float *XY=(float*) alloca(n*sizeof(*N));
  113038. float tN, tX, tXX, tY, tXY;
  113039. int i;
  113040. int lo, hi;
  113041. float R, A, B, D;
  113042. float w, x, y;
  113043. tN = tX = tXX = tY = tXY = 0.f;
  113044. y = f[0] + offset;
  113045. if (y < 1.f) y = 1.f;
  113046. w = y * y * .5;
  113047. tN += w;
  113048. tX += w;
  113049. tY += w * y;
  113050. N[0] = tN;
  113051. X[0] = tX;
  113052. XX[0] = tXX;
  113053. Y[0] = tY;
  113054. XY[0] = tXY;
  113055. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  113056. y = f[i] + offset;
  113057. if (y < 1.f) y = 1.f;
  113058. w = y * y;
  113059. tN += w;
  113060. tX += w * x;
  113061. tXX += w * x * x;
  113062. tY += w * y;
  113063. tXY += w * x * y;
  113064. N[i] = tN;
  113065. X[i] = tX;
  113066. XX[i] = tXX;
  113067. Y[i] = tY;
  113068. XY[i] = tXY;
  113069. }
  113070. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113071. lo = b[i] >> 16;
  113072. if( lo>=0 ) break;
  113073. hi = b[i] & 0xffff;
  113074. tN = N[hi] + N[-lo];
  113075. tX = X[hi] - X[-lo];
  113076. tXX = XX[hi] + XX[-lo];
  113077. tY = Y[hi] + Y[-lo];
  113078. tXY = XY[hi] - XY[-lo];
  113079. A = tY * tXX - tX * tXY;
  113080. B = tN * tXY - tX * tY;
  113081. D = tN * tXX - tX * tX;
  113082. R = (A + x * B) / D;
  113083. if (R < 0.f)
  113084. R = 0.f;
  113085. noise[i] = R - offset;
  113086. }
  113087. for ( ;; i++, x += 1.f) {
  113088. lo = b[i] >> 16;
  113089. hi = b[i] & 0xffff;
  113090. if(hi>=n)break;
  113091. tN = N[hi] - N[lo];
  113092. tX = X[hi] - X[lo];
  113093. tXX = XX[hi] - XX[lo];
  113094. tY = Y[hi] - Y[lo];
  113095. tXY = XY[hi] - XY[lo];
  113096. A = tY * tXX - tX * tXY;
  113097. B = tN * tXY - tX * tY;
  113098. D = tN * tXX - tX * tX;
  113099. R = (A + x * B) / D;
  113100. if (R < 0.f) R = 0.f;
  113101. noise[i] = R - offset;
  113102. }
  113103. for ( ; i < n; i++, x += 1.f) {
  113104. R = (A + x * B) / D;
  113105. if (R < 0.f) R = 0.f;
  113106. noise[i] = R - offset;
  113107. }
  113108. if (fixed <= 0) return;
  113109. for (i = 0, x = 0.f;; i++, x += 1.f) {
  113110. hi = i + fixed / 2;
  113111. lo = hi - fixed;
  113112. if(lo>=0)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 - offset < noise[i]) noise[i] = R - offset;
  113123. }
  113124. for ( ;; i++, x += 1.f) {
  113125. hi = i + fixed / 2;
  113126. lo = hi - fixed;
  113127. if(hi>=n)break;
  113128. tN = N[hi] - N[lo];
  113129. tX = X[hi] - X[lo];
  113130. tXX = XX[hi] - XX[lo];
  113131. tY = Y[hi] - Y[lo];
  113132. tXY = XY[hi] - XY[lo];
  113133. A = tY * tXX - tX * tXY;
  113134. B = tN * tXY - tX * tY;
  113135. D = tN * tXX - tX * tX;
  113136. R = (A + x * B) / D;
  113137. if (R - offset < noise[i]) noise[i] = R - offset;
  113138. }
  113139. for ( ; i < n; i++, x += 1.f) {
  113140. R = (A + x * B) / D;
  113141. if (R - offset < noise[i]) noise[i] = R - offset;
  113142. }
  113143. }
  113144. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  113145. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  113146. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  113147. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  113148. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  113149. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  113150. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  113151. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  113152. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  113153. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  113154. 973377.F, 913981.F, 858210.F, 805842.F,
  113155. 756669.F, 710497.F, 667142.F, 626433.F,
  113156. 588208.F, 552316.F, 518613.F, 486967.F,
  113157. 457252.F, 429351.F, 403152.F, 378551.F,
  113158. 355452.F, 333762.F, 313396.F, 294273.F,
  113159. 276316.F, 259455.F, 243623.F, 228757.F,
  113160. 214798.F, 201691.F, 189384.F, 177828.F,
  113161. 166977.F, 156788.F, 147221.F, 138237.F,
  113162. 129802.F, 121881.F, 114444.F, 107461.F,
  113163. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  113164. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  113165. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  113166. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  113167. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  113168. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  113169. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  113170. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  113171. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  113172. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  113173. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  113174. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  113175. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  113176. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  113177. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  113178. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  113179. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  113180. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  113181. 1084.32F, 1018.15F, 956.024F, 897.687F,
  113182. 842.910F, 791.475F, 743.179F, 697.830F,
  113183. 655.249F, 615.265F, 577.722F, 542.469F,
  113184. 509.367F, 478.286F, 449.101F, 421.696F,
  113185. 395.964F, 371.803F, 349.115F, 327.812F,
  113186. 307.809F, 289.026F, 271.390F, 254.830F,
  113187. 239.280F, 224.679F, 210.969F, 198.096F,
  113188. 186.008F, 174.658F, 164.000F, 153.993F,
  113189. 144.596F, 135.773F, 127.488F, 119.708F,
  113190. 112.404F, 105.545F, 99.1046F, 93.0572F,
  113191. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  113192. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  113193. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  113194. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  113195. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  113196. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  113197. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  113198. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  113199. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  113200. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  113201. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  113202. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  113203. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  113204. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  113205. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  113206. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  113207. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  113208. 1.20790F, 1.13419F, 1.06499F, 1.F
  113209. };
  113210. void _vp_remove_floor(vorbis_look_psy *p,
  113211. float *mdct,
  113212. int *codedflr,
  113213. float *residue,
  113214. int sliding_lowpass){
  113215. int i,n=p->n;
  113216. if(sliding_lowpass>n)sliding_lowpass=n;
  113217. for(i=0;i<sliding_lowpass;i++){
  113218. residue[i]=
  113219. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  113220. }
  113221. for(;i<n;i++)
  113222. residue[i]=0.;
  113223. }
  113224. void _vp_noisemask(vorbis_look_psy *p,
  113225. float *logmdct,
  113226. float *logmask){
  113227. int i,n=p->n;
  113228. float *work=(float*) alloca(n*sizeof(*work));
  113229. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  113230. 140.,-1);
  113231. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  113232. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  113233. p->vi->noisewindowfixed);
  113234. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  113235. #if 0
  113236. {
  113237. static int seq=0;
  113238. float work2[n];
  113239. for(i=0;i<n;i++){
  113240. work2[i]=logmask[i]+work[i];
  113241. }
  113242. if(seq&1)
  113243. _analysis_output("median2R",seq/2,work,n,1,0,0);
  113244. else
  113245. _analysis_output("median2L",seq/2,work,n,1,0,0);
  113246. if(seq&1)
  113247. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  113248. else
  113249. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  113250. seq++;
  113251. }
  113252. #endif
  113253. for(i=0;i<n;i++){
  113254. int dB=logmask[i]+.5;
  113255. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  113256. if(dB<0)dB=0;
  113257. logmask[i]= work[i]+p->vi->noisecompand[dB];
  113258. }
  113259. }
  113260. void _vp_tonemask(vorbis_look_psy *p,
  113261. float *logfft,
  113262. float *logmask,
  113263. float global_specmax,
  113264. float local_specmax){
  113265. int i,n=p->n;
  113266. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  113267. float att=local_specmax+p->vi->ath_adjatt;
  113268. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  113269. /* set the ATH (floating below localmax, not global max by a
  113270. specified att) */
  113271. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  113272. for(i=0;i<n;i++)
  113273. logmask[i]=p->ath[i]+att;
  113274. /* tone masking */
  113275. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  113276. max_seeds(p,seed,logmask);
  113277. }
  113278. void _vp_offset_and_mix(vorbis_look_psy *p,
  113279. float *noise,
  113280. float *tone,
  113281. int offset_select,
  113282. float *logmask,
  113283. float *mdct,
  113284. float *logmdct){
  113285. int i,n=p->n;
  113286. float de, coeffi, cx;/* AoTuV */
  113287. float toneatt=p->vi->tone_masteratt[offset_select];
  113288. cx = p->m_val;
  113289. for(i=0;i<n;i++){
  113290. float val= noise[i]+p->noiseoffset[offset_select][i];
  113291. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  113292. logmask[i]=max(val,tone[i]+toneatt);
  113293. /* AoTuV */
  113294. /** @ M1 **
  113295. The following codes improve a noise problem.
  113296. A fundamental idea uses the value of masking and carries out
  113297. the relative compensation of the MDCT.
  113298. However, this code is not perfect and all noise problems cannot be solved.
  113299. by Aoyumi @ 2004/04/18
  113300. */
  113301. if(offset_select == 1) {
  113302. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  113303. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  113304. if(val > coeffi){
  113305. /* mdct value is > -17.2 dB below floor */
  113306. de = 1.0-((val-coeffi)*0.005*cx);
  113307. /* pro-rated attenuation:
  113308. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  113309. -0.77 dB boost if mdct value is 0dB (relative to floor)
  113310. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  113311. etc... */
  113312. if(de < 0) de = 0.0001;
  113313. }else
  113314. /* mdct value is <= -17.2 dB below floor */
  113315. de = 1.0-((val-coeffi)*0.0003*cx);
  113316. /* pro-rated attenuation:
  113317. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  113318. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  113319. etc... */
  113320. mdct[i] *= de;
  113321. }
  113322. }
  113323. }
  113324. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  113325. vorbis_info *vi=vd->vi;
  113326. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113327. vorbis_info_psy_global *gi=&ci->psy_g_param;
  113328. int n=ci->blocksizes[vd->W]/2;
  113329. float secs=(float)n/vi->rate;
  113330. amp+=secs*gi->ampmax_att_per_sec;
  113331. if(amp<-9999)amp=-9999;
  113332. return(amp);
  113333. }
  113334. static void couple_lossless(float A, float B,
  113335. float *qA, float *qB){
  113336. int test1=fabs(*qA)>fabs(*qB);
  113337. test1-= fabs(*qA)<fabs(*qB);
  113338. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  113339. if(test1==1){
  113340. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  113341. }else{
  113342. float temp=*qB;
  113343. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  113344. *qA=temp;
  113345. }
  113346. if(*qB>fabs(*qA)*1.9999f){
  113347. *qB= -fabs(*qA)*2.f;
  113348. *qA= -*qA;
  113349. }
  113350. }
  113351. static float hypot_lookup[32]={
  113352. -0.009935, -0.011245, -0.012726, -0.014397,
  113353. -0.016282, -0.018407, -0.020800, -0.023494,
  113354. -0.026522, -0.029923, -0.033737, -0.038010,
  113355. -0.042787, -0.048121, -0.054064, -0.060671,
  113356. -0.068000, -0.076109, -0.085054, -0.094892,
  113357. -0.105675, -0.117451, -0.130260, -0.144134,
  113358. -0.159093, -0.175146, -0.192286, -0.210490,
  113359. -0.229718, -0.249913, -0.271001, -0.292893};
  113360. static void precomputed_couple_point(float premag,
  113361. int floorA,int floorB,
  113362. float *mag, float *ang){
  113363. int test=(floorA>floorB)-1;
  113364. int offset=31-abs(floorA-floorB);
  113365. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  113366. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  113367. *mag=premag*floormag;
  113368. *ang=0.f;
  113369. }
  113370. /* just like below, this is currently set up to only do
  113371. single-step-depth coupling. Otherwise, we'd have to do more
  113372. copying (which will be inevitable later) */
  113373. /* doing the real circular magnitude calculation is audibly superior
  113374. to (A+B)/sqrt(2) */
  113375. static float dipole_hypot(float a, float b){
  113376. if(a>0.){
  113377. if(b>0.)return sqrt(a*a+b*b);
  113378. if(a>-b)return sqrt(a*a-b*b);
  113379. return -sqrt(b*b-a*a);
  113380. }
  113381. if(b<0.)return -sqrt(a*a+b*b);
  113382. if(-a>b)return -sqrt(a*a-b*b);
  113383. return sqrt(b*b-a*a);
  113384. }
  113385. static float round_hypot(float a, float b){
  113386. if(a>0.){
  113387. if(b>0.)return sqrt(a*a+b*b);
  113388. if(a>-b)return sqrt(a*a+b*b);
  113389. return -sqrt(b*b+a*a);
  113390. }
  113391. if(b<0.)return -sqrt(a*a+b*b);
  113392. if(-a>b)return -sqrt(a*a+b*b);
  113393. return sqrt(b*b+a*a);
  113394. }
  113395. /* revert to round hypot for now */
  113396. float **_vp_quantize_couple_memo(vorbis_block *vb,
  113397. vorbis_info_psy_global *g,
  113398. vorbis_look_psy *p,
  113399. vorbis_info_mapping0 *vi,
  113400. float **mdct){
  113401. int i,j,n=p->n;
  113402. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113403. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113404. for(i=0;i<vi->coupling_steps;i++){
  113405. float *mdctM=mdct[vi->coupling_mag[i]];
  113406. float *mdctA=mdct[vi->coupling_ang[i]];
  113407. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113408. for(j=0;j<limit;j++)
  113409. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  113410. for(;j<n;j++)
  113411. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  113412. }
  113413. return(ret);
  113414. }
  113415. /* this is for per-channel noise normalization */
  113416. static int apsort(const void *a, const void *b){
  113417. float f1=fabs(**(float**)a);
  113418. float f2=fabs(**(float**)b);
  113419. return (f1<f2)-(f1>f2);
  113420. }
  113421. int **_vp_quantize_couple_sort(vorbis_block *vb,
  113422. vorbis_look_psy *p,
  113423. vorbis_info_mapping0 *vi,
  113424. float **mags){
  113425. if(p->vi->normal_point_p){
  113426. int i,j,k,n=p->n;
  113427. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  113428. int partition=p->vi->normal_partition;
  113429. float **work=(float**) alloca(sizeof(*work)*partition);
  113430. for(i=0;i<vi->coupling_steps;i++){
  113431. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  113432. for(j=0;j<n;j+=partition){
  113433. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  113434. qsort(work,partition,sizeof(*work),apsort);
  113435. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  113436. }
  113437. }
  113438. return(ret);
  113439. }
  113440. return(NULL);
  113441. }
  113442. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  113443. float *magnitudes,int *sortedindex){
  113444. int i,j,n=p->n;
  113445. vorbis_info_psy *vi=p->vi;
  113446. int partition=vi->normal_partition;
  113447. float **work=(float**) alloca(sizeof(*work)*partition);
  113448. int start=vi->normal_start;
  113449. for(j=start;j<n;j+=partition){
  113450. if(j+partition>n)partition=n-j;
  113451. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  113452. qsort(work,partition,sizeof(*work),apsort);
  113453. for(i=0;i<partition;i++){
  113454. sortedindex[i+j-start]=work[i]-magnitudes;
  113455. }
  113456. }
  113457. }
  113458. void _vp_noise_normalize(vorbis_look_psy *p,
  113459. float *in,float *out,int *sortedindex){
  113460. int flag=0,i,j=0,n=p->n;
  113461. vorbis_info_psy *vi=p->vi;
  113462. int partition=vi->normal_partition;
  113463. int start=vi->normal_start;
  113464. if(start>n)start=n;
  113465. if(vi->normal_channel_p){
  113466. for(;j<start;j++)
  113467. out[j]=rint(in[j]);
  113468. for(;j+partition<=n;j+=partition){
  113469. float acc=0.;
  113470. int k;
  113471. for(i=j;i<j+partition;i++)
  113472. acc+=in[i]*in[i];
  113473. for(i=0;i<partition;i++){
  113474. k=sortedindex[i+j-start];
  113475. if(in[k]*in[k]>=.25f){
  113476. out[k]=rint(in[k]);
  113477. acc-=in[k]*in[k];
  113478. flag=1;
  113479. }else{
  113480. if(acc<vi->normal_thresh)break;
  113481. out[k]=unitnorm(in[k]);
  113482. acc-=1.;
  113483. }
  113484. }
  113485. for(;i<partition;i++){
  113486. k=sortedindex[i+j-start];
  113487. out[k]=0.;
  113488. }
  113489. }
  113490. }
  113491. for(;j<n;j++)
  113492. out[j]=rint(in[j]);
  113493. }
  113494. void _vp_couple(int blobno,
  113495. vorbis_info_psy_global *g,
  113496. vorbis_look_psy *p,
  113497. vorbis_info_mapping0 *vi,
  113498. float **res,
  113499. float **mag_memo,
  113500. int **mag_sort,
  113501. int **ifloor,
  113502. int *nonzero,
  113503. int sliding_lowpass){
  113504. int i,j,k,n=p->n;
  113505. /* perform any requested channel coupling */
  113506. /* point stereo can only be used in a first stage (in this encoder)
  113507. because of the dependency on floor lookups */
  113508. for(i=0;i<vi->coupling_steps;i++){
  113509. /* once we're doing multistage coupling in which a channel goes
  113510. through more than one coupling step, the floor vector
  113511. magnitudes will also have to be recalculated an propogated
  113512. along with PCM. Right now, we're not (that will wait until 5.1
  113513. most likely), so the code isn't here yet. The memory management
  113514. here is all assuming single depth couplings anyway. */
  113515. /* make sure coupling a zero and a nonzero channel results in two
  113516. nonzero channels. */
  113517. if(nonzero[vi->coupling_mag[i]] ||
  113518. nonzero[vi->coupling_ang[i]]){
  113519. float *rM=res[vi->coupling_mag[i]];
  113520. float *rA=res[vi->coupling_ang[i]];
  113521. float *qM=rM+n;
  113522. float *qA=rA+n;
  113523. int *floorM=ifloor[vi->coupling_mag[i]];
  113524. int *floorA=ifloor[vi->coupling_ang[i]];
  113525. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  113526. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  113527. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  113528. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  113529. int pointlimit=limit;
  113530. nonzero[vi->coupling_mag[i]]=1;
  113531. nonzero[vi->coupling_ang[i]]=1;
  113532. /* The threshold of a stereo is changed with the size of n */
  113533. if(n > 1000)
  113534. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  113535. for(j=0;j<p->n;j+=partition){
  113536. float acc=0.f;
  113537. for(k=0;k<partition;k++){
  113538. int l=k+j;
  113539. if(l<sliding_lowpass){
  113540. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  113541. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  113542. precomputed_couple_point(mag_memo[i][l],
  113543. floorM[l],floorA[l],
  113544. qM+l,qA+l);
  113545. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  113546. }else{
  113547. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  113548. }
  113549. }else{
  113550. qM[l]=0.;
  113551. qA[l]=0.;
  113552. }
  113553. }
  113554. if(p->vi->normal_point_p){
  113555. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  113556. int l=mag_sort[i][j+k];
  113557. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  113558. qM[l]=unitnorm(qM[l]);
  113559. acc-=1.f;
  113560. }
  113561. }
  113562. }
  113563. }
  113564. }
  113565. }
  113566. }
  113567. /* AoTuV */
  113568. /** @ M2 **
  113569. The boost problem by the combination of noise normalization and point stereo is eased.
  113570. However, this is a temporary patch.
  113571. by Aoyumi @ 2004/04/18
  113572. */
  113573. void hf_reduction(vorbis_info_psy_global *g,
  113574. vorbis_look_psy *p,
  113575. vorbis_info_mapping0 *vi,
  113576. float **mdct){
  113577. int i,j,n=p->n, de=0.3*p->m_val;
  113578. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  113579. for(i=0; i<vi->coupling_steps; i++){
  113580. /* for(j=start; j<limit; j++){} // ???*/
  113581. for(j=limit; j<n; j++)
  113582. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  113583. }
  113584. }
  113585. #endif
  113586. /********* End of inlined file: psy.c *********/
  113587. /********* Start of inlined file: registry.c *********/
  113588. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113589. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113590. // tasks..
  113591. #ifdef _MSC_VER
  113592. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113593. #endif
  113594. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113595. #if JUCE_USE_OGGVORBIS
  113596. /* seems like major overkill now; the backend numbers will grow into
  113597. the infrastructure soon enough */
  113598. extern vorbis_func_floor floor0_exportbundle;
  113599. extern vorbis_func_floor floor1_exportbundle;
  113600. extern vorbis_func_residue residue0_exportbundle;
  113601. extern vorbis_func_residue residue1_exportbundle;
  113602. extern vorbis_func_residue residue2_exportbundle;
  113603. extern vorbis_func_mapping mapping0_exportbundle;
  113604. vorbis_func_floor *_floor_P[]={
  113605. &floor0_exportbundle,
  113606. &floor1_exportbundle,
  113607. };
  113608. vorbis_func_residue *_residue_P[]={
  113609. &residue0_exportbundle,
  113610. &residue1_exportbundle,
  113611. &residue2_exportbundle,
  113612. };
  113613. vorbis_func_mapping *_mapping_P[]={
  113614. &mapping0_exportbundle,
  113615. };
  113616. #endif
  113617. /********* End of inlined file: registry.c *********/
  113618. /********* Start of inlined file: res0.c *********/
  113619. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  113620. encode/decode loops are coded for clarity and performance is not
  113621. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  113622. it's slow. */
  113623. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113624. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113625. // tasks..
  113626. #ifdef _MSC_VER
  113627. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113628. #endif
  113629. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113630. #if JUCE_USE_OGGVORBIS
  113631. #include <stdlib.h>
  113632. #include <string.h>
  113633. #include <math.h>
  113634. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113635. #include <stdio.h>
  113636. #endif
  113637. typedef struct {
  113638. vorbis_info_residue0 *info;
  113639. int parts;
  113640. int stages;
  113641. codebook *fullbooks;
  113642. codebook *phrasebook;
  113643. codebook ***partbooks;
  113644. int partvals;
  113645. int **decodemap;
  113646. long postbits;
  113647. long phrasebits;
  113648. long frames;
  113649. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  113650. int train_seq;
  113651. long *training_data[8][64];
  113652. float training_max[8][64];
  113653. float training_min[8][64];
  113654. float tmin;
  113655. float tmax;
  113656. #endif
  113657. } vorbis_look_residue0;
  113658. void res0_free_info(vorbis_info_residue *i){
  113659. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  113660. if(info){
  113661. memset(info,0,sizeof(*info));
  113662. _ogg_free(info);
  113663. }
  113664. }
  113665. void res0_free_look(vorbis_look_residue *i){
  113666. int j;
  113667. if(i){
  113668. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  113669. #ifdef TRAIN_RES
  113670. {
  113671. int j,k,l;
  113672. for(j=0;j<look->parts;j++){
  113673. /*fprintf(stderr,"partition %d: ",j);*/
  113674. for(k=0;k<8;k++)
  113675. if(look->training_data[k][j]){
  113676. char buffer[80];
  113677. FILE *of;
  113678. codebook *statebook=look->partbooks[j][k];
  113679. /* long and short into the same bucket by current convention */
  113680. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  113681. of=fopen(buffer,"a");
  113682. for(l=0;l<statebook->entries;l++)
  113683. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  113684. fclose(of);
  113685. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  113686. look->training_min[k][j],look->training_max[k][j]);*/
  113687. _ogg_free(look->training_data[k][j]);
  113688. look->training_data[k][j]=NULL;
  113689. }
  113690. /*fprintf(stderr,"\n");*/
  113691. }
  113692. }
  113693. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  113694. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  113695. (float)look->phrasebits/look->frames,
  113696. (float)look->postbits/look->frames,
  113697. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113698. #endif
  113699. /*vorbis_info_residue0 *info=look->info;
  113700. fprintf(stderr,
  113701. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  113702. "(%g/frame) \n",look->frames,look->phrasebits,
  113703. look->resbitsflat,
  113704. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  113705. for(j=0;j<look->parts;j++){
  113706. long acc=0;
  113707. fprintf(stderr,"\t[%d] == ",j);
  113708. for(k=0;k<look->stages;k++)
  113709. if((info->secondstages[j]>>k)&1){
  113710. fprintf(stderr,"%ld,",look->resbits[j][k]);
  113711. acc+=look->resbits[j][k];
  113712. }
  113713. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  113714. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  113715. }
  113716. fprintf(stderr,"\n");*/
  113717. for(j=0;j<look->parts;j++)
  113718. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  113719. _ogg_free(look->partbooks);
  113720. for(j=0;j<look->partvals;j++)
  113721. _ogg_free(look->decodemap[j]);
  113722. _ogg_free(look->decodemap);
  113723. memset(look,0,sizeof(*look));
  113724. _ogg_free(look);
  113725. }
  113726. }
  113727. static int icount(unsigned int v){
  113728. int ret=0;
  113729. while(v){
  113730. ret+=v&1;
  113731. v>>=1;
  113732. }
  113733. return(ret);
  113734. }
  113735. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  113736. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113737. int j,acc=0;
  113738. oggpack_write(opb,info->begin,24);
  113739. oggpack_write(opb,info->end,24);
  113740. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  113741. code with a partitioned book */
  113742. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  113743. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  113744. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  113745. bitmask of one indicates this partition class has bits to write
  113746. this pass */
  113747. for(j=0;j<info->partitions;j++){
  113748. if(ilog(info->secondstages[j])>3){
  113749. /* yes, this is a minor hack due to not thinking ahead */
  113750. oggpack_write(opb,info->secondstages[j],3);
  113751. oggpack_write(opb,1,1);
  113752. oggpack_write(opb,info->secondstages[j]>>3,5);
  113753. }else
  113754. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  113755. acc+=icount(info->secondstages[j]);
  113756. }
  113757. for(j=0;j<acc;j++)
  113758. oggpack_write(opb,info->booklist[j],8);
  113759. }
  113760. /* vorbis_info is for range checking */
  113761. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  113762. int j,acc=0;
  113763. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  113764. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113765. info->begin=oggpack_read(opb,24);
  113766. info->end=oggpack_read(opb,24);
  113767. info->grouping=oggpack_read(opb,24)+1;
  113768. info->partitions=oggpack_read(opb,6)+1;
  113769. info->groupbook=oggpack_read(opb,8);
  113770. for(j=0;j<info->partitions;j++){
  113771. int cascade=oggpack_read(opb,3);
  113772. if(oggpack_read(opb,1))
  113773. cascade|=(oggpack_read(opb,5)<<3);
  113774. info->secondstages[j]=cascade;
  113775. acc+=icount(cascade);
  113776. }
  113777. for(j=0;j<acc;j++)
  113778. info->booklist[j]=oggpack_read(opb,8);
  113779. if(info->groupbook>=ci->books)goto errout;
  113780. for(j=0;j<acc;j++)
  113781. if(info->booklist[j]>=ci->books)goto errout;
  113782. return(info);
  113783. errout:
  113784. res0_free_info(info);
  113785. return(NULL);
  113786. }
  113787. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  113788. vorbis_info_residue *vr){
  113789. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  113790. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  113791. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  113792. int j,k,acc=0;
  113793. int dim;
  113794. int maxstage=0;
  113795. look->info=info;
  113796. look->parts=info->partitions;
  113797. look->fullbooks=ci->fullbooks;
  113798. look->phrasebook=ci->fullbooks+info->groupbook;
  113799. dim=look->phrasebook->dim;
  113800. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  113801. for(j=0;j<look->parts;j++){
  113802. int stages=ilog(info->secondstages[j]);
  113803. if(stages){
  113804. if(stages>maxstage)maxstage=stages;
  113805. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  113806. for(k=0;k<stages;k++)
  113807. if(info->secondstages[j]&(1<<k)){
  113808. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  113809. #ifdef TRAIN_RES
  113810. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  113811. sizeof(***look->training_data));
  113812. #endif
  113813. }
  113814. }
  113815. }
  113816. look->partvals=rint(pow((float)look->parts,(float)dim));
  113817. look->stages=maxstage;
  113818. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  113819. for(j=0;j<look->partvals;j++){
  113820. long val=j;
  113821. long mult=look->partvals/look->parts;
  113822. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  113823. for(k=0;k<dim;k++){
  113824. long deco=val/mult;
  113825. val-=deco*mult;
  113826. mult/=look->parts;
  113827. look->decodemap[j][k]=deco;
  113828. }
  113829. }
  113830. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113831. {
  113832. static int train_seq=0;
  113833. look->train_seq=train_seq++;
  113834. }
  113835. #endif
  113836. return(look);
  113837. }
  113838. /* break an abstraction and copy some code for performance purposes */
  113839. static int local_book_besterror(codebook *book,float *a){
  113840. int dim=book->dim,i,k,o;
  113841. int best=0;
  113842. encode_aux_threshmatch *tt=book->c->thresh_tree;
  113843. /* find the quant val of each scalar */
  113844. for(k=0,o=dim;k<dim;++k){
  113845. float val=a[--o];
  113846. i=tt->threshvals>>1;
  113847. if(val<tt->quantthresh[i]){
  113848. if(val<tt->quantthresh[i-1]){
  113849. for(--i;i>0;--i)
  113850. if(val>=tt->quantthresh[i-1])
  113851. break;
  113852. }
  113853. }else{
  113854. for(++i;i<tt->threshvals-1;++i)
  113855. if(val<tt->quantthresh[i])break;
  113856. }
  113857. best=(best*tt->quantvals)+tt->quantmap[i];
  113858. }
  113859. /* regular lattices are easy :-) */
  113860. if(book->c->lengthlist[best]<=0){
  113861. const static_codebook *c=book->c;
  113862. int i,j;
  113863. float bestf=0.f;
  113864. float *e=book->valuelist;
  113865. best=-1;
  113866. for(i=0;i<book->entries;i++){
  113867. if(c->lengthlist[i]>0){
  113868. float thisx=0.f;
  113869. for(j=0;j<dim;j++){
  113870. float val=(e[j]-a[j]);
  113871. thisx+=val*val;
  113872. }
  113873. if(best==-1 || thisx<bestf){
  113874. bestf=thisx;
  113875. best=i;
  113876. }
  113877. }
  113878. e+=dim;
  113879. }
  113880. }
  113881. {
  113882. float *ptr=book->valuelist+best*dim;
  113883. for(i=0;i<dim;i++)
  113884. *a++ -= *ptr++;
  113885. }
  113886. return(best);
  113887. }
  113888. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  113889. codebook *book,long *acc){
  113890. int i,bits=0;
  113891. int dim=book->dim;
  113892. int step=n/dim;
  113893. for(i=0;i<step;i++){
  113894. int entry=local_book_besterror(book,vec+i*dim);
  113895. #ifdef TRAIN_RES
  113896. acc[entry]++;
  113897. #endif
  113898. bits+=vorbis_book_encode(book,entry,opb);
  113899. }
  113900. return(bits);
  113901. }
  113902. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  113903. float **in,int ch){
  113904. long i,j,k;
  113905. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113906. vorbis_info_residue0 *info=look->info;
  113907. /* move all this setup out later */
  113908. int samples_per_partition=info->grouping;
  113909. int possible_partitions=info->partitions;
  113910. int n=info->end-info->begin;
  113911. int partvals=n/samples_per_partition;
  113912. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  113913. float scale=100./samples_per_partition;
  113914. /* we find the partition type for each partition of each
  113915. channel. We'll go back and do the interleaved encoding in a
  113916. bit. For now, clarity */
  113917. for(i=0;i<ch;i++){
  113918. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  113919. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  113920. }
  113921. for(i=0;i<partvals;i++){
  113922. int offset=i*samples_per_partition+info->begin;
  113923. for(j=0;j<ch;j++){
  113924. float max=0.;
  113925. float ent=0.;
  113926. for(k=0;k<samples_per_partition;k++){
  113927. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  113928. ent+=fabs(rint(in[j][offset+k]));
  113929. }
  113930. ent*=scale;
  113931. for(k=0;k<possible_partitions-1;k++)
  113932. if(max<=info->classmetric1[k] &&
  113933. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  113934. break;
  113935. partword[j][i]=k;
  113936. }
  113937. }
  113938. #ifdef TRAIN_RESAUX
  113939. {
  113940. FILE *of;
  113941. char buffer[80];
  113942. for(i=0;i<ch;i++){
  113943. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113944. of=fopen(buffer,"a");
  113945. for(j=0;j<partvals;j++)
  113946. fprintf(of,"%ld, ",partword[i][j]);
  113947. fprintf(of,"\n");
  113948. fclose(of);
  113949. }
  113950. }
  113951. #endif
  113952. look->frames++;
  113953. return(partword);
  113954. }
  113955. /* designed for stereo or other modes where the partition size is an
  113956. integer multiple of the number of channels encoded in the current
  113957. submap */
  113958. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  113959. int ch){
  113960. long i,j,k,l;
  113961. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  113962. vorbis_info_residue0 *info=look->info;
  113963. /* move all this setup out later */
  113964. int samples_per_partition=info->grouping;
  113965. int possible_partitions=info->partitions;
  113966. int n=info->end-info->begin;
  113967. int partvals=n/samples_per_partition;
  113968. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  113969. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  113970. FILE *of;
  113971. char buffer[80];
  113972. #endif
  113973. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  113974. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  113975. for(i=0,l=info->begin/ch;i<partvals;i++){
  113976. float magmax=0.f;
  113977. float angmax=0.f;
  113978. for(j=0;j<samples_per_partition;j+=ch){
  113979. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  113980. for(k=1;k<ch;k++)
  113981. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  113982. l++;
  113983. }
  113984. for(j=0;j<possible_partitions-1;j++)
  113985. if(magmax<=info->classmetric1[j] &&
  113986. angmax<=info->classmetric2[j])
  113987. break;
  113988. partword[0][i]=j;
  113989. }
  113990. #ifdef TRAIN_RESAUX
  113991. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  113992. of=fopen(buffer,"a");
  113993. for(i=0;i<partvals;i++)
  113994. fprintf(of,"%ld, ",partword[0][i]);
  113995. fprintf(of,"\n");
  113996. fclose(of);
  113997. #endif
  113998. look->frames++;
  113999. return(partword);
  114000. }
  114001. static int _01forward(oggpack_buffer *opb,
  114002. vorbis_block *vb,vorbis_look_residue *vl,
  114003. float **in,int ch,
  114004. long **partword,
  114005. int (*encode)(oggpack_buffer *,float *,int,
  114006. codebook *,long *)){
  114007. long i,j,k,s;
  114008. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114009. vorbis_info_residue0 *info=look->info;
  114010. /* move all this setup out later */
  114011. int samples_per_partition=info->grouping;
  114012. int possible_partitions=info->partitions;
  114013. int partitions_per_word=look->phrasebook->dim;
  114014. int n=info->end-info->begin;
  114015. int partvals=n/samples_per_partition;
  114016. long resbits[128];
  114017. long resvals[128];
  114018. #ifdef TRAIN_RES
  114019. for(i=0;i<ch;i++)
  114020. for(j=info->begin;j<info->end;j++){
  114021. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  114022. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  114023. }
  114024. #endif
  114025. memset(resbits,0,sizeof(resbits));
  114026. memset(resvals,0,sizeof(resvals));
  114027. /* we code the partition words for each channel, then the residual
  114028. words for a partition per channel until we've written all the
  114029. residual words for that partition word. Then write the next
  114030. partition channel words... */
  114031. for(s=0;s<look->stages;s++){
  114032. for(i=0;i<partvals;){
  114033. /* first we encode a partition codeword for each channel */
  114034. if(s==0){
  114035. for(j=0;j<ch;j++){
  114036. long val=partword[j][i];
  114037. for(k=1;k<partitions_per_word;k++){
  114038. val*=possible_partitions;
  114039. if(i+k<partvals)
  114040. val+=partword[j][i+k];
  114041. }
  114042. /* training hack */
  114043. if(val<look->phrasebook->entries)
  114044. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  114045. #if 0 /*def TRAIN_RES*/
  114046. else
  114047. fprintf(stderr,"!");
  114048. #endif
  114049. }
  114050. }
  114051. /* now we encode interleaved residual values for the partitions */
  114052. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  114053. long offset=i*samples_per_partition+info->begin;
  114054. for(j=0;j<ch;j++){
  114055. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  114056. if(info->secondstages[partword[j][i]]&(1<<s)){
  114057. codebook *statebook=look->partbooks[partword[j][i]][s];
  114058. if(statebook){
  114059. int ret;
  114060. long *accumulator=NULL;
  114061. #ifdef TRAIN_RES
  114062. accumulator=look->training_data[s][partword[j][i]];
  114063. {
  114064. int l;
  114065. float *samples=in[j]+offset;
  114066. for(l=0;l<samples_per_partition;l++){
  114067. if(samples[l]<look->training_min[s][partword[j][i]])
  114068. look->training_min[s][partword[j][i]]=samples[l];
  114069. if(samples[l]>look->training_max[s][partword[j][i]])
  114070. look->training_max[s][partword[j][i]]=samples[l];
  114071. }
  114072. }
  114073. #endif
  114074. ret=encode(opb,in[j]+offset,samples_per_partition,
  114075. statebook,accumulator);
  114076. look->postbits+=ret;
  114077. resbits[partword[j][i]]+=ret;
  114078. }
  114079. }
  114080. }
  114081. }
  114082. }
  114083. }
  114084. /*{
  114085. long total=0;
  114086. long totalbits=0;
  114087. fprintf(stderr,"%d :: ",vb->mode);
  114088. for(k=0;k<possible_partitions;k++){
  114089. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  114090. total+=resvals[k];
  114091. totalbits+=resbits[k];
  114092. }
  114093. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  114094. }*/
  114095. return(0);
  114096. }
  114097. /* a truncated packet here just means 'stop working'; it's not an error */
  114098. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114099. float **in,int ch,
  114100. long (*decodepart)(codebook *, float *,
  114101. oggpack_buffer *,int)){
  114102. long i,j,k,l,s;
  114103. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114104. vorbis_info_residue0 *info=look->info;
  114105. /* move all this setup out later */
  114106. int samples_per_partition=info->grouping;
  114107. int partitions_per_word=look->phrasebook->dim;
  114108. int n=info->end-info->begin;
  114109. int partvals=n/samples_per_partition;
  114110. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114111. int ***partword=(int***)alloca(ch*sizeof(*partword));
  114112. for(j=0;j<ch;j++)
  114113. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  114114. for(s=0;s<look->stages;s++){
  114115. /* each loop decodes on partition codeword containing
  114116. partitions_pre_word partitions */
  114117. for(i=0,l=0;i<partvals;l++){
  114118. if(s==0){
  114119. /* fetch the partition word for each channel */
  114120. for(j=0;j<ch;j++){
  114121. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114122. if(temp==-1)goto eopbreak;
  114123. partword[j][l]=look->decodemap[temp];
  114124. if(partword[j][l]==NULL)goto errout;
  114125. }
  114126. }
  114127. /* now we decode residual values for the partitions */
  114128. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114129. for(j=0;j<ch;j++){
  114130. long offset=info->begin+i*samples_per_partition;
  114131. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  114132. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  114133. if(stagebook){
  114134. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  114135. samples_per_partition)==-1)goto eopbreak;
  114136. }
  114137. }
  114138. }
  114139. }
  114140. }
  114141. errout:
  114142. eopbreak:
  114143. return(0);
  114144. }
  114145. #if 0
  114146. /* residue 0 and 1 are just slight variants of one another. 0 is
  114147. interleaved, 1 is not */
  114148. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  114149. float **in,int *nonzero,int ch){
  114150. /* we encode only the nonzero parts of a bundle */
  114151. int i,used=0;
  114152. for(i=0;i<ch;i++)
  114153. if(nonzero[i])
  114154. in[used++]=in[i];
  114155. if(used)
  114156. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  114157. return(_01class(vb,vl,in,used));
  114158. else
  114159. return(0);
  114160. }
  114161. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  114162. float **in,float **out,int *nonzero,int ch,
  114163. long **partword){
  114164. /* we encode only the nonzero parts of a bundle */
  114165. int i,j,used=0,n=vb->pcmend/2;
  114166. for(i=0;i<ch;i++)
  114167. if(nonzero[i]){
  114168. if(out)
  114169. for(j=0;j<n;j++)
  114170. out[i][j]+=in[i][j];
  114171. in[used++]=in[i];
  114172. }
  114173. if(used){
  114174. int ret=_01forward(vb,vl,in,used,partword,
  114175. _interleaved_encodepart);
  114176. if(out){
  114177. used=0;
  114178. for(i=0;i<ch;i++)
  114179. if(nonzero[i]){
  114180. for(j=0;j<n;j++)
  114181. out[i][j]-=in[used][j];
  114182. used++;
  114183. }
  114184. }
  114185. return(ret);
  114186. }else{
  114187. return(0);
  114188. }
  114189. }
  114190. #endif
  114191. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114192. float **in,int *nonzero,int ch){
  114193. int i,used=0;
  114194. for(i=0;i<ch;i++)
  114195. if(nonzero[i])
  114196. in[used++]=in[i];
  114197. if(used)
  114198. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  114199. else
  114200. return(0);
  114201. }
  114202. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  114203. float **in,float **out,int *nonzero,int ch,
  114204. long **partword){
  114205. int i,j,used=0,n=vb->pcmend/2;
  114206. for(i=0;i<ch;i++)
  114207. if(nonzero[i]){
  114208. if(out)
  114209. for(j=0;j<n;j++)
  114210. out[i][j]+=in[i][j];
  114211. in[used++]=in[i];
  114212. }
  114213. if(used){
  114214. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  114215. if(out){
  114216. used=0;
  114217. for(i=0;i<ch;i++)
  114218. if(nonzero[i]){
  114219. for(j=0;j<n;j++)
  114220. out[i][j]-=in[used][j];
  114221. used++;
  114222. }
  114223. }
  114224. return(ret);
  114225. }else{
  114226. return(0);
  114227. }
  114228. }
  114229. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  114230. float **in,int *nonzero,int ch){
  114231. int i,used=0;
  114232. for(i=0;i<ch;i++)
  114233. if(nonzero[i])
  114234. in[used++]=in[i];
  114235. if(used)
  114236. return(_01class(vb,vl,in,used));
  114237. else
  114238. return(0);
  114239. }
  114240. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114241. float **in,int *nonzero,int ch){
  114242. int i,used=0;
  114243. for(i=0;i<ch;i++)
  114244. if(nonzero[i])
  114245. in[used++]=in[i];
  114246. if(used)
  114247. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  114248. else
  114249. return(0);
  114250. }
  114251. long **res2_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])used++;
  114256. if(used)
  114257. return(_2class(vb,vl,in,ch));
  114258. else
  114259. return(0);
  114260. }
  114261. /* res2 is slightly more different; all the channels are interleaved
  114262. into a single vector and encoded. */
  114263. int res2_forward(oggpack_buffer *opb,
  114264. vorbis_block *vb,vorbis_look_residue *vl,
  114265. float **in,float **out,int *nonzero,int ch,
  114266. long **partword){
  114267. long i,j,k,n=vb->pcmend/2,used=0;
  114268. /* don't duplicate the code; use a working vector hack for now and
  114269. reshape ourselves into a single channel res1 */
  114270. /* ugly; reallocs for each coupling pass :-( */
  114271. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  114272. for(i=0;i<ch;i++){
  114273. float *pcm=in[i];
  114274. if(nonzero[i])used++;
  114275. for(j=0,k=i;j<n;j++,k+=ch)
  114276. work[k]=pcm[j];
  114277. }
  114278. if(used){
  114279. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  114280. /* update the sofar vector */
  114281. if(out){
  114282. for(i=0;i<ch;i++){
  114283. float *pcm=in[i];
  114284. float *sofar=out[i];
  114285. for(j=0,k=i;j<n;j++,k+=ch)
  114286. sofar[j]+=pcm[j]-work[k];
  114287. }
  114288. }
  114289. return(ret);
  114290. }else{
  114291. return(0);
  114292. }
  114293. }
  114294. /* duplicate code here as speed is somewhat more important */
  114295. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  114296. float **in,int *nonzero,int ch){
  114297. long i,k,l,s;
  114298. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  114299. vorbis_info_residue0 *info=look->info;
  114300. /* move all this setup out later */
  114301. int samples_per_partition=info->grouping;
  114302. int partitions_per_word=look->phrasebook->dim;
  114303. int n=info->end-info->begin;
  114304. int partvals=n/samples_per_partition;
  114305. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  114306. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  114307. for(i=0;i<ch;i++)if(nonzero[i])break;
  114308. if(i==ch)return(0); /* no nonzero vectors */
  114309. for(s=0;s<look->stages;s++){
  114310. for(i=0,l=0;i<partvals;l++){
  114311. if(s==0){
  114312. /* fetch the partition word */
  114313. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  114314. if(temp==-1)goto eopbreak;
  114315. partword[l]=look->decodemap[temp];
  114316. if(partword[l]==NULL)goto errout;
  114317. }
  114318. /* now we decode residual values for the partitions */
  114319. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  114320. if(info->secondstages[partword[l][k]]&(1<<s)){
  114321. codebook *stagebook=look->partbooks[partword[l][k]][s];
  114322. if(stagebook){
  114323. if(vorbis_book_decodevv_add(stagebook,in,
  114324. i*samples_per_partition+info->begin,ch,
  114325. &vb->opb,samples_per_partition)==-1)
  114326. goto eopbreak;
  114327. }
  114328. }
  114329. }
  114330. }
  114331. errout:
  114332. eopbreak:
  114333. return(0);
  114334. }
  114335. vorbis_func_residue residue0_exportbundle={
  114336. NULL,
  114337. &res0_unpack,
  114338. &res0_look,
  114339. &res0_free_info,
  114340. &res0_free_look,
  114341. NULL,
  114342. NULL,
  114343. &res0_inverse
  114344. };
  114345. vorbis_func_residue residue1_exportbundle={
  114346. &res0_pack,
  114347. &res0_unpack,
  114348. &res0_look,
  114349. &res0_free_info,
  114350. &res0_free_look,
  114351. &res1_class,
  114352. &res1_forward,
  114353. &res1_inverse
  114354. };
  114355. vorbis_func_residue residue2_exportbundle={
  114356. &res0_pack,
  114357. &res0_unpack,
  114358. &res0_look,
  114359. &res0_free_info,
  114360. &res0_free_look,
  114361. &res2_class,
  114362. &res2_forward,
  114363. &res2_inverse
  114364. };
  114365. #endif
  114366. /********* End of inlined file: res0.c *********/
  114367. /********* Start of inlined file: sharedbook.c *********/
  114368. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114369. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114370. // tasks..
  114371. #ifdef _MSC_VER
  114372. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114373. #endif
  114374. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114375. #if JUCE_USE_OGGVORBIS
  114376. #include <stdlib.h>
  114377. #include <math.h>
  114378. #include <string.h>
  114379. /**** pack/unpack helpers ******************************************/
  114380. int _ilog(unsigned int v){
  114381. int ret=0;
  114382. while(v){
  114383. ret++;
  114384. v>>=1;
  114385. }
  114386. return(ret);
  114387. }
  114388. /* 32 bit float (not IEEE; nonnormalized mantissa +
  114389. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  114390. Why not IEEE? It's just not that important here. */
  114391. #define VQ_FEXP 10
  114392. #define VQ_FMAN 21
  114393. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  114394. /* doesn't currently guard under/overflow */
  114395. long _float32_pack(float val){
  114396. int sign=0;
  114397. long exp;
  114398. long mant;
  114399. if(val<0){
  114400. sign=0x80000000;
  114401. val= -val;
  114402. }
  114403. exp= floor(log(val)/log(2.f));
  114404. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  114405. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  114406. return(sign|exp|mant);
  114407. }
  114408. float _float32_unpack(long val){
  114409. double mant=val&0x1fffff;
  114410. int sign=val&0x80000000;
  114411. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  114412. if(sign)mant= -mant;
  114413. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  114414. }
  114415. /* given a list of word lengths, generate a list of codewords. Works
  114416. for length ordered or unordered, always assigns the lowest valued
  114417. codewords first. Extended to handle unused entries (length 0) */
  114418. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  114419. long i,j,count=0;
  114420. ogg_uint32_t marker[33];
  114421. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  114422. memset(marker,0,sizeof(marker));
  114423. for(i=0;i<n;i++){
  114424. long length=l[i];
  114425. if(length>0){
  114426. ogg_uint32_t entry=marker[length];
  114427. /* when we claim a node for an entry, we also claim the nodes
  114428. below it (pruning off the imagined tree that may have dangled
  114429. from it) as well as blocking the use of any nodes directly
  114430. above for leaves */
  114431. /* update ourself */
  114432. if(length<32 && (entry>>length)){
  114433. /* error condition; the lengths must specify an overpopulated tree */
  114434. _ogg_free(r);
  114435. return(NULL);
  114436. }
  114437. r[count++]=entry;
  114438. /* Look to see if the next shorter marker points to the node
  114439. above. if so, update it and repeat. */
  114440. {
  114441. for(j=length;j>0;j--){
  114442. if(marker[j]&1){
  114443. /* have to jump branches */
  114444. if(j==1)
  114445. marker[1]++;
  114446. else
  114447. marker[j]=marker[j-1]<<1;
  114448. break; /* invariant says next upper marker would already
  114449. have been moved if it was on the same path */
  114450. }
  114451. marker[j]++;
  114452. }
  114453. }
  114454. /* prune the tree; the implicit invariant says all the longer
  114455. markers were dangling from our just-taken node. Dangle them
  114456. from our *new* node. */
  114457. for(j=length+1;j<33;j++)
  114458. if((marker[j]>>1) == entry){
  114459. entry=marker[j];
  114460. marker[j]=marker[j-1]<<1;
  114461. }else
  114462. break;
  114463. }else
  114464. if(sparsecount==0)count++;
  114465. }
  114466. /* bitreverse the words because our bitwise packer/unpacker is LSb
  114467. endian */
  114468. for(i=0,count=0;i<n;i++){
  114469. ogg_uint32_t temp=0;
  114470. for(j=0;j<l[i];j++){
  114471. temp<<=1;
  114472. temp|=(r[count]>>j)&1;
  114473. }
  114474. if(sparsecount){
  114475. if(l[i])
  114476. r[count++]=temp;
  114477. }else
  114478. r[count++]=temp;
  114479. }
  114480. return(r);
  114481. }
  114482. /* there might be a straightforward one-line way to do the below
  114483. that's portable and totally safe against roundoff, but I haven't
  114484. thought of it. Therefore, we opt on the side of caution */
  114485. long _book_maptype1_quantvals(const static_codebook *b){
  114486. long vals=floor(pow((float)b->entries,1.f/b->dim));
  114487. /* the above *should* be reliable, but we'll not assume that FP is
  114488. ever reliable when bitstream sync is at stake; verify via integer
  114489. means that vals really is the greatest value of dim for which
  114490. vals^b->bim <= b->entries */
  114491. /* treat the above as an initial guess */
  114492. while(1){
  114493. long acc=1;
  114494. long acc1=1;
  114495. int i;
  114496. for(i=0;i<b->dim;i++){
  114497. acc*=vals;
  114498. acc1*=vals+1;
  114499. }
  114500. if(acc<=b->entries && acc1>b->entries){
  114501. return(vals);
  114502. }else{
  114503. if(acc>b->entries){
  114504. vals--;
  114505. }else{
  114506. vals++;
  114507. }
  114508. }
  114509. }
  114510. }
  114511. /* unpack the quantized list of values for encode/decode ***********/
  114512. /* we need to deal with two map types: in map type 1, the values are
  114513. generated algorithmically (each column of the vector counts through
  114514. the values in the quant vector). in map type 2, all the values came
  114515. in in an explicit list. Both value lists must be unpacked */
  114516. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  114517. long j,k,count=0;
  114518. if(b->maptype==1 || b->maptype==2){
  114519. int quantvals;
  114520. float mindel=_float32_unpack(b->q_min);
  114521. float delta=_float32_unpack(b->q_delta);
  114522. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  114523. /* maptype 1 and 2 both use a quantized value vector, but
  114524. different sizes */
  114525. switch(b->maptype){
  114526. case 1:
  114527. /* most of the time, entries%dimensions == 0, but we need to be
  114528. well defined. We define that the possible vales at each
  114529. scalar is values == entries/dim. If entries%dim != 0, we'll
  114530. have 'too few' values (values*dim<entries), which means that
  114531. we'll have 'left over' entries; left over entries use zeroed
  114532. values (and are wasted). So don't generate codebooks like
  114533. that */
  114534. quantvals=_book_maptype1_quantvals(b);
  114535. for(j=0;j<b->entries;j++){
  114536. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114537. float last=0.f;
  114538. int indexdiv=1;
  114539. for(k=0;k<b->dim;k++){
  114540. int index= (j/indexdiv)%quantvals;
  114541. float val=b->quantlist[index];
  114542. val=fabs(val)*delta+mindel+last;
  114543. if(b->q_sequencep)last=val;
  114544. if(sparsemap)
  114545. r[sparsemap[count]*b->dim+k]=val;
  114546. else
  114547. r[count*b->dim+k]=val;
  114548. indexdiv*=quantvals;
  114549. }
  114550. count++;
  114551. }
  114552. }
  114553. break;
  114554. case 2:
  114555. for(j=0;j<b->entries;j++){
  114556. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  114557. float last=0.f;
  114558. for(k=0;k<b->dim;k++){
  114559. float val=b->quantlist[j*b->dim+k];
  114560. val=fabs(val)*delta+mindel+last;
  114561. if(b->q_sequencep)last=val;
  114562. if(sparsemap)
  114563. r[sparsemap[count]*b->dim+k]=val;
  114564. else
  114565. r[count*b->dim+k]=val;
  114566. }
  114567. count++;
  114568. }
  114569. }
  114570. break;
  114571. }
  114572. return(r);
  114573. }
  114574. return(NULL);
  114575. }
  114576. void vorbis_staticbook_clear(static_codebook *b){
  114577. if(b->allocedp){
  114578. if(b->quantlist)_ogg_free(b->quantlist);
  114579. if(b->lengthlist)_ogg_free(b->lengthlist);
  114580. if(b->nearest_tree){
  114581. _ogg_free(b->nearest_tree->ptr0);
  114582. _ogg_free(b->nearest_tree->ptr1);
  114583. _ogg_free(b->nearest_tree->p);
  114584. _ogg_free(b->nearest_tree->q);
  114585. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  114586. _ogg_free(b->nearest_tree);
  114587. }
  114588. if(b->thresh_tree){
  114589. _ogg_free(b->thresh_tree->quantthresh);
  114590. _ogg_free(b->thresh_tree->quantmap);
  114591. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  114592. _ogg_free(b->thresh_tree);
  114593. }
  114594. memset(b,0,sizeof(*b));
  114595. }
  114596. }
  114597. void vorbis_staticbook_destroy(static_codebook *b){
  114598. if(b->allocedp){
  114599. vorbis_staticbook_clear(b);
  114600. _ogg_free(b);
  114601. }
  114602. }
  114603. void vorbis_book_clear(codebook *b){
  114604. /* static book is not cleared; we're likely called on the lookup and
  114605. the static codebook belongs to the info struct */
  114606. if(b->valuelist)_ogg_free(b->valuelist);
  114607. if(b->codelist)_ogg_free(b->codelist);
  114608. if(b->dec_index)_ogg_free(b->dec_index);
  114609. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  114610. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  114611. memset(b,0,sizeof(*b));
  114612. }
  114613. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  114614. memset(c,0,sizeof(*c));
  114615. c->c=s;
  114616. c->entries=s->entries;
  114617. c->used_entries=s->entries;
  114618. c->dim=s->dim;
  114619. c->codelist=_make_words(s->lengthlist,s->entries,0);
  114620. c->valuelist=_book_unquantize(s,s->entries,NULL);
  114621. return(0);
  114622. }
  114623. static int sort32a(const void *a,const void *b){
  114624. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  114625. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  114626. }
  114627. /* decode codebook arrangement is more heavily optimized than encode */
  114628. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  114629. int i,j,n=0,tabn;
  114630. int *sortindex;
  114631. memset(c,0,sizeof(*c));
  114632. /* count actually used entries */
  114633. for(i=0;i<s->entries;i++)
  114634. if(s->lengthlist[i]>0)
  114635. n++;
  114636. c->entries=s->entries;
  114637. c->used_entries=n;
  114638. c->dim=s->dim;
  114639. /* two different remappings go on here.
  114640. First, we collapse the likely sparse codebook down only to
  114641. actually represented values/words. This collapsing needs to be
  114642. indexed as map-valueless books are used to encode original entry
  114643. positions as integers.
  114644. Second, we reorder all vectors, including the entry index above,
  114645. by sorted bitreversed codeword to allow treeless decode. */
  114646. {
  114647. /* perform sort */
  114648. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  114649. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  114650. if(codes==NULL)goto err_out;
  114651. for(i=0;i<n;i++){
  114652. codes[i]=ogg_bitreverse(codes[i]);
  114653. codep[i]=codes+i;
  114654. }
  114655. qsort(codep,n,sizeof(*codep),sort32a);
  114656. sortindex=(int*)alloca(n*sizeof(*sortindex));
  114657. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  114658. /* the index is a reverse index */
  114659. for(i=0;i<n;i++){
  114660. int position=codep[i]-codes;
  114661. sortindex[position]=i;
  114662. }
  114663. for(i=0;i<n;i++)
  114664. c->codelist[sortindex[i]]=codes[i];
  114665. _ogg_free(codes);
  114666. }
  114667. c->valuelist=_book_unquantize(s,n,sortindex);
  114668. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  114669. for(n=0,i=0;i<s->entries;i++)
  114670. if(s->lengthlist[i]>0)
  114671. c->dec_index[sortindex[n++]]=i;
  114672. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  114673. for(n=0,i=0;i<s->entries;i++)
  114674. if(s->lengthlist[i]>0)
  114675. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  114676. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  114677. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  114678. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  114679. tabn=1<<c->dec_firsttablen;
  114680. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  114681. c->dec_maxlength=0;
  114682. for(i=0;i<n;i++){
  114683. if(c->dec_maxlength<c->dec_codelengths[i])
  114684. c->dec_maxlength=c->dec_codelengths[i];
  114685. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  114686. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  114687. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  114688. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  114689. }
  114690. }
  114691. /* now fill in 'unused' entries in the firsttable with hi/lo search
  114692. hints for the non-direct-hits */
  114693. {
  114694. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  114695. long lo=0,hi=0;
  114696. for(i=0;i<tabn;i++){
  114697. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  114698. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  114699. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  114700. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  114701. /* we only actually have 15 bits per hint to play with here.
  114702. In order to overflow gracefully (nothing breaks, efficiency
  114703. just drops), encode as the difference from the extremes. */
  114704. {
  114705. unsigned long loval=lo;
  114706. unsigned long hival=n-hi;
  114707. if(loval>0x7fff)loval=0x7fff;
  114708. if(hival>0x7fff)hival=0x7fff;
  114709. c->dec_firsttable[ogg_bitreverse(word)]=
  114710. 0x80000000UL | (loval<<15) | hival;
  114711. }
  114712. }
  114713. }
  114714. }
  114715. return(0);
  114716. err_out:
  114717. vorbis_book_clear(c);
  114718. return(-1);
  114719. }
  114720. static float _dist(int el,float *ref, float *b,int step){
  114721. int i;
  114722. float acc=0.f;
  114723. for(i=0;i<el;i++){
  114724. float val=(ref[i]-b[i*step]);
  114725. acc+=val*val;
  114726. }
  114727. return(acc);
  114728. }
  114729. int _best(codebook *book, float *a, int step){
  114730. encode_aux_threshmatch *tt=book->c->thresh_tree;
  114731. #if 0
  114732. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  114733. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  114734. #endif
  114735. int dim=book->dim;
  114736. int k,o;
  114737. /*int savebest=-1;
  114738. float saverr;*/
  114739. /* do we have a threshhold encode hint? */
  114740. if(tt){
  114741. int index=0,i;
  114742. /* find the quant val of each scalar */
  114743. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114744. i=tt->threshvals>>1;
  114745. if(a[o]<tt->quantthresh[i]){
  114746. for(;i>0;i--)
  114747. if(a[o]>=tt->quantthresh[i-1])
  114748. break;
  114749. }else{
  114750. for(i++;i<tt->threshvals-1;i++)
  114751. if(a[o]<tt->quantthresh[i])break;
  114752. }
  114753. index=(index*tt->quantvals)+tt->quantmap[i];
  114754. }
  114755. /* regular lattices are easy :-) */
  114756. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  114757. use a decision tree after all
  114758. and fall through*/
  114759. return(index);
  114760. }
  114761. #if 0
  114762. /* do we have a pigeonhole encode hint? */
  114763. if(pt){
  114764. const static_codebook *c=book->c;
  114765. int i,besti=-1;
  114766. float best=0.f;
  114767. int entry=0;
  114768. /* dealing with sequentialness is a pain in the ass */
  114769. if(c->q_sequencep){
  114770. int pv;
  114771. long mul=1;
  114772. float qlast=0;
  114773. for(k=0,o=0;k<dim;k++,o+=step){
  114774. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  114775. if(pv<0 || pv>=pt->mapentries)break;
  114776. entry+=pt->pigeonmap[pv]*mul;
  114777. mul*=pt->quantvals;
  114778. qlast+=pv*pt->del+pt->min;
  114779. }
  114780. }else{
  114781. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  114782. int pv=(int)((a[o]-pt->min)/pt->del);
  114783. if(pv<0 || pv>=pt->mapentries)break;
  114784. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  114785. }
  114786. }
  114787. /* must be within the pigeonholable range; if we quant outside (or
  114788. in an entry that we define no list for), brute force it */
  114789. if(k==dim && pt->fitlength[entry]){
  114790. /* search the abbreviated list */
  114791. long *list=pt->fitlist+pt->fitmap[entry];
  114792. for(i=0;i<pt->fitlength[entry];i++){
  114793. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  114794. if(besti==-1 || this<best){
  114795. best=this;
  114796. besti=list[i];
  114797. }
  114798. }
  114799. return(besti);
  114800. }
  114801. }
  114802. if(nt){
  114803. /* optimized using the decision tree */
  114804. while(1){
  114805. float c=0.f;
  114806. float *p=book->valuelist+nt->p[ptr];
  114807. float *q=book->valuelist+nt->q[ptr];
  114808. for(k=0,o=0;k<dim;k++,o+=step)
  114809. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  114810. if(c>0.f) /* in A */
  114811. ptr= -nt->ptr0[ptr];
  114812. else /* in B */
  114813. ptr= -nt->ptr1[ptr];
  114814. if(ptr<=0)break;
  114815. }
  114816. return(-ptr);
  114817. }
  114818. #endif
  114819. /* brute force it! */
  114820. {
  114821. const static_codebook *c=book->c;
  114822. int i,besti=-1;
  114823. float best=0.f;
  114824. float *e=book->valuelist;
  114825. for(i=0;i<book->entries;i++){
  114826. if(c->lengthlist[i]>0){
  114827. float thisx=_dist(dim,e,a,step);
  114828. if(besti==-1 || thisx<best){
  114829. best=thisx;
  114830. besti=i;
  114831. }
  114832. }
  114833. e+=dim;
  114834. }
  114835. /*if(savebest!=-1 && savebest!=besti){
  114836. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  114837. "original:");
  114838. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  114839. fprintf(stderr,"\n"
  114840. "pigeonhole (entry %d, err %g):",savebest,saverr);
  114841. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114842. (book->valuelist+savebest*dim)[i]);
  114843. fprintf(stderr,"\n"
  114844. "bruteforce (entry %d, err %g):",besti,best);
  114845. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  114846. (book->valuelist+besti*dim)[i]);
  114847. fprintf(stderr,"\n");
  114848. }*/
  114849. return(besti);
  114850. }
  114851. }
  114852. long vorbis_book_codeword(codebook *book,int entry){
  114853. if(book->c) /* only use with encode; decode optimizations are
  114854. allowed to break this */
  114855. return book->codelist[entry];
  114856. return -1;
  114857. }
  114858. long vorbis_book_codelen(codebook *book,int entry){
  114859. if(book->c) /* only use with encode; decode optimizations are
  114860. allowed to break this */
  114861. return book->c->lengthlist[entry];
  114862. return -1;
  114863. }
  114864. #ifdef _V_SELFTEST
  114865. /* Unit tests of the dequantizer; this stuff will be OK
  114866. cross-platform, I simply want to be sure that special mapping cases
  114867. actually work properly; a bug could go unnoticed for a while */
  114868. #include <stdio.h>
  114869. /* cases:
  114870. no mapping
  114871. full, explicit mapping
  114872. algorithmic mapping
  114873. nonsequential
  114874. sequential
  114875. */
  114876. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  114877. static long partial_quantlist1[]={0,7,2};
  114878. /* no mapping */
  114879. static_codebook test1={
  114880. 4,16,
  114881. NULL,
  114882. 0,
  114883. 0,0,0,0,
  114884. NULL,
  114885. NULL,NULL
  114886. };
  114887. static float *test1_result=NULL;
  114888. /* linear, full mapping, nonsequential */
  114889. static_codebook test2={
  114890. 4,3,
  114891. NULL,
  114892. 2,
  114893. -533200896,1611661312,4,0,
  114894. full_quantlist1,
  114895. NULL,NULL
  114896. };
  114897. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  114898. /* linear, full mapping, sequential */
  114899. static_codebook test3={
  114900. 4,3,
  114901. NULL,
  114902. 2,
  114903. -533200896,1611661312,4,1,
  114904. full_quantlist1,
  114905. NULL,NULL
  114906. };
  114907. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  114908. /* linear, algorithmic mapping, nonsequential */
  114909. static_codebook test4={
  114910. 3,27,
  114911. NULL,
  114912. 1,
  114913. -533200896,1611661312,4,0,
  114914. partial_quantlist1,
  114915. NULL,NULL
  114916. };
  114917. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  114918. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  114919. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  114920. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  114921. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  114922. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  114923. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  114924. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  114925. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  114926. /* linear, algorithmic mapping, sequential */
  114927. static_codebook test5={
  114928. 3,27,
  114929. NULL,
  114930. 1,
  114931. -533200896,1611661312,4,1,
  114932. partial_quantlist1,
  114933. NULL,NULL
  114934. };
  114935. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  114936. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  114937. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  114938. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  114939. -3, 1, 5, 4, 8,12, -1, 3, 7,
  114940. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  114941. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  114942. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  114943. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  114944. void run_test(static_codebook *b,float *comp){
  114945. float *out=_book_unquantize(b,b->entries,NULL);
  114946. int i;
  114947. if(comp){
  114948. if(!out){
  114949. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  114950. exit(1);
  114951. }
  114952. for(i=0;i<b->entries*b->dim;i++)
  114953. if(fabs(out[i]-comp[i])>.0001){
  114954. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  114955. "position %d, %g != %g\n",i,out[i],comp[i]);
  114956. exit(1);
  114957. }
  114958. }else{
  114959. if(out){
  114960. fprintf(stderr,"_book_unquantize returned a value array: \n"
  114961. " correct result should have been NULL\n");
  114962. exit(1);
  114963. }
  114964. }
  114965. }
  114966. int main(){
  114967. /* run the nine dequant tests, and compare to the hand-rolled results */
  114968. fprintf(stderr,"Dequant test 1... ");
  114969. run_test(&test1,test1_result);
  114970. fprintf(stderr,"OK\nDequant test 2... ");
  114971. run_test(&test2,test2_result);
  114972. fprintf(stderr,"OK\nDequant test 3... ");
  114973. run_test(&test3,test3_result);
  114974. fprintf(stderr,"OK\nDequant test 4... ");
  114975. run_test(&test4,test4_result);
  114976. fprintf(stderr,"OK\nDequant test 5... ");
  114977. run_test(&test5,test5_result);
  114978. fprintf(stderr,"OK\n\n");
  114979. return(0);
  114980. }
  114981. #endif
  114982. #endif
  114983. /********* End of inlined file: sharedbook.c *********/
  114984. /********* Start of inlined file: smallft.c *********/
  114985. /* FFT implementation from OggSquish, minus cosine transforms,
  114986. * minus all but radix 2/4 case. In Vorbis we only need this
  114987. * cut-down version.
  114988. *
  114989. * To do more than just power-of-two sized vectors, see the full
  114990. * version I wrote for NetLib.
  114991. *
  114992. * Note that the packing is a little strange; rather than the FFT r/i
  114993. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  114994. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  114995. * FORTRAN version
  114996. */
  114997. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114998. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114999. // tasks..
  115000. #ifdef _MSC_VER
  115001. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115002. #endif
  115003. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115004. #if JUCE_USE_OGGVORBIS
  115005. #include <stdlib.h>
  115006. #include <string.h>
  115007. #include <math.h>
  115008. static void drfti1(int n, float *wa, int *ifac){
  115009. static int ntryh[4] = { 4,2,3,5 };
  115010. static float tpi = 6.28318530717958648f;
  115011. float arg,argh,argld,fi;
  115012. int ntry=0,i,j=-1;
  115013. int k1, l1, l2, ib;
  115014. int ld, ii, ip, is, nq, nr;
  115015. int ido, ipm, nfm1;
  115016. int nl=n;
  115017. int nf=0;
  115018. L101:
  115019. j++;
  115020. if (j < 4)
  115021. ntry=ntryh[j];
  115022. else
  115023. ntry+=2;
  115024. L104:
  115025. nq=nl/ntry;
  115026. nr=nl-ntry*nq;
  115027. if (nr!=0) goto L101;
  115028. nf++;
  115029. ifac[nf+1]=ntry;
  115030. nl=nq;
  115031. if(ntry!=2)goto L107;
  115032. if(nf==1)goto L107;
  115033. for (i=1;i<nf;i++){
  115034. ib=nf-i+1;
  115035. ifac[ib+1]=ifac[ib];
  115036. }
  115037. ifac[2] = 2;
  115038. L107:
  115039. if(nl!=1)goto L104;
  115040. ifac[0]=n;
  115041. ifac[1]=nf;
  115042. argh=tpi/n;
  115043. is=0;
  115044. nfm1=nf-1;
  115045. l1=1;
  115046. if(nfm1==0)return;
  115047. for (k1=0;k1<nfm1;k1++){
  115048. ip=ifac[k1+2];
  115049. ld=0;
  115050. l2=l1*ip;
  115051. ido=n/l2;
  115052. ipm=ip-1;
  115053. for (j=0;j<ipm;j++){
  115054. ld+=l1;
  115055. i=is;
  115056. argld=(float)ld*argh;
  115057. fi=0.f;
  115058. for (ii=2;ii<ido;ii+=2){
  115059. fi+=1.f;
  115060. arg=fi*argld;
  115061. wa[i++]=cos(arg);
  115062. wa[i++]=sin(arg);
  115063. }
  115064. is+=ido;
  115065. }
  115066. l1=l2;
  115067. }
  115068. }
  115069. static void fdrffti(int n, float *wsave, int *ifac){
  115070. if (n == 1) return;
  115071. drfti1(n, wsave+n, ifac);
  115072. }
  115073. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  115074. int i,k;
  115075. float ti2,tr2;
  115076. int t0,t1,t2,t3,t4,t5,t6;
  115077. t1=0;
  115078. t0=(t2=l1*ido);
  115079. t3=ido<<1;
  115080. for(k=0;k<l1;k++){
  115081. ch[t1<<1]=cc[t1]+cc[t2];
  115082. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  115083. t1+=ido;
  115084. t2+=ido;
  115085. }
  115086. if(ido<2)return;
  115087. if(ido==2)goto L105;
  115088. t1=0;
  115089. t2=t0;
  115090. for(k=0;k<l1;k++){
  115091. t3=t2;
  115092. t4=(t1<<1)+(ido<<1);
  115093. t5=t1;
  115094. t6=t1+t1;
  115095. for(i=2;i<ido;i+=2){
  115096. t3+=2;
  115097. t4-=2;
  115098. t5+=2;
  115099. t6+=2;
  115100. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115101. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115102. ch[t6]=cc[t5]+ti2;
  115103. ch[t4]=ti2-cc[t5];
  115104. ch[t6-1]=cc[t5-1]+tr2;
  115105. ch[t4-1]=cc[t5-1]-tr2;
  115106. }
  115107. t1+=ido;
  115108. t2+=ido;
  115109. }
  115110. if(ido%2==1)return;
  115111. L105:
  115112. t3=(t2=(t1=ido)-1);
  115113. t2+=t0;
  115114. for(k=0;k<l1;k++){
  115115. ch[t1]=-cc[t2];
  115116. ch[t1-1]=cc[t3];
  115117. t1+=ido<<1;
  115118. t2+=ido;
  115119. t3+=ido;
  115120. }
  115121. }
  115122. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  115123. float *wa2,float *wa3){
  115124. static float hsqt2 = .70710678118654752f;
  115125. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115126. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115127. t0=l1*ido;
  115128. t1=t0;
  115129. t4=t1<<1;
  115130. t2=t1+(t1<<1);
  115131. t3=0;
  115132. for(k=0;k<l1;k++){
  115133. tr1=cc[t1]+cc[t2];
  115134. tr2=cc[t3]+cc[t4];
  115135. ch[t5=t3<<2]=tr1+tr2;
  115136. ch[(ido<<2)+t5-1]=tr2-tr1;
  115137. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  115138. ch[t5]=cc[t2]-cc[t1];
  115139. t1+=ido;
  115140. t2+=ido;
  115141. t3+=ido;
  115142. t4+=ido;
  115143. }
  115144. if(ido<2)return;
  115145. if(ido==2)goto L105;
  115146. t1=0;
  115147. for(k=0;k<l1;k++){
  115148. t2=t1;
  115149. t4=t1<<2;
  115150. t5=(t6=ido<<1)+t4;
  115151. for(i=2;i<ido;i+=2){
  115152. t3=(t2+=2);
  115153. t4+=2;
  115154. t5-=2;
  115155. t3+=t0;
  115156. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  115157. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  115158. t3+=t0;
  115159. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  115160. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  115161. t3+=t0;
  115162. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  115163. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  115164. tr1=cr2+cr4;
  115165. tr4=cr4-cr2;
  115166. ti1=ci2+ci4;
  115167. ti4=ci2-ci4;
  115168. ti2=cc[t2]+ci3;
  115169. ti3=cc[t2]-ci3;
  115170. tr2=cc[t2-1]+cr3;
  115171. tr3=cc[t2-1]-cr3;
  115172. ch[t4-1]=tr1+tr2;
  115173. ch[t4]=ti1+ti2;
  115174. ch[t5-1]=tr3-ti4;
  115175. ch[t5]=tr4-ti3;
  115176. ch[t4+t6-1]=ti4+tr3;
  115177. ch[t4+t6]=tr4+ti3;
  115178. ch[t5+t6-1]=tr2-tr1;
  115179. ch[t5+t6]=ti1-ti2;
  115180. }
  115181. t1+=ido;
  115182. }
  115183. if(ido&1)return;
  115184. L105:
  115185. t2=(t1=t0+ido-1)+(t0<<1);
  115186. t3=ido<<2;
  115187. t4=ido;
  115188. t5=ido<<1;
  115189. t6=ido;
  115190. for(k=0;k<l1;k++){
  115191. ti1=-hsqt2*(cc[t1]+cc[t2]);
  115192. tr1=hsqt2*(cc[t1]-cc[t2]);
  115193. ch[t4-1]=tr1+cc[t6-1];
  115194. ch[t4+t5-1]=cc[t6-1]-tr1;
  115195. ch[t4]=ti1-cc[t1+t0];
  115196. ch[t4+t5]=ti1+cc[t1+t0];
  115197. t1+=ido;
  115198. t2+=ido;
  115199. t4+=t3;
  115200. t6+=ido;
  115201. }
  115202. }
  115203. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115204. float *c2,float *ch,float *ch2,float *wa){
  115205. static float tpi=6.283185307179586f;
  115206. int idij,ipph,i,j,k,l,ic,ik,is;
  115207. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115208. float dc2,ai1,ai2,ar1,ar2,ds2;
  115209. int nbd;
  115210. float dcp,arg,dsp,ar1h,ar2h;
  115211. int idp2,ipp2;
  115212. arg=tpi/(float)ip;
  115213. dcp=cos(arg);
  115214. dsp=sin(arg);
  115215. ipph=(ip+1)>>1;
  115216. ipp2=ip;
  115217. idp2=ido;
  115218. nbd=(ido-1)>>1;
  115219. t0=l1*ido;
  115220. t10=ip*ido;
  115221. if(ido==1)goto L119;
  115222. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  115223. t1=0;
  115224. for(j=1;j<ip;j++){
  115225. t1+=t0;
  115226. t2=t1;
  115227. for(k=0;k<l1;k++){
  115228. ch[t2]=c1[t2];
  115229. t2+=ido;
  115230. }
  115231. }
  115232. is=-ido;
  115233. t1=0;
  115234. if(nbd>l1){
  115235. for(j=1;j<ip;j++){
  115236. t1+=t0;
  115237. is+=ido;
  115238. t2= -ido+t1;
  115239. for(k=0;k<l1;k++){
  115240. idij=is-1;
  115241. t2+=ido;
  115242. t3=t2;
  115243. for(i=2;i<ido;i+=2){
  115244. idij+=2;
  115245. t3+=2;
  115246. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115247. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115248. }
  115249. }
  115250. }
  115251. }else{
  115252. for(j=1;j<ip;j++){
  115253. is+=ido;
  115254. idij=is-1;
  115255. t1+=t0;
  115256. t2=t1;
  115257. for(i=2;i<ido;i+=2){
  115258. idij+=2;
  115259. t2+=2;
  115260. t3=t2;
  115261. for(k=0;k<l1;k++){
  115262. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  115263. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  115264. t3+=ido;
  115265. }
  115266. }
  115267. }
  115268. }
  115269. t1=0;
  115270. t2=ipp2*t0;
  115271. if(nbd<l1){
  115272. for(j=1;j<ipph;j++){
  115273. t1+=t0;
  115274. t2-=t0;
  115275. t3=t1;
  115276. t4=t2;
  115277. for(i=2;i<ido;i+=2){
  115278. t3+=2;
  115279. t4+=2;
  115280. t5=t3-ido;
  115281. t6=t4-ido;
  115282. for(k=0;k<l1;k++){
  115283. t5+=ido;
  115284. t6+=ido;
  115285. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115286. c1[t6-1]=ch[t5]-ch[t6];
  115287. c1[t5]=ch[t5]+ch[t6];
  115288. c1[t6]=ch[t6-1]-ch[t5-1];
  115289. }
  115290. }
  115291. }
  115292. }else{
  115293. for(j=1;j<ipph;j++){
  115294. t1+=t0;
  115295. t2-=t0;
  115296. t3=t1;
  115297. t4=t2;
  115298. for(k=0;k<l1;k++){
  115299. t5=t3;
  115300. t6=t4;
  115301. for(i=2;i<ido;i+=2){
  115302. t5+=2;
  115303. t6+=2;
  115304. c1[t5-1]=ch[t5-1]+ch[t6-1];
  115305. c1[t6-1]=ch[t5]-ch[t6];
  115306. c1[t5]=ch[t5]+ch[t6];
  115307. c1[t6]=ch[t6-1]-ch[t5-1];
  115308. }
  115309. t3+=ido;
  115310. t4+=ido;
  115311. }
  115312. }
  115313. }
  115314. L119:
  115315. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115316. t1=0;
  115317. t2=ipp2*idl1;
  115318. for(j=1;j<ipph;j++){
  115319. t1+=t0;
  115320. t2-=t0;
  115321. t3=t1-ido;
  115322. t4=t2-ido;
  115323. for(k=0;k<l1;k++){
  115324. t3+=ido;
  115325. t4+=ido;
  115326. c1[t3]=ch[t3]+ch[t4];
  115327. c1[t4]=ch[t4]-ch[t3];
  115328. }
  115329. }
  115330. ar1=1.f;
  115331. ai1=0.f;
  115332. t1=0;
  115333. t2=ipp2*idl1;
  115334. t3=(ip-1)*idl1;
  115335. for(l=1;l<ipph;l++){
  115336. t1+=idl1;
  115337. t2-=idl1;
  115338. ar1h=dcp*ar1-dsp*ai1;
  115339. ai1=dcp*ai1+dsp*ar1;
  115340. ar1=ar1h;
  115341. t4=t1;
  115342. t5=t2;
  115343. t6=t3;
  115344. t7=idl1;
  115345. for(ik=0;ik<idl1;ik++){
  115346. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  115347. ch2[t5++]=ai1*c2[t6++];
  115348. }
  115349. dc2=ar1;
  115350. ds2=ai1;
  115351. ar2=ar1;
  115352. ai2=ai1;
  115353. t4=idl1;
  115354. t5=(ipp2-1)*idl1;
  115355. for(j=2;j<ipph;j++){
  115356. t4+=idl1;
  115357. t5-=idl1;
  115358. ar2h=dc2*ar2-ds2*ai2;
  115359. ai2=dc2*ai2+ds2*ar2;
  115360. ar2=ar2h;
  115361. t6=t1;
  115362. t7=t2;
  115363. t8=t4;
  115364. t9=t5;
  115365. for(ik=0;ik<idl1;ik++){
  115366. ch2[t6++]+=ar2*c2[t8++];
  115367. ch2[t7++]+=ai2*c2[t9++];
  115368. }
  115369. }
  115370. }
  115371. t1=0;
  115372. for(j=1;j<ipph;j++){
  115373. t1+=idl1;
  115374. t2=t1;
  115375. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  115376. }
  115377. if(ido<l1)goto L132;
  115378. t1=0;
  115379. t2=0;
  115380. for(k=0;k<l1;k++){
  115381. t3=t1;
  115382. t4=t2;
  115383. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  115384. t1+=ido;
  115385. t2+=t10;
  115386. }
  115387. goto L135;
  115388. L132:
  115389. for(i=0;i<ido;i++){
  115390. t1=i;
  115391. t2=i;
  115392. for(k=0;k<l1;k++){
  115393. cc[t2]=ch[t1];
  115394. t1+=ido;
  115395. t2+=t10;
  115396. }
  115397. }
  115398. L135:
  115399. t1=0;
  115400. t2=ido<<1;
  115401. t3=0;
  115402. t4=ipp2*t0;
  115403. for(j=1;j<ipph;j++){
  115404. t1+=t2;
  115405. t3+=t0;
  115406. t4-=t0;
  115407. t5=t1;
  115408. t6=t3;
  115409. t7=t4;
  115410. for(k=0;k<l1;k++){
  115411. cc[t5-1]=ch[t6];
  115412. cc[t5]=ch[t7];
  115413. t5+=t10;
  115414. t6+=ido;
  115415. t7+=ido;
  115416. }
  115417. }
  115418. if(ido==1)return;
  115419. if(nbd<l1)goto L141;
  115420. t1=-ido;
  115421. t3=0;
  115422. t4=0;
  115423. t5=ipp2*t0;
  115424. for(j=1;j<ipph;j++){
  115425. t1+=t2;
  115426. t3+=t2;
  115427. t4+=t0;
  115428. t5-=t0;
  115429. t6=t1;
  115430. t7=t3;
  115431. t8=t4;
  115432. t9=t5;
  115433. for(k=0;k<l1;k++){
  115434. for(i=2;i<ido;i+=2){
  115435. ic=idp2-i;
  115436. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  115437. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  115438. cc[i+t7]=ch[i+t8]+ch[i+t9];
  115439. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  115440. }
  115441. t6+=t10;
  115442. t7+=t10;
  115443. t8+=ido;
  115444. t9+=ido;
  115445. }
  115446. }
  115447. return;
  115448. L141:
  115449. t1=-ido;
  115450. t3=0;
  115451. t4=0;
  115452. t5=ipp2*t0;
  115453. for(j=1;j<ipph;j++){
  115454. t1+=t2;
  115455. t3+=t2;
  115456. t4+=t0;
  115457. t5-=t0;
  115458. for(i=2;i<ido;i+=2){
  115459. t6=idp2+t1-i;
  115460. t7=i+t3;
  115461. t8=i+t4;
  115462. t9=i+t5;
  115463. for(k=0;k<l1;k++){
  115464. cc[t7-1]=ch[t8-1]+ch[t9-1];
  115465. cc[t6-1]=ch[t8-1]-ch[t9-1];
  115466. cc[t7]=ch[t8]+ch[t9];
  115467. cc[t6]=ch[t9]-ch[t8];
  115468. t6+=t10;
  115469. t7+=t10;
  115470. t8+=ido;
  115471. t9+=ido;
  115472. }
  115473. }
  115474. }
  115475. }
  115476. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  115477. int i,k1,l1,l2;
  115478. int na,kh,nf;
  115479. int ip,iw,ido,idl1,ix2,ix3;
  115480. nf=ifac[1];
  115481. na=1;
  115482. l2=n;
  115483. iw=n;
  115484. for(k1=0;k1<nf;k1++){
  115485. kh=nf-k1;
  115486. ip=ifac[kh+1];
  115487. l1=l2/ip;
  115488. ido=n/l2;
  115489. idl1=ido*l1;
  115490. iw-=(ip-1)*ido;
  115491. na=1-na;
  115492. if(ip!=4)goto L102;
  115493. ix2=iw+ido;
  115494. ix3=ix2+ido;
  115495. if(na!=0)
  115496. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115497. else
  115498. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  115499. goto L110;
  115500. L102:
  115501. if(ip!=2)goto L104;
  115502. if(na!=0)goto L103;
  115503. dradf2(ido,l1,c,ch,wa+iw-1);
  115504. goto L110;
  115505. L103:
  115506. dradf2(ido,l1,ch,c,wa+iw-1);
  115507. goto L110;
  115508. L104:
  115509. if(ido==1)na=1-na;
  115510. if(na!=0)goto L109;
  115511. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  115512. na=1;
  115513. goto L110;
  115514. L109:
  115515. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  115516. na=0;
  115517. L110:
  115518. l2=l1;
  115519. }
  115520. if(na==1)return;
  115521. for(i=0;i<n;i++)c[i]=ch[i];
  115522. }
  115523. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  115524. int i,k,t0,t1,t2,t3,t4,t5,t6;
  115525. float ti2,tr2;
  115526. t0=l1*ido;
  115527. t1=0;
  115528. t2=0;
  115529. t3=(ido<<1)-1;
  115530. for(k=0;k<l1;k++){
  115531. ch[t1]=cc[t2]+cc[t3+t2];
  115532. ch[t1+t0]=cc[t2]-cc[t3+t2];
  115533. t2=(t1+=ido)<<1;
  115534. }
  115535. if(ido<2)return;
  115536. if(ido==2)goto L105;
  115537. t1=0;
  115538. t2=0;
  115539. for(k=0;k<l1;k++){
  115540. t3=t1;
  115541. t5=(t4=t2)+(ido<<1);
  115542. t6=t0+t1;
  115543. for(i=2;i<ido;i+=2){
  115544. t3+=2;
  115545. t4+=2;
  115546. t5-=2;
  115547. t6+=2;
  115548. ch[t3-1]=cc[t4-1]+cc[t5-1];
  115549. tr2=cc[t4-1]-cc[t5-1];
  115550. ch[t3]=cc[t4]-cc[t5];
  115551. ti2=cc[t4]+cc[t5];
  115552. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  115553. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  115554. }
  115555. t2=(t1+=ido)<<1;
  115556. }
  115557. if(ido%2==1)return;
  115558. L105:
  115559. t1=ido-1;
  115560. t2=ido-1;
  115561. for(k=0;k<l1;k++){
  115562. ch[t1]=cc[t2]+cc[t2];
  115563. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  115564. t1+=ido;
  115565. t2+=ido<<1;
  115566. }
  115567. }
  115568. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  115569. float *wa2){
  115570. static float taur = -.5f;
  115571. static float taui = .8660254037844386f;
  115572. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  115573. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  115574. t0=l1*ido;
  115575. t1=0;
  115576. t2=t0<<1;
  115577. t3=ido<<1;
  115578. t4=ido+(ido<<1);
  115579. t5=0;
  115580. for(k=0;k<l1;k++){
  115581. tr2=cc[t3-1]+cc[t3-1];
  115582. cr2=cc[t5]+(taur*tr2);
  115583. ch[t1]=cc[t5]+tr2;
  115584. ci3=taui*(cc[t3]+cc[t3]);
  115585. ch[t1+t0]=cr2-ci3;
  115586. ch[t1+t2]=cr2+ci3;
  115587. t1+=ido;
  115588. t3+=t4;
  115589. t5+=t4;
  115590. }
  115591. if(ido==1)return;
  115592. t1=0;
  115593. t3=ido<<1;
  115594. for(k=0;k<l1;k++){
  115595. t7=t1+(t1<<1);
  115596. t6=(t5=t7+t3);
  115597. t8=t1;
  115598. t10=(t9=t1+t0)+t0;
  115599. for(i=2;i<ido;i+=2){
  115600. t5+=2;
  115601. t6-=2;
  115602. t7+=2;
  115603. t8+=2;
  115604. t9+=2;
  115605. t10+=2;
  115606. tr2=cc[t5-1]+cc[t6-1];
  115607. cr2=cc[t7-1]+(taur*tr2);
  115608. ch[t8-1]=cc[t7-1]+tr2;
  115609. ti2=cc[t5]-cc[t6];
  115610. ci2=cc[t7]+(taur*ti2);
  115611. ch[t8]=cc[t7]+ti2;
  115612. cr3=taui*(cc[t5-1]-cc[t6-1]);
  115613. ci3=taui*(cc[t5]+cc[t6]);
  115614. dr2=cr2-ci3;
  115615. dr3=cr2+ci3;
  115616. di2=ci2+cr3;
  115617. di3=ci2-cr3;
  115618. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  115619. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  115620. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  115621. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  115622. }
  115623. t1+=ido;
  115624. }
  115625. }
  115626. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  115627. float *wa2,float *wa3){
  115628. static float sqrt2=1.414213562373095f;
  115629. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  115630. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  115631. t0=l1*ido;
  115632. t1=0;
  115633. t2=ido<<2;
  115634. t3=0;
  115635. t6=ido<<1;
  115636. for(k=0;k<l1;k++){
  115637. t4=t3+t6;
  115638. t5=t1;
  115639. tr3=cc[t4-1]+cc[t4-1];
  115640. tr4=cc[t4]+cc[t4];
  115641. tr1=cc[t3]-cc[(t4+=t6)-1];
  115642. tr2=cc[t3]+cc[t4-1];
  115643. ch[t5]=tr2+tr3;
  115644. ch[t5+=t0]=tr1-tr4;
  115645. ch[t5+=t0]=tr2-tr3;
  115646. ch[t5+=t0]=tr1+tr4;
  115647. t1+=ido;
  115648. t3+=t2;
  115649. }
  115650. if(ido<2)return;
  115651. if(ido==2)goto L105;
  115652. t1=0;
  115653. for(k=0;k<l1;k++){
  115654. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  115655. t7=t1;
  115656. for(i=2;i<ido;i+=2){
  115657. t2+=2;
  115658. t3+=2;
  115659. t4-=2;
  115660. t5-=2;
  115661. t7+=2;
  115662. ti1=cc[t2]+cc[t5];
  115663. ti2=cc[t2]-cc[t5];
  115664. ti3=cc[t3]-cc[t4];
  115665. tr4=cc[t3]+cc[t4];
  115666. tr1=cc[t2-1]-cc[t5-1];
  115667. tr2=cc[t2-1]+cc[t5-1];
  115668. ti4=cc[t3-1]-cc[t4-1];
  115669. tr3=cc[t3-1]+cc[t4-1];
  115670. ch[t7-1]=tr2+tr3;
  115671. cr3=tr2-tr3;
  115672. ch[t7]=ti2+ti3;
  115673. ci3=ti2-ti3;
  115674. cr2=tr1-tr4;
  115675. cr4=tr1+tr4;
  115676. ci2=ti1+ti4;
  115677. ci4=ti1-ti4;
  115678. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  115679. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  115680. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  115681. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  115682. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  115683. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  115684. }
  115685. t1+=ido;
  115686. }
  115687. if(ido%2 == 1)return;
  115688. L105:
  115689. t1=ido;
  115690. t2=ido<<2;
  115691. t3=ido-1;
  115692. t4=ido+(ido<<1);
  115693. for(k=0;k<l1;k++){
  115694. t5=t3;
  115695. ti1=cc[t1]+cc[t4];
  115696. ti2=cc[t4]-cc[t1];
  115697. tr1=cc[t1-1]-cc[t4-1];
  115698. tr2=cc[t1-1]+cc[t4-1];
  115699. ch[t5]=tr2+tr2;
  115700. ch[t5+=t0]=sqrt2*(tr1-ti1);
  115701. ch[t5+=t0]=ti2+ti2;
  115702. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  115703. t3+=ido;
  115704. t1+=t2;
  115705. t4+=t2;
  115706. }
  115707. }
  115708. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  115709. float *c2,float *ch,float *ch2,float *wa){
  115710. static float tpi=6.283185307179586f;
  115711. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  115712. t11,t12;
  115713. float dc2,ai1,ai2,ar1,ar2,ds2;
  115714. int nbd;
  115715. float dcp,arg,dsp,ar1h,ar2h;
  115716. int ipp2;
  115717. t10=ip*ido;
  115718. t0=l1*ido;
  115719. arg=tpi/(float)ip;
  115720. dcp=cos(arg);
  115721. dsp=sin(arg);
  115722. nbd=(ido-1)>>1;
  115723. ipp2=ip;
  115724. ipph=(ip+1)>>1;
  115725. if(ido<l1)goto L103;
  115726. t1=0;
  115727. t2=0;
  115728. for(k=0;k<l1;k++){
  115729. t3=t1;
  115730. t4=t2;
  115731. for(i=0;i<ido;i++){
  115732. ch[t3]=cc[t4];
  115733. t3++;
  115734. t4++;
  115735. }
  115736. t1+=ido;
  115737. t2+=t10;
  115738. }
  115739. goto L106;
  115740. L103:
  115741. t1=0;
  115742. for(i=0;i<ido;i++){
  115743. t2=t1;
  115744. t3=t1;
  115745. for(k=0;k<l1;k++){
  115746. ch[t2]=cc[t3];
  115747. t2+=ido;
  115748. t3+=t10;
  115749. }
  115750. t1++;
  115751. }
  115752. L106:
  115753. t1=0;
  115754. t2=ipp2*t0;
  115755. t7=(t5=ido<<1);
  115756. for(j=1;j<ipph;j++){
  115757. t1+=t0;
  115758. t2-=t0;
  115759. t3=t1;
  115760. t4=t2;
  115761. t6=t5;
  115762. for(k=0;k<l1;k++){
  115763. ch[t3]=cc[t6-1]+cc[t6-1];
  115764. ch[t4]=cc[t6]+cc[t6];
  115765. t3+=ido;
  115766. t4+=ido;
  115767. t6+=t10;
  115768. }
  115769. t5+=t7;
  115770. }
  115771. if (ido == 1)goto L116;
  115772. if(nbd<l1)goto L112;
  115773. t1=0;
  115774. t2=ipp2*t0;
  115775. t7=0;
  115776. for(j=1;j<ipph;j++){
  115777. t1+=t0;
  115778. t2-=t0;
  115779. t3=t1;
  115780. t4=t2;
  115781. t7+=(ido<<1);
  115782. t8=t7;
  115783. for(k=0;k<l1;k++){
  115784. t5=t3;
  115785. t6=t4;
  115786. t9=t8;
  115787. t11=t8;
  115788. for(i=2;i<ido;i+=2){
  115789. t5+=2;
  115790. t6+=2;
  115791. t9+=2;
  115792. t11-=2;
  115793. ch[t5-1]=cc[t9-1]+cc[t11-1];
  115794. ch[t6-1]=cc[t9-1]-cc[t11-1];
  115795. ch[t5]=cc[t9]-cc[t11];
  115796. ch[t6]=cc[t9]+cc[t11];
  115797. }
  115798. t3+=ido;
  115799. t4+=ido;
  115800. t8+=t10;
  115801. }
  115802. }
  115803. goto L116;
  115804. L112:
  115805. t1=0;
  115806. t2=ipp2*t0;
  115807. t7=0;
  115808. for(j=1;j<ipph;j++){
  115809. t1+=t0;
  115810. t2-=t0;
  115811. t3=t1;
  115812. t4=t2;
  115813. t7+=(ido<<1);
  115814. t8=t7;
  115815. t9=t7;
  115816. for(i=2;i<ido;i+=2){
  115817. t3+=2;
  115818. t4+=2;
  115819. t8+=2;
  115820. t9-=2;
  115821. t5=t3;
  115822. t6=t4;
  115823. t11=t8;
  115824. t12=t9;
  115825. for(k=0;k<l1;k++){
  115826. ch[t5-1]=cc[t11-1]+cc[t12-1];
  115827. ch[t6-1]=cc[t11-1]-cc[t12-1];
  115828. ch[t5]=cc[t11]-cc[t12];
  115829. ch[t6]=cc[t11]+cc[t12];
  115830. t5+=ido;
  115831. t6+=ido;
  115832. t11+=t10;
  115833. t12+=t10;
  115834. }
  115835. }
  115836. }
  115837. L116:
  115838. ar1=1.f;
  115839. ai1=0.f;
  115840. t1=0;
  115841. t9=(t2=ipp2*idl1);
  115842. t3=(ip-1)*idl1;
  115843. for(l=1;l<ipph;l++){
  115844. t1+=idl1;
  115845. t2-=idl1;
  115846. ar1h=dcp*ar1-dsp*ai1;
  115847. ai1=dcp*ai1+dsp*ar1;
  115848. ar1=ar1h;
  115849. t4=t1;
  115850. t5=t2;
  115851. t6=0;
  115852. t7=idl1;
  115853. t8=t3;
  115854. for(ik=0;ik<idl1;ik++){
  115855. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  115856. c2[t5++]=ai1*ch2[t8++];
  115857. }
  115858. dc2=ar1;
  115859. ds2=ai1;
  115860. ar2=ar1;
  115861. ai2=ai1;
  115862. t6=idl1;
  115863. t7=t9-idl1;
  115864. for(j=2;j<ipph;j++){
  115865. t6+=idl1;
  115866. t7-=idl1;
  115867. ar2h=dc2*ar2-ds2*ai2;
  115868. ai2=dc2*ai2+ds2*ar2;
  115869. ar2=ar2h;
  115870. t4=t1;
  115871. t5=t2;
  115872. t11=t6;
  115873. t12=t7;
  115874. for(ik=0;ik<idl1;ik++){
  115875. c2[t4++]+=ar2*ch2[t11++];
  115876. c2[t5++]+=ai2*ch2[t12++];
  115877. }
  115878. }
  115879. }
  115880. t1=0;
  115881. for(j=1;j<ipph;j++){
  115882. t1+=idl1;
  115883. t2=t1;
  115884. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  115885. }
  115886. t1=0;
  115887. t2=ipp2*t0;
  115888. for(j=1;j<ipph;j++){
  115889. t1+=t0;
  115890. t2-=t0;
  115891. t3=t1;
  115892. t4=t2;
  115893. for(k=0;k<l1;k++){
  115894. ch[t3]=c1[t3]-c1[t4];
  115895. ch[t4]=c1[t3]+c1[t4];
  115896. t3+=ido;
  115897. t4+=ido;
  115898. }
  115899. }
  115900. if(ido==1)goto L132;
  115901. if(nbd<l1)goto L128;
  115902. t1=0;
  115903. t2=ipp2*t0;
  115904. for(j=1;j<ipph;j++){
  115905. t1+=t0;
  115906. t2-=t0;
  115907. t3=t1;
  115908. t4=t2;
  115909. for(k=0;k<l1;k++){
  115910. t5=t3;
  115911. t6=t4;
  115912. for(i=2;i<ido;i+=2){
  115913. t5+=2;
  115914. t6+=2;
  115915. ch[t5-1]=c1[t5-1]-c1[t6];
  115916. ch[t6-1]=c1[t5-1]+c1[t6];
  115917. ch[t5]=c1[t5]+c1[t6-1];
  115918. ch[t6]=c1[t5]-c1[t6-1];
  115919. }
  115920. t3+=ido;
  115921. t4+=ido;
  115922. }
  115923. }
  115924. goto L132;
  115925. L128:
  115926. t1=0;
  115927. t2=ipp2*t0;
  115928. for(j=1;j<ipph;j++){
  115929. t1+=t0;
  115930. t2-=t0;
  115931. t3=t1;
  115932. t4=t2;
  115933. for(i=2;i<ido;i+=2){
  115934. t3+=2;
  115935. t4+=2;
  115936. t5=t3;
  115937. t6=t4;
  115938. for(k=0;k<l1;k++){
  115939. ch[t5-1]=c1[t5-1]-c1[t6];
  115940. ch[t6-1]=c1[t5-1]+c1[t6];
  115941. ch[t5]=c1[t5]+c1[t6-1];
  115942. ch[t6]=c1[t5]-c1[t6-1];
  115943. t5+=ido;
  115944. t6+=ido;
  115945. }
  115946. }
  115947. }
  115948. L132:
  115949. if(ido==1)return;
  115950. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  115951. t1=0;
  115952. for(j=1;j<ip;j++){
  115953. t2=(t1+=t0);
  115954. for(k=0;k<l1;k++){
  115955. c1[t2]=ch[t2];
  115956. t2+=ido;
  115957. }
  115958. }
  115959. if(nbd>l1)goto L139;
  115960. is= -ido-1;
  115961. t1=0;
  115962. for(j=1;j<ip;j++){
  115963. is+=ido;
  115964. t1+=t0;
  115965. idij=is;
  115966. t2=t1;
  115967. for(i=2;i<ido;i+=2){
  115968. t2+=2;
  115969. idij+=2;
  115970. t3=t2;
  115971. for(k=0;k<l1;k++){
  115972. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115973. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115974. t3+=ido;
  115975. }
  115976. }
  115977. }
  115978. return;
  115979. L139:
  115980. is= -ido-1;
  115981. t1=0;
  115982. for(j=1;j<ip;j++){
  115983. is+=ido;
  115984. t1+=t0;
  115985. t2=t1;
  115986. for(k=0;k<l1;k++){
  115987. idij=is;
  115988. t3=t2;
  115989. for(i=2;i<ido;i+=2){
  115990. idij+=2;
  115991. t3+=2;
  115992. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  115993. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  115994. }
  115995. t2+=ido;
  115996. }
  115997. }
  115998. }
  115999. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  116000. int i,k1,l1,l2;
  116001. int na;
  116002. int nf,ip,iw,ix2,ix3,ido,idl1;
  116003. nf=ifac[1];
  116004. na=0;
  116005. l1=1;
  116006. iw=1;
  116007. for(k1=0;k1<nf;k1++){
  116008. ip=ifac[k1 + 2];
  116009. l2=ip*l1;
  116010. ido=n/l2;
  116011. idl1=ido*l1;
  116012. if(ip!=4)goto L103;
  116013. ix2=iw+ido;
  116014. ix3=ix2+ido;
  116015. if(na!=0)
  116016. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116017. else
  116018. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  116019. na=1-na;
  116020. goto L115;
  116021. L103:
  116022. if(ip!=2)goto L106;
  116023. if(na!=0)
  116024. dradb2(ido,l1,ch,c,wa+iw-1);
  116025. else
  116026. dradb2(ido,l1,c,ch,wa+iw-1);
  116027. na=1-na;
  116028. goto L115;
  116029. L106:
  116030. if(ip!=3)goto L109;
  116031. ix2=iw+ido;
  116032. if(na!=0)
  116033. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  116034. else
  116035. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  116036. na=1-na;
  116037. goto L115;
  116038. L109:
  116039. /* The radix five case can be translated later..... */
  116040. /* if(ip!=5)goto L112;
  116041. ix2=iw+ido;
  116042. ix3=ix2+ido;
  116043. ix4=ix3+ido;
  116044. if(na!=0)
  116045. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116046. else
  116047. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  116048. na=1-na;
  116049. goto L115;
  116050. L112:*/
  116051. if(na!=0)
  116052. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  116053. else
  116054. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  116055. if(ido==1)na=1-na;
  116056. L115:
  116057. l1=l2;
  116058. iw+=(ip-1)*ido;
  116059. }
  116060. if(na==0)return;
  116061. for(i=0;i<n;i++)c[i]=ch[i];
  116062. }
  116063. void drft_forward(drft_lookup *l,float *data){
  116064. if(l->n==1)return;
  116065. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116066. }
  116067. void drft_backward(drft_lookup *l,float *data){
  116068. if (l->n==1)return;
  116069. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  116070. }
  116071. void drft_init(drft_lookup *l,int n){
  116072. l->n=n;
  116073. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  116074. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  116075. fdrffti(n, l->trigcache, l->splitcache);
  116076. }
  116077. void drft_clear(drft_lookup *l){
  116078. if(l){
  116079. if(l->trigcache)_ogg_free(l->trigcache);
  116080. if(l->splitcache)_ogg_free(l->splitcache);
  116081. memset(l,0,sizeof(*l));
  116082. }
  116083. }
  116084. #endif
  116085. /********* End of inlined file: smallft.c *********/
  116086. /********* Start of inlined file: synthesis.c *********/
  116087. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116088. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116089. // tasks..
  116090. #ifdef _MSC_VER
  116091. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116092. #endif
  116093. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116094. #if JUCE_USE_OGGVORBIS
  116095. #include <stdio.h>
  116096. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  116097. vorbis_dsp_state *vd=vb->vd;
  116098. private_state *b=(private_state*)vd->backend_state;
  116099. vorbis_info *vi=vd->vi;
  116100. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  116101. oggpack_buffer *opb=&vb->opb;
  116102. int type,mode,i;
  116103. /* first things first. Make sure decode is ready */
  116104. _vorbis_block_ripcord(vb);
  116105. oggpack_readinit(opb,op->packet,op->bytes);
  116106. /* Check the packet type */
  116107. if(oggpack_read(opb,1)!=0){
  116108. /* Oops. This is not an audio data packet */
  116109. return(OV_ENOTAUDIO);
  116110. }
  116111. /* read our mode and pre/post windowsize */
  116112. mode=oggpack_read(opb,b->modebits);
  116113. if(mode==-1)return(OV_EBADPACKET);
  116114. vb->mode=mode;
  116115. vb->W=ci->mode_param[mode]->blockflag;
  116116. if(vb->W){
  116117. /* this doesn;t get mapped through mode selection as it's used
  116118. only for window selection */
  116119. vb->lW=oggpack_read(opb,1);
  116120. vb->nW=oggpack_read(opb,1);
  116121. if(vb->nW==-1) return(OV_EBADPACKET);
  116122. }else{
  116123. vb->lW=0;
  116124. vb->nW=0;
  116125. }
  116126. /* more setup */
  116127. vb->granulepos=op->granulepos;
  116128. vb->sequence=op->packetno;
  116129. vb->eofflag=op->e_o_s;
  116130. /* alloc pcm passback storage */
  116131. vb->pcmend=ci->blocksizes[vb->W];
  116132. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  116133. for(i=0;i<vi->channels;i++)
  116134. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  116135. /* unpack_header enforces range checking */
  116136. type=ci->map_type[ci->mode_param[mode]->mapping];
  116137. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  116138. mapping]));
  116139. }
  116140. /* used to track pcm position without actually performing decode.
  116141. Useful for sequential 'fast forward' */
  116142. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  116143. vorbis_dsp_state *vd=vb->vd;
  116144. private_state *b=(private_state*)vd->backend_state;
  116145. vorbis_info *vi=vd->vi;
  116146. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116147. oggpack_buffer *opb=&vb->opb;
  116148. int mode;
  116149. /* first things first. Make sure decode is ready */
  116150. _vorbis_block_ripcord(vb);
  116151. oggpack_readinit(opb,op->packet,op->bytes);
  116152. /* Check the packet type */
  116153. if(oggpack_read(opb,1)!=0){
  116154. /* Oops. This is not an audio data packet */
  116155. return(OV_ENOTAUDIO);
  116156. }
  116157. /* read our mode and pre/post windowsize */
  116158. mode=oggpack_read(opb,b->modebits);
  116159. if(mode==-1)return(OV_EBADPACKET);
  116160. vb->mode=mode;
  116161. vb->W=ci->mode_param[mode]->blockflag;
  116162. if(vb->W){
  116163. vb->lW=oggpack_read(opb,1);
  116164. vb->nW=oggpack_read(opb,1);
  116165. if(vb->nW==-1) return(OV_EBADPACKET);
  116166. }else{
  116167. vb->lW=0;
  116168. vb->nW=0;
  116169. }
  116170. /* more setup */
  116171. vb->granulepos=op->granulepos;
  116172. vb->sequence=op->packetno;
  116173. vb->eofflag=op->e_o_s;
  116174. /* no pcm */
  116175. vb->pcmend=0;
  116176. vb->pcm=NULL;
  116177. return(0);
  116178. }
  116179. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  116180. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116181. oggpack_buffer opb;
  116182. int mode;
  116183. oggpack_readinit(&opb,op->packet,op->bytes);
  116184. /* Check the packet type */
  116185. if(oggpack_read(&opb,1)!=0){
  116186. /* Oops. This is not an audio data packet */
  116187. return(OV_ENOTAUDIO);
  116188. }
  116189. {
  116190. int modebits=0;
  116191. int v=ci->modes;
  116192. while(v>1){
  116193. modebits++;
  116194. v>>=1;
  116195. }
  116196. /* read our mode and pre/post windowsize */
  116197. mode=oggpack_read(&opb,modebits);
  116198. }
  116199. if(mode==-1)return(OV_EBADPACKET);
  116200. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  116201. }
  116202. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  116203. /* set / clear half-sample-rate mode */
  116204. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116205. /* right now, our MDCT can't handle < 64 sample windows. */
  116206. if(ci->blocksizes[0]<=64 && flag)return -1;
  116207. ci->halfrate_flag=(flag?1:0);
  116208. return 0;
  116209. }
  116210. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  116211. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116212. return ci->halfrate_flag;
  116213. }
  116214. #endif
  116215. /********* End of inlined file: synthesis.c *********/
  116216. /********* Start of inlined file: vorbisenc.c *********/
  116217. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  116218. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116219. // tasks..
  116220. #ifdef _MSC_VER
  116221. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116222. #endif
  116223. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116224. #if JUCE_USE_OGGVORBIS
  116225. #include <stdlib.h>
  116226. #include <string.h>
  116227. #include <math.h>
  116228. /* careful with this; it's using static array sizing to make managing
  116229. all the modes a little less annoying. If we use a residue backend
  116230. with > 12 partition types, or a different division of iteration,
  116231. this needs to be updated. */
  116232. typedef struct {
  116233. static_codebook *books[12][3];
  116234. } static_bookblock;
  116235. typedef struct {
  116236. int res_type;
  116237. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  116238. vorbis_info_residue0 *res;
  116239. static_codebook *book_aux;
  116240. static_codebook *book_aux_managed;
  116241. static_bookblock *books_base;
  116242. static_bookblock *books_base_managed;
  116243. } vorbis_residue_template;
  116244. typedef struct {
  116245. vorbis_info_mapping0 *map;
  116246. vorbis_residue_template *res;
  116247. } vorbis_mapping_template;
  116248. typedef struct vp_adjblock{
  116249. int block[P_BANDS];
  116250. } vp_adjblock;
  116251. typedef struct {
  116252. int data[NOISE_COMPAND_LEVELS];
  116253. } compandblock;
  116254. /* high level configuration information for setting things up
  116255. step-by-step with the detailed vorbis_encode_ctl interface.
  116256. There's a fair amount of redundancy such that interactive setup
  116257. does not directly deal with any vorbis_info or codec_setup_info
  116258. initialization; it's all stored (until full init) in this highlevel
  116259. setup, then flushed out to the real codec setup structs later. */
  116260. typedef struct {
  116261. int att[P_NOISECURVES];
  116262. float boost;
  116263. float decay;
  116264. } att3;
  116265. typedef struct { int data[P_NOISECURVES]; } adj3;
  116266. typedef struct {
  116267. int pre[PACKETBLOBS];
  116268. int post[PACKETBLOBS];
  116269. float kHz[PACKETBLOBS];
  116270. float lowpasskHz[PACKETBLOBS];
  116271. } adj_stereo;
  116272. typedef struct {
  116273. int lo;
  116274. int hi;
  116275. int fixed;
  116276. } noiseguard;
  116277. typedef struct {
  116278. int data[P_NOISECURVES][17];
  116279. } noise3;
  116280. typedef struct {
  116281. int mappings;
  116282. double *rate_mapping;
  116283. double *quality_mapping;
  116284. int coupling_restriction;
  116285. long samplerate_min_restriction;
  116286. long samplerate_max_restriction;
  116287. int *blocksize_short;
  116288. int *blocksize_long;
  116289. att3 *psy_tone_masteratt;
  116290. int *psy_tone_0dB;
  116291. int *psy_tone_dBsuppress;
  116292. vp_adjblock *psy_tone_adj_impulse;
  116293. vp_adjblock *psy_tone_adj_long;
  116294. vp_adjblock *psy_tone_adj_other;
  116295. noiseguard *psy_noiseguards;
  116296. noise3 *psy_noise_bias_impulse;
  116297. noise3 *psy_noise_bias_padding;
  116298. noise3 *psy_noise_bias_trans;
  116299. noise3 *psy_noise_bias_long;
  116300. int *psy_noise_dBsuppress;
  116301. compandblock *psy_noise_compand;
  116302. double *psy_noise_compand_short_mapping;
  116303. double *psy_noise_compand_long_mapping;
  116304. int *psy_noise_normal_start[2];
  116305. int *psy_noise_normal_partition[2];
  116306. double *psy_noise_normal_thresh;
  116307. int *psy_ath_float;
  116308. int *psy_ath_abs;
  116309. double *psy_lowpass;
  116310. vorbis_info_psy_global *global_params;
  116311. double *global_mapping;
  116312. adj_stereo *stereo_modes;
  116313. static_codebook ***floor_books;
  116314. vorbis_info_floor1 *floor_params;
  116315. int *floor_short_mapping;
  116316. int *floor_long_mapping;
  116317. vorbis_mapping_template *maps;
  116318. } ve_setup_data_template;
  116319. /* a few static coder conventions */
  116320. static vorbis_info_mode _mode_template[2]={
  116321. {0,0,0,0},
  116322. {1,0,0,1}
  116323. };
  116324. static vorbis_info_mapping0 _map_nominal[2]={
  116325. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  116326. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  116327. };
  116328. /********* Start of inlined file: setup_44.h *********/
  116329. /********* Start of inlined file: floor_all.h *********/
  116330. /********* Start of inlined file: floor_books.h *********/
  116331. static long _huff_lengthlist_line_256x7_0sub1[] = {
  116332. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  116333. };
  116334. static static_codebook _huff_book_line_256x7_0sub1 = {
  116335. 1, 9,
  116336. _huff_lengthlist_line_256x7_0sub1,
  116337. 0, 0, 0, 0, 0,
  116338. NULL,
  116339. NULL,
  116340. NULL,
  116341. NULL,
  116342. 0
  116343. };
  116344. static long _huff_lengthlist_line_256x7_0sub2[] = {
  116345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  116346. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  116347. };
  116348. static static_codebook _huff_book_line_256x7_0sub2 = {
  116349. 1, 25,
  116350. _huff_lengthlist_line_256x7_0sub2,
  116351. 0, 0, 0, 0, 0,
  116352. NULL,
  116353. NULL,
  116354. NULL,
  116355. NULL,
  116356. 0
  116357. };
  116358. static long _huff_lengthlist_line_256x7_0sub3[] = {
  116359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  116361. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  116362. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  116363. };
  116364. static static_codebook _huff_book_line_256x7_0sub3 = {
  116365. 1, 64,
  116366. _huff_lengthlist_line_256x7_0sub3,
  116367. 0, 0, 0, 0, 0,
  116368. NULL,
  116369. NULL,
  116370. NULL,
  116371. NULL,
  116372. 0
  116373. };
  116374. static long _huff_lengthlist_line_256x7_1sub1[] = {
  116375. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  116376. };
  116377. static static_codebook _huff_book_line_256x7_1sub1 = {
  116378. 1, 9,
  116379. _huff_lengthlist_line_256x7_1sub1,
  116380. 0, 0, 0, 0, 0,
  116381. NULL,
  116382. NULL,
  116383. NULL,
  116384. NULL,
  116385. 0
  116386. };
  116387. static long _huff_lengthlist_line_256x7_1sub2[] = {
  116388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  116389. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  116390. };
  116391. static static_codebook _huff_book_line_256x7_1sub2 = {
  116392. 1, 25,
  116393. _huff_lengthlist_line_256x7_1sub2,
  116394. 0, 0, 0, 0, 0,
  116395. NULL,
  116396. NULL,
  116397. NULL,
  116398. NULL,
  116399. 0
  116400. };
  116401. static long _huff_lengthlist_line_256x7_1sub3[] = {
  116402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  116404. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116405. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  116406. };
  116407. static static_codebook _huff_book_line_256x7_1sub3 = {
  116408. 1, 64,
  116409. _huff_lengthlist_line_256x7_1sub3,
  116410. 0, 0, 0, 0, 0,
  116411. NULL,
  116412. NULL,
  116413. NULL,
  116414. NULL,
  116415. 0
  116416. };
  116417. static long _huff_lengthlist_line_256x7_class0[] = {
  116418. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  116419. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  116420. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  116421. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  116422. };
  116423. static static_codebook _huff_book_line_256x7_class0 = {
  116424. 1, 64,
  116425. _huff_lengthlist_line_256x7_class0,
  116426. 0, 0, 0, 0, 0,
  116427. NULL,
  116428. NULL,
  116429. NULL,
  116430. NULL,
  116431. 0
  116432. };
  116433. static long _huff_lengthlist_line_256x7_class1[] = {
  116434. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  116435. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  116436. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  116437. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  116438. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  116439. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  116440. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  116441. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  116442. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  116443. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  116444. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  116445. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  116446. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116447. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116448. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  116449. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  116450. };
  116451. static static_codebook _huff_book_line_256x7_class1 = {
  116452. 1, 256,
  116453. _huff_lengthlist_line_256x7_class1,
  116454. 0, 0, 0, 0, 0,
  116455. NULL,
  116456. NULL,
  116457. NULL,
  116458. NULL,
  116459. 0
  116460. };
  116461. static long _huff_lengthlist_line_512x17_0sub0[] = {
  116462. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  116463. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  116464. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  116465. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  116466. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  116467. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  116468. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  116469. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  116470. };
  116471. static static_codebook _huff_book_line_512x17_0sub0 = {
  116472. 1, 128,
  116473. _huff_lengthlist_line_512x17_0sub0,
  116474. 0, 0, 0, 0, 0,
  116475. NULL,
  116476. NULL,
  116477. NULL,
  116478. NULL,
  116479. 0
  116480. };
  116481. static long _huff_lengthlist_line_512x17_1sub0[] = {
  116482. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  116483. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  116484. };
  116485. static static_codebook _huff_book_line_512x17_1sub0 = {
  116486. 1, 32,
  116487. _huff_lengthlist_line_512x17_1sub0,
  116488. 0, 0, 0, 0, 0,
  116489. NULL,
  116490. NULL,
  116491. NULL,
  116492. NULL,
  116493. 0
  116494. };
  116495. static long _huff_lengthlist_line_512x17_1sub1[] = {
  116496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116498. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  116499. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  116500. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  116501. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  116502. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  116503. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  116504. };
  116505. static static_codebook _huff_book_line_512x17_1sub1 = {
  116506. 1, 128,
  116507. _huff_lengthlist_line_512x17_1sub1,
  116508. 0, 0, 0, 0, 0,
  116509. NULL,
  116510. NULL,
  116511. NULL,
  116512. NULL,
  116513. 0
  116514. };
  116515. static long _huff_lengthlist_line_512x17_2sub1[] = {
  116516. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  116517. 5, 3,
  116518. };
  116519. static static_codebook _huff_book_line_512x17_2sub1 = {
  116520. 1, 18,
  116521. _huff_lengthlist_line_512x17_2sub1,
  116522. 0, 0, 0, 0, 0,
  116523. NULL,
  116524. NULL,
  116525. NULL,
  116526. NULL,
  116527. 0
  116528. };
  116529. static long _huff_lengthlist_line_512x17_2sub2[] = {
  116530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116531. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  116532. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  116533. 9, 8,
  116534. };
  116535. static static_codebook _huff_book_line_512x17_2sub2 = {
  116536. 1, 50,
  116537. _huff_lengthlist_line_512x17_2sub2,
  116538. 0, 0, 0, 0, 0,
  116539. NULL,
  116540. NULL,
  116541. NULL,
  116542. NULL,
  116543. 0
  116544. };
  116545. static long _huff_lengthlist_line_512x17_2sub3[] = {
  116546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116549. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  116550. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  116551. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116552. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116553. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116554. };
  116555. static static_codebook _huff_book_line_512x17_2sub3 = {
  116556. 1, 128,
  116557. _huff_lengthlist_line_512x17_2sub3,
  116558. 0, 0, 0, 0, 0,
  116559. NULL,
  116560. NULL,
  116561. NULL,
  116562. NULL,
  116563. 0
  116564. };
  116565. static long _huff_lengthlist_line_512x17_3sub1[] = {
  116566. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  116567. 5, 5,
  116568. };
  116569. static static_codebook _huff_book_line_512x17_3sub1 = {
  116570. 1, 18,
  116571. _huff_lengthlist_line_512x17_3sub1,
  116572. 0, 0, 0, 0, 0,
  116573. NULL,
  116574. NULL,
  116575. NULL,
  116576. NULL,
  116577. 0
  116578. };
  116579. static long _huff_lengthlist_line_512x17_3sub2[] = {
  116580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116581. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  116582. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  116583. 11,14,
  116584. };
  116585. static static_codebook _huff_book_line_512x17_3sub2 = {
  116586. 1, 50,
  116587. _huff_lengthlist_line_512x17_3sub2,
  116588. 0, 0, 0, 0, 0,
  116589. NULL,
  116590. NULL,
  116591. NULL,
  116592. NULL,
  116593. 0
  116594. };
  116595. static long _huff_lengthlist_line_512x17_3sub3[] = {
  116596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116599. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  116600. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116601. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116602. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116603. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116604. };
  116605. static static_codebook _huff_book_line_512x17_3sub3 = {
  116606. 1, 128,
  116607. _huff_lengthlist_line_512x17_3sub3,
  116608. 0, 0, 0, 0, 0,
  116609. NULL,
  116610. NULL,
  116611. NULL,
  116612. NULL,
  116613. 0
  116614. };
  116615. static long _huff_lengthlist_line_512x17_class1[] = {
  116616. 1, 2, 3, 6, 5, 4, 7, 7,
  116617. };
  116618. static static_codebook _huff_book_line_512x17_class1 = {
  116619. 1, 8,
  116620. _huff_lengthlist_line_512x17_class1,
  116621. 0, 0, 0, 0, 0,
  116622. NULL,
  116623. NULL,
  116624. NULL,
  116625. NULL,
  116626. 0
  116627. };
  116628. static long _huff_lengthlist_line_512x17_class2[] = {
  116629. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  116630. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  116631. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  116632. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  116633. };
  116634. static static_codebook _huff_book_line_512x17_class2 = {
  116635. 1, 64,
  116636. _huff_lengthlist_line_512x17_class2,
  116637. 0, 0, 0, 0, 0,
  116638. NULL,
  116639. NULL,
  116640. NULL,
  116641. NULL,
  116642. 0
  116643. };
  116644. static long _huff_lengthlist_line_512x17_class3[] = {
  116645. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  116646. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  116647. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  116648. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  116649. };
  116650. static static_codebook _huff_book_line_512x17_class3 = {
  116651. 1, 64,
  116652. _huff_lengthlist_line_512x17_class3,
  116653. 0, 0, 0, 0, 0,
  116654. NULL,
  116655. NULL,
  116656. NULL,
  116657. NULL,
  116658. 0
  116659. };
  116660. static long _huff_lengthlist_line_128x4_class0[] = {
  116661. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  116662. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  116663. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  116664. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  116665. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  116666. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  116667. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  116668. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  116669. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  116670. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  116671. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  116672. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  116673. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  116674. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  116675. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  116676. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  116677. };
  116678. static static_codebook _huff_book_line_128x4_class0 = {
  116679. 1, 256,
  116680. _huff_lengthlist_line_128x4_class0,
  116681. 0, 0, 0, 0, 0,
  116682. NULL,
  116683. NULL,
  116684. NULL,
  116685. NULL,
  116686. 0
  116687. };
  116688. static long _huff_lengthlist_line_128x4_0sub0[] = {
  116689. 2, 2, 2, 2,
  116690. };
  116691. static static_codebook _huff_book_line_128x4_0sub0 = {
  116692. 1, 4,
  116693. _huff_lengthlist_line_128x4_0sub0,
  116694. 0, 0, 0, 0, 0,
  116695. NULL,
  116696. NULL,
  116697. NULL,
  116698. NULL,
  116699. 0
  116700. };
  116701. static long _huff_lengthlist_line_128x4_0sub1[] = {
  116702. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  116703. };
  116704. static static_codebook _huff_book_line_128x4_0sub1 = {
  116705. 1, 10,
  116706. _huff_lengthlist_line_128x4_0sub1,
  116707. 0, 0, 0, 0, 0,
  116708. NULL,
  116709. NULL,
  116710. NULL,
  116711. NULL,
  116712. 0
  116713. };
  116714. static long _huff_lengthlist_line_128x4_0sub2[] = {
  116715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  116716. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  116717. };
  116718. static static_codebook _huff_book_line_128x4_0sub2 = {
  116719. 1, 25,
  116720. _huff_lengthlist_line_128x4_0sub2,
  116721. 0, 0, 0, 0, 0,
  116722. NULL,
  116723. NULL,
  116724. NULL,
  116725. NULL,
  116726. 0
  116727. };
  116728. static long _huff_lengthlist_line_128x4_0sub3[] = {
  116729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116731. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  116732. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  116733. };
  116734. static static_codebook _huff_book_line_128x4_0sub3 = {
  116735. 1, 64,
  116736. _huff_lengthlist_line_128x4_0sub3,
  116737. 0, 0, 0, 0, 0,
  116738. NULL,
  116739. NULL,
  116740. NULL,
  116741. NULL,
  116742. 0
  116743. };
  116744. static long _huff_lengthlist_line_256x4_class0[] = {
  116745. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  116746. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  116747. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  116748. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  116749. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  116750. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  116751. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  116752. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  116753. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  116754. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  116755. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  116756. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  116757. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  116758. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  116759. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  116760. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  116761. };
  116762. static static_codebook _huff_book_line_256x4_class0 = {
  116763. 1, 256,
  116764. _huff_lengthlist_line_256x4_class0,
  116765. 0, 0, 0, 0, 0,
  116766. NULL,
  116767. NULL,
  116768. NULL,
  116769. NULL,
  116770. 0
  116771. };
  116772. static long _huff_lengthlist_line_256x4_0sub0[] = {
  116773. 2, 2, 2, 2,
  116774. };
  116775. static static_codebook _huff_book_line_256x4_0sub0 = {
  116776. 1, 4,
  116777. _huff_lengthlist_line_256x4_0sub0,
  116778. 0, 0, 0, 0, 0,
  116779. NULL,
  116780. NULL,
  116781. NULL,
  116782. NULL,
  116783. 0
  116784. };
  116785. static long _huff_lengthlist_line_256x4_0sub1[] = {
  116786. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  116787. };
  116788. static static_codebook _huff_book_line_256x4_0sub1 = {
  116789. 1, 10,
  116790. _huff_lengthlist_line_256x4_0sub1,
  116791. 0, 0, 0, 0, 0,
  116792. NULL,
  116793. NULL,
  116794. NULL,
  116795. NULL,
  116796. 0
  116797. };
  116798. static long _huff_lengthlist_line_256x4_0sub2[] = {
  116799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  116800. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  116801. };
  116802. static static_codebook _huff_book_line_256x4_0sub2 = {
  116803. 1, 25,
  116804. _huff_lengthlist_line_256x4_0sub2,
  116805. 0, 0, 0, 0, 0,
  116806. NULL,
  116807. NULL,
  116808. NULL,
  116809. NULL,
  116810. 0
  116811. };
  116812. static long _huff_lengthlist_line_256x4_0sub3[] = {
  116813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  116815. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  116816. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  116817. };
  116818. static static_codebook _huff_book_line_256x4_0sub3 = {
  116819. 1, 64,
  116820. _huff_lengthlist_line_256x4_0sub3,
  116821. 0, 0, 0, 0, 0,
  116822. NULL,
  116823. NULL,
  116824. NULL,
  116825. NULL,
  116826. 0
  116827. };
  116828. static long _huff_lengthlist_line_128x7_class0[] = {
  116829. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  116830. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  116831. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  116832. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  116833. };
  116834. static static_codebook _huff_book_line_128x7_class0 = {
  116835. 1, 64,
  116836. _huff_lengthlist_line_128x7_class0,
  116837. 0, 0, 0, 0, 0,
  116838. NULL,
  116839. NULL,
  116840. NULL,
  116841. NULL,
  116842. 0
  116843. };
  116844. static long _huff_lengthlist_line_128x7_class1[] = {
  116845. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  116846. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  116847. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  116848. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  116849. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  116850. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  116851. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  116852. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  116853. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  116854. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  116855. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  116856. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  116857. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  116858. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  116859. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  116860. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  116861. };
  116862. static static_codebook _huff_book_line_128x7_class1 = {
  116863. 1, 256,
  116864. _huff_lengthlist_line_128x7_class1,
  116865. 0, 0, 0, 0, 0,
  116866. NULL,
  116867. NULL,
  116868. NULL,
  116869. NULL,
  116870. 0
  116871. };
  116872. static long _huff_lengthlist_line_128x7_0sub1[] = {
  116873. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  116874. };
  116875. static static_codebook _huff_book_line_128x7_0sub1 = {
  116876. 1, 9,
  116877. _huff_lengthlist_line_128x7_0sub1,
  116878. 0, 0, 0, 0, 0,
  116879. NULL,
  116880. NULL,
  116881. NULL,
  116882. NULL,
  116883. 0
  116884. };
  116885. static long _huff_lengthlist_line_128x7_0sub2[] = {
  116886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  116887. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  116888. };
  116889. static static_codebook _huff_book_line_128x7_0sub2 = {
  116890. 1, 25,
  116891. _huff_lengthlist_line_128x7_0sub2,
  116892. 0, 0, 0, 0, 0,
  116893. NULL,
  116894. NULL,
  116895. NULL,
  116896. NULL,
  116897. 0
  116898. };
  116899. static long _huff_lengthlist_line_128x7_0sub3[] = {
  116900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  116902. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  116903. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  116904. };
  116905. static static_codebook _huff_book_line_128x7_0sub3 = {
  116906. 1, 64,
  116907. _huff_lengthlist_line_128x7_0sub3,
  116908. 0, 0, 0, 0, 0,
  116909. NULL,
  116910. NULL,
  116911. NULL,
  116912. NULL,
  116913. 0
  116914. };
  116915. static long _huff_lengthlist_line_128x7_1sub1[] = {
  116916. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  116917. };
  116918. static static_codebook _huff_book_line_128x7_1sub1 = {
  116919. 1, 9,
  116920. _huff_lengthlist_line_128x7_1sub1,
  116921. 0, 0, 0, 0, 0,
  116922. NULL,
  116923. NULL,
  116924. NULL,
  116925. NULL,
  116926. 0
  116927. };
  116928. static long _huff_lengthlist_line_128x7_1sub2[] = {
  116929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  116930. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  116931. };
  116932. static static_codebook _huff_book_line_128x7_1sub2 = {
  116933. 1, 25,
  116934. _huff_lengthlist_line_128x7_1sub2,
  116935. 0, 0, 0, 0, 0,
  116936. NULL,
  116937. NULL,
  116938. NULL,
  116939. NULL,
  116940. 0
  116941. };
  116942. static long _huff_lengthlist_line_128x7_1sub3[] = {
  116943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  116945. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  116946. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  116947. };
  116948. static static_codebook _huff_book_line_128x7_1sub3 = {
  116949. 1, 64,
  116950. _huff_lengthlist_line_128x7_1sub3,
  116951. 0, 0, 0, 0, 0,
  116952. NULL,
  116953. NULL,
  116954. NULL,
  116955. NULL,
  116956. 0
  116957. };
  116958. static long _huff_lengthlist_line_128x11_class1[] = {
  116959. 1, 6, 3, 7, 2, 4, 5, 7,
  116960. };
  116961. static static_codebook _huff_book_line_128x11_class1 = {
  116962. 1, 8,
  116963. _huff_lengthlist_line_128x11_class1,
  116964. 0, 0, 0, 0, 0,
  116965. NULL,
  116966. NULL,
  116967. NULL,
  116968. NULL,
  116969. 0
  116970. };
  116971. static long _huff_lengthlist_line_128x11_class2[] = {
  116972. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  116973. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  116974. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  116975. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  116976. };
  116977. static static_codebook _huff_book_line_128x11_class2 = {
  116978. 1, 64,
  116979. _huff_lengthlist_line_128x11_class2,
  116980. 0, 0, 0, 0, 0,
  116981. NULL,
  116982. NULL,
  116983. NULL,
  116984. NULL,
  116985. 0
  116986. };
  116987. static long _huff_lengthlist_line_128x11_class3[] = {
  116988. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  116989. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  116990. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  116991. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  116992. };
  116993. static static_codebook _huff_book_line_128x11_class3 = {
  116994. 1, 64,
  116995. _huff_lengthlist_line_128x11_class3,
  116996. 0, 0, 0, 0, 0,
  116997. NULL,
  116998. NULL,
  116999. NULL,
  117000. NULL,
  117001. 0
  117002. };
  117003. static long _huff_lengthlist_line_128x11_0sub0[] = {
  117004. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117005. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  117006. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  117007. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  117008. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  117009. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  117010. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  117011. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  117012. };
  117013. static static_codebook _huff_book_line_128x11_0sub0 = {
  117014. 1, 128,
  117015. _huff_lengthlist_line_128x11_0sub0,
  117016. 0, 0, 0, 0, 0,
  117017. NULL,
  117018. NULL,
  117019. NULL,
  117020. NULL,
  117021. 0
  117022. };
  117023. static long _huff_lengthlist_line_128x11_1sub0[] = {
  117024. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117025. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  117026. };
  117027. static static_codebook _huff_book_line_128x11_1sub0 = {
  117028. 1, 32,
  117029. _huff_lengthlist_line_128x11_1sub0,
  117030. 0, 0, 0, 0, 0,
  117031. NULL,
  117032. NULL,
  117033. NULL,
  117034. NULL,
  117035. 0
  117036. };
  117037. static long _huff_lengthlist_line_128x11_1sub1[] = {
  117038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117040. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117041. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  117042. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  117043. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  117044. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  117045. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  117046. };
  117047. static static_codebook _huff_book_line_128x11_1sub1 = {
  117048. 1, 128,
  117049. _huff_lengthlist_line_128x11_1sub1,
  117050. 0, 0, 0, 0, 0,
  117051. NULL,
  117052. NULL,
  117053. NULL,
  117054. NULL,
  117055. 0
  117056. };
  117057. static long _huff_lengthlist_line_128x11_2sub1[] = {
  117058. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  117059. 5, 5,
  117060. };
  117061. static static_codebook _huff_book_line_128x11_2sub1 = {
  117062. 1, 18,
  117063. _huff_lengthlist_line_128x11_2sub1,
  117064. 0, 0, 0, 0, 0,
  117065. NULL,
  117066. NULL,
  117067. NULL,
  117068. NULL,
  117069. 0
  117070. };
  117071. static long _huff_lengthlist_line_128x11_2sub2[] = {
  117072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117073. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  117074. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  117075. 8,11,
  117076. };
  117077. static static_codebook _huff_book_line_128x11_2sub2 = {
  117078. 1, 50,
  117079. _huff_lengthlist_line_128x11_2sub2,
  117080. 0, 0, 0, 0, 0,
  117081. NULL,
  117082. NULL,
  117083. NULL,
  117084. NULL,
  117085. 0
  117086. };
  117087. static long _huff_lengthlist_line_128x11_2sub3[] = {
  117088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117091. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  117092. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117093. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117094. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117095. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117096. };
  117097. static static_codebook _huff_book_line_128x11_2sub3 = {
  117098. 1, 128,
  117099. _huff_lengthlist_line_128x11_2sub3,
  117100. 0, 0, 0, 0, 0,
  117101. NULL,
  117102. NULL,
  117103. NULL,
  117104. NULL,
  117105. 0
  117106. };
  117107. static long _huff_lengthlist_line_128x11_3sub1[] = {
  117108. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  117109. 5, 4,
  117110. };
  117111. static static_codebook _huff_book_line_128x11_3sub1 = {
  117112. 1, 18,
  117113. _huff_lengthlist_line_128x11_3sub1,
  117114. 0, 0, 0, 0, 0,
  117115. NULL,
  117116. NULL,
  117117. NULL,
  117118. NULL,
  117119. 0
  117120. };
  117121. static long _huff_lengthlist_line_128x11_3sub2[] = {
  117122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117123. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  117124. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  117125. 12, 6,
  117126. };
  117127. static static_codebook _huff_book_line_128x11_3sub2 = {
  117128. 1, 50,
  117129. _huff_lengthlist_line_128x11_3sub2,
  117130. 0, 0, 0, 0, 0,
  117131. NULL,
  117132. NULL,
  117133. NULL,
  117134. NULL,
  117135. 0
  117136. };
  117137. static long _huff_lengthlist_line_128x11_3sub3[] = {
  117138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117141. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  117142. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  117143. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117144. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  117145. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  117146. };
  117147. static static_codebook _huff_book_line_128x11_3sub3 = {
  117148. 1, 128,
  117149. _huff_lengthlist_line_128x11_3sub3,
  117150. 0, 0, 0, 0, 0,
  117151. NULL,
  117152. NULL,
  117153. NULL,
  117154. NULL,
  117155. 0
  117156. };
  117157. static long _huff_lengthlist_line_128x17_class1[] = {
  117158. 1, 3, 4, 7, 2, 5, 6, 7,
  117159. };
  117160. static static_codebook _huff_book_line_128x17_class1 = {
  117161. 1, 8,
  117162. _huff_lengthlist_line_128x17_class1,
  117163. 0, 0, 0, 0, 0,
  117164. NULL,
  117165. NULL,
  117166. NULL,
  117167. NULL,
  117168. 0
  117169. };
  117170. static long _huff_lengthlist_line_128x17_class2[] = {
  117171. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  117172. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  117173. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  117174. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  117175. };
  117176. static static_codebook _huff_book_line_128x17_class2 = {
  117177. 1, 64,
  117178. _huff_lengthlist_line_128x17_class2,
  117179. 0, 0, 0, 0, 0,
  117180. NULL,
  117181. NULL,
  117182. NULL,
  117183. NULL,
  117184. 0
  117185. };
  117186. static long _huff_lengthlist_line_128x17_class3[] = {
  117187. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  117188. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  117189. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  117190. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  117191. };
  117192. static static_codebook _huff_book_line_128x17_class3 = {
  117193. 1, 64,
  117194. _huff_lengthlist_line_128x17_class3,
  117195. 0, 0, 0, 0, 0,
  117196. NULL,
  117197. NULL,
  117198. NULL,
  117199. NULL,
  117200. 0
  117201. };
  117202. static long _huff_lengthlist_line_128x17_0sub0[] = {
  117203. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117204. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  117205. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  117206. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  117207. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  117208. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  117209. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  117210. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117211. };
  117212. static static_codebook _huff_book_line_128x17_0sub0 = {
  117213. 1, 128,
  117214. _huff_lengthlist_line_128x17_0sub0,
  117215. 0, 0, 0, 0, 0,
  117216. NULL,
  117217. NULL,
  117218. NULL,
  117219. NULL,
  117220. 0
  117221. };
  117222. static long _huff_lengthlist_line_128x17_1sub0[] = {
  117223. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117224. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  117225. };
  117226. static static_codebook _huff_book_line_128x17_1sub0 = {
  117227. 1, 32,
  117228. _huff_lengthlist_line_128x17_1sub0,
  117229. 0, 0, 0, 0, 0,
  117230. NULL,
  117231. NULL,
  117232. NULL,
  117233. NULL,
  117234. 0
  117235. };
  117236. static long _huff_lengthlist_line_128x17_1sub1[] = {
  117237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117239. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  117240. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  117241. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  117242. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  117243. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  117244. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  117245. };
  117246. static static_codebook _huff_book_line_128x17_1sub1 = {
  117247. 1, 128,
  117248. _huff_lengthlist_line_128x17_1sub1,
  117249. 0, 0, 0, 0, 0,
  117250. NULL,
  117251. NULL,
  117252. NULL,
  117253. NULL,
  117254. 0
  117255. };
  117256. static long _huff_lengthlist_line_128x17_2sub1[] = {
  117257. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  117258. 9, 4,
  117259. };
  117260. static static_codebook _huff_book_line_128x17_2sub1 = {
  117261. 1, 18,
  117262. _huff_lengthlist_line_128x17_2sub1,
  117263. 0, 0, 0, 0, 0,
  117264. NULL,
  117265. NULL,
  117266. NULL,
  117267. NULL,
  117268. 0
  117269. };
  117270. static long _huff_lengthlist_line_128x17_2sub2[] = {
  117271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117272. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  117273. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  117274. 13,13,
  117275. };
  117276. static static_codebook _huff_book_line_128x17_2sub2 = {
  117277. 1, 50,
  117278. _huff_lengthlist_line_128x17_2sub2,
  117279. 0, 0, 0, 0, 0,
  117280. NULL,
  117281. NULL,
  117282. NULL,
  117283. NULL,
  117284. 0
  117285. };
  117286. static long _huff_lengthlist_line_128x17_2sub3[] = {
  117287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117290. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117291. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  117292. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117293. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117294. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117295. };
  117296. static static_codebook _huff_book_line_128x17_2sub3 = {
  117297. 1, 128,
  117298. _huff_lengthlist_line_128x17_2sub3,
  117299. 0, 0, 0, 0, 0,
  117300. NULL,
  117301. NULL,
  117302. NULL,
  117303. NULL,
  117304. 0
  117305. };
  117306. static long _huff_lengthlist_line_128x17_3sub1[] = {
  117307. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  117308. 6, 4,
  117309. };
  117310. static static_codebook _huff_book_line_128x17_3sub1 = {
  117311. 1, 18,
  117312. _huff_lengthlist_line_128x17_3sub1,
  117313. 0, 0, 0, 0, 0,
  117314. NULL,
  117315. NULL,
  117316. NULL,
  117317. NULL,
  117318. 0
  117319. };
  117320. static long _huff_lengthlist_line_128x17_3sub2[] = {
  117321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117322. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  117323. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  117324. 10, 8,
  117325. };
  117326. static static_codebook _huff_book_line_128x17_3sub2 = {
  117327. 1, 50,
  117328. _huff_lengthlist_line_128x17_3sub2,
  117329. 0, 0, 0, 0, 0,
  117330. NULL,
  117331. NULL,
  117332. NULL,
  117333. NULL,
  117334. 0
  117335. };
  117336. static long _huff_lengthlist_line_128x17_3sub3[] = {
  117337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117340. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  117341. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  117342. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117345. };
  117346. static static_codebook _huff_book_line_128x17_3sub3 = {
  117347. 1, 128,
  117348. _huff_lengthlist_line_128x17_3sub3,
  117349. 0, 0, 0, 0, 0,
  117350. NULL,
  117351. NULL,
  117352. NULL,
  117353. NULL,
  117354. 0
  117355. };
  117356. static long _huff_lengthlist_line_1024x27_class1[] = {
  117357. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  117358. };
  117359. static static_codebook _huff_book_line_1024x27_class1 = {
  117360. 1, 16,
  117361. _huff_lengthlist_line_1024x27_class1,
  117362. 0, 0, 0, 0, 0,
  117363. NULL,
  117364. NULL,
  117365. NULL,
  117366. NULL,
  117367. 0
  117368. };
  117369. static long _huff_lengthlist_line_1024x27_class2[] = {
  117370. 1, 4, 2, 6, 3, 7, 5, 7,
  117371. };
  117372. static static_codebook _huff_book_line_1024x27_class2 = {
  117373. 1, 8,
  117374. _huff_lengthlist_line_1024x27_class2,
  117375. 0, 0, 0, 0, 0,
  117376. NULL,
  117377. NULL,
  117378. NULL,
  117379. NULL,
  117380. 0
  117381. };
  117382. static long _huff_lengthlist_line_1024x27_class3[] = {
  117383. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  117384. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  117385. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  117386. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  117387. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  117388. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  117389. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  117390. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  117391. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  117392. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  117393. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  117394. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117395. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  117396. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  117397. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  117398. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  117399. };
  117400. static static_codebook _huff_book_line_1024x27_class3 = {
  117401. 1, 256,
  117402. _huff_lengthlist_line_1024x27_class3,
  117403. 0, 0, 0, 0, 0,
  117404. NULL,
  117405. NULL,
  117406. NULL,
  117407. NULL,
  117408. 0
  117409. };
  117410. static long _huff_lengthlist_line_1024x27_class4[] = {
  117411. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  117412. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  117413. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  117414. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  117415. };
  117416. static static_codebook _huff_book_line_1024x27_class4 = {
  117417. 1, 64,
  117418. _huff_lengthlist_line_1024x27_class4,
  117419. 0, 0, 0, 0, 0,
  117420. NULL,
  117421. NULL,
  117422. NULL,
  117423. NULL,
  117424. 0
  117425. };
  117426. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  117427. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117428. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  117429. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  117430. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  117431. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  117432. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  117433. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  117434. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  117435. };
  117436. static static_codebook _huff_book_line_1024x27_0sub0 = {
  117437. 1, 128,
  117438. _huff_lengthlist_line_1024x27_0sub0,
  117439. 0, 0, 0, 0, 0,
  117440. NULL,
  117441. NULL,
  117442. NULL,
  117443. NULL,
  117444. 0
  117445. };
  117446. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  117447. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  117448. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  117449. };
  117450. static static_codebook _huff_book_line_1024x27_1sub0 = {
  117451. 1, 32,
  117452. _huff_lengthlist_line_1024x27_1sub0,
  117453. 0, 0, 0, 0, 0,
  117454. NULL,
  117455. NULL,
  117456. NULL,
  117457. NULL,
  117458. 0
  117459. };
  117460. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  117461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117463. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  117464. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  117465. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  117466. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  117467. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  117468. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  117469. };
  117470. static static_codebook _huff_book_line_1024x27_1sub1 = {
  117471. 1, 128,
  117472. _huff_lengthlist_line_1024x27_1sub1,
  117473. 0, 0, 0, 0, 0,
  117474. NULL,
  117475. NULL,
  117476. NULL,
  117477. NULL,
  117478. 0
  117479. };
  117480. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  117481. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117482. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  117483. };
  117484. static static_codebook _huff_book_line_1024x27_2sub0 = {
  117485. 1, 32,
  117486. _huff_lengthlist_line_1024x27_2sub0,
  117487. 0, 0, 0, 0, 0,
  117488. NULL,
  117489. NULL,
  117490. NULL,
  117491. NULL,
  117492. 0
  117493. };
  117494. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  117495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117497. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  117498. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  117499. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  117500. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  117501. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  117502. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  117503. };
  117504. static static_codebook _huff_book_line_1024x27_2sub1 = {
  117505. 1, 128,
  117506. _huff_lengthlist_line_1024x27_2sub1,
  117507. 0, 0, 0, 0, 0,
  117508. NULL,
  117509. NULL,
  117510. NULL,
  117511. NULL,
  117512. 0
  117513. };
  117514. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  117515. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  117516. 5, 5,
  117517. };
  117518. static static_codebook _huff_book_line_1024x27_3sub1 = {
  117519. 1, 18,
  117520. _huff_lengthlist_line_1024x27_3sub1,
  117521. 0, 0, 0, 0, 0,
  117522. NULL,
  117523. NULL,
  117524. NULL,
  117525. NULL,
  117526. 0
  117527. };
  117528. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  117529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117530. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  117531. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  117532. 9,11,
  117533. };
  117534. static static_codebook _huff_book_line_1024x27_3sub2 = {
  117535. 1, 50,
  117536. _huff_lengthlist_line_1024x27_3sub2,
  117537. 0, 0, 0, 0, 0,
  117538. NULL,
  117539. NULL,
  117540. NULL,
  117541. NULL,
  117542. 0
  117543. };
  117544. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  117545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117548. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  117549. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  117550. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117551. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117552. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117553. };
  117554. static static_codebook _huff_book_line_1024x27_3sub3 = {
  117555. 1, 128,
  117556. _huff_lengthlist_line_1024x27_3sub3,
  117557. 0, 0, 0, 0, 0,
  117558. NULL,
  117559. NULL,
  117560. NULL,
  117561. NULL,
  117562. 0
  117563. };
  117564. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  117565. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  117566. 5, 4,
  117567. };
  117568. static static_codebook _huff_book_line_1024x27_4sub1 = {
  117569. 1, 18,
  117570. _huff_lengthlist_line_1024x27_4sub1,
  117571. 0, 0, 0, 0, 0,
  117572. NULL,
  117573. NULL,
  117574. NULL,
  117575. NULL,
  117576. 0
  117577. };
  117578. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  117579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117580. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  117581. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  117582. 9,12,
  117583. };
  117584. static static_codebook _huff_book_line_1024x27_4sub2 = {
  117585. 1, 50,
  117586. _huff_lengthlist_line_1024x27_4sub2,
  117587. 0, 0, 0, 0, 0,
  117588. NULL,
  117589. NULL,
  117590. NULL,
  117591. NULL,
  117592. 0
  117593. };
  117594. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  117595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117598. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  117599. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  117600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  117602. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  117603. };
  117604. static static_codebook _huff_book_line_1024x27_4sub3 = {
  117605. 1, 128,
  117606. _huff_lengthlist_line_1024x27_4sub3,
  117607. 0, 0, 0, 0, 0,
  117608. NULL,
  117609. NULL,
  117610. NULL,
  117611. NULL,
  117612. 0
  117613. };
  117614. static long _huff_lengthlist_line_2048x27_class1[] = {
  117615. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  117616. };
  117617. static static_codebook _huff_book_line_2048x27_class1 = {
  117618. 1, 16,
  117619. _huff_lengthlist_line_2048x27_class1,
  117620. 0, 0, 0, 0, 0,
  117621. NULL,
  117622. NULL,
  117623. NULL,
  117624. NULL,
  117625. 0
  117626. };
  117627. static long _huff_lengthlist_line_2048x27_class2[] = {
  117628. 1, 2, 3, 6, 4, 7, 5, 7,
  117629. };
  117630. static static_codebook _huff_book_line_2048x27_class2 = {
  117631. 1, 8,
  117632. _huff_lengthlist_line_2048x27_class2,
  117633. 0, 0, 0, 0, 0,
  117634. NULL,
  117635. NULL,
  117636. NULL,
  117637. NULL,
  117638. 0
  117639. };
  117640. static long _huff_lengthlist_line_2048x27_class3[] = {
  117641. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  117642. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  117643. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  117644. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  117645. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  117646. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  117647. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  117648. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  117649. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  117650. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  117651. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  117652. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117653. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  117654. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  117655. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117656. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  117657. };
  117658. static static_codebook _huff_book_line_2048x27_class3 = {
  117659. 1, 256,
  117660. _huff_lengthlist_line_2048x27_class3,
  117661. 0, 0, 0, 0, 0,
  117662. NULL,
  117663. NULL,
  117664. NULL,
  117665. NULL,
  117666. 0
  117667. };
  117668. static long _huff_lengthlist_line_2048x27_class4[] = {
  117669. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  117670. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  117671. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  117672. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  117673. };
  117674. static static_codebook _huff_book_line_2048x27_class4 = {
  117675. 1, 64,
  117676. _huff_lengthlist_line_2048x27_class4,
  117677. 0, 0, 0, 0, 0,
  117678. NULL,
  117679. NULL,
  117680. NULL,
  117681. NULL,
  117682. 0
  117683. };
  117684. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  117685. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  117686. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  117687. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  117688. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  117689. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  117690. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  117691. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  117692. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  117693. };
  117694. static static_codebook _huff_book_line_2048x27_0sub0 = {
  117695. 1, 128,
  117696. _huff_lengthlist_line_2048x27_0sub0,
  117697. 0, 0, 0, 0, 0,
  117698. NULL,
  117699. NULL,
  117700. NULL,
  117701. NULL,
  117702. 0
  117703. };
  117704. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  117705. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  117706. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  117707. };
  117708. static static_codebook _huff_book_line_2048x27_1sub0 = {
  117709. 1, 32,
  117710. _huff_lengthlist_line_2048x27_1sub0,
  117711. 0, 0, 0, 0, 0,
  117712. NULL,
  117713. NULL,
  117714. NULL,
  117715. NULL,
  117716. 0
  117717. };
  117718. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  117719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117721. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  117722. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  117723. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  117724. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  117725. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  117726. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  117727. };
  117728. static static_codebook _huff_book_line_2048x27_1sub1 = {
  117729. 1, 128,
  117730. _huff_lengthlist_line_2048x27_1sub1,
  117731. 0, 0, 0, 0, 0,
  117732. NULL,
  117733. NULL,
  117734. NULL,
  117735. NULL,
  117736. 0
  117737. };
  117738. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  117739. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  117740. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  117741. };
  117742. static static_codebook _huff_book_line_2048x27_2sub0 = {
  117743. 1, 32,
  117744. _huff_lengthlist_line_2048x27_2sub0,
  117745. 0, 0, 0, 0, 0,
  117746. NULL,
  117747. NULL,
  117748. NULL,
  117749. NULL,
  117750. 0
  117751. };
  117752. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  117753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117755. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  117756. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  117757. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  117758. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  117759. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  117760. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  117761. };
  117762. static static_codebook _huff_book_line_2048x27_2sub1 = {
  117763. 1, 128,
  117764. _huff_lengthlist_line_2048x27_2sub1,
  117765. 0, 0, 0, 0, 0,
  117766. NULL,
  117767. NULL,
  117768. NULL,
  117769. NULL,
  117770. 0
  117771. };
  117772. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  117773. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  117774. 5, 5,
  117775. };
  117776. static static_codebook _huff_book_line_2048x27_3sub1 = {
  117777. 1, 18,
  117778. _huff_lengthlist_line_2048x27_3sub1,
  117779. 0, 0, 0, 0, 0,
  117780. NULL,
  117781. NULL,
  117782. NULL,
  117783. NULL,
  117784. 0
  117785. };
  117786. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  117787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117788. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  117789. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  117790. 10,12,
  117791. };
  117792. static static_codebook _huff_book_line_2048x27_3sub2 = {
  117793. 1, 50,
  117794. _huff_lengthlist_line_2048x27_3sub2,
  117795. 0, 0, 0, 0, 0,
  117796. NULL,
  117797. NULL,
  117798. NULL,
  117799. NULL,
  117800. 0
  117801. };
  117802. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  117803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117806. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  117807. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117808. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117809. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117810. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117811. };
  117812. static static_codebook _huff_book_line_2048x27_3sub3 = {
  117813. 1, 128,
  117814. _huff_lengthlist_line_2048x27_3sub3,
  117815. 0, 0, 0, 0, 0,
  117816. NULL,
  117817. NULL,
  117818. NULL,
  117819. NULL,
  117820. 0
  117821. };
  117822. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  117823. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  117824. 4, 5,
  117825. };
  117826. static static_codebook _huff_book_line_2048x27_4sub1 = {
  117827. 1, 18,
  117828. _huff_lengthlist_line_2048x27_4sub1,
  117829. 0, 0, 0, 0, 0,
  117830. NULL,
  117831. NULL,
  117832. NULL,
  117833. NULL,
  117834. 0
  117835. };
  117836. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  117837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117838. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  117839. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  117840. 10,10,
  117841. };
  117842. static static_codebook _huff_book_line_2048x27_4sub2 = {
  117843. 1, 50,
  117844. _huff_lengthlist_line_2048x27_4sub2,
  117845. 0, 0, 0, 0, 0,
  117846. NULL,
  117847. NULL,
  117848. NULL,
  117849. NULL,
  117850. 0
  117851. };
  117852. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  117853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117856. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  117857. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  117858. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117859. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  117860. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  117861. };
  117862. static static_codebook _huff_book_line_2048x27_4sub3 = {
  117863. 1, 128,
  117864. _huff_lengthlist_line_2048x27_4sub3,
  117865. 0, 0, 0, 0, 0,
  117866. NULL,
  117867. NULL,
  117868. NULL,
  117869. NULL,
  117870. 0
  117871. };
  117872. static long _huff_lengthlist_line_256x4low_class0[] = {
  117873. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  117874. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  117875. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  117876. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  117877. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  117878. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  117879. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  117880. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  117881. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  117882. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  117883. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  117884. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  117885. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  117886. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  117887. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  117888. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  117889. };
  117890. static static_codebook _huff_book_line_256x4low_class0 = {
  117891. 1, 256,
  117892. _huff_lengthlist_line_256x4low_class0,
  117893. 0, 0, 0, 0, 0,
  117894. NULL,
  117895. NULL,
  117896. NULL,
  117897. NULL,
  117898. 0
  117899. };
  117900. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  117901. 1, 3, 2, 3,
  117902. };
  117903. static static_codebook _huff_book_line_256x4low_0sub0 = {
  117904. 1, 4,
  117905. _huff_lengthlist_line_256x4low_0sub0,
  117906. 0, 0, 0, 0, 0,
  117907. NULL,
  117908. NULL,
  117909. NULL,
  117910. NULL,
  117911. 0
  117912. };
  117913. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  117914. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  117915. };
  117916. static static_codebook _huff_book_line_256x4low_0sub1 = {
  117917. 1, 10,
  117918. _huff_lengthlist_line_256x4low_0sub1,
  117919. 0, 0, 0, 0, 0,
  117920. NULL,
  117921. NULL,
  117922. NULL,
  117923. NULL,
  117924. 0
  117925. };
  117926. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  117927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  117928. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  117929. };
  117930. static static_codebook _huff_book_line_256x4low_0sub2 = {
  117931. 1, 25,
  117932. _huff_lengthlist_line_256x4low_0sub2,
  117933. 0, 0, 0, 0, 0,
  117934. NULL,
  117935. NULL,
  117936. NULL,
  117937. NULL,
  117938. 0
  117939. };
  117940. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  117941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  117943. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  117944. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  117945. };
  117946. static static_codebook _huff_book_line_256x4low_0sub3 = {
  117947. 1, 64,
  117948. _huff_lengthlist_line_256x4low_0sub3,
  117949. 0, 0, 0, 0, 0,
  117950. NULL,
  117951. NULL,
  117952. NULL,
  117953. NULL,
  117954. 0
  117955. };
  117956. /********* End of inlined file: floor_books.h *********/
  117957. static static_codebook *_floor_128x4_books[]={
  117958. &_huff_book_line_128x4_class0,
  117959. &_huff_book_line_128x4_0sub0,
  117960. &_huff_book_line_128x4_0sub1,
  117961. &_huff_book_line_128x4_0sub2,
  117962. &_huff_book_line_128x4_0sub3,
  117963. };
  117964. static static_codebook *_floor_256x4_books[]={
  117965. &_huff_book_line_256x4_class0,
  117966. &_huff_book_line_256x4_0sub0,
  117967. &_huff_book_line_256x4_0sub1,
  117968. &_huff_book_line_256x4_0sub2,
  117969. &_huff_book_line_256x4_0sub3,
  117970. };
  117971. static static_codebook *_floor_128x7_books[]={
  117972. &_huff_book_line_128x7_class0,
  117973. &_huff_book_line_128x7_class1,
  117974. &_huff_book_line_128x7_0sub1,
  117975. &_huff_book_line_128x7_0sub2,
  117976. &_huff_book_line_128x7_0sub3,
  117977. &_huff_book_line_128x7_1sub1,
  117978. &_huff_book_line_128x7_1sub2,
  117979. &_huff_book_line_128x7_1sub3,
  117980. };
  117981. static static_codebook *_floor_256x7_books[]={
  117982. &_huff_book_line_256x7_class0,
  117983. &_huff_book_line_256x7_class1,
  117984. &_huff_book_line_256x7_0sub1,
  117985. &_huff_book_line_256x7_0sub2,
  117986. &_huff_book_line_256x7_0sub3,
  117987. &_huff_book_line_256x7_1sub1,
  117988. &_huff_book_line_256x7_1sub2,
  117989. &_huff_book_line_256x7_1sub3,
  117990. };
  117991. static static_codebook *_floor_128x11_books[]={
  117992. &_huff_book_line_128x11_class1,
  117993. &_huff_book_line_128x11_class2,
  117994. &_huff_book_line_128x11_class3,
  117995. &_huff_book_line_128x11_0sub0,
  117996. &_huff_book_line_128x11_1sub0,
  117997. &_huff_book_line_128x11_1sub1,
  117998. &_huff_book_line_128x11_2sub1,
  117999. &_huff_book_line_128x11_2sub2,
  118000. &_huff_book_line_128x11_2sub3,
  118001. &_huff_book_line_128x11_3sub1,
  118002. &_huff_book_line_128x11_3sub2,
  118003. &_huff_book_line_128x11_3sub3,
  118004. };
  118005. static static_codebook *_floor_128x17_books[]={
  118006. &_huff_book_line_128x17_class1,
  118007. &_huff_book_line_128x17_class2,
  118008. &_huff_book_line_128x17_class3,
  118009. &_huff_book_line_128x17_0sub0,
  118010. &_huff_book_line_128x17_1sub0,
  118011. &_huff_book_line_128x17_1sub1,
  118012. &_huff_book_line_128x17_2sub1,
  118013. &_huff_book_line_128x17_2sub2,
  118014. &_huff_book_line_128x17_2sub3,
  118015. &_huff_book_line_128x17_3sub1,
  118016. &_huff_book_line_128x17_3sub2,
  118017. &_huff_book_line_128x17_3sub3,
  118018. };
  118019. static static_codebook *_floor_256x4low_books[]={
  118020. &_huff_book_line_256x4low_class0,
  118021. &_huff_book_line_256x4low_0sub0,
  118022. &_huff_book_line_256x4low_0sub1,
  118023. &_huff_book_line_256x4low_0sub2,
  118024. &_huff_book_line_256x4low_0sub3,
  118025. };
  118026. static static_codebook *_floor_1024x27_books[]={
  118027. &_huff_book_line_1024x27_class1,
  118028. &_huff_book_line_1024x27_class2,
  118029. &_huff_book_line_1024x27_class3,
  118030. &_huff_book_line_1024x27_class4,
  118031. &_huff_book_line_1024x27_0sub0,
  118032. &_huff_book_line_1024x27_1sub0,
  118033. &_huff_book_line_1024x27_1sub1,
  118034. &_huff_book_line_1024x27_2sub0,
  118035. &_huff_book_line_1024x27_2sub1,
  118036. &_huff_book_line_1024x27_3sub1,
  118037. &_huff_book_line_1024x27_3sub2,
  118038. &_huff_book_line_1024x27_3sub3,
  118039. &_huff_book_line_1024x27_4sub1,
  118040. &_huff_book_line_1024x27_4sub2,
  118041. &_huff_book_line_1024x27_4sub3,
  118042. };
  118043. static static_codebook *_floor_2048x27_books[]={
  118044. &_huff_book_line_2048x27_class1,
  118045. &_huff_book_line_2048x27_class2,
  118046. &_huff_book_line_2048x27_class3,
  118047. &_huff_book_line_2048x27_class4,
  118048. &_huff_book_line_2048x27_0sub0,
  118049. &_huff_book_line_2048x27_1sub0,
  118050. &_huff_book_line_2048x27_1sub1,
  118051. &_huff_book_line_2048x27_2sub0,
  118052. &_huff_book_line_2048x27_2sub1,
  118053. &_huff_book_line_2048x27_3sub1,
  118054. &_huff_book_line_2048x27_3sub2,
  118055. &_huff_book_line_2048x27_3sub3,
  118056. &_huff_book_line_2048x27_4sub1,
  118057. &_huff_book_line_2048x27_4sub2,
  118058. &_huff_book_line_2048x27_4sub3,
  118059. };
  118060. static static_codebook *_floor_512x17_books[]={
  118061. &_huff_book_line_512x17_class1,
  118062. &_huff_book_line_512x17_class2,
  118063. &_huff_book_line_512x17_class3,
  118064. &_huff_book_line_512x17_0sub0,
  118065. &_huff_book_line_512x17_1sub0,
  118066. &_huff_book_line_512x17_1sub1,
  118067. &_huff_book_line_512x17_2sub1,
  118068. &_huff_book_line_512x17_2sub2,
  118069. &_huff_book_line_512x17_2sub3,
  118070. &_huff_book_line_512x17_3sub1,
  118071. &_huff_book_line_512x17_3sub2,
  118072. &_huff_book_line_512x17_3sub3,
  118073. };
  118074. static static_codebook **_floor_books[10]={
  118075. _floor_128x4_books,
  118076. _floor_256x4_books,
  118077. _floor_128x7_books,
  118078. _floor_256x7_books,
  118079. _floor_128x11_books,
  118080. _floor_128x17_books,
  118081. _floor_256x4low_books,
  118082. _floor_1024x27_books,
  118083. _floor_2048x27_books,
  118084. _floor_512x17_books,
  118085. };
  118086. static vorbis_info_floor1 _floor[10]={
  118087. /* 128 x 4 */
  118088. {
  118089. 1,{0},{4},{2},{0},
  118090. {{1,2,3,4}},
  118091. 4,{0,128, 33,8,16,70},
  118092. 60,30,500, 1.,18., -1
  118093. },
  118094. /* 256 x 4 */
  118095. {
  118096. 1,{0},{4},{2},{0},
  118097. {{1,2,3,4}},
  118098. 4,{0,256, 66,16,32,140},
  118099. 60,30,500, 1.,18., -1
  118100. },
  118101. /* 128 x 7 */
  118102. {
  118103. 2,{0,1},{3,4},{2,2},{0,1},
  118104. {{-1,2,3,4},{-1,5,6,7}},
  118105. 4,{0,128, 14,4,58, 2,8,28,90},
  118106. 60,30,500, 1.,18., -1
  118107. },
  118108. /* 256 x 7 */
  118109. {
  118110. 2,{0,1},{3,4},{2,2},{0,1},
  118111. {{-1,2,3,4},{-1,5,6,7}},
  118112. 4,{0,256, 28,8,116, 4,16,56,180},
  118113. 60,30,500, 1.,18., -1
  118114. },
  118115. /* 128 x 11 */
  118116. {
  118117. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118118. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118119. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  118120. 60,30,500, 1,18., -1
  118121. },
  118122. /* 128 x 17 */
  118123. {
  118124. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118125. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118126. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  118127. 60,30,500, 1,18., -1
  118128. },
  118129. /* 256 x 4 (low bitrate version) */
  118130. {
  118131. 1,{0},{4},{2},{0},
  118132. {{1,2,3,4}},
  118133. 4,{0,256, 66,16,32,140},
  118134. 60,30,500, 1.,18., -1
  118135. },
  118136. /* 1024 x 27 */
  118137. {
  118138. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118139. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118140. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  118141. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  118142. 60,30,500, 3,18., -1 /* lowpass */
  118143. },
  118144. /* 2048 x 27 */
  118145. {
  118146. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  118147. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  118148. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  118149. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  118150. 60,30,500, 3,18., -1 /* lowpass */
  118151. },
  118152. /* 512 x 17 */
  118153. {
  118154. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  118155. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  118156. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  118157. 7,23,39, 55,79,110, 156,232,360},
  118158. 60,30,500, 1,18., -1 /* lowpass! */
  118159. },
  118160. };
  118161. /********* End of inlined file: floor_all.h *********/
  118162. /********* Start of inlined file: residue_44.h *********/
  118163. /********* Start of inlined file: res_books_stereo.h *********/
  118164. static long _vq_quantlist__16c0_s_p1_0[] = {
  118165. 1,
  118166. 0,
  118167. 2,
  118168. };
  118169. static long _vq_lengthlist__16c0_s_p1_0[] = {
  118170. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  118171. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118175. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  118176. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118180. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  118181. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118193. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118198. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118203. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  118216. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  118221. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  118226. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 0, 0, 0, 0, 0, 0, 0,
  118238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  118243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  118248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  118262. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  118267. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  118272. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118284. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118289. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118581. };
  118582. static float _vq_quantthresh__16c0_s_p1_0[] = {
  118583. -0.5, 0.5,
  118584. };
  118585. static long _vq_quantmap__16c0_s_p1_0[] = {
  118586. 1, 0, 2,
  118587. };
  118588. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  118589. _vq_quantthresh__16c0_s_p1_0,
  118590. _vq_quantmap__16c0_s_p1_0,
  118591. 3,
  118592. 3
  118593. };
  118594. static static_codebook _16c0_s_p1_0 = {
  118595. 8, 6561,
  118596. _vq_lengthlist__16c0_s_p1_0,
  118597. 1, -535822336, 1611661312, 2, 0,
  118598. _vq_quantlist__16c0_s_p1_0,
  118599. NULL,
  118600. &_vq_auxt__16c0_s_p1_0,
  118601. NULL,
  118602. 0
  118603. };
  118604. static long _vq_quantlist__16c0_s_p2_0[] = {
  118605. 2,
  118606. 1,
  118607. 3,
  118608. 0,
  118609. 4,
  118610. };
  118611. static long _vq_lengthlist__16c0_s_p2_0[] = {
  118612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118652. };
  118653. static float _vq_quantthresh__16c0_s_p2_0[] = {
  118654. -1.5, -0.5, 0.5, 1.5,
  118655. };
  118656. static long _vq_quantmap__16c0_s_p2_0[] = {
  118657. 3, 1, 0, 2, 4,
  118658. };
  118659. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  118660. _vq_quantthresh__16c0_s_p2_0,
  118661. _vq_quantmap__16c0_s_p2_0,
  118662. 5,
  118663. 5
  118664. };
  118665. static static_codebook _16c0_s_p2_0 = {
  118666. 4, 625,
  118667. _vq_lengthlist__16c0_s_p2_0,
  118668. 1, -533725184, 1611661312, 3, 0,
  118669. _vq_quantlist__16c0_s_p2_0,
  118670. NULL,
  118671. &_vq_auxt__16c0_s_p2_0,
  118672. NULL,
  118673. 0
  118674. };
  118675. static long _vq_quantlist__16c0_s_p3_0[] = {
  118676. 2,
  118677. 1,
  118678. 3,
  118679. 0,
  118680. 4,
  118681. };
  118682. static long _vq_lengthlist__16c0_s_p3_0[] = {
  118683. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  118685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118686. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  118688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118689. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  118690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  118723. };
  118724. static float _vq_quantthresh__16c0_s_p3_0[] = {
  118725. -1.5, -0.5, 0.5, 1.5,
  118726. };
  118727. static long _vq_quantmap__16c0_s_p3_0[] = {
  118728. 3, 1, 0, 2, 4,
  118729. };
  118730. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  118731. _vq_quantthresh__16c0_s_p3_0,
  118732. _vq_quantmap__16c0_s_p3_0,
  118733. 5,
  118734. 5
  118735. };
  118736. static static_codebook _16c0_s_p3_0 = {
  118737. 4, 625,
  118738. _vq_lengthlist__16c0_s_p3_0,
  118739. 1, -533725184, 1611661312, 3, 0,
  118740. _vq_quantlist__16c0_s_p3_0,
  118741. NULL,
  118742. &_vq_auxt__16c0_s_p3_0,
  118743. NULL,
  118744. 0
  118745. };
  118746. static long _vq_quantlist__16c0_s_p4_0[] = {
  118747. 4,
  118748. 3,
  118749. 5,
  118750. 2,
  118751. 6,
  118752. 1,
  118753. 7,
  118754. 0,
  118755. 8,
  118756. };
  118757. static long _vq_lengthlist__16c0_s_p4_0[] = {
  118758. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  118759. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  118760. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  118761. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  118762. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118763. 0,
  118764. };
  118765. static float _vq_quantthresh__16c0_s_p4_0[] = {
  118766. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118767. };
  118768. static long _vq_quantmap__16c0_s_p4_0[] = {
  118769. 7, 5, 3, 1, 0, 2, 4, 6,
  118770. 8,
  118771. };
  118772. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  118773. _vq_quantthresh__16c0_s_p4_0,
  118774. _vq_quantmap__16c0_s_p4_0,
  118775. 9,
  118776. 9
  118777. };
  118778. static static_codebook _16c0_s_p4_0 = {
  118779. 2, 81,
  118780. _vq_lengthlist__16c0_s_p4_0,
  118781. 1, -531628032, 1611661312, 4, 0,
  118782. _vq_quantlist__16c0_s_p4_0,
  118783. NULL,
  118784. &_vq_auxt__16c0_s_p4_0,
  118785. NULL,
  118786. 0
  118787. };
  118788. static long _vq_quantlist__16c0_s_p5_0[] = {
  118789. 4,
  118790. 3,
  118791. 5,
  118792. 2,
  118793. 6,
  118794. 1,
  118795. 7,
  118796. 0,
  118797. 8,
  118798. };
  118799. static long _vq_lengthlist__16c0_s_p5_0[] = {
  118800. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  118801. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  118802. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  118803. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  118804. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  118805. 10,
  118806. };
  118807. static float _vq_quantthresh__16c0_s_p5_0[] = {
  118808. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118809. };
  118810. static long _vq_quantmap__16c0_s_p5_0[] = {
  118811. 7, 5, 3, 1, 0, 2, 4, 6,
  118812. 8,
  118813. };
  118814. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  118815. _vq_quantthresh__16c0_s_p5_0,
  118816. _vq_quantmap__16c0_s_p5_0,
  118817. 9,
  118818. 9
  118819. };
  118820. static static_codebook _16c0_s_p5_0 = {
  118821. 2, 81,
  118822. _vq_lengthlist__16c0_s_p5_0,
  118823. 1, -531628032, 1611661312, 4, 0,
  118824. _vq_quantlist__16c0_s_p5_0,
  118825. NULL,
  118826. &_vq_auxt__16c0_s_p5_0,
  118827. NULL,
  118828. 0
  118829. };
  118830. static long _vq_quantlist__16c0_s_p6_0[] = {
  118831. 8,
  118832. 7,
  118833. 9,
  118834. 6,
  118835. 10,
  118836. 5,
  118837. 11,
  118838. 4,
  118839. 12,
  118840. 3,
  118841. 13,
  118842. 2,
  118843. 14,
  118844. 1,
  118845. 15,
  118846. 0,
  118847. 16,
  118848. };
  118849. static long _vq_lengthlist__16c0_s_p6_0[] = {
  118850. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  118851. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  118852. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  118853. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  118854. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  118855. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  118856. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  118857. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  118858. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  118859. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  118860. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  118861. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  118862. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  118863. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  118864. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  118865. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  118866. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  118867. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  118868. 14,
  118869. };
  118870. static float _vq_quantthresh__16c0_s_p6_0[] = {
  118871. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118872. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118873. };
  118874. static long _vq_quantmap__16c0_s_p6_0[] = {
  118875. 15, 13, 11, 9, 7, 5, 3, 1,
  118876. 0, 2, 4, 6, 8, 10, 12, 14,
  118877. 16,
  118878. };
  118879. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  118880. _vq_quantthresh__16c0_s_p6_0,
  118881. _vq_quantmap__16c0_s_p6_0,
  118882. 17,
  118883. 17
  118884. };
  118885. static static_codebook _16c0_s_p6_0 = {
  118886. 2, 289,
  118887. _vq_lengthlist__16c0_s_p6_0,
  118888. 1, -529530880, 1611661312, 5, 0,
  118889. _vq_quantlist__16c0_s_p6_0,
  118890. NULL,
  118891. &_vq_auxt__16c0_s_p6_0,
  118892. NULL,
  118893. 0
  118894. };
  118895. static long _vq_quantlist__16c0_s_p7_0[] = {
  118896. 1,
  118897. 0,
  118898. 2,
  118899. };
  118900. static long _vq_lengthlist__16c0_s_p7_0[] = {
  118901. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  118902. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  118903. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  118904. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  118905. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  118906. 13,
  118907. };
  118908. static float _vq_quantthresh__16c0_s_p7_0[] = {
  118909. -5.5, 5.5,
  118910. };
  118911. static long _vq_quantmap__16c0_s_p7_0[] = {
  118912. 1, 0, 2,
  118913. };
  118914. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  118915. _vq_quantthresh__16c0_s_p7_0,
  118916. _vq_quantmap__16c0_s_p7_0,
  118917. 3,
  118918. 3
  118919. };
  118920. static static_codebook _16c0_s_p7_0 = {
  118921. 4, 81,
  118922. _vq_lengthlist__16c0_s_p7_0,
  118923. 1, -529137664, 1618345984, 2, 0,
  118924. _vq_quantlist__16c0_s_p7_0,
  118925. NULL,
  118926. &_vq_auxt__16c0_s_p7_0,
  118927. NULL,
  118928. 0
  118929. };
  118930. static long _vq_quantlist__16c0_s_p7_1[] = {
  118931. 5,
  118932. 4,
  118933. 6,
  118934. 3,
  118935. 7,
  118936. 2,
  118937. 8,
  118938. 1,
  118939. 9,
  118940. 0,
  118941. 10,
  118942. };
  118943. static long _vq_lengthlist__16c0_s_p7_1[] = {
  118944. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  118945. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  118946. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  118947. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  118948. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  118949. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  118950. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  118951. 11,11,11, 9, 9, 9, 9,10,10,
  118952. };
  118953. static float _vq_quantthresh__16c0_s_p7_1[] = {
  118954. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118955. 3.5, 4.5,
  118956. };
  118957. static long _vq_quantmap__16c0_s_p7_1[] = {
  118958. 9, 7, 5, 3, 1, 0, 2, 4,
  118959. 6, 8, 10,
  118960. };
  118961. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  118962. _vq_quantthresh__16c0_s_p7_1,
  118963. _vq_quantmap__16c0_s_p7_1,
  118964. 11,
  118965. 11
  118966. };
  118967. static static_codebook _16c0_s_p7_1 = {
  118968. 2, 121,
  118969. _vq_lengthlist__16c0_s_p7_1,
  118970. 1, -531365888, 1611661312, 4, 0,
  118971. _vq_quantlist__16c0_s_p7_1,
  118972. NULL,
  118973. &_vq_auxt__16c0_s_p7_1,
  118974. NULL,
  118975. 0
  118976. };
  118977. static long _vq_quantlist__16c0_s_p8_0[] = {
  118978. 6,
  118979. 5,
  118980. 7,
  118981. 4,
  118982. 8,
  118983. 3,
  118984. 9,
  118985. 2,
  118986. 10,
  118987. 1,
  118988. 11,
  118989. 0,
  118990. 12,
  118991. };
  118992. static long _vq_lengthlist__16c0_s_p8_0[] = {
  118993. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  118994. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  118995. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  118996. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  118997. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  118998. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  118999. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  119000. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  119001. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  119002. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  119003. 0,12,13,13,12,13,14,14,14,
  119004. };
  119005. static float _vq_quantthresh__16c0_s_p8_0[] = {
  119006. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119007. 12.5, 17.5, 22.5, 27.5,
  119008. };
  119009. static long _vq_quantmap__16c0_s_p8_0[] = {
  119010. 11, 9, 7, 5, 3, 1, 0, 2,
  119011. 4, 6, 8, 10, 12,
  119012. };
  119013. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  119014. _vq_quantthresh__16c0_s_p8_0,
  119015. _vq_quantmap__16c0_s_p8_0,
  119016. 13,
  119017. 13
  119018. };
  119019. static static_codebook _16c0_s_p8_0 = {
  119020. 2, 169,
  119021. _vq_lengthlist__16c0_s_p8_0,
  119022. 1, -526516224, 1616117760, 4, 0,
  119023. _vq_quantlist__16c0_s_p8_0,
  119024. NULL,
  119025. &_vq_auxt__16c0_s_p8_0,
  119026. NULL,
  119027. 0
  119028. };
  119029. static long _vq_quantlist__16c0_s_p8_1[] = {
  119030. 2,
  119031. 1,
  119032. 3,
  119033. 0,
  119034. 4,
  119035. };
  119036. static long _vq_lengthlist__16c0_s_p8_1[] = {
  119037. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  119038. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119039. };
  119040. static float _vq_quantthresh__16c0_s_p8_1[] = {
  119041. -1.5, -0.5, 0.5, 1.5,
  119042. };
  119043. static long _vq_quantmap__16c0_s_p8_1[] = {
  119044. 3, 1, 0, 2, 4,
  119045. };
  119046. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  119047. _vq_quantthresh__16c0_s_p8_1,
  119048. _vq_quantmap__16c0_s_p8_1,
  119049. 5,
  119050. 5
  119051. };
  119052. static static_codebook _16c0_s_p8_1 = {
  119053. 2, 25,
  119054. _vq_lengthlist__16c0_s_p8_1,
  119055. 1, -533725184, 1611661312, 3, 0,
  119056. _vq_quantlist__16c0_s_p8_1,
  119057. NULL,
  119058. &_vq_auxt__16c0_s_p8_1,
  119059. NULL,
  119060. 0
  119061. };
  119062. static long _vq_quantlist__16c0_s_p9_0[] = {
  119063. 1,
  119064. 0,
  119065. 2,
  119066. };
  119067. static long _vq_lengthlist__16c0_s_p9_0[] = {
  119068. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119069. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119070. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119071. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119072. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119073. 7,
  119074. };
  119075. static float _vq_quantthresh__16c0_s_p9_0[] = {
  119076. -157.5, 157.5,
  119077. };
  119078. static long _vq_quantmap__16c0_s_p9_0[] = {
  119079. 1, 0, 2,
  119080. };
  119081. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  119082. _vq_quantthresh__16c0_s_p9_0,
  119083. _vq_quantmap__16c0_s_p9_0,
  119084. 3,
  119085. 3
  119086. };
  119087. static static_codebook _16c0_s_p9_0 = {
  119088. 4, 81,
  119089. _vq_lengthlist__16c0_s_p9_0,
  119090. 1, -518803456, 1628680192, 2, 0,
  119091. _vq_quantlist__16c0_s_p9_0,
  119092. NULL,
  119093. &_vq_auxt__16c0_s_p9_0,
  119094. NULL,
  119095. 0
  119096. };
  119097. static long _vq_quantlist__16c0_s_p9_1[] = {
  119098. 7,
  119099. 6,
  119100. 8,
  119101. 5,
  119102. 9,
  119103. 4,
  119104. 10,
  119105. 3,
  119106. 11,
  119107. 2,
  119108. 12,
  119109. 1,
  119110. 13,
  119111. 0,
  119112. 14,
  119113. };
  119114. static long _vq_lengthlist__16c0_s_p9_1[] = {
  119115. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  119116. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  119117. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  119118. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  119119. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119120. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119121. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119122. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119123. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119124. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119125. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119126. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119127. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119128. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  119129. 10,
  119130. };
  119131. static float _vq_quantthresh__16c0_s_p9_1[] = {
  119132. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119133. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119134. };
  119135. static long _vq_quantmap__16c0_s_p9_1[] = {
  119136. 13, 11, 9, 7, 5, 3, 1, 0,
  119137. 2, 4, 6, 8, 10, 12, 14,
  119138. };
  119139. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  119140. _vq_quantthresh__16c0_s_p9_1,
  119141. _vq_quantmap__16c0_s_p9_1,
  119142. 15,
  119143. 15
  119144. };
  119145. static static_codebook _16c0_s_p9_1 = {
  119146. 2, 225,
  119147. _vq_lengthlist__16c0_s_p9_1,
  119148. 1, -520986624, 1620377600, 4, 0,
  119149. _vq_quantlist__16c0_s_p9_1,
  119150. NULL,
  119151. &_vq_auxt__16c0_s_p9_1,
  119152. NULL,
  119153. 0
  119154. };
  119155. static long _vq_quantlist__16c0_s_p9_2[] = {
  119156. 10,
  119157. 9,
  119158. 11,
  119159. 8,
  119160. 12,
  119161. 7,
  119162. 13,
  119163. 6,
  119164. 14,
  119165. 5,
  119166. 15,
  119167. 4,
  119168. 16,
  119169. 3,
  119170. 17,
  119171. 2,
  119172. 18,
  119173. 1,
  119174. 19,
  119175. 0,
  119176. 20,
  119177. };
  119178. static long _vq_lengthlist__16c0_s_p9_2[] = {
  119179. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  119180. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  119181. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  119182. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  119183. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  119184. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  119185. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  119186. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  119187. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  119188. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  119189. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  119190. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  119191. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  119192. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  119193. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  119194. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  119195. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  119196. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  119197. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  119198. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  119199. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  119200. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  119201. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  119202. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  119203. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  119204. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  119205. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  119206. 10,11,10,10,11, 9,10,10,10,
  119207. };
  119208. static float _vq_quantthresh__16c0_s_p9_2[] = {
  119209. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  119210. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  119211. 6.5, 7.5, 8.5, 9.5,
  119212. };
  119213. static long _vq_quantmap__16c0_s_p9_2[] = {
  119214. 19, 17, 15, 13, 11, 9, 7, 5,
  119215. 3, 1, 0, 2, 4, 6, 8, 10,
  119216. 12, 14, 16, 18, 20,
  119217. };
  119218. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  119219. _vq_quantthresh__16c0_s_p9_2,
  119220. _vq_quantmap__16c0_s_p9_2,
  119221. 21,
  119222. 21
  119223. };
  119224. static static_codebook _16c0_s_p9_2 = {
  119225. 2, 441,
  119226. _vq_lengthlist__16c0_s_p9_2,
  119227. 1, -529268736, 1611661312, 5, 0,
  119228. _vq_quantlist__16c0_s_p9_2,
  119229. NULL,
  119230. &_vq_auxt__16c0_s_p9_2,
  119231. NULL,
  119232. 0
  119233. };
  119234. static long _huff_lengthlist__16c0_s_single[] = {
  119235. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  119236. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  119237. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  119238. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  119239. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  119240. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  119241. 16,16,18,18,
  119242. };
  119243. static static_codebook _huff_book__16c0_s_single = {
  119244. 2, 100,
  119245. _huff_lengthlist__16c0_s_single,
  119246. 0, 0, 0, 0, 0,
  119247. NULL,
  119248. NULL,
  119249. NULL,
  119250. NULL,
  119251. 0
  119252. };
  119253. static long _huff_lengthlist__16c1_s_long[] = {
  119254. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  119255. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  119256. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  119257. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  119258. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  119259. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  119260. 12,11,11,13,
  119261. };
  119262. static static_codebook _huff_book__16c1_s_long = {
  119263. 2, 100,
  119264. _huff_lengthlist__16c1_s_long,
  119265. 0, 0, 0, 0, 0,
  119266. NULL,
  119267. NULL,
  119268. NULL,
  119269. NULL,
  119270. 0
  119271. };
  119272. static long _vq_quantlist__16c1_s_p1_0[] = {
  119273. 1,
  119274. 0,
  119275. 2,
  119276. };
  119277. static long _vq_lengthlist__16c1_s_p1_0[] = {
  119278. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119279. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119283. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  119284. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119288. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  119289. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119301. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119306. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119311. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  119324. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  119329. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  119334. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  119346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  119351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  119356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119370. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  119375. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  119380. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119392. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119397. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  119689. };
  119690. static float _vq_quantthresh__16c1_s_p1_0[] = {
  119691. -0.5, 0.5,
  119692. };
  119693. static long _vq_quantmap__16c1_s_p1_0[] = {
  119694. 1, 0, 2,
  119695. };
  119696. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  119697. _vq_quantthresh__16c1_s_p1_0,
  119698. _vq_quantmap__16c1_s_p1_0,
  119699. 3,
  119700. 3
  119701. };
  119702. static static_codebook _16c1_s_p1_0 = {
  119703. 8, 6561,
  119704. _vq_lengthlist__16c1_s_p1_0,
  119705. 1, -535822336, 1611661312, 2, 0,
  119706. _vq_quantlist__16c1_s_p1_0,
  119707. NULL,
  119708. &_vq_auxt__16c1_s_p1_0,
  119709. NULL,
  119710. 0
  119711. };
  119712. static long _vq_quantlist__16c1_s_p2_0[] = {
  119713. 2,
  119714. 1,
  119715. 3,
  119716. 0,
  119717. 4,
  119718. };
  119719. static long _vq_lengthlist__16c1_s_p2_0[] = {
  119720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  119760. };
  119761. static float _vq_quantthresh__16c1_s_p2_0[] = {
  119762. -1.5, -0.5, 0.5, 1.5,
  119763. };
  119764. static long _vq_quantmap__16c1_s_p2_0[] = {
  119765. 3, 1, 0, 2, 4,
  119766. };
  119767. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  119768. _vq_quantthresh__16c1_s_p2_0,
  119769. _vq_quantmap__16c1_s_p2_0,
  119770. 5,
  119771. 5
  119772. };
  119773. static static_codebook _16c1_s_p2_0 = {
  119774. 4, 625,
  119775. _vq_lengthlist__16c1_s_p2_0,
  119776. 1, -533725184, 1611661312, 3, 0,
  119777. _vq_quantlist__16c1_s_p2_0,
  119778. NULL,
  119779. &_vq_auxt__16c1_s_p2_0,
  119780. NULL,
  119781. 0
  119782. };
  119783. static long _vq_quantlist__16c1_s_p3_0[] = {
  119784. 2,
  119785. 1,
  119786. 3,
  119787. 0,
  119788. 4,
  119789. };
  119790. static long _vq_lengthlist__16c1_s_p3_0[] = {
  119791. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  119793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119794. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  119796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119797. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  119798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  119831. };
  119832. static float _vq_quantthresh__16c1_s_p3_0[] = {
  119833. -1.5, -0.5, 0.5, 1.5,
  119834. };
  119835. static long _vq_quantmap__16c1_s_p3_0[] = {
  119836. 3, 1, 0, 2, 4,
  119837. };
  119838. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  119839. _vq_quantthresh__16c1_s_p3_0,
  119840. _vq_quantmap__16c1_s_p3_0,
  119841. 5,
  119842. 5
  119843. };
  119844. static static_codebook _16c1_s_p3_0 = {
  119845. 4, 625,
  119846. _vq_lengthlist__16c1_s_p3_0,
  119847. 1, -533725184, 1611661312, 3, 0,
  119848. _vq_quantlist__16c1_s_p3_0,
  119849. NULL,
  119850. &_vq_auxt__16c1_s_p3_0,
  119851. NULL,
  119852. 0
  119853. };
  119854. static long _vq_quantlist__16c1_s_p4_0[] = {
  119855. 4,
  119856. 3,
  119857. 5,
  119858. 2,
  119859. 6,
  119860. 1,
  119861. 7,
  119862. 0,
  119863. 8,
  119864. };
  119865. static long _vq_lengthlist__16c1_s_p4_0[] = {
  119866. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119867. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119868. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119869. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  119870. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119871. 0,
  119872. };
  119873. static float _vq_quantthresh__16c1_s_p4_0[] = {
  119874. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119875. };
  119876. static long _vq_quantmap__16c1_s_p4_0[] = {
  119877. 7, 5, 3, 1, 0, 2, 4, 6,
  119878. 8,
  119879. };
  119880. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  119881. _vq_quantthresh__16c1_s_p4_0,
  119882. _vq_quantmap__16c1_s_p4_0,
  119883. 9,
  119884. 9
  119885. };
  119886. static static_codebook _16c1_s_p4_0 = {
  119887. 2, 81,
  119888. _vq_lengthlist__16c1_s_p4_0,
  119889. 1, -531628032, 1611661312, 4, 0,
  119890. _vq_quantlist__16c1_s_p4_0,
  119891. NULL,
  119892. &_vq_auxt__16c1_s_p4_0,
  119893. NULL,
  119894. 0
  119895. };
  119896. static long _vq_quantlist__16c1_s_p5_0[] = {
  119897. 4,
  119898. 3,
  119899. 5,
  119900. 2,
  119901. 6,
  119902. 1,
  119903. 7,
  119904. 0,
  119905. 8,
  119906. };
  119907. static long _vq_lengthlist__16c1_s_p5_0[] = {
  119908. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119909. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  119910. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  119911. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119912. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119913. 10,
  119914. };
  119915. static float _vq_quantthresh__16c1_s_p5_0[] = {
  119916. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119917. };
  119918. static long _vq_quantmap__16c1_s_p5_0[] = {
  119919. 7, 5, 3, 1, 0, 2, 4, 6,
  119920. 8,
  119921. };
  119922. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  119923. _vq_quantthresh__16c1_s_p5_0,
  119924. _vq_quantmap__16c1_s_p5_0,
  119925. 9,
  119926. 9
  119927. };
  119928. static static_codebook _16c1_s_p5_0 = {
  119929. 2, 81,
  119930. _vq_lengthlist__16c1_s_p5_0,
  119931. 1, -531628032, 1611661312, 4, 0,
  119932. _vq_quantlist__16c1_s_p5_0,
  119933. NULL,
  119934. &_vq_auxt__16c1_s_p5_0,
  119935. NULL,
  119936. 0
  119937. };
  119938. static long _vq_quantlist__16c1_s_p6_0[] = {
  119939. 8,
  119940. 7,
  119941. 9,
  119942. 6,
  119943. 10,
  119944. 5,
  119945. 11,
  119946. 4,
  119947. 12,
  119948. 3,
  119949. 13,
  119950. 2,
  119951. 14,
  119952. 1,
  119953. 15,
  119954. 0,
  119955. 16,
  119956. };
  119957. static long _vq_lengthlist__16c1_s_p6_0[] = {
  119958. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  119959. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119960. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119961. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  119962. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  119963. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  119964. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  119965. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  119966. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  119967. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119968. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  119969. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  119970. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  119971. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  119972. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  119973. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  119974. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  119975. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  119976. 14,
  119977. };
  119978. static float _vq_quantthresh__16c1_s_p6_0[] = {
  119979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119981. };
  119982. static long _vq_quantmap__16c1_s_p6_0[] = {
  119983. 15, 13, 11, 9, 7, 5, 3, 1,
  119984. 0, 2, 4, 6, 8, 10, 12, 14,
  119985. 16,
  119986. };
  119987. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  119988. _vq_quantthresh__16c1_s_p6_0,
  119989. _vq_quantmap__16c1_s_p6_0,
  119990. 17,
  119991. 17
  119992. };
  119993. static static_codebook _16c1_s_p6_0 = {
  119994. 2, 289,
  119995. _vq_lengthlist__16c1_s_p6_0,
  119996. 1, -529530880, 1611661312, 5, 0,
  119997. _vq_quantlist__16c1_s_p6_0,
  119998. NULL,
  119999. &_vq_auxt__16c1_s_p6_0,
  120000. NULL,
  120001. 0
  120002. };
  120003. static long _vq_quantlist__16c1_s_p7_0[] = {
  120004. 1,
  120005. 0,
  120006. 2,
  120007. };
  120008. static long _vq_lengthlist__16c1_s_p7_0[] = {
  120009. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  120010. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  120011. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  120012. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  120013. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  120014. 11,
  120015. };
  120016. static float _vq_quantthresh__16c1_s_p7_0[] = {
  120017. -5.5, 5.5,
  120018. };
  120019. static long _vq_quantmap__16c1_s_p7_0[] = {
  120020. 1, 0, 2,
  120021. };
  120022. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  120023. _vq_quantthresh__16c1_s_p7_0,
  120024. _vq_quantmap__16c1_s_p7_0,
  120025. 3,
  120026. 3
  120027. };
  120028. static static_codebook _16c1_s_p7_0 = {
  120029. 4, 81,
  120030. _vq_lengthlist__16c1_s_p7_0,
  120031. 1, -529137664, 1618345984, 2, 0,
  120032. _vq_quantlist__16c1_s_p7_0,
  120033. NULL,
  120034. &_vq_auxt__16c1_s_p7_0,
  120035. NULL,
  120036. 0
  120037. };
  120038. static long _vq_quantlist__16c1_s_p7_1[] = {
  120039. 5,
  120040. 4,
  120041. 6,
  120042. 3,
  120043. 7,
  120044. 2,
  120045. 8,
  120046. 1,
  120047. 9,
  120048. 0,
  120049. 10,
  120050. };
  120051. static long _vq_lengthlist__16c1_s_p7_1[] = {
  120052. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  120053. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  120054. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120055. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  120056. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  120057. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  120058. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  120059. 10,10,10, 8, 8, 8, 8, 9, 9,
  120060. };
  120061. static float _vq_quantthresh__16c1_s_p7_1[] = {
  120062. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120063. 3.5, 4.5,
  120064. };
  120065. static long _vq_quantmap__16c1_s_p7_1[] = {
  120066. 9, 7, 5, 3, 1, 0, 2, 4,
  120067. 6, 8, 10,
  120068. };
  120069. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  120070. _vq_quantthresh__16c1_s_p7_1,
  120071. _vq_quantmap__16c1_s_p7_1,
  120072. 11,
  120073. 11
  120074. };
  120075. static static_codebook _16c1_s_p7_1 = {
  120076. 2, 121,
  120077. _vq_lengthlist__16c1_s_p7_1,
  120078. 1, -531365888, 1611661312, 4, 0,
  120079. _vq_quantlist__16c1_s_p7_1,
  120080. NULL,
  120081. &_vq_auxt__16c1_s_p7_1,
  120082. NULL,
  120083. 0
  120084. };
  120085. static long _vq_quantlist__16c1_s_p8_0[] = {
  120086. 6,
  120087. 5,
  120088. 7,
  120089. 4,
  120090. 8,
  120091. 3,
  120092. 9,
  120093. 2,
  120094. 10,
  120095. 1,
  120096. 11,
  120097. 0,
  120098. 12,
  120099. };
  120100. static long _vq_lengthlist__16c1_s_p8_0[] = {
  120101. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  120102. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  120103. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  120104. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  120105. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  120106. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  120107. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  120108. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  120109. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  120110. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  120111. 0,12,12,12,12,13,13,14,15,
  120112. };
  120113. static float _vq_quantthresh__16c1_s_p8_0[] = {
  120114. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120115. 12.5, 17.5, 22.5, 27.5,
  120116. };
  120117. static long _vq_quantmap__16c1_s_p8_0[] = {
  120118. 11, 9, 7, 5, 3, 1, 0, 2,
  120119. 4, 6, 8, 10, 12,
  120120. };
  120121. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  120122. _vq_quantthresh__16c1_s_p8_0,
  120123. _vq_quantmap__16c1_s_p8_0,
  120124. 13,
  120125. 13
  120126. };
  120127. static static_codebook _16c1_s_p8_0 = {
  120128. 2, 169,
  120129. _vq_lengthlist__16c1_s_p8_0,
  120130. 1, -526516224, 1616117760, 4, 0,
  120131. _vq_quantlist__16c1_s_p8_0,
  120132. NULL,
  120133. &_vq_auxt__16c1_s_p8_0,
  120134. NULL,
  120135. 0
  120136. };
  120137. static long _vq_quantlist__16c1_s_p8_1[] = {
  120138. 2,
  120139. 1,
  120140. 3,
  120141. 0,
  120142. 4,
  120143. };
  120144. static long _vq_lengthlist__16c1_s_p8_1[] = {
  120145. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120146. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120147. };
  120148. static float _vq_quantthresh__16c1_s_p8_1[] = {
  120149. -1.5, -0.5, 0.5, 1.5,
  120150. };
  120151. static long _vq_quantmap__16c1_s_p8_1[] = {
  120152. 3, 1, 0, 2, 4,
  120153. };
  120154. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  120155. _vq_quantthresh__16c1_s_p8_1,
  120156. _vq_quantmap__16c1_s_p8_1,
  120157. 5,
  120158. 5
  120159. };
  120160. static static_codebook _16c1_s_p8_1 = {
  120161. 2, 25,
  120162. _vq_lengthlist__16c1_s_p8_1,
  120163. 1, -533725184, 1611661312, 3, 0,
  120164. _vq_quantlist__16c1_s_p8_1,
  120165. NULL,
  120166. &_vq_auxt__16c1_s_p8_1,
  120167. NULL,
  120168. 0
  120169. };
  120170. static long _vq_quantlist__16c1_s_p9_0[] = {
  120171. 6,
  120172. 5,
  120173. 7,
  120174. 4,
  120175. 8,
  120176. 3,
  120177. 9,
  120178. 2,
  120179. 10,
  120180. 1,
  120181. 11,
  120182. 0,
  120183. 12,
  120184. };
  120185. static long _vq_lengthlist__16c1_s_p9_0[] = {
  120186. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120187. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120188. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120189. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120190. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  120191. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120192. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120193. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120194. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120195. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120196. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120197. };
  120198. static float _vq_quantthresh__16c1_s_p9_0[] = {
  120199. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  120200. 787.5, 1102.5, 1417.5, 1732.5,
  120201. };
  120202. static long _vq_quantmap__16c1_s_p9_0[] = {
  120203. 11, 9, 7, 5, 3, 1, 0, 2,
  120204. 4, 6, 8, 10, 12,
  120205. };
  120206. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  120207. _vq_quantthresh__16c1_s_p9_0,
  120208. _vq_quantmap__16c1_s_p9_0,
  120209. 13,
  120210. 13
  120211. };
  120212. static static_codebook _16c1_s_p9_0 = {
  120213. 2, 169,
  120214. _vq_lengthlist__16c1_s_p9_0,
  120215. 1, -513964032, 1628680192, 4, 0,
  120216. _vq_quantlist__16c1_s_p9_0,
  120217. NULL,
  120218. &_vq_auxt__16c1_s_p9_0,
  120219. NULL,
  120220. 0
  120221. };
  120222. static long _vq_quantlist__16c1_s_p9_1[] = {
  120223. 7,
  120224. 6,
  120225. 8,
  120226. 5,
  120227. 9,
  120228. 4,
  120229. 10,
  120230. 3,
  120231. 11,
  120232. 2,
  120233. 12,
  120234. 1,
  120235. 13,
  120236. 0,
  120237. 14,
  120238. };
  120239. static long _vq_lengthlist__16c1_s_p9_1[] = {
  120240. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  120241. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  120242. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  120243. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  120244. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  120245. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  120246. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  120247. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120248. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120249. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  120250. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120251. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120252. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  120253. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  120254. 13,
  120255. };
  120256. static float _vq_quantthresh__16c1_s_p9_1[] = {
  120257. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120258. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120259. };
  120260. static long _vq_quantmap__16c1_s_p9_1[] = {
  120261. 13, 11, 9, 7, 5, 3, 1, 0,
  120262. 2, 4, 6, 8, 10, 12, 14,
  120263. };
  120264. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  120265. _vq_quantthresh__16c1_s_p9_1,
  120266. _vq_quantmap__16c1_s_p9_1,
  120267. 15,
  120268. 15
  120269. };
  120270. static static_codebook _16c1_s_p9_1 = {
  120271. 2, 225,
  120272. _vq_lengthlist__16c1_s_p9_1,
  120273. 1, -520986624, 1620377600, 4, 0,
  120274. _vq_quantlist__16c1_s_p9_1,
  120275. NULL,
  120276. &_vq_auxt__16c1_s_p9_1,
  120277. NULL,
  120278. 0
  120279. };
  120280. static long _vq_quantlist__16c1_s_p9_2[] = {
  120281. 10,
  120282. 9,
  120283. 11,
  120284. 8,
  120285. 12,
  120286. 7,
  120287. 13,
  120288. 6,
  120289. 14,
  120290. 5,
  120291. 15,
  120292. 4,
  120293. 16,
  120294. 3,
  120295. 17,
  120296. 2,
  120297. 18,
  120298. 1,
  120299. 19,
  120300. 0,
  120301. 20,
  120302. };
  120303. static long _vq_lengthlist__16c1_s_p9_2[] = {
  120304. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  120305. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  120306. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  120307. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  120308. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  120309. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  120310. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  120311. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  120312. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  120313. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  120314. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  120315. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  120316. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  120317. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  120318. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  120319. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  120320. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  120321. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  120322. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  120323. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  120324. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  120325. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  120326. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  120327. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  120328. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  120329. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  120330. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  120331. 11,11,11,11,12,11,11,12,11,
  120332. };
  120333. static float _vq_quantthresh__16c1_s_p9_2[] = {
  120334. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120335. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120336. 6.5, 7.5, 8.5, 9.5,
  120337. };
  120338. static long _vq_quantmap__16c1_s_p9_2[] = {
  120339. 19, 17, 15, 13, 11, 9, 7, 5,
  120340. 3, 1, 0, 2, 4, 6, 8, 10,
  120341. 12, 14, 16, 18, 20,
  120342. };
  120343. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  120344. _vq_quantthresh__16c1_s_p9_2,
  120345. _vq_quantmap__16c1_s_p9_2,
  120346. 21,
  120347. 21
  120348. };
  120349. static static_codebook _16c1_s_p9_2 = {
  120350. 2, 441,
  120351. _vq_lengthlist__16c1_s_p9_2,
  120352. 1, -529268736, 1611661312, 5, 0,
  120353. _vq_quantlist__16c1_s_p9_2,
  120354. NULL,
  120355. &_vq_auxt__16c1_s_p9_2,
  120356. NULL,
  120357. 0
  120358. };
  120359. static long _huff_lengthlist__16c1_s_short[] = {
  120360. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  120361. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  120362. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  120363. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  120364. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  120365. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  120366. 9, 9,10,13,
  120367. };
  120368. static static_codebook _huff_book__16c1_s_short = {
  120369. 2, 100,
  120370. _huff_lengthlist__16c1_s_short,
  120371. 0, 0, 0, 0, 0,
  120372. NULL,
  120373. NULL,
  120374. NULL,
  120375. NULL,
  120376. 0
  120377. };
  120378. static long _huff_lengthlist__16c2_s_long[] = {
  120379. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  120380. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  120381. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  120382. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  120383. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  120384. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  120385. 14,14,16,18,
  120386. };
  120387. static static_codebook _huff_book__16c2_s_long = {
  120388. 2, 100,
  120389. _huff_lengthlist__16c2_s_long,
  120390. 0, 0, 0, 0, 0,
  120391. NULL,
  120392. NULL,
  120393. NULL,
  120394. NULL,
  120395. 0
  120396. };
  120397. static long _vq_quantlist__16c2_s_p1_0[] = {
  120398. 1,
  120399. 0,
  120400. 2,
  120401. };
  120402. static long _vq_lengthlist__16c2_s_p1_0[] = {
  120403. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  120404. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120408. 0,
  120409. };
  120410. static float _vq_quantthresh__16c2_s_p1_0[] = {
  120411. -0.5, 0.5,
  120412. };
  120413. static long _vq_quantmap__16c2_s_p1_0[] = {
  120414. 1, 0, 2,
  120415. };
  120416. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  120417. _vq_quantthresh__16c2_s_p1_0,
  120418. _vq_quantmap__16c2_s_p1_0,
  120419. 3,
  120420. 3
  120421. };
  120422. static static_codebook _16c2_s_p1_0 = {
  120423. 4, 81,
  120424. _vq_lengthlist__16c2_s_p1_0,
  120425. 1, -535822336, 1611661312, 2, 0,
  120426. _vq_quantlist__16c2_s_p1_0,
  120427. NULL,
  120428. &_vq_auxt__16c2_s_p1_0,
  120429. NULL,
  120430. 0
  120431. };
  120432. static long _vq_quantlist__16c2_s_p2_0[] = {
  120433. 2,
  120434. 1,
  120435. 3,
  120436. 0,
  120437. 4,
  120438. };
  120439. static long _vq_lengthlist__16c2_s_p2_0[] = {
  120440. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  120441. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  120442. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  120443. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  120444. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  120445. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  120446. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  120447. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  120448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120452. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  120453. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  120454. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  120455. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  120456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120460. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  120461. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  120462. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  120463. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120468. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  120469. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  120470. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  120471. 0, 0,13,13, 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, 0, 0, 0, 0, 0, 0, 0, 0,
  120475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  120476. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  120477. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  120478. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  120479. 13,
  120480. };
  120481. static float _vq_quantthresh__16c2_s_p2_0[] = {
  120482. -1.5, -0.5, 0.5, 1.5,
  120483. };
  120484. static long _vq_quantmap__16c2_s_p2_0[] = {
  120485. 3, 1, 0, 2, 4,
  120486. };
  120487. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  120488. _vq_quantthresh__16c2_s_p2_0,
  120489. _vq_quantmap__16c2_s_p2_0,
  120490. 5,
  120491. 5
  120492. };
  120493. static static_codebook _16c2_s_p2_0 = {
  120494. 4, 625,
  120495. _vq_lengthlist__16c2_s_p2_0,
  120496. 1, -533725184, 1611661312, 3, 0,
  120497. _vq_quantlist__16c2_s_p2_0,
  120498. NULL,
  120499. &_vq_auxt__16c2_s_p2_0,
  120500. NULL,
  120501. 0
  120502. };
  120503. static long _vq_quantlist__16c2_s_p3_0[] = {
  120504. 4,
  120505. 3,
  120506. 5,
  120507. 2,
  120508. 6,
  120509. 1,
  120510. 7,
  120511. 0,
  120512. 8,
  120513. };
  120514. static long _vq_lengthlist__16c2_s_p3_0[] = {
  120515. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  120516. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  120517. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  120518. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  120519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120520. 0,
  120521. };
  120522. static float _vq_quantthresh__16c2_s_p3_0[] = {
  120523. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120524. };
  120525. static long _vq_quantmap__16c2_s_p3_0[] = {
  120526. 7, 5, 3, 1, 0, 2, 4, 6,
  120527. 8,
  120528. };
  120529. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  120530. _vq_quantthresh__16c2_s_p3_0,
  120531. _vq_quantmap__16c2_s_p3_0,
  120532. 9,
  120533. 9
  120534. };
  120535. static static_codebook _16c2_s_p3_0 = {
  120536. 2, 81,
  120537. _vq_lengthlist__16c2_s_p3_0,
  120538. 1, -531628032, 1611661312, 4, 0,
  120539. _vq_quantlist__16c2_s_p3_0,
  120540. NULL,
  120541. &_vq_auxt__16c2_s_p3_0,
  120542. NULL,
  120543. 0
  120544. };
  120545. static long _vq_quantlist__16c2_s_p4_0[] = {
  120546. 8,
  120547. 7,
  120548. 9,
  120549. 6,
  120550. 10,
  120551. 5,
  120552. 11,
  120553. 4,
  120554. 12,
  120555. 3,
  120556. 13,
  120557. 2,
  120558. 14,
  120559. 1,
  120560. 15,
  120561. 0,
  120562. 16,
  120563. };
  120564. static long _vq_lengthlist__16c2_s_p4_0[] = {
  120565. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  120566. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  120567. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  120568. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  120569. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  120570. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  120571. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  120572. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  120573. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  120574. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  120575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120583. 0,
  120584. };
  120585. static float _vq_quantthresh__16c2_s_p4_0[] = {
  120586. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120587. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120588. };
  120589. static long _vq_quantmap__16c2_s_p4_0[] = {
  120590. 15, 13, 11, 9, 7, 5, 3, 1,
  120591. 0, 2, 4, 6, 8, 10, 12, 14,
  120592. 16,
  120593. };
  120594. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  120595. _vq_quantthresh__16c2_s_p4_0,
  120596. _vq_quantmap__16c2_s_p4_0,
  120597. 17,
  120598. 17
  120599. };
  120600. static static_codebook _16c2_s_p4_0 = {
  120601. 2, 289,
  120602. _vq_lengthlist__16c2_s_p4_0,
  120603. 1, -529530880, 1611661312, 5, 0,
  120604. _vq_quantlist__16c2_s_p4_0,
  120605. NULL,
  120606. &_vq_auxt__16c2_s_p4_0,
  120607. NULL,
  120608. 0
  120609. };
  120610. static long _vq_quantlist__16c2_s_p5_0[] = {
  120611. 1,
  120612. 0,
  120613. 2,
  120614. };
  120615. static long _vq_lengthlist__16c2_s_p5_0[] = {
  120616. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  120617. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  120618. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  120619. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  120620. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  120621. 12,
  120622. };
  120623. static float _vq_quantthresh__16c2_s_p5_0[] = {
  120624. -5.5, 5.5,
  120625. };
  120626. static long _vq_quantmap__16c2_s_p5_0[] = {
  120627. 1, 0, 2,
  120628. };
  120629. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  120630. _vq_quantthresh__16c2_s_p5_0,
  120631. _vq_quantmap__16c2_s_p5_0,
  120632. 3,
  120633. 3
  120634. };
  120635. static static_codebook _16c2_s_p5_0 = {
  120636. 4, 81,
  120637. _vq_lengthlist__16c2_s_p5_0,
  120638. 1, -529137664, 1618345984, 2, 0,
  120639. _vq_quantlist__16c2_s_p5_0,
  120640. NULL,
  120641. &_vq_auxt__16c2_s_p5_0,
  120642. NULL,
  120643. 0
  120644. };
  120645. static long _vq_quantlist__16c2_s_p5_1[] = {
  120646. 5,
  120647. 4,
  120648. 6,
  120649. 3,
  120650. 7,
  120651. 2,
  120652. 8,
  120653. 1,
  120654. 9,
  120655. 0,
  120656. 10,
  120657. };
  120658. static long _vq_lengthlist__16c2_s_p5_1[] = {
  120659. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  120660. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  120661. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  120662. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  120663. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  120664. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  120665. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  120666. 11,11,11, 7, 7, 8, 8, 8, 8,
  120667. };
  120668. static float _vq_quantthresh__16c2_s_p5_1[] = {
  120669. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120670. 3.5, 4.5,
  120671. };
  120672. static long _vq_quantmap__16c2_s_p5_1[] = {
  120673. 9, 7, 5, 3, 1, 0, 2, 4,
  120674. 6, 8, 10,
  120675. };
  120676. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  120677. _vq_quantthresh__16c2_s_p5_1,
  120678. _vq_quantmap__16c2_s_p5_1,
  120679. 11,
  120680. 11
  120681. };
  120682. static static_codebook _16c2_s_p5_1 = {
  120683. 2, 121,
  120684. _vq_lengthlist__16c2_s_p5_1,
  120685. 1, -531365888, 1611661312, 4, 0,
  120686. _vq_quantlist__16c2_s_p5_1,
  120687. NULL,
  120688. &_vq_auxt__16c2_s_p5_1,
  120689. NULL,
  120690. 0
  120691. };
  120692. static long _vq_quantlist__16c2_s_p6_0[] = {
  120693. 6,
  120694. 5,
  120695. 7,
  120696. 4,
  120697. 8,
  120698. 3,
  120699. 9,
  120700. 2,
  120701. 10,
  120702. 1,
  120703. 11,
  120704. 0,
  120705. 12,
  120706. };
  120707. static long _vq_lengthlist__16c2_s_p6_0[] = {
  120708. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120709. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  120710. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  120711. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  120712. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  120713. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  120714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120718. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120719. };
  120720. static float _vq_quantthresh__16c2_s_p6_0[] = {
  120721. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120722. 12.5, 17.5, 22.5, 27.5,
  120723. };
  120724. static long _vq_quantmap__16c2_s_p6_0[] = {
  120725. 11, 9, 7, 5, 3, 1, 0, 2,
  120726. 4, 6, 8, 10, 12,
  120727. };
  120728. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  120729. _vq_quantthresh__16c2_s_p6_0,
  120730. _vq_quantmap__16c2_s_p6_0,
  120731. 13,
  120732. 13
  120733. };
  120734. static static_codebook _16c2_s_p6_0 = {
  120735. 2, 169,
  120736. _vq_lengthlist__16c2_s_p6_0,
  120737. 1, -526516224, 1616117760, 4, 0,
  120738. _vq_quantlist__16c2_s_p6_0,
  120739. NULL,
  120740. &_vq_auxt__16c2_s_p6_0,
  120741. NULL,
  120742. 0
  120743. };
  120744. static long _vq_quantlist__16c2_s_p6_1[] = {
  120745. 2,
  120746. 1,
  120747. 3,
  120748. 0,
  120749. 4,
  120750. };
  120751. static long _vq_lengthlist__16c2_s_p6_1[] = {
  120752. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120753. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120754. };
  120755. static float _vq_quantthresh__16c2_s_p6_1[] = {
  120756. -1.5, -0.5, 0.5, 1.5,
  120757. };
  120758. static long _vq_quantmap__16c2_s_p6_1[] = {
  120759. 3, 1, 0, 2, 4,
  120760. };
  120761. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  120762. _vq_quantthresh__16c2_s_p6_1,
  120763. _vq_quantmap__16c2_s_p6_1,
  120764. 5,
  120765. 5
  120766. };
  120767. static static_codebook _16c2_s_p6_1 = {
  120768. 2, 25,
  120769. _vq_lengthlist__16c2_s_p6_1,
  120770. 1, -533725184, 1611661312, 3, 0,
  120771. _vq_quantlist__16c2_s_p6_1,
  120772. NULL,
  120773. &_vq_auxt__16c2_s_p6_1,
  120774. NULL,
  120775. 0
  120776. };
  120777. static long _vq_quantlist__16c2_s_p7_0[] = {
  120778. 6,
  120779. 5,
  120780. 7,
  120781. 4,
  120782. 8,
  120783. 3,
  120784. 9,
  120785. 2,
  120786. 10,
  120787. 1,
  120788. 11,
  120789. 0,
  120790. 12,
  120791. };
  120792. static long _vq_lengthlist__16c2_s_p7_0[] = {
  120793. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  120794. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  120795. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  120796. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  120797. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  120798. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  120799. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  120800. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  120801. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  120802. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  120803. 18,13,14,13,13,14,13,15,14,
  120804. };
  120805. static float _vq_quantthresh__16c2_s_p7_0[] = {
  120806. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  120807. 27.5, 38.5, 49.5, 60.5,
  120808. };
  120809. static long _vq_quantmap__16c2_s_p7_0[] = {
  120810. 11, 9, 7, 5, 3, 1, 0, 2,
  120811. 4, 6, 8, 10, 12,
  120812. };
  120813. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  120814. _vq_quantthresh__16c2_s_p7_0,
  120815. _vq_quantmap__16c2_s_p7_0,
  120816. 13,
  120817. 13
  120818. };
  120819. static static_codebook _16c2_s_p7_0 = {
  120820. 2, 169,
  120821. _vq_lengthlist__16c2_s_p7_0,
  120822. 1, -523206656, 1618345984, 4, 0,
  120823. _vq_quantlist__16c2_s_p7_0,
  120824. NULL,
  120825. &_vq_auxt__16c2_s_p7_0,
  120826. NULL,
  120827. 0
  120828. };
  120829. static long _vq_quantlist__16c2_s_p7_1[] = {
  120830. 5,
  120831. 4,
  120832. 6,
  120833. 3,
  120834. 7,
  120835. 2,
  120836. 8,
  120837. 1,
  120838. 9,
  120839. 0,
  120840. 10,
  120841. };
  120842. static long _vq_lengthlist__16c2_s_p7_1[] = {
  120843. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  120844. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  120845. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  120846. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120847. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  120848. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  120849. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  120850. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  120851. };
  120852. static float _vq_quantthresh__16c2_s_p7_1[] = {
  120853. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120854. 3.5, 4.5,
  120855. };
  120856. static long _vq_quantmap__16c2_s_p7_1[] = {
  120857. 9, 7, 5, 3, 1, 0, 2, 4,
  120858. 6, 8, 10,
  120859. };
  120860. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  120861. _vq_quantthresh__16c2_s_p7_1,
  120862. _vq_quantmap__16c2_s_p7_1,
  120863. 11,
  120864. 11
  120865. };
  120866. static static_codebook _16c2_s_p7_1 = {
  120867. 2, 121,
  120868. _vq_lengthlist__16c2_s_p7_1,
  120869. 1, -531365888, 1611661312, 4, 0,
  120870. _vq_quantlist__16c2_s_p7_1,
  120871. NULL,
  120872. &_vq_auxt__16c2_s_p7_1,
  120873. NULL,
  120874. 0
  120875. };
  120876. static long _vq_quantlist__16c2_s_p8_0[] = {
  120877. 7,
  120878. 6,
  120879. 8,
  120880. 5,
  120881. 9,
  120882. 4,
  120883. 10,
  120884. 3,
  120885. 11,
  120886. 2,
  120887. 12,
  120888. 1,
  120889. 13,
  120890. 0,
  120891. 14,
  120892. };
  120893. static long _vq_lengthlist__16c2_s_p8_0[] = {
  120894. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  120895. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  120896. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  120897. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  120898. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  120899. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  120900. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  120901. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  120902. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  120903. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  120904. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  120905. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  120906. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  120907. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  120908. 13,
  120909. };
  120910. static float _vq_quantthresh__16c2_s_p8_0[] = {
  120911. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  120912. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  120913. };
  120914. static long _vq_quantmap__16c2_s_p8_0[] = {
  120915. 13, 11, 9, 7, 5, 3, 1, 0,
  120916. 2, 4, 6, 8, 10, 12, 14,
  120917. };
  120918. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  120919. _vq_quantthresh__16c2_s_p8_0,
  120920. _vq_quantmap__16c2_s_p8_0,
  120921. 15,
  120922. 15
  120923. };
  120924. static static_codebook _16c2_s_p8_0 = {
  120925. 2, 225,
  120926. _vq_lengthlist__16c2_s_p8_0,
  120927. 1, -520986624, 1620377600, 4, 0,
  120928. _vq_quantlist__16c2_s_p8_0,
  120929. NULL,
  120930. &_vq_auxt__16c2_s_p8_0,
  120931. NULL,
  120932. 0
  120933. };
  120934. static long _vq_quantlist__16c2_s_p8_1[] = {
  120935. 10,
  120936. 9,
  120937. 11,
  120938. 8,
  120939. 12,
  120940. 7,
  120941. 13,
  120942. 6,
  120943. 14,
  120944. 5,
  120945. 15,
  120946. 4,
  120947. 16,
  120948. 3,
  120949. 17,
  120950. 2,
  120951. 18,
  120952. 1,
  120953. 19,
  120954. 0,
  120955. 20,
  120956. };
  120957. static long _vq_lengthlist__16c2_s_p8_1[] = {
  120958. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  120959. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  120960. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  120961. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  120962. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  120963. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  120964. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  120965. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  120966. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  120967. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  120968. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  120969. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  120970. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  120971. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  120972. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  120973. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  120974. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  120975. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  120976. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  120977. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  120978. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  120979. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  120980. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  120981. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  120982. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  120983. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  120984. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  120985. 10,11,10,10,10,10,10,10,10,
  120986. };
  120987. static float _vq_quantthresh__16c2_s_p8_1[] = {
  120988. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120989. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120990. 6.5, 7.5, 8.5, 9.5,
  120991. };
  120992. static long _vq_quantmap__16c2_s_p8_1[] = {
  120993. 19, 17, 15, 13, 11, 9, 7, 5,
  120994. 3, 1, 0, 2, 4, 6, 8, 10,
  120995. 12, 14, 16, 18, 20,
  120996. };
  120997. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  120998. _vq_quantthresh__16c2_s_p8_1,
  120999. _vq_quantmap__16c2_s_p8_1,
  121000. 21,
  121001. 21
  121002. };
  121003. static static_codebook _16c2_s_p8_1 = {
  121004. 2, 441,
  121005. _vq_lengthlist__16c2_s_p8_1,
  121006. 1, -529268736, 1611661312, 5, 0,
  121007. _vq_quantlist__16c2_s_p8_1,
  121008. NULL,
  121009. &_vq_auxt__16c2_s_p8_1,
  121010. NULL,
  121011. 0
  121012. };
  121013. static long _vq_quantlist__16c2_s_p9_0[] = {
  121014. 6,
  121015. 5,
  121016. 7,
  121017. 4,
  121018. 8,
  121019. 3,
  121020. 9,
  121021. 2,
  121022. 10,
  121023. 1,
  121024. 11,
  121025. 0,
  121026. 12,
  121027. };
  121028. static long _vq_lengthlist__16c2_s_p9_0[] = {
  121029. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121030. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121031. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121032. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121033. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  121034. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121035. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121036. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121037. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121038. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121039. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121040. };
  121041. static float _vq_quantthresh__16c2_s_p9_0[] = {
  121042. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  121043. 2327.5, 3258.5, 4189.5, 5120.5,
  121044. };
  121045. static long _vq_quantmap__16c2_s_p9_0[] = {
  121046. 11, 9, 7, 5, 3, 1, 0, 2,
  121047. 4, 6, 8, 10, 12,
  121048. };
  121049. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  121050. _vq_quantthresh__16c2_s_p9_0,
  121051. _vq_quantmap__16c2_s_p9_0,
  121052. 13,
  121053. 13
  121054. };
  121055. static static_codebook _16c2_s_p9_0 = {
  121056. 2, 169,
  121057. _vq_lengthlist__16c2_s_p9_0,
  121058. 1, -510275072, 1631393792, 4, 0,
  121059. _vq_quantlist__16c2_s_p9_0,
  121060. NULL,
  121061. &_vq_auxt__16c2_s_p9_0,
  121062. NULL,
  121063. 0
  121064. };
  121065. static long _vq_quantlist__16c2_s_p9_1[] = {
  121066. 8,
  121067. 7,
  121068. 9,
  121069. 6,
  121070. 10,
  121071. 5,
  121072. 11,
  121073. 4,
  121074. 12,
  121075. 3,
  121076. 13,
  121077. 2,
  121078. 14,
  121079. 1,
  121080. 15,
  121081. 0,
  121082. 16,
  121083. };
  121084. static long _vq_lengthlist__16c2_s_p9_1[] = {
  121085. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  121086. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  121087. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  121088. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  121089. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  121090. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  121091. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  121092. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  121093. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  121094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  121095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121096. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121098. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121099. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121100. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  121101. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  121102. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121103. 10,
  121104. };
  121105. static float _vq_quantthresh__16c2_s_p9_1[] = {
  121106. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  121107. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  121108. };
  121109. static long _vq_quantmap__16c2_s_p9_1[] = {
  121110. 15, 13, 11, 9, 7, 5, 3, 1,
  121111. 0, 2, 4, 6, 8, 10, 12, 14,
  121112. 16,
  121113. };
  121114. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  121115. _vq_quantthresh__16c2_s_p9_1,
  121116. _vq_quantmap__16c2_s_p9_1,
  121117. 17,
  121118. 17
  121119. };
  121120. static static_codebook _16c2_s_p9_1 = {
  121121. 2, 289,
  121122. _vq_lengthlist__16c2_s_p9_1,
  121123. 1, -518488064, 1622704128, 5, 0,
  121124. _vq_quantlist__16c2_s_p9_1,
  121125. NULL,
  121126. &_vq_auxt__16c2_s_p9_1,
  121127. NULL,
  121128. 0
  121129. };
  121130. static long _vq_quantlist__16c2_s_p9_2[] = {
  121131. 13,
  121132. 12,
  121133. 14,
  121134. 11,
  121135. 15,
  121136. 10,
  121137. 16,
  121138. 9,
  121139. 17,
  121140. 8,
  121141. 18,
  121142. 7,
  121143. 19,
  121144. 6,
  121145. 20,
  121146. 5,
  121147. 21,
  121148. 4,
  121149. 22,
  121150. 3,
  121151. 23,
  121152. 2,
  121153. 24,
  121154. 1,
  121155. 25,
  121156. 0,
  121157. 26,
  121158. };
  121159. static long _vq_lengthlist__16c2_s_p9_2[] = {
  121160. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  121161. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  121162. };
  121163. static float _vq_quantthresh__16c2_s_p9_2[] = {
  121164. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  121165. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  121166. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  121167. 11.5, 12.5,
  121168. };
  121169. static long _vq_quantmap__16c2_s_p9_2[] = {
  121170. 25, 23, 21, 19, 17, 15, 13, 11,
  121171. 9, 7, 5, 3, 1, 0, 2, 4,
  121172. 6, 8, 10, 12, 14, 16, 18, 20,
  121173. 22, 24, 26,
  121174. };
  121175. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  121176. _vq_quantthresh__16c2_s_p9_2,
  121177. _vq_quantmap__16c2_s_p9_2,
  121178. 27,
  121179. 27
  121180. };
  121181. static static_codebook _16c2_s_p9_2 = {
  121182. 1, 27,
  121183. _vq_lengthlist__16c2_s_p9_2,
  121184. 1, -528875520, 1611661312, 5, 0,
  121185. _vq_quantlist__16c2_s_p9_2,
  121186. NULL,
  121187. &_vq_auxt__16c2_s_p9_2,
  121188. NULL,
  121189. 0
  121190. };
  121191. static long _huff_lengthlist__16c2_s_short[] = {
  121192. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  121193. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  121194. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  121195. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  121196. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  121197. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  121198. 15,12,14,14,
  121199. };
  121200. static static_codebook _huff_book__16c2_s_short = {
  121201. 2, 100,
  121202. _huff_lengthlist__16c2_s_short,
  121203. 0, 0, 0, 0, 0,
  121204. NULL,
  121205. NULL,
  121206. NULL,
  121207. NULL,
  121208. 0
  121209. };
  121210. static long _vq_quantlist__8c0_s_p1_0[] = {
  121211. 1,
  121212. 0,
  121213. 2,
  121214. };
  121215. static long _vq_lengthlist__8c0_s_p1_0[] = {
  121216. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  121217. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121221. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  121222. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121226. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  121227. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121239. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121244. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121249. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  121262. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  121267. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  121272. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  121284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  121289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  121294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  121308. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  121313. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  121318. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121330. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121335. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121627. };
  121628. static float _vq_quantthresh__8c0_s_p1_0[] = {
  121629. -0.5, 0.5,
  121630. };
  121631. static long _vq_quantmap__8c0_s_p1_0[] = {
  121632. 1, 0, 2,
  121633. };
  121634. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  121635. _vq_quantthresh__8c0_s_p1_0,
  121636. _vq_quantmap__8c0_s_p1_0,
  121637. 3,
  121638. 3
  121639. };
  121640. static static_codebook _8c0_s_p1_0 = {
  121641. 8, 6561,
  121642. _vq_lengthlist__8c0_s_p1_0,
  121643. 1, -535822336, 1611661312, 2, 0,
  121644. _vq_quantlist__8c0_s_p1_0,
  121645. NULL,
  121646. &_vq_auxt__8c0_s_p1_0,
  121647. NULL,
  121648. 0
  121649. };
  121650. static long _vq_quantlist__8c0_s_p2_0[] = {
  121651. 2,
  121652. 1,
  121653. 3,
  121654. 0,
  121655. 4,
  121656. };
  121657. static long _vq_lengthlist__8c0_s_p2_0[] = {
  121658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121698. };
  121699. static float _vq_quantthresh__8c0_s_p2_0[] = {
  121700. -1.5, -0.5, 0.5, 1.5,
  121701. };
  121702. static long _vq_quantmap__8c0_s_p2_0[] = {
  121703. 3, 1, 0, 2, 4,
  121704. };
  121705. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  121706. _vq_quantthresh__8c0_s_p2_0,
  121707. _vq_quantmap__8c0_s_p2_0,
  121708. 5,
  121709. 5
  121710. };
  121711. static static_codebook _8c0_s_p2_0 = {
  121712. 4, 625,
  121713. _vq_lengthlist__8c0_s_p2_0,
  121714. 1, -533725184, 1611661312, 3, 0,
  121715. _vq_quantlist__8c0_s_p2_0,
  121716. NULL,
  121717. &_vq_auxt__8c0_s_p2_0,
  121718. NULL,
  121719. 0
  121720. };
  121721. static long _vq_quantlist__8c0_s_p3_0[] = {
  121722. 2,
  121723. 1,
  121724. 3,
  121725. 0,
  121726. 4,
  121727. };
  121728. static long _vq_lengthlist__8c0_s_p3_0[] = {
  121729. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  121731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121732. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  121734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121735. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  121736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  121769. };
  121770. static float _vq_quantthresh__8c0_s_p3_0[] = {
  121771. -1.5, -0.5, 0.5, 1.5,
  121772. };
  121773. static long _vq_quantmap__8c0_s_p3_0[] = {
  121774. 3, 1, 0, 2, 4,
  121775. };
  121776. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  121777. _vq_quantthresh__8c0_s_p3_0,
  121778. _vq_quantmap__8c0_s_p3_0,
  121779. 5,
  121780. 5
  121781. };
  121782. static static_codebook _8c0_s_p3_0 = {
  121783. 4, 625,
  121784. _vq_lengthlist__8c0_s_p3_0,
  121785. 1, -533725184, 1611661312, 3, 0,
  121786. _vq_quantlist__8c0_s_p3_0,
  121787. NULL,
  121788. &_vq_auxt__8c0_s_p3_0,
  121789. NULL,
  121790. 0
  121791. };
  121792. static long _vq_quantlist__8c0_s_p4_0[] = {
  121793. 4,
  121794. 3,
  121795. 5,
  121796. 2,
  121797. 6,
  121798. 1,
  121799. 7,
  121800. 0,
  121801. 8,
  121802. };
  121803. static long _vq_lengthlist__8c0_s_p4_0[] = {
  121804. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  121805. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  121806. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  121807. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  121808. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121809. 0,
  121810. };
  121811. static float _vq_quantthresh__8c0_s_p4_0[] = {
  121812. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121813. };
  121814. static long _vq_quantmap__8c0_s_p4_0[] = {
  121815. 7, 5, 3, 1, 0, 2, 4, 6,
  121816. 8,
  121817. };
  121818. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  121819. _vq_quantthresh__8c0_s_p4_0,
  121820. _vq_quantmap__8c0_s_p4_0,
  121821. 9,
  121822. 9
  121823. };
  121824. static static_codebook _8c0_s_p4_0 = {
  121825. 2, 81,
  121826. _vq_lengthlist__8c0_s_p4_0,
  121827. 1, -531628032, 1611661312, 4, 0,
  121828. _vq_quantlist__8c0_s_p4_0,
  121829. NULL,
  121830. &_vq_auxt__8c0_s_p4_0,
  121831. NULL,
  121832. 0
  121833. };
  121834. static long _vq_quantlist__8c0_s_p5_0[] = {
  121835. 4,
  121836. 3,
  121837. 5,
  121838. 2,
  121839. 6,
  121840. 1,
  121841. 7,
  121842. 0,
  121843. 8,
  121844. };
  121845. static long _vq_lengthlist__8c0_s_p5_0[] = {
  121846. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  121847. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  121848. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  121849. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121850. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  121851. 10,
  121852. };
  121853. static float _vq_quantthresh__8c0_s_p5_0[] = {
  121854. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121855. };
  121856. static long _vq_quantmap__8c0_s_p5_0[] = {
  121857. 7, 5, 3, 1, 0, 2, 4, 6,
  121858. 8,
  121859. };
  121860. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  121861. _vq_quantthresh__8c0_s_p5_0,
  121862. _vq_quantmap__8c0_s_p5_0,
  121863. 9,
  121864. 9
  121865. };
  121866. static static_codebook _8c0_s_p5_0 = {
  121867. 2, 81,
  121868. _vq_lengthlist__8c0_s_p5_0,
  121869. 1, -531628032, 1611661312, 4, 0,
  121870. _vq_quantlist__8c0_s_p5_0,
  121871. NULL,
  121872. &_vq_auxt__8c0_s_p5_0,
  121873. NULL,
  121874. 0
  121875. };
  121876. static long _vq_quantlist__8c0_s_p6_0[] = {
  121877. 8,
  121878. 7,
  121879. 9,
  121880. 6,
  121881. 10,
  121882. 5,
  121883. 11,
  121884. 4,
  121885. 12,
  121886. 3,
  121887. 13,
  121888. 2,
  121889. 14,
  121890. 1,
  121891. 15,
  121892. 0,
  121893. 16,
  121894. };
  121895. static long _vq_lengthlist__8c0_s_p6_0[] = {
  121896. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  121897. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121898. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121899. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  121900. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  121901. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  121902. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  121903. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  121904. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  121905. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121906. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  121907. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  121908. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  121909. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  121910. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  121911. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  121912. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  121913. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  121914. 14,
  121915. };
  121916. static float _vq_quantthresh__8c0_s_p6_0[] = {
  121917. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121918. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121919. };
  121920. static long _vq_quantmap__8c0_s_p6_0[] = {
  121921. 15, 13, 11, 9, 7, 5, 3, 1,
  121922. 0, 2, 4, 6, 8, 10, 12, 14,
  121923. 16,
  121924. };
  121925. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  121926. _vq_quantthresh__8c0_s_p6_0,
  121927. _vq_quantmap__8c0_s_p6_0,
  121928. 17,
  121929. 17
  121930. };
  121931. static static_codebook _8c0_s_p6_0 = {
  121932. 2, 289,
  121933. _vq_lengthlist__8c0_s_p6_0,
  121934. 1, -529530880, 1611661312, 5, 0,
  121935. _vq_quantlist__8c0_s_p6_0,
  121936. NULL,
  121937. &_vq_auxt__8c0_s_p6_0,
  121938. NULL,
  121939. 0
  121940. };
  121941. static long _vq_quantlist__8c0_s_p7_0[] = {
  121942. 1,
  121943. 0,
  121944. 2,
  121945. };
  121946. static long _vq_lengthlist__8c0_s_p7_0[] = {
  121947. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  121948. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  121949. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  121950. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  121951. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  121952. 10,
  121953. };
  121954. static float _vq_quantthresh__8c0_s_p7_0[] = {
  121955. -5.5, 5.5,
  121956. };
  121957. static long _vq_quantmap__8c0_s_p7_0[] = {
  121958. 1, 0, 2,
  121959. };
  121960. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  121961. _vq_quantthresh__8c0_s_p7_0,
  121962. _vq_quantmap__8c0_s_p7_0,
  121963. 3,
  121964. 3
  121965. };
  121966. static static_codebook _8c0_s_p7_0 = {
  121967. 4, 81,
  121968. _vq_lengthlist__8c0_s_p7_0,
  121969. 1, -529137664, 1618345984, 2, 0,
  121970. _vq_quantlist__8c0_s_p7_0,
  121971. NULL,
  121972. &_vq_auxt__8c0_s_p7_0,
  121973. NULL,
  121974. 0
  121975. };
  121976. static long _vq_quantlist__8c0_s_p7_1[] = {
  121977. 5,
  121978. 4,
  121979. 6,
  121980. 3,
  121981. 7,
  121982. 2,
  121983. 8,
  121984. 1,
  121985. 9,
  121986. 0,
  121987. 10,
  121988. };
  121989. static long _vq_lengthlist__8c0_s_p7_1[] = {
  121990. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  121991. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  121992. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  121993. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  121994. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  121995. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  121996. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  121997. 10,10,10, 9, 9, 9,10,10,10,
  121998. };
  121999. static float _vq_quantthresh__8c0_s_p7_1[] = {
  122000. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122001. 3.5, 4.5,
  122002. };
  122003. static long _vq_quantmap__8c0_s_p7_1[] = {
  122004. 9, 7, 5, 3, 1, 0, 2, 4,
  122005. 6, 8, 10,
  122006. };
  122007. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  122008. _vq_quantthresh__8c0_s_p7_1,
  122009. _vq_quantmap__8c0_s_p7_1,
  122010. 11,
  122011. 11
  122012. };
  122013. static static_codebook _8c0_s_p7_1 = {
  122014. 2, 121,
  122015. _vq_lengthlist__8c0_s_p7_1,
  122016. 1, -531365888, 1611661312, 4, 0,
  122017. _vq_quantlist__8c0_s_p7_1,
  122018. NULL,
  122019. &_vq_auxt__8c0_s_p7_1,
  122020. NULL,
  122021. 0
  122022. };
  122023. static long _vq_quantlist__8c0_s_p8_0[] = {
  122024. 6,
  122025. 5,
  122026. 7,
  122027. 4,
  122028. 8,
  122029. 3,
  122030. 9,
  122031. 2,
  122032. 10,
  122033. 1,
  122034. 11,
  122035. 0,
  122036. 12,
  122037. };
  122038. static long _vq_lengthlist__8c0_s_p8_0[] = {
  122039. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  122040. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  122041. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  122042. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  122043. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  122044. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  122045. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  122046. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  122047. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  122048. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  122049. 0, 0,13,13,11,13,13,11,12,
  122050. };
  122051. static float _vq_quantthresh__8c0_s_p8_0[] = {
  122052. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122053. 12.5, 17.5, 22.5, 27.5,
  122054. };
  122055. static long _vq_quantmap__8c0_s_p8_0[] = {
  122056. 11, 9, 7, 5, 3, 1, 0, 2,
  122057. 4, 6, 8, 10, 12,
  122058. };
  122059. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  122060. _vq_quantthresh__8c0_s_p8_0,
  122061. _vq_quantmap__8c0_s_p8_0,
  122062. 13,
  122063. 13
  122064. };
  122065. static static_codebook _8c0_s_p8_0 = {
  122066. 2, 169,
  122067. _vq_lengthlist__8c0_s_p8_0,
  122068. 1, -526516224, 1616117760, 4, 0,
  122069. _vq_quantlist__8c0_s_p8_0,
  122070. NULL,
  122071. &_vq_auxt__8c0_s_p8_0,
  122072. NULL,
  122073. 0
  122074. };
  122075. static long _vq_quantlist__8c0_s_p8_1[] = {
  122076. 2,
  122077. 1,
  122078. 3,
  122079. 0,
  122080. 4,
  122081. };
  122082. static long _vq_lengthlist__8c0_s_p8_1[] = {
  122083. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  122084. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  122085. };
  122086. static float _vq_quantthresh__8c0_s_p8_1[] = {
  122087. -1.5, -0.5, 0.5, 1.5,
  122088. };
  122089. static long _vq_quantmap__8c0_s_p8_1[] = {
  122090. 3, 1, 0, 2, 4,
  122091. };
  122092. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  122093. _vq_quantthresh__8c0_s_p8_1,
  122094. _vq_quantmap__8c0_s_p8_1,
  122095. 5,
  122096. 5
  122097. };
  122098. static static_codebook _8c0_s_p8_1 = {
  122099. 2, 25,
  122100. _vq_lengthlist__8c0_s_p8_1,
  122101. 1, -533725184, 1611661312, 3, 0,
  122102. _vq_quantlist__8c0_s_p8_1,
  122103. NULL,
  122104. &_vq_auxt__8c0_s_p8_1,
  122105. NULL,
  122106. 0
  122107. };
  122108. static long _vq_quantlist__8c0_s_p9_0[] = {
  122109. 1,
  122110. 0,
  122111. 2,
  122112. };
  122113. static long _vq_lengthlist__8c0_s_p9_0[] = {
  122114. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122115. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  122116. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122117. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122118. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122119. 7,
  122120. };
  122121. static float _vq_quantthresh__8c0_s_p9_0[] = {
  122122. -157.5, 157.5,
  122123. };
  122124. static long _vq_quantmap__8c0_s_p9_0[] = {
  122125. 1, 0, 2,
  122126. };
  122127. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  122128. _vq_quantthresh__8c0_s_p9_0,
  122129. _vq_quantmap__8c0_s_p9_0,
  122130. 3,
  122131. 3
  122132. };
  122133. static static_codebook _8c0_s_p9_0 = {
  122134. 4, 81,
  122135. _vq_lengthlist__8c0_s_p9_0,
  122136. 1, -518803456, 1628680192, 2, 0,
  122137. _vq_quantlist__8c0_s_p9_0,
  122138. NULL,
  122139. &_vq_auxt__8c0_s_p9_0,
  122140. NULL,
  122141. 0
  122142. };
  122143. static long _vq_quantlist__8c0_s_p9_1[] = {
  122144. 7,
  122145. 6,
  122146. 8,
  122147. 5,
  122148. 9,
  122149. 4,
  122150. 10,
  122151. 3,
  122152. 11,
  122153. 2,
  122154. 12,
  122155. 1,
  122156. 13,
  122157. 0,
  122158. 14,
  122159. };
  122160. static long _vq_lengthlist__8c0_s_p9_1[] = {
  122161. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  122162. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  122163. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  122164. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  122165. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122166. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  122167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122175. 11,
  122176. };
  122177. static float _vq_quantthresh__8c0_s_p9_1[] = {
  122178. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  122179. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  122180. };
  122181. static long _vq_quantmap__8c0_s_p9_1[] = {
  122182. 13, 11, 9, 7, 5, 3, 1, 0,
  122183. 2, 4, 6, 8, 10, 12, 14,
  122184. };
  122185. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  122186. _vq_quantthresh__8c0_s_p9_1,
  122187. _vq_quantmap__8c0_s_p9_1,
  122188. 15,
  122189. 15
  122190. };
  122191. static static_codebook _8c0_s_p9_1 = {
  122192. 2, 225,
  122193. _vq_lengthlist__8c0_s_p9_1,
  122194. 1, -520986624, 1620377600, 4, 0,
  122195. _vq_quantlist__8c0_s_p9_1,
  122196. NULL,
  122197. &_vq_auxt__8c0_s_p9_1,
  122198. NULL,
  122199. 0
  122200. };
  122201. static long _vq_quantlist__8c0_s_p9_2[] = {
  122202. 10,
  122203. 9,
  122204. 11,
  122205. 8,
  122206. 12,
  122207. 7,
  122208. 13,
  122209. 6,
  122210. 14,
  122211. 5,
  122212. 15,
  122213. 4,
  122214. 16,
  122215. 3,
  122216. 17,
  122217. 2,
  122218. 18,
  122219. 1,
  122220. 19,
  122221. 0,
  122222. 20,
  122223. };
  122224. static long _vq_lengthlist__8c0_s_p9_2[] = {
  122225. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  122226. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  122227. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  122228. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  122229. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  122230. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  122231. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  122232. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  122233. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  122234. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  122235. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  122236. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  122237. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  122238. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  122239. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  122240. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  122241. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  122242. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  122243. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  122244. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  122245. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  122246. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  122247. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  122248. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  122249. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  122250. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  122251. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  122252. 10,11, 9,11,10, 9,10, 9,10,
  122253. };
  122254. static float _vq_quantthresh__8c0_s_p9_2[] = {
  122255. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  122256. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  122257. 6.5, 7.5, 8.5, 9.5,
  122258. };
  122259. static long _vq_quantmap__8c0_s_p9_2[] = {
  122260. 19, 17, 15, 13, 11, 9, 7, 5,
  122261. 3, 1, 0, 2, 4, 6, 8, 10,
  122262. 12, 14, 16, 18, 20,
  122263. };
  122264. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  122265. _vq_quantthresh__8c0_s_p9_2,
  122266. _vq_quantmap__8c0_s_p9_2,
  122267. 21,
  122268. 21
  122269. };
  122270. static static_codebook _8c0_s_p9_2 = {
  122271. 2, 441,
  122272. _vq_lengthlist__8c0_s_p9_2,
  122273. 1, -529268736, 1611661312, 5, 0,
  122274. _vq_quantlist__8c0_s_p9_2,
  122275. NULL,
  122276. &_vq_auxt__8c0_s_p9_2,
  122277. NULL,
  122278. 0
  122279. };
  122280. static long _huff_lengthlist__8c0_s_single[] = {
  122281. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  122282. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  122283. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  122284. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  122285. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  122286. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  122287. 17,16,17,17,
  122288. };
  122289. static static_codebook _huff_book__8c0_s_single = {
  122290. 2, 100,
  122291. _huff_lengthlist__8c0_s_single,
  122292. 0, 0, 0, 0, 0,
  122293. NULL,
  122294. NULL,
  122295. NULL,
  122296. NULL,
  122297. 0
  122298. };
  122299. static long _vq_quantlist__8c1_s_p1_0[] = {
  122300. 1,
  122301. 0,
  122302. 2,
  122303. };
  122304. static long _vq_lengthlist__8c1_s_p1_0[] = {
  122305. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122306. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122310. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  122311. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122315. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  122316. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122328. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122333. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122338. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  122351. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  122356. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  122361. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  122373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  122378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  122383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  122397. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  122402. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  122407. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122419. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122424. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122716. };
  122717. static float _vq_quantthresh__8c1_s_p1_0[] = {
  122718. -0.5, 0.5,
  122719. };
  122720. static long _vq_quantmap__8c1_s_p1_0[] = {
  122721. 1, 0, 2,
  122722. };
  122723. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  122724. _vq_quantthresh__8c1_s_p1_0,
  122725. _vq_quantmap__8c1_s_p1_0,
  122726. 3,
  122727. 3
  122728. };
  122729. static static_codebook _8c1_s_p1_0 = {
  122730. 8, 6561,
  122731. _vq_lengthlist__8c1_s_p1_0,
  122732. 1, -535822336, 1611661312, 2, 0,
  122733. _vq_quantlist__8c1_s_p1_0,
  122734. NULL,
  122735. &_vq_auxt__8c1_s_p1_0,
  122736. NULL,
  122737. 0
  122738. };
  122739. static long _vq_quantlist__8c1_s_p2_0[] = {
  122740. 2,
  122741. 1,
  122742. 3,
  122743. 0,
  122744. 4,
  122745. };
  122746. static long _vq_lengthlist__8c1_s_p2_0[] = {
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122787. };
  122788. static float _vq_quantthresh__8c1_s_p2_0[] = {
  122789. -1.5, -0.5, 0.5, 1.5,
  122790. };
  122791. static long _vq_quantmap__8c1_s_p2_0[] = {
  122792. 3, 1, 0, 2, 4,
  122793. };
  122794. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  122795. _vq_quantthresh__8c1_s_p2_0,
  122796. _vq_quantmap__8c1_s_p2_0,
  122797. 5,
  122798. 5
  122799. };
  122800. static static_codebook _8c1_s_p2_0 = {
  122801. 4, 625,
  122802. _vq_lengthlist__8c1_s_p2_0,
  122803. 1, -533725184, 1611661312, 3, 0,
  122804. _vq_quantlist__8c1_s_p2_0,
  122805. NULL,
  122806. &_vq_auxt__8c1_s_p2_0,
  122807. NULL,
  122808. 0
  122809. };
  122810. static long _vq_quantlist__8c1_s_p3_0[] = {
  122811. 2,
  122812. 1,
  122813. 3,
  122814. 0,
  122815. 4,
  122816. };
  122817. static long _vq_lengthlist__8c1_s_p3_0[] = {
  122818. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  122858. };
  122859. static float _vq_quantthresh__8c1_s_p3_0[] = {
  122860. -1.5, -0.5, 0.5, 1.5,
  122861. };
  122862. static long _vq_quantmap__8c1_s_p3_0[] = {
  122863. 3, 1, 0, 2, 4,
  122864. };
  122865. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  122866. _vq_quantthresh__8c1_s_p3_0,
  122867. _vq_quantmap__8c1_s_p3_0,
  122868. 5,
  122869. 5
  122870. };
  122871. static static_codebook _8c1_s_p3_0 = {
  122872. 4, 625,
  122873. _vq_lengthlist__8c1_s_p3_0,
  122874. 1, -533725184, 1611661312, 3, 0,
  122875. _vq_quantlist__8c1_s_p3_0,
  122876. NULL,
  122877. &_vq_auxt__8c1_s_p3_0,
  122878. NULL,
  122879. 0
  122880. };
  122881. static long _vq_quantlist__8c1_s_p4_0[] = {
  122882. 4,
  122883. 3,
  122884. 5,
  122885. 2,
  122886. 6,
  122887. 1,
  122888. 7,
  122889. 0,
  122890. 8,
  122891. };
  122892. static long _vq_lengthlist__8c1_s_p4_0[] = {
  122893. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  122894. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  122895. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  122896. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  122897. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0,
  122899. };
  122900. static float _vq_quantthresh__8c1_s_p4_0[] = {
  122901. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122902. };
  122903. static long _vq_quantmap__8c1_s_p4_0[] = {
  122904. 7, 5, 3, 1, 0, 2, 4, 6,
  122905. 8,
  122906. };
  122907. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  122908. _vq_quantthresh__8c1_s_p4_0,
  122909. _vq_quantmap__8c1_s_p4_0,
  122910. 9,
  122911. 9
  122912. };
  122913. static static_codebook _8c1_s_p4_0 = {
  122914. 2, 81,
  122915. _vq_lengthlist__8c1_s_p4_0,
  122916. 1, -531628032, 1611661312, 4, 0,
  122917. _vq_quantlist__8c1_s_p4_0,
  122918. NULL,
  122919. &_vq_auxt__8c1_s_p4_0,
  122920. NULL,
  122921. 0
  122922. };
  122923. static long _vq_quantlist__8c1_s_p5_0[] = {
  122924. 4,
  122925. 3,
  122926. 5,
  122927. 2,
  122928. 6,
  122929. 1,
  122930. 7,
  122931. 0,
  122932. 8,
  122933. };
  122934. static long _vq_lengthlist__8c1_s_p5_0[] = {
  122935. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  122936. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  122937. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  122938. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  122939. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  122940. 10,
  122941. };
  122942. static float _vq_quantthresh__8c1_s_p5_0[] = {
  122943. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122944. };
  122945. static long _vq_quantmap__8c1_s_p5_0[] = {
  122946. 7, 5, 3, 1, 0, 2, 4, 6,
  122947. 8,
  122948. };
  122949. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  122950. _vq_quantthresh__8c1_s_p5_0,
  122951. _vq_quantmap__8c1_s_p5_0,
  122952. 9,
  122953. 9
  122954. };
  122955. static static_codebook _8c1_s_p5_0 = {
  122956. 2, 81,
  122957. _vq_lengthlist__8c1_s_p5_0,
  122958. 1, -531628032, 1611661312, 4, 0,
  122959. _vq_quantlist__8c1_s_p5_0,
  122960. NULL,
  122961. &_vq_auxt__8c1_s_p5_0,
  122962. NULL,
  122963. 0
  122964. };
  122965. static long _vq_quantlist__8c1_s_p6_0[] = {
  122966. 8,
  122967. 7,
  122968. 9,
  122969. 6,
  122970. 10,
  122971. 5,
  122972. 11,
  122973. 4,
  122974. 12,
  122975. 3,
  122976. 13,
  122977. 2,
  122978. 14,
  122979. 1,
  122980. 15,
  122981. 0,
  122982. 16,
  122983. };
  122984. static long _vq_lengthlist__8c1_s_p6_0[] = {
  122985. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  122986. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  122987. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122988. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  122989. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  122990. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  122991. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  122992. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  122993. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  122994. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  122995. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  122996. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  122997. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  122998. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  122999. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  123000. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  123001. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  123002. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  123003. 14,
  123004. };
  123005. static float _vq_quantthresh__8c1_s_p6_0[] = {
  123006. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123007. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123008. };
  123009. static long _vq_quantmap__8c1_s_p6_0[] = {
  123010. 15, 13, 11, 9, 7, 5, 3, 1,
  123011. 0, 2, 4, 6, 8, 10, 12, 14,
  123012. 16,
  123013. };
  123014. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  123015. _vq_quantthresh__8c1_s_p6_0,
  123016. _vq_quantmap__8c1_s_p6_0,
  123017. 17,
  123018. 17
  123019. };
  123020. static static_codebook _8c1_s_p6_0 = {
  123021. 2, 289,
  123022. _vq_lengthlist__8c1_s_p6_0,
  123023. 1, -529530880, 1611661312, 5, 0,
  123024. _vq_quantlist__8c1_s_p6_0,
  123025. NULL,
  123026. &_vq_auxt__8c1_s_p6_0,
  123027. NULL,
  123028. 0
  123029. };
  123030. static long _vq_quantlist__8c1_s_p7_0[] = {
  123031. 1,
  123032. 0,
  123033. 2,
  123034. };
  123035. static long _vq_lengthlist__8c1_s_p7_0[] = {
  123036. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  123037. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  123038. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  123039. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  123040. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  123041. 9,
  123042. };
  123043. static float _vq_quantthresh__8c1_s_p7_0[] = {
  123044. -5.5, 5.5,
  123045. };
  123046. static long _vq_quantmap__8c1_s_p7_0[] = {
  123047. 1, 0, 2,
  123048. };
  123049. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  123050. _vq_quantthresh__8c1_s_p7_0,
  123051. _vq_quantmap__8c1_s_p7_0,
  123052. 3,
  123053. 3
  123054. };
  123055. static static_codebook _8c1_s_p7_0 = {
  123056. 4, 81,
  123057. _vq_lengthlist__8c1_s_p7_0,
  123058. 1, -529137664, 1618345984, 2, 0,
  123059. _vq_quantlist__8c1_s_p7_0,
  123060. NULL,
  123061. &_vq_auxt__8c1_s_p7_0,
  123062. NULL,
  123063. 0
  123064. };
  123065. static long _vq_quantlist__8c1_s_p7_1[] = {
  123066. 5,
  123067. 4,
  123068. 6,
  123069. 3,
  123070. 7,
  123071. 2,
  123072. 8,
  123073. 1,
  123074. 9,
  123075. 0,
  123076. 10,
  123077. };
  123078. static long _vq_lengthlist__8c1_s_p7_1[] = {
  123079. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  123080. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  123081. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  123082. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123083. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123084. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123085. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  123086. 10,10,10, 8, 8, 8, 8, 8, 8,
  123087. };
  123088. static float _vq_quantthresh__8c1_s_p7_1[] = {
  123089. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123090. 3.5, 4.5,
  123091. };
  123092. static long _vq_quantmap__8c1_s_p7_1[] = {
  123093. 9, 7, 5, 3, 1, 0, 2, 4,
  123094. 6, 8, 10,
  123095. };
  123096. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  123097. _vq_quantthresh__8c1_s_p7_1,
  123098. _vq_quantmap__8c1_s_p7_1,
  123099. 11,
  123100. 11
  123101. };
  123102. static static_codebook _8c1_s_p7_1 = {
  123103. 2, 121,
  123104. _vq_lengthlist__8c1_s_p7_1,
  123105. 1, -531365888, 1611661312, 4, 0,
  123106. _vq_quantlist__8c1_s_p7_1,
  123107. NULL,
  123108. &_vq_auxt__8c1_s_p7_1,
  123109. NULL,
  123110. 0
  123111. };
  123112. static long _vq_quantlist__8c1_s_p8_0[] = {
  123113. 6,
  123114. 5,
  123115. 7,
  123116. 4,
  123117. 8,
  123118. 3,
  123119. 9,
  123120. 2,
  123121. 10,
  123122. 1,
  123123. 11,
  123124. 0,
  123125. 12,
  123126. };
  123127. static long _vq_lengthlist__8c1_s_p8_0[] = {
  123128. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  123129. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  123130. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123131. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123132. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  123133. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  123134. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  123135. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  123136. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  123137. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  123138. 0,12,12,11,10,12,11,13,12,
  123139. };
  123140. static float _vq_quantthresh__8c1_s_p8_0[] = {
  123141. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123142. 12.5, 17.5, 22.5, 27.5,
  123143. };
  123144. static long _vq_quantmap__8c1_s_p8_0[] = {
  123145. 11, 9, 7, 5, 3, 1, 0, 2,
  123146. 4, 6, 8, 10, 12,
  123147. };
  123148. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  123149. _vq_quantthresh__8c1_s_p8_0,
  123150. _vq_quantmap__8c1_s_p8_0,
  123151. 13,
  123152. 13
  123153. };
  123154. static static_codebook _8c1_s_p8_0 = {
  123155. 2, 169,
  123156. _vq_lengthlist__8c1_s_p8_0,
  123157. 1, -526516224, 1616117760, 4, 0,
  123158. _vq_quantlist__8c1_s_p8_0,
  123159. NULL,
  123160. &_vq_auxt__8c1_s_p8_0,
  123161. NULL,
  123162. 0
  123163. };
  123164. static long _vq_quantlist__8c1_s_p8_1[] = {
  123165. 2,
  123166. 1,
  123167. 3,
  123168. 0,
  123169. 4,
  123170. };
  123171. static long _vq_lengthlist__8c1_s_p8_1[] = {
  123172. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  123173. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  123174. };
  123175. static float _vq_quantthresh__8c1_s_p8_1[] = {
  123176. -1.5, -0.5, 0.5, 1.5,
  123177. };
  123178. static long _vq_quantmap__8c1_s_p8_1[] = {
  123179. 3, 1, 0, 2, 4,
  123180. };
  123181. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  123182. _vq_quantthresh__8c1_s_p8_1,
  123183. _vq_quantmap__8c1_s_p8_1,
  123184. 5,
  123185. 5
  123186. };
  123187. static static_codebook _8c1_s_p8_1 = {
  123188. 2, 25,
  123189. _vq_lengthlist__8c1_s_p8_1,
  123190. 1, -533725184, 1611661312, 3, 0,
  123191. _vq_quantlist__8c1_s_p8_1,
  123192. NULL,
  123193. &_vq_auxt__8c1_s_p8_1,
  123194. NULL,
  123195. 0
  123196. };
  123197. static long _vq_quantlist__8c1_s_p9_0[] = {
  123198. 6,
  123199. 5,
  123200. 7,
  123201. 4,
  123202. 8,
  123203. 3,
  123204. 9,
  123205. 2,
  123206. 10,
  123207. 1,
  123208. 11,
  123209. 0,
  123210. 12,
  123211. };
  123212. static long _vq_lengthlist__8c1_s_p9_0[] = {
  123213. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  123214. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  123215. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123216. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123217. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123218. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123219. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123220. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123221. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123222. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123223. 10,10,10,10,10, 9, 9, 9, 9,
  123224. };
  123225. static float _vq_quantthresh__8c1_s_p9_0[] = {
  123226. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  123227. 787.5, 1102.5, 1417.5, 1732.5,
  123228. };
  123229. static long _vq_quantmap__8c1_s_p9_0[] = {
  123230. 11, 9, 7, 5, 3, 1, 0, 2,
  123231. 4, 6, 8, 10, 12,
  123232. };
  123233. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  123234. _vq_quantthresh__8c1_s_p9_0,
  123235. _vq_quantmap__8c1_s_p9_0,
  123236. 13,
  123237. 13
  123238. };
  123239. static static_codebook _8c1_s_p9_0 = {
  123240. 2, 169,
  123241. _vq_lengthlist__8c1_s_p9_0,
  123242. 1, -513964032, 1628680192, 4, 0,
  123243. _vq_quantlist__8c1_s_p9_0,
  123244. NULL,
  123245. &_vq_auxt__8c1_s_p9_0,
  123246. NULL,
  123247. 0
  123248. };
  123249. static long _vq_quantlist__8c1_s_p9_1[] = {
  123250. 7,
  123251. 6,
  123252. 8,
  123253. 5,
  123254. 9,
  123255. 4,
  123256. 10,
  123257. 3,
  123258. 11,
  123259. 2,
  123260. 12,
  123261. 1,
  123262. 13,
  123263. 0,
  123264. 14,
  123265. };
  123266. static long _vq_lengthlist__8c1_s_p9_1[] = {
  123267. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  123268. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  123269. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  123270. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  123271. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  123272. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  123273. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  123274. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  123275. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  123276. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  123277. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  123278. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  123279. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  123280. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  123281. 15,
  123282. };
  123283. static float _vq_quantthresh__8c1_s_p9_1[] = {
  123284. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123285. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123286. };
  123287. static long _vq_quantmap__8c1_s_p9_1[] = {
  123288. 13, 11, 9, 7, 5, 3, 1, 0,
  123289. 2, 4, 6, 8, 10, 12, 14,
  123290. };
  123291. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  123292. _vq_quantthresh__8c1_s_p9_1,
  123293. _vq_quantmap__8c1_s_p9_1,
  123294. 15,
  123295. 15
  123296. };
  123297. static static_codebook _8c1_s_p9_1 = {
  123298. 2, 225,
  123299. _vq_lengthlist__8c1_s_p9_1,
  123300. 1, -520986624, 1620377600, 4, 0,
  123301. _vq_quantlist__8c1_s_p9_1,
  123302. NULL,
  123303. &_vq_auxt__8c1_s_p9_1,
  123304. NULL,
  123305. 0
  123306. };
  123307. static long _vq_quantlist__8c1_s_p9_2[] = {
  123308. 10,
  123309. 9,
  123310. 11,
  123311. 8,
  123312. 12,
  123313. 7,
  123314. 13,
  123315. 6,
  123316. 14,
  123317. 5,
  123318. 15,
  123319. 4,
  123320. 16,
  123321. 3,
  123322. 17,
  123323. 2,
  123324. 18,
  123325. 1,
  123326. 19,
  123327. 0,
  123328. 20,
  123329. };
  123330. static long _vq_lengthlist__8c1_s_p9_2[] = {
  123331. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  123332. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  123333. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  123334. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  123335. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123336. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123337. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  123338. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  123339. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  123340. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  123341. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  123342. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  123343. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  123344. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  123345. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  123346. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  123347. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123348. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  123349. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  123350. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  123351. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123352. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  123353. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  123354. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  123355. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  123356. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  123357. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  123358. 10,10,10,10,10,10,10,10,10,
  123359. };
  123360. static float _vq_quantthresh__8c1_s_p9_2[] = {
  123361. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123362. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123363. 6.5, 7.5, 8.5, 9.5,
  123364. };
  123365. static long _vq_quantmap__8c1_s_p9_2[] = {
  123366. 19, 17, 15, 13, 11, 9, 7, 5,
  123367. 3, 1, 0, 2, 4, 6, 8, 10,
  123368. 12, 14, 16, 18, 20,
  123369. };
  123370. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  123371. _vq_quantthresh__8c1_s_p9_2,
  123372. _vq_quantmap__8c1_s_p9_2,
  123373. 21,
  123374. 21
  123375. };
  123376. static static_codebook _8c1_s_p9_2 = {
  123377. 2, 441,
  123378. _vq_lengthlist__8c1_s_p9_2,
  123379. 1, -529268736, 1611661312, 5, 0,
  123380. _vq_quantlist__8c1_s_p9_2,
  123381. NULL,
  123382. &_vq_auxt__8c1_s_p9_2,
  123383. NULL,
  123384. 0
  123385. };
  123386. static long _huff_lengthlist__8c1_s_single[] = {
  123387. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  123388. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  123389. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  123390. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  123391. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  123392. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  123393. 9, 7, 7, 8,
  123394. };
  123395. static static_codebook _huff_book__8c1_s_single = {
  123396. 2, 100,
  123397. _huff_lengthlist__8c1_s_single,
  123398. 0, 0, 0, 0, 0,
  123399. NULL,
  123400. NULL,
  123401. NULL,
  123402. NULL,
  123403. 0
  123404. };
  123405. static long _huff_lengthlist__44c2_s_long[] = {
  123406. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  123407. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  123408. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  123409. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  123410. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  123411. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  123412. 10, 8, 8, 9,
  123413. };
  123414. static static_codebook _huff_book__44c2_s_long = {
  123415. 2, 100,
  123416. _huff_lengthlist__44c2_s_long,
  123417. 0, 0, 0, 0, 0,
  123418. NULL,
  123419. NULL,
  123420. NULL,
  123421. NULL,
  123422. 0
  123423. };
  123424. static long _vq_quantlist__44c2_s_p1_0[] = {
  123425. 1,
  123426. 0,
  123427. 2,
  123428. };
  123429. static long _vq_lengthlist__44c2_s_p1_0[] = {
  123430. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123431. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123435. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123436. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123440. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123441. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123453. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123458. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123463. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  123476. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  123481. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  123486. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  123498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  123503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  123508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123522. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123527. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123532. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123841. };
  123842. static float _vq_quantthresh__44c2_s_p1_0[] = {
  123843. -0.5, 0.5,
  123844. };
  123845. static long _vq_quantmap__44c2_s_p1_0[] = {
  123846. 1, 0, 2,
  123847. };
  123848. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  123849. _vq_quantthresh__44c2_s_p1_0,
  123850. _vq_quantmap__44c2_s_p1_0,
  123851. 3,
  123852. 3
  123853. };
  123854. static static_codebook _44c2_s_p1_0 = {
  123855. 8, 6561,
  123856. _vq_lengthlist__44c2_s_p1_0,
  123857. 1, -535822336, 1611661312, 2, 0,
  123858. _vq_quantlist__44c2_s_p1_0,
  123859. NULL,
  123860. &_vq_auxt__44c2_s_p1_0,
  123861. NULL,
  123862. 0
  123863. };
  123864. static long _vq_quantlist__44c2_s_p2_0[] = {
  123865. 2,
  123866. 1,
  123867. 3,
  123868. 0,
  123869. 4,
  123870. };
  123871. static long _vq_lengthlist__44c2_s_p2_0[] = {
  123872. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  123873. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  123874. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  123875. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  123876. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  123882. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  123883. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  123884. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  123890. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  123891. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  123898. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  123899. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 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,
  123912. };
  123913. static float _vq_quantthresh__44c2_s_p2_0[] = {
  123914. -1.5, -0.5, 0.5, 1.5,
  123915. };
  123916. static long _vq_quantmap__44c2_s_p2_0[] = {
  123917. 3, 1, 0, 2, 4,
  123918. };
  123919. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  123920. _vq_quantthresh__44c2_s_p2_0,
  123921. _vq_quantmap__44c2_s_p2_0,
  123922. 5,
  123923. 5
  123924. };
  123925. static static_codebook _44c2_s_p2_0 = {
  123926. 4, 625,
  123927. _vq_lengthlist__44c2_s_p2_0,
  123928. 1, -533725184, 1611661312, 3, 0,
  123929. _vq_quantlist__44c2_s_p2_0,
  123930. NULL,
  123931. &_vq_auxt__44c2_s_p2_0,
  123932. NULL,
  123933. 0
  123934. };
  123935. static long _vq_quantlist__44c2_s_p3_0[] = {
  123936. 2,
  123937. 1,
  123938. 3,
  123939. 0,
  123940. 4,
  123941. };
  123942. static long _vq_lengthlist__44c2_s_p3_0[] = {
  123943. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  123983. };
  123984. static float _vq_quantthresh__44c2_s_p3_0[] = {
  123985. -1.5, -0.5, 0.5, 1.5,
  123986. };
  123987. static long _vq_quantmap__44c2_s_p3_0[] = {
  123988. 3, 1, 0, 2, 4,
  123989. };
  123990. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  123991. _vq_quantthresh__44c2_s_p3_0,
  123992. _vq_quantmap__44c2_s_p3_0,
  123993. 5,
  123994. 5
  123995. };
  123996. static static_codebook _44c2_s_p3_0 = {
  123997. 4, 625,
  123998. _vq_lengthlist__44c2_s_p3_0,
  123999. 1, -533725184, 1611661312, 3, 0,
  124000. _vq_quantlist__44c2_s_p3_0,
  124001. NULL,
  124002. &_vq_auxt__44c2_s_p3_0,
  124003. NULL,
  124004. 0
  124005. };
  124006. static long _vq_quantlist__44c2_s_p4_0[] = {
  124007. 4,
  124008. 3,
  124009. 5,
  124010. 2,
  124011. 6,
  124012. 1,
  124013. 7,
  124014. 0,
  124015. 8,
  124016. };
  124017. static long _vq_lengthlist__44c2_s_p4_0[] = {
  124018. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  124019. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  124020. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  124021. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  124022. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0,
  124024. };
  124025. static float _vq_quantthresh__44c2_s_p4_0[] = {
  124026. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124027. };
  124028. static long _vq_quantmap__44c2_s_p4_0[] = {
  124029. 7, 5, 3, 1, 0, 2, 4, 6,
  124030. 8,
  124031. };
  124032. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  124033. _vq_quantthresh__44c2_s_p4_0,
  124034. _vq_quantmap__44c2_s_p4_0,
  124035. 9,
  124036. 9
  124037. };
  124038. static static_codebook _44c2_s_p4_0 = {
  124039. 2, 81,
  124040. _vq_lengthlist__44c2_s_p4_0,
  124041. 1, -531628032, 1611661312, 4, 0,
  124042. _vq_quantlist__44c2_s_p4_0,
  124043. NULL,
  124044. &_vq_auxt__44c2_s_p4_0,
  124045. NULL,
  124046. 0
  124047. };
  124048. static long _vq_quantlist__44c2_s_p5_0[] = {
  124049. 4,
  124050. 3,
  124051. 5,
  124052. 2,
  124053. 6,
  124054. 1,
  124055. 7,
  124056. 0,
  124057. 8,
  124058. };
  124059. static long _vq_lengthlist__44c2_s_p5_0[] = {
  124060. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  124061. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  124062. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124063. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124064. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  124065. 11,
  124066. };
  124067. static float _vq_quantthresh__44c2_s_p5_0[] = {
  124068. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124069. };
  124070. static long _vq_quantmap__44c2_s_p5_0[] = {
  124071. 7, 5, 3, 1, 0, 2, 4, 6,
  124072. 8,
  124073. };
  124074. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  124075. _vq_quantthresh__44c2_s_p5_0,
  124076. _vq_quantmap__44c2_s_p5_0,
  124077. 9,
  124078. 9
  124079. };
  124080. static static_codebook _44c2_s_p5_0 = {
  124081. 2, 81,
  124082. _vq_lengthlist__44c2_s_p5_0,
  124083. 1, -531628032, 1611661312, 4, 0,
  124084. _vq_quantlist__44c2_s_p5_0,
  124085. NULL,
  124086. &_vq_auxt__44c2_s_p5_0,
  124087. NULL,
  124088. 0
  124089. };
  124090. static long _vq_quantlist__44c2_s_p6_0[] = {
  124091. 8,
  124092. 7,
  124093. 9,
  124094. 6,
  124095. 10,
  124096. 5,
  124097. 11,
  124098. 4,
  124099. 12,
  124100. 3,
  124101. 13,
  124102. 2,
  124103. 14,
  124104. 1,
  124105. 15,
  124106. 0,
  124107. 16,
  124108. };
  124109. static long _vq_lengthlist__44c2_s_p6_0[] = {
  124110. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  124111. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124112. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124113. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  124114. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  124115. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124116. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124117. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124118. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124119. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124120. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124121. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  124122. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  124123. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124124. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  124125. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  124126. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124127. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124128. 14,
  124129. };
  124130. static float _vq_quantthresh__44c2_s_p6_0[] = {
  124131. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124132. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124133. };
  124134. static long _vq_quantmap__44c2_s_p6_0[] = {
  124135. 15, 13, 11, 9, 7, 5, 3, 1,
  124136. 0, 2, 4, 6, 8, 10, 12, 14,
  124137. 16,
  124138. };
  124139. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  124140. _vq_quantthresh__44c2_s_p6_0,
  124141. _vq_quantmap__44c2_s_p6_0,
  124142. 17,
  124143. 17
  124144. };
  124145. static static_codebook _44c2_s_p6_0 = {
  124146. 2, 289,
  124147. _vq_lengthlist__44c2_s_p6_0,
  124148. 1, -529530880, 1611661312, 5, 0,
  124149. _vq_quantlist__44c2_s_p6_0,
  124150. NULL,
  124151. &_vq_auxt__44c2_s_p6_0,
  124152. NULL,
  124153. 0
  124154. };
  124155. static long _vq_quantlist__44c2_s_p7_0[] = {
  124156. 1,
  124157. 0,
  124158. 2,
  124159. };
  124160. static long _vq_lengthlist__44c2_s_p7_0[] = {
  124161. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124162. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  124163. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124164. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  124165. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  124166. 11,
  124167. };
  124168. static float _vq_quantthresh__44c2_s_p7_0[] = {
  124169. -5.5, 5.5,
  124170. };
  124171. static long _vq_quantmap__44c2_s_p7_0[] = {
  124172. 1, 0, 2,
  124173. };
  124174. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  124175. _vq_quantthresh__44c2_s_p7_0,
  124176. _vq_quantmap__44c2_s_p7_0,
  124177. 3,
  124178. 3
  124179. };
  124180. static static_codebook _44c2_s_p7_0 = {
  124181. 4, 81,
  124182. _vq_lengthlist__44c2_s_p7_0,
  124183. 1, -529137664, 1618345984, 2, 0,
  124184. _vq_quantlist__44c2_s_p7_0,
  124185. NULL,
  124186. &_vq_auxt__44c2_s_p7_0,
  124187. NULL,
  124188. 0
  124189. };
  124190. static long _vq_quantlist__44c2_s_p7_1[] = {
  124191. 5,
  124192. 4,
  124193. 6,
  124194. 3,
  124195. 7,
  124196. 2,
  124197. 8,
  124198. 1,
  124199. 9,
  124200. 0,
  124201. 10,
  124202. };
  124203. static long _vq_lengthlist__44c2_s_p7_1[] = {
  124204. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  124205. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  124206. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124207. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124208. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  124209. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124210. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  124211. 10,10,10, 8, 8, 8, 8, 8, 8,
  124212. };
  124213. static float _vq_quantthresh__44c2_s_p7_1[] = {
  124214. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124215. 3.5, 4.5,
  124216. };
  124217. static long _vq_quantmap__44c2_s_p7_1[] = {
  124218. 9, 7, 5, 3, 1, 0, 2, 4,
  124219. 6, 8, 10,
  124220. };
  124221. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  124222. _vq_quantthresh__44c2_s_p7_1,
  124223. _vq_quantmap__44c2_s_p7_1,
  124224. 11,
  124225. 11
  124226. };
  124227. static static_codebook _44c2_s_p7_1 = {
  124228. 2, 121,
  124229. _vq_lengthlist__44c2_s_p7_1,
  124230. 1, -531365888, 1611661312, 4, 0,
  124231. _vq_quantlist__44c2_s_p7_1,
  124232. NULL,
  124233. &_vq_auxt__44c2_s_p7_1,
  124234. NULL,
  124235. 0
  124236. };
  124237. static long _vq_quantlist__44c2_s_p8_0[] = {
  124238. 6,
  124239. 5,
  124240. 7,
  124241. 4,
  124242. 8,
  124243. 3,
  124244. 9,
  124245. 2,
  124246. 10,
  124247. 1,
  124248. 11,
  124249. 0,
  124250. 12,
  124251. };
  124252. static long _vq_lengthlist__44c2_s_p8_0[] = {
  124253. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124254. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  124255. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124256. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124257. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  124258. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124259. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  124260. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  124261. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  124262. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  124263. 0,12,12,12,12,13,12,14,14,
  124264. };
  124265. static float _vq_quantthresh__44c2_s_p8_0[] = {
  124266. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124267. 12.5, 17.5, 22.5, 27.5,
  124268. };
  124269. static long _vq_quantmap__44c2_s_p8_0[] = {
  124270. 11, 9, 7, 5, 3, 1, 0, 2,
  124271. 4, 6, 8, 10, 12,
  124272. };
  124273. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  124274. _vq_quantthresh__44c2_s_p8_0,
  124275. _vq_quantmap__44c2_s_p8_0,
  124276. 13,
  124277. 13
  124278. };
  124279. static static_codebook _44c2_s_p8_0 = {
  124280. 2, 169,
  124281. _vq_lengthlist__44c2_s_p8_0,
  124282. 1, -526516224, 1616117760, 4, 0,
  124283. _vq_quantlist__44c2_s_p8_0,
  124284. NULL,
  124285. &_vq_auxt__44c2_s_p8_0,
  124286. NULL,
  124287. 0
  124288. };
  124289. static long _vq_quantlist__44c2_s_p8_1[] = {
  124290. 2,
  124291. 1,
  124292. 3,
  124293. 0,
  124294. 4,
  124295. };
  124296. static long _vq_lengthlist__44c2_s_p8_1[] = {
  124297. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  124298. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124299. };
  124300. static float _vq_quantthresh__44c2_s_p8_1[] = {
  124301. -1.5, -0.5, 0.5, 1.5,
  124302. };
  124303. static long _vq_quantmap__44c2_s_p8_1[] = {
  124304. 3, 1, 0, 2, 4,
  124305. };
  124306. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  124307. _vq_quantthresh__44c2_s_p8_1,
  124308. _vq_quantmap__44c2_s_p8_1,
  124309. 5,
  124310. 5
  124311. };
  124312. static static_codebook _44c2_s_p8_1 = {
  124313. 2, 25,
  124314. _vq_lengthlist__44c2_s_p8_1,
  124315. 1, -533725184, 1611661312, 3, 0,
  124316. _vq_quantlist__44c2_s_p8_1,
  124317. NULL,
  124318. &_vq_auxt__44c2_s_p8_1,
  124319. NULL,
  124320. 0
  124321. };
  124322. static long _vq_quantlist__44c2_s_p9_0[] = {
  124323. 6,
  124324. 5,
  124325. 7,
  124326. 4,
  124327. 8,
  124328. 3,
  124329. 9,
  124330. 2,
  124331. 10,
  124332. 1,
  124333. 11,
  124334. 0,
  124335. 12,
  124336. };
  124337. static long _vq_lengthlist__44c2_s_p9_0[] = {
  124338. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  124339. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  124340. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124341. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  124342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  124348. 11,11,11,11,11,11,11,11,11,
  124349. };
  124350. static float _vq_quantthresh__44c2_s_p9_0[] = {
  124351. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  124352. 552.5, 773.5, 994.5, 1215.5,
  124353. };
  124354. static long _vq_quantmap__44c2_s_p9_0[] = {
  124355. 11, 9, 7, 5, 3, 1, 0, 2,
  124356. 4, 6, 8, 10, 12,
  124357. };
  124358. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  124359. _vq_quantthresh__44c2_s_p9_0,
  124360. _vq_quantmap__44c2_s_p9_0,
  124361. 13,
  124362. 13
  124363. };
  124364. static static_codebook _44c2_s_p9_0 = {
  124365. 2, 169,
  124366. _vq_lengthlist__44c2_s_p9_0,
  124367. 1, -514541568, 1627103232, 4, 0,
  124368. _vq_quantlist__44c2_s_p9_0,
  124369. NULL,
  124370. &_vq_auxt__44c2_s_p9_0,
  124371. NULL,
  124372. 0
  124373. };
  124374. static long _vq_quantlist__44c2_s_p9_1[] = {
  124375. 6,
  124376. 5,
  124377. 7,
  124378. 4,
  124379. 8,
  124380. 3,
  124381. 9,
  124382. 2,
  124383. 10,
  124384. 1,
  124385. 11,
  124386. 0,
  124387. 12,
  124388. };
  124389. static long _vq_lengthlist__44c2_s_p9_1[] = {
  124390. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  124391. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  124392. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  124393. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  124394. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  124395. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  124396. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  124397. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  124398. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  124399. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  124400. 17,13,12,12,10,13,11,14,14,
  124401. };
  124402. static float _vq_quantthresh__44c2_s_p9_1[] = {
  124403. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  124404. 42.5, 59.5, 76.5, 93.5,
  124405. };
  124406. static long _vq_quantmap__44c2_s_p9_1[] = {
  124407. 11, 9, 7, 5, 3, 1, 0, 2,
  124408. 4, 6, 8, 10, 12,
  124409. };
  124410. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  124411. _vq_quantthresh__44c2_s_p9_1,
  124412. _vq_quantmap__44c2_s_p9_1,
  124413. 13,
  124414. 13
  124415. };
  124416. static static_codebook _44c2_s_p9_1 = {
  124417. 2, 169,
  124418. _vq_lengthlist__44c2_s_p9_1,
  124419. 1, -522616832, 1620115456, 4, 0,
  124420. _vq_quantlist__44c2_s_p9_1,
  124421. NULL,
  124422. &_vq_auxt__44c2_s_p9_1,
  124423. NULL,
  124424. 0
  124425. };
  124426. static long _vq_quantlist__44c2_s_p9_2[] = {
  124427. 8,
  124428. 7,
  124429. 9,
  124430. 6,
  124431. 10,
  124432. 5,
  124433. 11,
  124434. 4,
  124435. 12,
  124436. 3,
  124437. 13,
  124438. 2,
  124439. 14,
  124440. 1,
  124441. 15,
  124442. 0,
  124443. 16,
  124444. };
  124445. static long _vq_lengthlist__44c2_s_p9_2[] = {
  124446. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  124447. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  124448. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  124449. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  124450. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  124451. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  124452. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  124453. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  124454. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  124455. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  124456. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  124457. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  124458. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  124459. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  124460. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  124461. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124462. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  124463. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  124464. 10,
  124465. };
  124466. static float _vq_quantthresh__44c2_s_p9_2[] = {
  124467. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124468. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124469. };
  124470. static long _vq_quantmap__44c2_s_p9_2[] = {
  124471. 15, 13, 11, 9, 7, 5, 3, 1,
  124472. 0, 2, 4, 6, 8, 10, 12, 14,
  124473. 16,
  124474. };
  124475. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  124476. _vq_quantthresh__44c2_s_p9_2,
  124477. _vq_quantmap__44c2_s_p9_2,
  124478. 17,
  124479. 17
  124480. };
  124481. static static_codebook _44c2_s_p9_2 = {
  124482. 2, 289,
  124483. _vq_lengthlist__44c2_s_p9_2,
  124484. 1, -529530880, 1611661312, 5, 0,
  124485. _vq_quantlist__44c2_s_p9_2,
  124486. NULL,
  124487. &_vq_auxt__44c2_s_p9_2,
  124488. NULL,
  124489. 0
  124490. };
  124491. static long _huff_lengthlist__44c2_s_short[] = {
  124492. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  124493. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  124494. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  124495. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  124496. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  124497. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  124498. 6, 8, 9,12,
  124499. };
  124500. static static_codebook _huff_book__44c2_s_short = {
  124501. 2, 100,
  124502. _huff_lengthlist__44c2_s_short,
  124503. 0, 0, 0, 0, 0,
  124504. NULL,
  124505. NULL,
  124506. NULL,
  124507. NULL,
  124508. 0
  124509. };
  124510. static long _huff_lengthlist__44c3_s_long[] = {
  124511. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  124512. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  124513. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  124514. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  124515. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  124516. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  124517. 9, 8, 8, 8,
  124518. };
  124519. static static_codebook _huff_book__44c3_s_long = {
  124520. 2, 100,
  124521. _huff_lengthlist__44c3_s_long,
  124522. 0, 0, 0, 0, 0,
  124523. NULL,
  124524. NULL,
  124525. NULL,
  124526. NULL,
  124527. 0
  124528. };
  124529. static long _vq_quantlist__44c3_s_p1_0[] = {
  124530. 1,
  124531. 0,
  124532. 2,
  124533. };
  124534. static long _vq_lengthlist__44c3_s_p1_0[] = {
  124535. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  124536. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124540. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  124541. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124545. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  124546. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124558. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124563. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124568. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  124581. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  124586. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  124591. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  124603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  124608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  124613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  124627. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  124632. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  124637. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  124946. };
  124947. static float _vq_quantthresh__44c3_s_p1_0[] = {
  124948. -0.5, 0.5,
  124949. };
  124950. static long _vq_quantmap__44c3_s_p1_0[] = {
  124951. 1, 0, 2,
  124952. };
  124953. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  124954. _vq_quantthresh__44c3_s_p1_0,
  124955. _vq_quantmap__44c3_s_p1_0,
  124956. 3,
  124957. 3
  124958. };
  124959. static static_codebook _44c3_s_p1_0 = {
  124960. 8, 6561,
  124961. _vq_lengthlist__44c3_s_p1_0,
  124962. 1, -535822336, 1611661312, 2, 0,
  124963. _vq_quantlist__44c3_s_p1_0,
  124964. NULL,
  124965. &_vq_auxt__44c3_s_p1_0,
  124966. NULL,
  124967. 0
  124968. };
  124969. static long _vq_quantlist__44c3_s_p2_0[] = {
  124970. 2,
  124971. 1,
  124972. 3,
  124973. 0,
  124974. 4,
  124975. };
  124976. static long _vq_lengthlist__44c3_s_p2_0[] = {
  124977. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  124978. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  124979. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  124980. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  124981. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124986. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  124987. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  124988. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  124989. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124994. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  124995. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  124996. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  124997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125002. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  125003. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  125004. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125011. 0, 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,
  125017. };
  125018. static float _vq_quantthresh__44c3_s_p2_0[] = {
  125019. -1.5, -0.5, 0.5, 1.5,
  125020. };
  125021. static long _vq_quantmap__44c3_s_p2_0[] = {
  125022. 3, 1, 0, 2, 4,
  125023. };
  125024. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  125025. _vq_quantthresh__44c3_s_p2_0,
  125026. _vq_quantmap__44c3_s_p2_0,
  125027. 5,
  125028. 5
  125029. };
  125030. static static_codebook _44c3_s_p2_0 = {
  125031. 4, 625,
  125032. _vq_lengthlist__44c3_s_p2_0,
  125033. 1, -533725184, 1611661312, 3, 0,
  125034. _vq_quantlist__44c3_s_p2_0,
  125035. NULL,
  125036. &_vq_auxt__44c3_s_p2_0,
  125037. NULL,
  125038. 0
  125039. };
  125040. static long _vq_quantlist__44c3_s_p3_0[] = {
  125041. 2,
  125042. 1,
  125043. 3,
  125044. 0,
  125045. 4,
  125046. };
  125047. static long _vq_lengthlist__44c3_s_p3_0[] = {
  125048. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  125055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  125088. };
  125089. static float _vq_quantthresh__44c3_s_p3_0[] = {
  125090. -1.5, -0.5, 0.5, 1.5,
  125091. };
  125092. static long _vq_quantmap__44c3_s_p3_0[] = {
  125093. 3, 1, 0, 2, 4,
  125094. };
  125095. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  125096. _vq_quantthresh__44c3_s_p3_0,
  125097. _vq_quantmap__44c3_s_p3_0,
  125098. 5,
  125099. 5
  125100. };
  125101. static static_codebook _44c3_s_p3_0 = {
  125102. 4, 625,
  125103. _vq_lengthlist__44c3_s_p3_0,
  125104. 1, -533725184, 1611661312, 3, 0,
  125105. _vq_quantlist__44c3_s_p3_0,
  125106. NULL,
  125107. &_vq_auxt__44c3_s_p3_0,
  125108. NULL,
  125109. 0
  125110. };
  125111. static long _vq_quantlist__44c3_s_p4_0[] = {
  125112. 4,
  125113. 3,
  125114. 5,
  125115. 2,
  125116. 6,
  125117. 1,
  125118. 7,
  125119. 0,
  125120. 8,
  125121. };
  125122. static long _vq_lengthlist__44c3_s_p4_0[] = {
  125123. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125124. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125125. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125126. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  125127. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125128. 0,
  125129. };
  125130. static float _vq_quantthresh__44c3_s_p4_0[] = {
  125131. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125132. };
  125133. static long _vq_quantmap__44c3_s_p4_0[] = {
  125134. 7, 5, 3, 1, 0, 2, 4, 6,
  125135. 8,
  125136. };
  125137. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  125138. _vq_quantthresh__44c3_s_p4_0,
  125139. _vq_quantmap__44c3_s_p4_0,
  125140. 9,
  125141. 9
  125142. };
  125143. static static_codebook _44c3_s_p4_0 = {
  125144. 2, 81,
  125145. _vq_lengthlist__44c3_s_p4_0,
  125146. 1, -531628032, 1611661312, 4, 0,
  125147. _vq_quantlist__44c3_s_p4_0,
  125148. NULL,
  125149. &_vq_auxt__44c3_s_p4_0,
  125150. NULL,
  125151. 0
  125152. };
  125153. static long _vq_quantlist__44c3_s_p5_0[] = {
  125154. 4,
  125155. 3,
  125156. 5,
  125157. 2,
  125158. 6,
  125159. 1,
  125160. 7,
  125161. 0,
  125162. 8,
  125163. };
  125164. static long _vq_lengthlist__44c3_s_p5_0[] = {
  125165. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  125166. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  125167. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  125168. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  125169. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  125170. 11,
  125171. };
  125172. static float _vq_quantthresh__44c3_s_p5_0[] = {
  125173. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125174. };
  125175. static long _vq_quantmap__44c3_s_p5_0[] = {
  125176. 7, 5, 3, 1, 0, 2, 4, 6,
  125177. 8,
  125178. };
  125179. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  125180. _vq_quantthresh__44c3_s_p5_0,
  125181. _vq_quantmap__44c3_s_p5_0,
  125182. 9,
  125183. 9
  125184. };
  125185. static static_codebook _44c3_s_p5_0 = {
  125186. 2, 81,
  125187. _vq_lengthlist__44c3_s_p5_0,
  125188. 1, -531628032, 1611661312, 4, 0,
  125189. _vq_quantlist__44c3_s_p5_0,
  125190. NULL,
  125191. &_vq_auxt__44c3_s_p5_0,
  125192. NULL,
  125193. 0
  125194. };
  125195. static long _vq_quantlist__44c3_s_p6_0[] = {
  125196. 8,
  125197. 7,
  125198. 9,
  125199. 6,
  125200. 10,
  125201. 5,
  125202. 11,
  125203. 4,
  125204. 12,
  125205. 3,
  125206. 13,
  125207. 2,
  125208. 14,
  125209. 1,
  125210. 15,
  125211. 0,
  125212. 16,
  125213. };
  125214. static long _vq_lengthlist__44c3_s_p6_0[] = {
  125215. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  125216. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125217. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  125218. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125219. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125220. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125221. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  125222. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  125223. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125224. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  125225. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  125226. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  125227. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  125228. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  125229. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  125230. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125231. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  125232. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125233. 13,
  125234. };
  125235. static float _vq_quantthresh__44c3_s_p6_0[] = {
  125236. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125237. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125238. };
  125239. static long _vq_quantmap__44c3_s_p6_0[] = {
  125240. 15, 13, 11, 9, 7, 5, 3, 1,
  125241. 0, 2, 4, 6, 8, 10, 12, 14,
  125242. 16,
  125243. };
  125244. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  125245. _vq_quantthresh__44c3_s_p6_0,
  125246. _vq_quantmap__44c3_s_p6_0,
  125247. 17,
  125248. 17
  125249. };
  125250. static static_codebook _44c3_s_p6_0 = {
  125251. 2, 289,
  125252. _vq_lengthlist__44c3_s_p6_0,
  125253. 1, -529530880, 1611661312, 5, 0,
  125254. _vq_quantlist__44c3_s_p6_0,
  125255. NULL,
  125256. &_vq_auxt__44c3_s_p6_0,
  125257. NULL,
  125258. 0
  125259. };
  125260. static long _vq_quantlist__44c3_s_p7_0[] = {
  125261. 1,
  125262. 0,
  125263. 2,
  125264. };
  125265. static long _vq_lengthlist__44c3_s_p7_0[] = {
  125266. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125267. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125268. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125269. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  125270. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125271. 10,
  125272. };
  125273. static float _vq_quantthresh__44c3_s_p7_0[] = {
  125274. -5.5, 5.5,
  125275. };
  125276. static long _vq_quantmap__44c3_s_p7_0[] = {
  125277. 1, 0, 2,
  125278. };
  125279. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  125280. _vq_quantthresh__44c3_s_p7_0,
  125281. _vq_quantmap__44c3_s_p7_0,
  125282. 3,
  125283. 3
  125284. };
  125285. static static_codebook _44c3_s_p7_0 = {
  125286. 4, 81,
  125287. _vq_lengthlist__44c3_s_p7_0,
  125288. 1, -529137664, 1618345984, 2, 0,
  125289. _vq_quantlist__44c3_s_p7_0,
  125290. NULL,
  125291. &_vq_auxt__44c3_s_p7_0,
  125292. NULL,
  125293. 0
  125294. };
  125295. static long _vq_quantlist__44c3_s_p7_1[] = {
  125296. 5,
  125297. 4,
  125298. 6,
  125299. 3,
  125300. 7,
  125301. 2,
  125302. 8,
  125303. 1,
  125304. 9,
  125305. 0,
  125306. 10,
  125307. };
  125308. static long _vq_lengthlist__44c3_s_p7_1[] = {
  125309. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  125310. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125311. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125312. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  125313. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  125314. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  125315. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  125316. 10,10,10, 8, 8, 8, 8, 8, 8,
  125317. };
  125318. static float _vq_quantthresh__44c3_s_p7_1[] = {
  125319. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125320. 3.5, 4.5,
  125321. };
  125322. static long _vq_quantmap__44c3_s_p7_1[] = {
  125323. 9, 7, 5, 3, 1, 0, 2, 4,
  125324. 6, 8, 10,
  125325. };
  125326. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  125327. _vq_quantthresh__44c3_s_p7_1,
  125328. _vq_quantmap__44c3_s_p7_1,
  125329. 11,
  125330. 11
  125331. };
  125332. static static_codebook _44c3_s_p7_1 = {
  125333. 2, 121,
  125334. _vq_lengthlist__44c3_s_p7_1,
  125335. 1, -531365888, 1611661312, 4, 0,
  125336. _vq_quantlist__44c3_s_p7_1,
  125337. NULL,
  125338. &_vq_auxt__44c3_s_p7_1,
  125339. NULL,
  125340. 0
  125341. };
  125342. static long _vq_quantlist__44c3_s_p8_0[] = {
  125343. 6,
  125344. 5,
  125345. 7,
  125346. 4,
  125347. 8,
  125348. 3,
  125349. 9,
  125350. 2,
  125351. 10,
  125352. 1,
  125353. 11,
  125354. 0,
  125355. 12,
  125356. };
  125357. static long _vq_lengthlist__44c3_s_p8_0[] = {
  125358. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125359. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  125360. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125361. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125362. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  125363. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125364. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  125365. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125366. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  125367. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  125368. 0,13,13,12,12,13,12,14,13,
  125369. };
  125370. static float _vq_quantthresh__44c3_s_p8_0[] = {
  125371. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125372. 12.5, 17.5, 22.5, 27.5,
  125373. };
  125374. static long _vq_quantmap__44c3_s_p8_0[] = {
  125375. 11, 9, 7, 5, 3, 1, 0, 2,
  125376. 4, 6, 8, 10, 12,
  125377. };
  125378. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  125379. _vq_quantthresh__44c3_s_p8_0,
  125380. _vq_quantmap__44c3_s_p8_0,
  125381. 13,
  125382. 13
  125383. };
  125384. static static_codebook _44c3_s_p8_0 = {
  125385. 2, 169,
  125386. _vq_lengthlist__44c3_s_p8_0,
  125387. 1, -526516224, 1616117760, 4, 0,
  125388. _vq_quantlist__44c3_s_p8_0,
  125389. NULL,
  125390. &_vq_auxt__44c3_s_p8_0,
  125391. NULL,
  125392. 0
  125393. };
  125394. static long _vq_quantlist__44c3_s_p8_1[] = {
  125395. 2,
  125396. 1,
  125397. 3,
  125398. 0,
  125399. 4,
  125400. };
  125401. static long _vq_lengthlist__44c3_s_p8_1[] = {
  125402. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125403. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125404. };
  125405. static float _vq_quantthresh__44c3_s_p8_1[] = {
  125406. -1.5, -0.5, 0.5, 1.5,
  125407. };
  125408. static long _vq_quantmap__44c3_s_p8_1[] = {
  125409. 3, 1, 0, 2, 4,
  125410. };
  125411. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  125412. _vq_quantthresh__44c3_s_p8_1,
  125413. _vq_quantmap__44c3_s_p8_1,
  125414. 5,
  125415. 5
  125416. };
  125417. static static_codebook _44c3_s_p8_1 = {
  125418. 2, 25,
  125419. _vq_lengthlist__44c3_s_p8_1,
  125420. 1, -533725184, 1611661312, 3, 0,
  125421. _vq_quantlist__44c3_s_p8_1,
  125422. NULL,
  125423. &_vq_auxt__44c3_s_p8_1,
  125424. NULL,
  125425. 0
  125426. };
  125427. static long _vq_quantlist__44c3_s_p9_0[] = {
  125428. 6,
  125429. 5,
  125430. 7,
  125431. 4,
  125432. 8,
  125433. 3,
  125434. 9,
  125435. 2,
  125436. 10,
  125437. 1,
  125438. 11,
  125439. 0,
  125440. 12,
  125441. };
  125442. static long _vq_lengthlist__44c3_s_p9_0[] = {
  125443. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  125444. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  125445. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125446. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  125447. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125448. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125449. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125450. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  125451. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  125452. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  125453. 11,11,11,11,11,11,11,11,11,
  125454. };
  125455. static float _vq_quantthresh__44c3_s_p9_0[] = {
  125456. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  125457. 637.5, 892.5, 1147.5, 1402.5,
  125458. };
  125459. static long _vq_quantmap__44c3_s_p9_0[] = {
  125460. 11, 9, 7, 5, 3, 1, 0, 2,
  125461. 4, 6, 8, 10, 12,
  125462. };
  125463. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  125464. _vq_quantthresh__44c3_s_p9_0,
  125465. _vq_quantmap__44c3_s_p9_0,
  125466. 13,
  125467. 13
  125468. };
  125469. static static_codebook _44c3_s_p9_0 = {
  125470. 2, 169,
  125471. _vq_lengthlist__44c3_s_p9_0,
  125472. 1, -514332672, 1627381760, 4, 0,
  125473. _vq_quantlist__44c3_s_p9_0,
  125474. NULL,
  125475. &_vq_auxt__44c3_s_p9_0,
  125476. NULL,
  125477. 0
  125478. };
  125479. static long _vq_quantlist__44c3_s_p9_1[] = {
  125480. 7,
  125481. 6,
  125482. 8,
  125483. 5,
  125484. 9,
  125485. 4,
  125486. 10,
  125487. 3,
  125488. 11,
  125489. 2,
  125490. 12,
  125491. 1,
  125492. 13,
  125493. 0,
  125494. 14,
  125495. };
  125496. static long _vq_lengthlist__44c3_s_p9_1[] = {
  125497. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  125498. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  125499. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  125500. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  125501. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  125502. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  125503. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  125504. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  125505. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  125506. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  125507. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  125508. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  125509. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  125510. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  125511. 15,
  125512. };
  125513. static float _vq_quantthresh__44c3_s_p9_1[] = {
  125514. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  125515. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  125516. };
  125517. static long _vq_quantmap__44c3_s_p9_1[] = {
  125518. 13, 11, 9, 7, 5, 3, 1, 0,
  125519. 2, 4, 6, 8, 10, 12, 14,
  125520. };
  125521. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  125522. _vq_quantthresh__44c3_s_p9_1,
  125523. _vq_quantmap__44c3_s_p9_1,
  125524. 15,
  125525. 15
  125526. };
  125527. static static_codebook _44c3_s_p9_1 = {
  125528. 2, 225,
  125529. _vq_lengthlist__44c3_s_p9_1,
  125530. 1, -522338304, 1620115456, 4, 0,
  125531. _vq_quantlist__44c3_s_p9_1,
  125532. NULL,
  125533. &_vq_auxt__44c3_s_p9_1,
  125534. NULL,
  125535. 0
  125536. };
  125537. static long _vq_quantlist__44c3_s_p9_2[] = {
  125538. 8,
  125539. 7,
  125540. 9,
  125541. 6,
  125542. 10,
  125543. 5,
  125544. 11,
  125545. 4,
  125546. 12,
  125547. 3,
  125548. 13,
  125549. 2,
  125550. 14,
  125551. 1,
  125552. 15,
  125553. 0,
  125554. 16,
  125555. };
  125556. static long _vq_lengthlist__44c3_s_p9_2[] = {
  125557. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  125558. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  125559. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125560. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  125561. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  125562. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  125563. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  125564. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  125565. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  125566. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  125567. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  125568. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  125569. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  125570. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  125571. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  125572. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  125573. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  125574. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  125575. 10,
  125576. };
  125577. static float _vq_quantthresh__44c3_s_p9_2[] = {
  125578. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125579. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125580. };
  125581. static long _vq_quantmap__44c3_s_p9_2[] = {
  125582. 15, 13, 11, 9, 7, 5, 3, 1,
  125583. 0, 2, 4, 6, 8, 10, 12, 14,
  125584. 16,
  125585. };
  125586. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  125587. _vq_quantthresh__44c3_s_p9_2,
  125588. _vq_quantmap__44c3_s_p9_2,
  125589. 17,
  125590. 17
  125591. };
  125592. static static_codebook _44c3_s_p9_2 = {
  125593. 2, 289,
  125594. _vq_lengthlist__44c3_s_p9_2,
  125595. 1, -529530880, 1611661312, 5, 0,
  125596. _vq_quantlist__44c3_s_p9_2,
  125597. NULL,
  125598. &_vq_auxt__44c3_s_p9_2,
  125599. NULL,
  125600. 0
  125601. };
  125602. static long _huff_lengthlist__44c3_s_short[] = {
  125603. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  125604. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  125605. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  125606. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  125607. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  125608. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  125609. 6, 8, 9,11,
  125610. };
  125611. static static_codebook _huff_book__44c3_s_short = {
  125612. 2, 100,
  125613. _huff_lengthlist__44c3_s_short,
  125614. 0, 0, 0, 0, 0,
  125615. NULL,
  125616. NULL,
  125617. NULL,
  125618. NULL,
  125619. 0
  125620. };
  125621. static long _huff_lengthlist__44c4_s_long[] = {
  125622. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  125623. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  125624. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  125625. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  125626. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  125627. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  125628. 9, 8, 7, 7,
  125629. };
  125630. static static_codebook _huff_book__44c4_s_long = {
  125631. 2, 100,
  125632. _huff_lengthlist__44c4_s_long,
  125633. 0, 0, 0, 0, 0,
  125634. NULL,
  125635. NULL,
  125636. NULL,
  125637. NULL,
  125638. 0
  125639. };
  125640. static long _vq_quantlist__44c4_s_p1_0[] = {
  125641. 1,
  125642. 0,
  125643. 2,
  125644. };
  125645. static long _vq_lengthlist__44c4_s_p1_0[] = {
  125646. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  125647. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125651. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  125652. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125656. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  125657. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125669. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125674. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125679. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  125692. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  125697. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  125702. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  125738. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  125743. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  125748. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126057. };
  126058. static float _vq_quantthresh__44c4_s_p1_0[] = {
  126059. -0.5, 0.5,
  126060. };
  126061. static long _vq_quantmap__44c4_s_p1_0[] = {
  126062. 1, 0, 2,
  126063. };
  126064. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  126065. _vq_quantthresh__44c4_s_p1_0,
  126066. _vq_quantmap__44c4_s_p1_0,
  126067. 3,
  126068. 3
  126069. };
  126070. static static_codebook _44c4_s_p1_0 = {
  126071. 8, 6561,
  126072. _vq_lengthlist__44c4_s_p1_0,
  126073. 1, -535822336, 1611661312, 2, 0,
  126074. _vq_quantlist__44c4_s_p1_0,
  126075. NULL,
  126076. &_vq_auxt__44c4_s_p1_0,
  126077. NULL,
  126078. 0
  126079. };
  126080. static long _vq_quantlist__44c4_s_p2_0[] = {
  126081. 2,
  126082. 1,
  126083. 3,
  126084. 0,
  126085. 4,
  126086. };
  126087. static long _vq_lengthlist__44c4_s_p2_0[] = {
  126088. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  126089. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  126090. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  126091. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  126092. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126097. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  126098. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  126099. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  126100. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126105. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  126106. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  126107. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  126108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126113. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  126114. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  126115. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 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,
  126128. };
  126129. static float _vq_quantthresh__44c4_s_p2_0[] = {
  126130. -1.5, -0.5, 0.5, 1.5,
  126131. };
  126132. static long _vq_quantmap__44c4_s_p2_0[] = {
  126133. 3, 1, 0, 2, 4,
  126134. };
  126135. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  126136. _vq_quantthresh__44c4_s_p2_0,
  126137. _vq_quantmap__44c4_s_p2_0,
  126138. 5,
  126139. 5
  126140. };
  126141. static static_codebook _44c4_s_p2_0 = {
  126142. 4, 625,
  126143. _vq_lengthlist__44c4_s_p2_0,
  126144. 1, -533725184, 1611661312, 3, 0,
  126145. _vq_quantlist__44c4_s_p2_0,
  126146. NULL,
  126147. &_vq_auxt__44c4_s_p2_0,
  126148. NULL,
  126149. 0
  126150. };
  126151. static long _vq_quantlist__44c4_s_p3_0[] = {
  126152. 2,
  126153. 1,
  126154. 3,
  126155. 0,
  126156. 4,
  126157. };
  126158. static long _vq_lengthlist__44c4_s_p3_0[] = {
  126159. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  126161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126162. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  126164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126165. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  126166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126199. };
  126200. static float _vq_quantthresh__44c4_s_p3_0[] = {
  126201. -1.5, -0.5, 0.5, 1.5,
  126202. };
  126203. static long _vq_quantmap__44c4_s_p3_0[] = {
  126204. 3, 1, 0, 2, 4,
  126205. };
  126206. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  126207. _vq_quantthresh__44c4_s_p3_0,
  126208. _vq_quantmap__44c4_s_p3_0,
  126209. 5,
  126210. 5
  126211. };
  126212. static static_codebook _44c4_s_p3_0 = {
  126213. 4, 625,
  126214. _vq_lengthlist__44c4_s_p3_0,
  126215. 1, -533725184, 1611661312, 3, 0,
  126216. _vq_quantlist__44c4_s_p3_0,
  126217. NULL,
  126218. &_vq_auxt__44c4_s_p3_0,
  126219. NULL,
  126220. 0
  126221. };
  126222. static long _vq_quantlist__44c4_s_p4_0[] = {
  126223. 4,
  126224. 3,
  126225. 5,
  126226. 2,
  126227. 6,
  126228. 1,
  126229. 7,
  126230. 0,
  126231. 8,
  126232. };
  126233. static long _vq_lengthlist__44c4_s_p4_0[] = {
  126234. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  126235. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  126236. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  126237. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  126238. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126239. 0,
  126240. };
  126241. static float _vq_quantthresh__44c4_s_p4_0[] = {
  126242. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126243. };
  126244. static long _vq_quantmap__44c4_s_p4_0[] = {
  126245. 7, 5, 3, 1, 0, 2, 4, 6,
  126246. 8,
  126247. };
  126248. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  126249. _vq_quantthresh__44c4_s_p4_0,
  126250. _vq_quantmap__44c4_s_p4_0,
  126251. 9,
  126252. 9
  126253. };
  126254. static static_codebook _44c4_s_p4_0 = {
  126255. 2, 81,
  126256. _vq_lengthlist__44c4_s_p4_0,
  126257. 1, -531628032, 1611661312, 4, 0,
  126258. _vq_quantlist__44c4_s_p4_0,
  126259. NULL,
  126260. &_vq_auxt__44c4_s_p4_0,
  126261. NULL,
  126262. 0
  126263. };
  126264. static long _vq_quantlist__44c4_s_p5_0[] = {
  126265. 4,
  126266. 3,
  126267. 5,
  126268. 2,
  126269. 6,
  126270. 1,
  126271. 7,
  126272. 0,
  126273. 8,
  126274. };
  126275. static long _vq_lengthlist__44c4_s_p5_0[] = {
  126276. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126277. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  126278. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  126279. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  126280. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  126281. 10,
  126282. };
  126283. static float _vq_quantthresh__44c4_s_p5_0[] = {
  126284. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126285. };
  126286. static long _vq_quantmap__44c4_s_p5_0[] = {
  126287. 7, 5, 3, 1, 0, 2, 4, 6,
  126288. 8,
  126289. };
  126290. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  126291. _vq_quantthresh__44c4_s_p5_0,
  126292. _vq_quantmap__44c4_s_p5_0,
  126293. 9,
  126294. 9
  126295. };
  126296. static static_codebook _44c4_s_p5_0 = {
  126297. 2, 81,
  126298. _vq_lengthlist__44c4_s_p5_0,
  126299. 1, -531628032, 1611661312, 4, 0,
  126300. _vq_quantlist__44c4_s_p5_0,
  126301. NULL,
  126302. &_vq_auxt__44c4_s_p5_0,
  126303. NULL,
  126304. 0
  126305. };
  126306. static long _vq_quantlist__44c4_s_p6_0[] = {
  126307. 8,
  126308. 7,
  126309. 9,
  126310. 6,
  126311. 10,
  126312. 5,
  126313. 11,
  126314. 4,
  126315. 12,
  126316. 3,
  126317. 13,
  126318. 2,
  126319. 14,
  126320. 1,
  126321. 15,
  126322. 0,
  126323. 16,
  126324. };
  126325. static long _vq_lengthlist__44c4_s_p6_0[] = {
  126326. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  126327. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126328. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  126329. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  126330. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  126331. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126332. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  126333. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  126334. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  126335. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  126336. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  126337. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  126338. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  126339. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  126340. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  126341. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  126342. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  126343. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  126344. 13,
  126345. };
  126346. static float _vq_quantthresh__44c4_s_p6_0[] = {
  126347. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126348. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126349. };
  126350. static long _vq_quantmap__44c4_s_p6_0[] = {
  126351. 15, 13, 11, 9, 7, 5, 3, 1,
  126352. 0, 2, 4, 6, 8, 10, 12, 14,
  126353. 16,
  126354. };
  126355. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  126356. _vq_quantthresh__44c4_s_p6_0,
  126357. _vq_quantmap__44c4_s_p6_0,
  126358. 17,
  126359. 17
  126360. };
  126361. static static_codebook _44c4_s_p6_0 = {
  126362. 2, 289,
  126363. _vq_lengthlist__44c4_s_p6_0,
  126364. 1, -529530880, 1611661312, 5, 0,
  126365. _vq_quantlist__44c4_s_p6_0,
  126366. NULL,
  126367. &_vq_auxt__44c4_s_p6_0,
  126368. NULL,
  126369. 0
  126370. };
  126371. static long _vq_quantlist__44c4_s_p7_0[] = {
  126372. 1,
  126373. 0,
  126374. 2,
  126375. };
  126376. static long _vq_lengthlist__44c4_s_p7_0[] = {
  126377. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  126378. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  126379. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  126380. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  126381. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  126382. 10,
  126383. };
  126384. static float _vq_quantthresh__44c4_s_p7_0[] = {
  126385. -5.5, 5.5,
  126386. };
  126387. static long _vq_quantmap__44c4_s_p7_0[] = {
  126388. 1, 0, 2,
  126389. };
  126390. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  126391. _vq_quantthresh__44c4_s_p7_0,
  126392. _vq_quantmap__44c4_s_p7_0,
  126393. 3,
  126394. 3
  126395. };
  126396. static static_codebook _44c4_s_p7_0 = {
  126397. 4, 81,
  126398. _vq_lengthlist__44c4_s_p7_0,
  126399. 1, -529137664, 1618345984, 2, 0,
  126400. _vq_quantlist__44c4_s_p7_0,
  126401. NULL,
  126402. &_vq_auxt__44c4_s_p7_0,
  126403. NULL,
  126404. 0
  126405. };
  126406. static long _vq_quantlist__44c4_s_p7_1[] = {
  126407. 5,
  126408. 4,
  126409. 6,
  126410. 3,
  126411. 7,
  126412. 2,
  126413. 8,
  126414. 1,
  126415. 9,
  126416. 0,
  126417. 10,
  126418. };
  126419. static long _vq_lengthlist__44c4_s_p7_1[] = {
  126420. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  126421. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  126422. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  126423. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  126424. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  126425. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  126426. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  126427. 10,10,10, 8, 8, 8, 8, 9, 9,
  126428. };
  126429. static float _vq_quantthresh__44c4_s_p7_1[] = {
  126430. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126431. 3.5, 4.5,
  126432. };
  126433. static long _vq_quantmap__44c4_s_p7_1[] = {
  126434. 9, 7, 5, 3, 1, 0, 2, 4,
  126435. 6, 8, 10,
  126436. };
  126437. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  126438. _vq_quantthresh__44c4_s_p7_1,
  126439. _vq_quantmap__44c4_s_p7_1,
  126440. 11,
  126441. 11
  126442. };
  126443. static static_codebook _44c4_s_p7_1 = {
  126444. 2, 121,
  126445. _vq_lengthlist__44c4_s_p7_1,
  126446. 1, -531365888, 1611661312, 4, 0,
  126447. _vq_quantlist__44c4_s_p7_1,
  126448. NULL,
  126449. &_vq_auxt__44c4_s_p7_1,
  126450. NULL,
  126451. 0
  126452. };
  126453. static long _vq_quantlist__44c4_s_p8_0[] = {
  126454. 6,
  126455. 5,
  126456. 7,
  126457. 4,
  126458. 8,
  126459. 3,
  126460. 9,
  126461. 2,
  126462. 10,
  126463. 1,
  126464. 11,
  126465. 0,
  126466. 12,
  126467. };
  126468. static long _vq_lengthlist__44c4_s_p8_0[] = {
  126469. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  126470. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126471. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  126472. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  126473. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  126474. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  126475. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  126476. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  126477. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  126478. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  126479. 0,13,12,12,12,12,12,13,13,
  126480. };
  126481. static float _vq_quantthresh__44c4_s_p8_0[] = {
  126482. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126483. 12.5, 17.5, 22.5, 27.5,
  126484. };
  126485. static long _vq_quantmap__44c4_s_p8_0[] = {
  126486. 11, 9, 7, 5, 3, 1, 0, 2,
  126487. 4, 6, 8, 10, 12,
  126488. };
  126489. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  126490. _vq_quantthresh__44c4_s_p8_0,
  126491. _vq_quantmap__44c4_s_p8_0,
  126492. 13,
  126493. 13
  126494. };
  126495. static static_codebook _44c4_s_p8_0 = {
  126496. 2, 169,
  126497. _vq_lengthlist__44c4_s_p8_0,
  126498. 1, -526516224, 1616117760, 4, 0,
  126499. _vq_quantlist__44c4_s_p8_0,
  126500. NULL,
  126501. &_vq_auxt__44c4_s_p8_0,
  126502. NULL,
  126503. 0
  126504. };
  126505. static long _vq_quantlist__44c4_s_p8_1[] = {
  126506. 2,
  126507. 1,
  126508. 3,
  126509. 0,
  126510. 4,
  126511. };
  126512. static long _vq_lengthlist__44c4_s_p8_1[] = {
  126513. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  126514. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126515. };
  126516. static float _vq_quantthresh__44c4_s_p8_1[] = {
  126517. -1.5, -0.5, 0.5, 1.5,
  126518. };
  126519. static long _vq_quantmap__44c4_s_p8_1[] = {
  126520. 3, 1, 0, 2, 4,
  126521. };
  126522. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  126523. _vq_quantthresh__44c4_s_p8_1,
  126524. _vq_quantmap__44c4_s_p8_1,
  126525. 5,
  126526. 5
  126527. };
  126528. static static_codebook _44c4_s_p8_1 = {
  126529. 2, 25,
  126530. _vq_lengthlist__44c4_s_p8_1,
  126531. 1, -533725184, 1611661312, 3, 0,
  126532. _vq_quantlist__44c4_s_p8_1,
  126533. NULL,
  126534. &_vq_auxt__44c4_s_p8_1,
  126535. NULL,
  126536. 0
  126537. };
  126538. static long _vq_quantlist__44c4_s_p9_0[] = {
  126539. 6,
  126540. 5,
  126541. 7,
  126542. 4,
  126543. 8,
  126544. 3,
  126545. 9,
  126546. 2,
  126547. 10,
  126548. 1,
  126549. 11,
  126550. 0,
  126551. 12,
  126552. };
  126553. static long _vq_lengthlist__44c4_s_p9_0[] = {
  126554. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  126555. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  126556. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126557. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126558. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126559. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126560. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126561. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126562. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126563. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  126564. 12,12,12,12,12,12,12,12,12,
  126565. };
  126566. static float _vq_quantthresh__44c4_s_p9_0[] = {
  126567. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  126568. 787.5, 1102.5, 1417.5, 1732.5,
  126569. };
  126570. static long _vq_quantmap__44c4_s_p9_0[] = {
  126571. 11, 9, 7, 5, 3, 1, 0, 2,
  126572. 4, 6, 8, 10, 12,
  126573. };
  126574. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  126575. _vq_quantthresh__44c4_s_p9_0,
  126576. _vq_quantmap__44c4_s_p9_0,
  126577. 13,
  126578. 13
  126579. };
  126580. static static_codebook _44c4_s_p9_0 = {
  126581. 2, 169,
  126582. _vq_lengthlist__44c4_s_p9_0,
  126583. 1, -513964032, 1628680192, 4, 0,
  126584. _vq_quantlist__44c4_s_p9_0,
  126585. NULL,
  126586. &_vq_auxt__44c4_s_p9_0,
  126587. NULL,
  126588. 0
  126589. };
  126590. static long _vq_quantlist__44c4_s_p9_1[] = {
  126591. 7,
  126592. 6,
  126593. 8,
  126594. 5,
  126595. 9,
  126596. 4,
  126597. 10,
  126598. 3,
  126599. 11,
  126600. 2,
  126601. 12,
  126602. 1,
  126603. 13,
  126604. 0,
  126605. 14,
  126606. };
  126607. static long _vq_lengthlist__44c4_s_p9_1[] = {
  126608. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  126609. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  126610. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  126611. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  126612. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  126613. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  126614. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  126615. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  126616. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  126617. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  126618. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  126619. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  126620. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  126621. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  126622. 15,
  126623. };
  126624. static float _vq_quantthresh__44c4_s_p9_1[] = {
  126625. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126626. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126627. };
  126628. static long _vq_quantmap__44c4_s_p9_1[] = {
  126629. 13, 11, 9, 7, 5, 3, 1, 0,
  126630. 2, 4, 6, 8, 10, 12, 14,
  126631. };
  126632. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  126633. _vq_quantthresh__44c4_s_p9_1,
  126634. _vq_quantmap__44c4_s_p9_1,
  126635. 15,
  126636. 15
  126637. };
  126638. static static_codebook _44c4_s_p9_1 = {
  126639. 2, 225,
  126640. _vq_lengthlist__44c4_s_p9_1,
  126641. 1, -520986624, 1620377600, 4, 0,
  126642. _vq_quantlist__44c4_s_p9_1,
  126643. NULL,
  126644. &_vq_auxt__44c4_s_p9_1,
  126645. NULL,
  126646. 0
  126647. };
  126648. static long _vq_quantlist__44c4_s_p9_2[] = {
  126649. 10,
  126650. 9,
  126651. 11,
  126652. 8,
  126653. 12,
  126654. 7,
  126655. 13,
  126656. 6,
  126657. 14,
  126658. 5,
  126659. 15,
  126660. 4,
  126661. 16,
  126662. 3,
  126663. 17,
  126664. 2,
  126665. 18,
  126666. 1,
  126667. 19,
  126668. 0,
  126669. 20,
  126670. };
  126671. static long _vq_lengthlist__44c4_s_p9_2[] = {
  126672. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  126673. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  126674. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  126675. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  126676. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  126677. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  126678. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  126679. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126680. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  126681. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  126682. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  126683. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  126684. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  126685. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  126686. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  126687. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  126688. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  126689. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  126690. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  126691. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  126692. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126693. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126694. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  126695. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  126696. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  126697. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  126698. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  126699. 10,10,10,10,10,10,10,10,10,
  126700. };
  126701. static float _vq_quantthresh__44c4_s_p9_2[] = {
  126702. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126703. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126704. 6.5, 7.5, 8.5, 9.5,
  126705. };
  126706. static long _vq_quantmap__44c4_s_p9_2[] = {
  126707. 19, 17, 15, 13, 11, 9, 7, 5,
  126708. 3, 1, 0, 2, 4, 6, 8, 10,
  126709. 12, 14, 16, 18, 20,
  126710. };
  126711. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  126712. _vq_quantthresh__44c4_s_p9_2,
  126713. _vq_quantmap__44c4_s_p9_2,
  126714. 21,
  126715. 21
  126716. };
  126717. static static_codebook _44c4_s_p9_2 = {
  126718. 2, 441,
  126719. _vq_lengthlist__44c4_s_p9_2,
  126720. 1, -529268736, 1611661312, 5, 0,
  126721. _vq_quantlist__44c4_s_p9_2,
  126722. NULL,
  126723. &_vq_auxt__44c4_s_p9_2,
  126724. NULL,
  126725. 0
  126726. };
  126727. static long _huff_lengthlist__44c4_s_short[] = {
  126728. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  126729. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  126730. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  126731. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  126732. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  126733. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  126734. 7, 9,12,17,
  126735. };
  126736. static static_codebook _huff_book__44c4_s_short = {
  126737. 2, 100,
  126738. _huff_lengthlist__44c4_s_short,
  126739. 0, 0, 0, 0, 0,
  126740. NULL,
  126741. NULL,
  126742. NULL,
  126743. NULL,
  126744. 0
  126745. };
  126746. static long _huff_lengthlist__44c5_s_long[] = {
  126747. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  126748. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  126749. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  126750. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  126751. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  126752. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  126753. 9, 8, 7, 7,
  126754. };
  126755. static static_codebook _huff_book__44c5_s_long = {
  126756. 2, 100,
  126757. _huff_lengthlist__44c5_s_long,
  126758. 0, 0, 0, 0, 0,
  126759. NULL,
  126760. NULL,
  126761. NULL,
  126762. NULL,
  126763. 0
  126764. };
  126765. static long _vq_quantlist__44c5_s_p1_0[] = {
  126766. 1,
  126767. 0,
  126768. 2,
  126769. };
  126770. static long _vq_lengthlist__44c5_s_p1_0[] = {
  126771. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  126772. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  126777. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126782. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  126817. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126822. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126827. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126863. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  126868. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126873. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127182. };
  127183. static float _vq_quantthresh__44c5_s_p1_0[] = {
  127184. -0.5, 0.5,
  127185. };
  127186. static long _vq_quantmap__44c5_s_p1_0[] = {
  127187. 1, 0, 2,
  127188. };
  127189. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  127190. _vq_quantthresh__44c5_s_p1_0,
  127191. _vq_quantmap__44c5_s_p1_0,
  127192. 3,
  127193. 3
  127194. };
  127195. static static_codebook _44c5_s_p1_0 = {
  127196. 8, 6561,
  127197. _vq_lengthlist__44c5_s_p1_0,
  127198. 1, -535822336, 1611661312, 2, 0,
  127199. _vq_quantlist__44c5_s_p1_0,
  127200. NULL,
  127201. &_vq_auxt__44c5_s_p1_0,
  127202. NULL,
  127203. 0
  127204. };
  127205. static long _vq_quantlist__44c5_s_p2_0[] = {
  127206. 2,
  127207. 1,
  127208. 3,
  127209. 0,
  127210. 4,
  127211. };
  127212. static long _vq_lengthlist__44c5_s_p2_0[] = {
  127213. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  127214. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  127215. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  127216. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  127217. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  127223. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  127224. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  127225. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  127231. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  127232. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  127239. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  127240. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 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,
  127253. };
  127254. static float _vq_quantthresh__44c5_s_p2_0[] = {
  127255. -1.5, -0.5, 0.5, 1.5,
  127256. };
  127257. static long _vq_quantmap__44c5_s_p2_0[] = {
  127258. 3, 1, 0, 2, 4,
  127259. };
  127260. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  127261. _vq_quantthresh__44c5_s_p2_0,
  127262. _vq_quantmap__44c5_s_p2_0,
  127263. 5,
  127264. 5
  127265. };
  127266. static static_codebook _44c5_s_p2_0 = {
  127267. 4, 625,
  127268. _vq_lengthlist__44c5_s_p2_0,
  127269. 1, -533725184, 1611661312, 3, 0,
  127270. _vq_quantlist__44c5_s_p2_0,
  127271. NULL,
  127272. &_vq_auxt__44c5_s_p2_0,
  127273. NULL,
  127274. 0
  127275. };
  127276. static long _vq_quantlist__44c5_s_p3_0[] = {
  127277. 2,
  127278. 1,
  127279. 3,
  127280. 0,
  127281. 4,
  127282. };
  127283. static long _vq_lengthlist__44c5_s_p3_0[] = {
  127284. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  127286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127324. };
  127325. static float _vq_quantthresh__44c5_s_p3_0[] = {
  127326. -1.5, -0.5, 0.5, 1.5,
  127327. };
  127328. static long _vq_quantmap__44c5_s_p3_0[] = {
  127329. 3, 1, 0, 2, 4,
  127330. };
  127331. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  127332. _vq_quantthresh__44c5_s_p3_0,
  127333. _vq_quantmap__44c5_s_p3_0,
  127334. 5,
  127335. 5
  127336. };
  127337. static static_codebook _44c5_s_p3_0 = {
  127338. 4, 625,
  127339. _vq_lengthlist__44c5_s_p3_0,
  127340. 1, -533725184, 1611661312, 3, 0,
  127341. _vq_quantlist__44c5_s_p3_0,
  127342. NULL,
  127343. &_vq_auxt__44c5_s_p3_0,
  127344. NULL,
  127345. 0
  127346. };
  127347. static long _vq_quantlist__44c5_s_p4_0[] = {
  127348. 4,
  127349. 3,
  127350. 5,
  127351. 2,
  127352. 6,
  127353. 1,
  127354. 7,
  127355. 0,
  127356. 8,
  127357. };
  127358. static long _vq_lengthlist__44c5_s_p4_0[] = {
  127359. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  127360. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  127361. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  127362. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  127363. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127364. 0,
  127365. };
  127366. static float _vq_quantthresh__44c5_s_p4_0[] = {
  127367. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127368. };
  127369. static long _vq_quantmap__44c5_s_p4_0[] = {
  127370. 7, 5, 3, 1, 0, 2, 4, 6,
  127371. 8,
  127372. };
  127373. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  127374. _vq_quantthresh__44c5_s_p4_0,
  127375. _vq_quantmap__44c5_s_p4_0,
  127376. 9,
  127377. 9
  127378. };
  127379. static static_codebook _44c5_s_p4_0 = {
  127380. 2, 81,
  127381. _vq_lengthlist__44c5_s_p4_0,
  127382. 1, -531628032, 1611661312, 4, 0,
  127383. _vq_quantlist__44c5_s_p4_0,
  127384. NULL,
  127385. &_vq_auxt__44c5_s_p4_0,
  127386. NULL,
  127387. 0
  127388. };
  127389. static long _vq_quantlist__44c5_s_p5_0[] = {
  127390. 4,
  127391. 3,
  127392. 5,
  127393. 2,
  127394. 6,
  127395. 1,
  127396. 7,
  127397. 0,
  127398. 8,
  127399. };
  127400. static long _vq_lengthlist__44c5_s_p5_0[] = {
  127401. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127402. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  127403. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  127404. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  127405. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127406. 10,
  127407. };
  127408. static float _vq_quantthresh__44c5_s_p5_0[] = {
  127409. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127410. };
  127411. static long _vq_quantmap__44c5_s_p5_0[] = {
  127412. 7, 5, 3, 1, 0, 2, 4, 6,
  127413. 8,
  127414. };
  127415. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  127416. _vq_quantthresh__44c5_s_p5_0,
  127417. _vq_quantmap__44c5_s_p5_0,
  127418. 9,
  127419. 9
  127420. };
  127421. static static_codebook _44c5_s_p5_0 = {
  127422. 2, 81,
  127423. _vq_lengthlist__44c5_s_p5_0,
  127424. 1, -531628032, 1611661312, 4, 0,
  127425. _vq_quantlist__44c5_s_p5_0,
  127426. NULL,
  127427. &_vq_auxt__44c5_s_p5_0,
  127428. NULL,
  127429. 0
  127430. };
  127431. static long _vq_quantlist__44c5_s_p6_0[] = {
  127432. 8,
  127433. 7,
  127434. 9,
  127435. 6,
  127436. 10,
  127437. 5,
  127438. 11,
  127439. 4,
  127440. 12,
  127441. 3,
  127442. 13,
  127443. 2,
  127444. 14,
  127445. 1,
  127446. 15,
  127447. 0,
  127448. 16,
  127449. };
  127450. static long _vq_lengthlist__44c5_s_p6_0[] = {
  127451. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  127452. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127453. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  127454. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  127455. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  127456. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  127457. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  127458. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  127459. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  127460. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  127461. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  127462. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127463. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  127464. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  127465. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  127466. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  127467. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  127469. 13,
  127470. };
  127471. static float _vq_quantthresh__44c5_s_p6_0[] = {
  127472. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127473. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127474. };
  127475. static long _vq_quantmap__44c5_s_p6_0[] = {
  127476. 15, 13, 11, 9, 7, 5, 3, 1,
  127477. 0, 2, 4, 6, 8, 10, 12, 14,
  127478. 16,
  127479. };
  127480. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  127481. _vq_quantthresh__44c5_s_p6_0,
  127482. _vq_quantmap__44c5_s_p6_0,
  127483. 17,
  127484. 17
  127485. };
  127486. static static_codebook _44c5_s_p6_0 = {
  127487. 2, 289,
  127488. _vq_lengthlist__44c5_s_p6_0,
  127489. 1, -529530880, 1611661312, 5, 0,
  127490. _vq_quantlist__44c5_s_p6_0,
  127491. NULL,
  127492. &_vq_auxt__44c5_s_p6_0,
  127493. NULL,
  127494. 0
  127495. };
  127496. static long _vq_quantlist__44c5_s_p7_0[] = {
  127497. 1,
  127498. 0,
  127499. 2,
  127500. };
  127501. static long _vq_lengthlist__44c5_s_p7_0[] = {
  127502. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  127503. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  127504. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  127505. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  127506. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  127507. 10,
  127508. };
  127509. static float _vq_quantthresh__44c5_s_p7_0[] = {
  127510. -5.5, 5.5,
  127511. };
  127512. static long _vq_quantmap__44c5_s_p7_0[] = {
  127513. 1, 0, 2,
  127514. };
  127515. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  127516. _vq_quantthresh__44c5_s_p7_0,
  127517. _vq_quantmap__44c5_s_p7_0,
  127518. 3,
  127519. 3
  127520. };
  127521. static static_codebook _44c5_s_p7_0 = {
  127522. 4, 81,
  127523. _vq_lengthlist__44c5_s_p7_0,
  127524. 1, -529137664, 1618345984, 2, 0,
  127525. _vq_quantlist__44c5_s_p7_0,
  127526. NULL,
  127527. &_vq_auxt__44c5_s_p7_0,
  127528. NULL,
  127529. 0
  127530. };
  127531. static long _vq_quantlist__44c5_s_p7_1[] = {
  127532. 5,
  127533. 4,
  127534. 6,
  127535. 3,
  127536. 7,
  127537. 2,
  127538. 8,
  127539. 1,
  127540. 9,
  127541. 0,
  127542. 10,
  127543. };
  127544. static long _vq_lengthlist__44c5_s_p7_1[] = {
  127545. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  127546. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127547. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  127548. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  127549. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  127550. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  127551. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  127552. 10,10,10, 8, 8, 8, 8, 8, 8,
  127553. };
  127554. static float _vq_quantthresh__44c5_s_p7_1[] = {
  127555. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127556. 3.5, 4.5,
  127557. };
  127558. static long _vq_quantmap__44c5_s_p7_1[] = {
  127559. 9, 7, 5, 3, 1, 0, 2, 4,
  127560. 6, 8, 10,
  127561. };
  127562. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  127563. _vq_quantthresh__44c5_s_p7_1,
  127564. _vq_quantmap__44c5_s_p7_1,
  127565. 11,
  127566. 11
  127567. };
  127568. static static_codebook _44c5_s_p7_1 = {
  127569. 2, 121,
  127570. _vq_lengthlist__44c5_s_p7_1,
  127571. 1, -531365888, 1611661312, 4, 0,
  127572. _vq_quantlist__44c5_s_p7_1,
  127573. NULL,
  127574. &_vq_auxt__44c5_s_p7_1,
  127575. NULL,
  127576. 0
  127577. };
  127578. static long _vq_quantlist__44c5_s_p8_0[] = {
  127579. 6,
  127580. 5,
  127581. 7,
  127582. 4,
  127583. 8,
  127584. 3,
  127585. 9,
  127586. 2,
  127587. 10,
  127588. 1,
  127589. 11,
  127590. 0,
  127591. 12,
  127592. };
  127593. static long _vq_lengthlist__44c5_s_p8_0[] = {
  127594. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127595. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  127596. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127597. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127598. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  127599. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  127600. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  127601. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  127602. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  127603. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  127604. 0,12,12,12,12,12,12,13,13,
  127605. };
  127606. static float _vq_quantthresh__44c5_s_p8_0[] = {
  127607. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127608. 12.5, 17.5, 22.5, 27.5,
  127609. };
  127610. static long _vq_quantmap__44c5_s_p8_0[] = {
  127611. 11, 9, 7, 5, 3, 1, 0, 2,
  127612. 4, 6, 8, 10, 12,
  127613. };
  127614. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  127615. _vq_quantthresh__44c5_s_p8_0,
  127616. _vq_quantmap__44c5_s_p8_0,
  127617. 13,
  127618. 13
  127619. };
  127620. static static_codebook _44c5_s_p8_0 = {
  127621. 2, 169,
  127622. _vq_lengthlist__44c5_s_p8_0,
  127623. 1, -526516224, 1616117760, 4, 0,
  127624. _vq_quantlist__44c5_s_p8_0,
  127625. NULL,
  127626. &_vq_auxt__44c5_s_p8_0,
  127627. NULL,
  127628. 0
  127629. };
  127630. static long _vq_quantlist__44c5_s_p8_1[] = {
  127631. 2,
  127632. 1,
  127633. 3,
  127634. 0,
  127635. 4,
  127636. };
  127637. static long _vq_lengthlist__44c5_s_p8_1[] = {
  127638. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  127639. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127640. };
  127641. static float _vq_quantthresh__44c5_s_p8_1[] = {
  127642. -1.5, -0.5, 0.5, 1.5,
  127643. };
  127644. static long _vq_quantmap__44c5_s_p8_1[] = {
  127645. 3, 1, 0, 2, 4,
  127646. };
  127647. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  127648. _vq_quantthresh__44c5_s_p8_1,
  127649. _vq_quantmap__44c5_s_p8_1,
  127650. 5,
  127651. 5
  127652. };
  127653. static static_codebook _44c5_s_p8_1 = {
  127654. 2, 25,
  127655. _vq_lengthlist__44c5_s_p8_1,
  127656. 1, -533725184, 1611661312, 3, 0,
  127657. _vq_quantlist__44c5_s_p8_1,
  127658. NULL,
  127659. &_vq_auxt__44c5_s_p8_1,
  127660. NULL,
  127661. 0
  127662. };
  127663. static long _vq_quantlist__44c5_s_p9_0[] = {
  127664. 7,
  127665. 6,
  127666. 8,
  127667. 5,
  127668. 9,
  127669. 4,
  127670. 10,
  127671. 3,
  127672. 11,
  127673. 2,
  127674. 12,
  127675. 1,
  127676. 13,
  127677. 0,
  127678. 14,
  127679. };
  127680. static long _vq_lengthlist__44c5_s_p9_0[] = {
  127681. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  127682. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  127683. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127684. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127685. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127686. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127687. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127688. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127689. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127690. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127691. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127692. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127693. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  127694. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  127695. 12,
  127696. };
  127697. static float _vq_quantthresh__44c5_s_p9_0[] = {
  127698. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  127699. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  127700. };
  127701. static long _vq_quantmap__44c5_s_p9_0[] = {
  127702. 13, 11, 9, 7, 5, 3, 1, 0,
  127703. 2, 4, 6, 8, 10, 12, 14,
  127704. };
  127705. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  127706. _vq_quantthresh__44c5_s_p9_0,
  127707. _vq_quantmap__44c5_s_p9_0,
  127708. 15,
  127709. 15
  127710. };
  127711. static static_codebook _44c5_s_p9_0 = {
  127712. 2, 225,
  127713. _vq_lengthlist__44c5_s_p9_0,
  127714. 1, -512522752, 1628852224, 4, 0,
  127715. _vq_quantlist__44c5_s_p9_0,
  127716. NULL,
  127717. &_vq_auxt__44c5_s_p9_0,
  127718. NULL,
  127719. 0
  127720. };
  127721. static long _vq_quantlist__44c5_s_p9_1[] = {
  127722. 8,
  127723. 7,
  127724. 9,
  127725. 6,
  127726. 10,
  127727. 5,
  127728. 11,
  127729. 4,
  127730. 12,
  127731. 3,
  127732. 13,
  127733. 2,
  127734. 14,
  127735. 1,
  127736. 15,
  127737. 0,
  127738. 16,
  127739. };
  127740. static long _vq_lengthlist__44c5_s_p9_1[] = {
  127741. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  127742. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  127743. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  127744. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  127745. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  127746. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  127747. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  127748. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  127749. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  127750. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  127751. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  127752. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  127753. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  127754. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  127755. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  127756. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  127757. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  127758. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  127759. 15,
  127760. };
  127761. static float _vq_quantthresh__44c5_s_p9_1[] = {
  127762. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  127763. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  127764. };
  127765. static long _vq_quantmap__44c5_s_p9_1[] = {
  127766. 15, 13, 11, 9, 7, 5, 3, 1,
  127767. 0, 2, 4, 6, 8, 10, 12, 14,
  127768. 16,
  127769. };
  127770. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  127771. _vq_quantthresh__44c5_s_p9_1,
  127772. _vq_quantmap__44c5_s_p9_1,
  127773. 17,
  127774. 17
  127775. };
  127776. static static_codebook _44c5_s_p9_1 = {
  127777. 2, 289,
  127778. _vq_lengthlist__44c5_s_p9_1,
  127779. 1, -520814592, 1620377600, 5, 0,
  127780. _vq_quantlist__44c5_s_p9_1,
  127781. NULL,
  127782. &_vq_auxt__44c5_s_p9_1,
  127783. NULL,
  127784. 0
  127785. };
  127786. static long _vq_quantlist__44c5_s_p9_2[] = {
  127787. 10,
  127788. 9,
  127789. 11,
  127790. 8,
  127791. 12,
  127792. 7,
  127793. 13,
  127794. 6,
  127795. 14,
  127796. 5,
  127797. 15,
  127798. 4,
  127799. 16,
  127800. 3,
  127801. 17,
  127802. 2,
  127803. 18,
  127804. 1,
  127805. 19,
  127806. 0,
  127807. 20,
  127808. };
  127809. static long _vq_lengthlist__44c5_s_p9_2[] = {
  127810. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  127811. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  127812. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  127813. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  127814. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  127815. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127816. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127817. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  127818. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127819. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127820. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  127821. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  127822. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  127823. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  127824. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  127825. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  127826. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  127827. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127828. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  127829. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  127830. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127831. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  127832. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  127833. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127834. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  127835. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  127836. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  127837. 10,10,10,10,10,10,10,10,10,
  127838. };
  127839. static float _vq_quantthresh__44c5_s_p9_2[] = {
  127840. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127841. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127842. 6.5, 7.5, 8.5, 9.5,
  127843. };
  127844. static long _vq_quantmap__44c5_s_p9_2[] = {
  127845. 19, 17, 15, 13, 11, 9, 7, 5,
  127846. 3, 1, 0, 2, 4, 6, 8, 10,
  127847. 12, 14, 16, 18, 20,
  127848. };
  127849. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  127850. _vq_quantthresh__44c5_s_p9_2,
  127851. _vq_quantmap__44c5_s_p9_2,
  127852. 21,
  127853. 21
  127854. };
  127855. static static_codebook _44c5_s_p9_2 = {
  127856. 2, 441,
  127857. _vq_lengthlist__44c5_s_p9_2,
  127858. 1, -529268736, 1611661312, 5, 0,
  127859. _vq_quantlist__44c5_s_p9_2,
  127860. NULL,
  127861. &_vq_auxt__44c5_s_p9_2,
  127862. NULL,
  127863. 0
  127864. };
  127865. static long _huff_lengthlist__44c5_s_short[] = {
  127866. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  127867. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  127868. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  127869. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  127870. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  127871. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  127872. 6, 8,11,16,
  127873. };
  127874. static static_codebook _huff_book__44c5_s_short = {
  127875. 2, 100,
  127876. _huff_lengthlist__44c5_s_short,
  127877. 0, 0, 0, 0, 0,
  127878. NULL,
  127879. NULL,
  127880. NULL,
  127881. NULL,
  127882. 0
  127883. };
  127884. static long _huff_lengthlist__44c6_s_long[] = {
  127885. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  127886. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  127887. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  127888. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  127889. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  127890. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  127891. 11,10,10,12,
  127892. };
  127893. static static_codebook _huff_book__44c6_s_long = {
  127894. 2, 100,
  127895. _huff_lengthlist__44c6_s_long,
  127896. 0, 0, 0, 0, 0,
  127897. NULL,
  127898. NULL,
  127899. NULL,
  127900. NULL,
  127901. 0
  127902. };
  127903. static long _vq_quantlist__44c6_s_p1_0[] = {
  127904. 1,
  127905. 0,
  127906. 2,
  127907. };
  127908. static long _vq_lengthlist__44c6_s_p1_0[] = {
  127909. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  127910. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127912. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127913. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  127914. 8,
  127915. };
  127916. static float _vq_quantthresh__44c6_s_p1_0[] = {
  127917. -0.5, 0.5,
  127918. };
  127919. static long _vq_quantmap__44c6_s_p1_0[] = {
  127920. 1, 0, 2,
  127921. };
  127922. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  127923. _vq_quantthresh__44c6_s_p1_0,
  127924. _vq_quantmap__44c6_s_p1_0,
  127925. 3,
  127926. 3
  127927. };
  127928. static static_codebook _44c6_s_p1_0 = {
  127929. 4, 81,
  127930. _vq_lengthlist__44c6_s_p1_0,
  127931. 1, -535822336, 1611661312, 2, 0,
  127932. _vq_quantlist__44c6_s_p1_0,
  127933. NULL,
  127934. &_vq_auxt__44c6_s_p1_0,
  127935. NULL,
  127936. 0
  127937. };
  127938. static long _vq_quantlist__44c6_s_p2_0[] = {
  127939. 2,
  127940. 1,
  127941. 3,
  127942. 0,
  127943. 4,
  127944. };
  127945. static long _vq_lengthlist__44c6_s_p2_0[] = {
  127946. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127947. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127948. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127949. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  127950. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  127951. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  127952. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  127953. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127956. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  127957. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127958. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  127959. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  127960. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  127961. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  127964. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  127965. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  127966. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  127967. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  127968. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  127969. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  127972. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  127973. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127974. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  127975. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  127976. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  127977. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127982. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  127983. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  127984. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  127985. 13,
  127986. };
  127987. static float _vq_quantthresh__44c6_s_p2_0[] = {
  127988. -1.5, -0.5, 0.5, 1.5,
  127989. };
  127990. static long _vq_quantmap__44c6_s_p2_0[] = {
  127991. 3, 1, 0, 2, 4,
  127992. };
  127993. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  127994. _vq_quantthresh__44c6_s_p2_0,
  127995. _vq_quantmap__44c6_s_p2_0,
  127996. 5,
  127997. 5
  127998. };
  127999. static static_codebook _44c6_s_p2_0 = {
  128000. 4, 625,
  128001. _vq_lengthlist__44c6_s_p2_0,
  128002. 1, -533725184, 1611661312, 3, 0,
  128003. _vq_quantlist__44c6_s_p2_0,
  128004. NULL,
  128005. &_vq_auxt__44c6_s_p2_0,
  128006. NULL,
  128007. 0
  128008. };
  128009. static long _vq_quantlist__44c6_s_p3_0[] = {
  128010. 4,
  128011. 3,
  128012. 5,
  128013. 2,
  128014. 6,
  128015. 1,
  128016. 7,
  128017. 0,
  128018. 8,
  128019. };
  128020. static long _vq_lengthlist__44c6_s_p3_0[] = {
  128021. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128022. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  128023. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  128024. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  128025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128026. 0,
  128027. };
  128028. static float _vq_quantthresh__44c6_s_p3_0[] = {
  128029. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128030. };
  128031. static long _vq_quantmap__44c6_s_p3_0[] = {
  128032. 7, 5, 3, 1, 0, 2, 4, 6,
  128033. 8,
  128034. };
  128035. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  128036. _vq_quantthresh__44c6_s_p3_0,
  128037. _vq_quantmap__44c6_s_p3_0,
  128038. 9,
  128039. 9
  128040. };
  128041. static static_codebook _44c6_s_p3_0 = {
  128042. 2, 81,
  128043. _vq_lengthlist__44c6_s_p3_0,
  128044. 1, -531628032, 1611661312, 4, 0,
  128045. _vq_quantlist__44c6_s_p3_0,
  128046. NULL,
  128047. &_vq_auxt__44c6_s_p3_0,
  128048. NULL,
  128049. 0
  128050. };
  128051. static long _vq_quantlist__44c6_s_p4_0[] = {
  128052. 8,
  128053. 7,
  128054. 9,
  128055. 6,
  128056. 10,
  128057. 5,
  128058. 11,
  128059. 4,
  128060. 12,
  128061. 3,
  128062. 13,
  128063. 2,
  128064. 14,
  128065. 1,
  128066. 15,
  128067. 0,
  128068. 16,
  128069. };
  128070. static long _vq_lengthlist__44c6_s_p4_0[] = {
  128071. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  128072. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128073. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  128074. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  128075. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  128076. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  128077. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  128078. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128079. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  128080. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128089. 0,
  128090. };
  128091. static float _vq_quantthresh__44c6_s_p4_0[] = {
  128092. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128093. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128094. };
  128095. static long _vq_quantmap__44c6_s_p4_0[] = {
  128096. 15, 13, 11, 9, 7, 5, 3, 1,
  128097. 0, 2, 4, 6, 8, 10, 12, 14,
  128098. 16,
  128099. };
  128100. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  128101. _vq_quantthresh__44c6_s_p4_0,
  128102. _vq_quantmap__44c6_s_p4_0,
  128103. 17,
  128104. 17
  128105. };
  128106. static static_codebook _44c6_s_p4_0 = {
  128107. 2, 289,
  128108. _vq_lengthlist__44c6_s_p4_0,
  128109. 1, -529530880, 1611661312, 5, 0,
  128110. _vq_quantlist__44c6_s_p4_0,
  128111. NULL,
  128112. &_vq_auxt__44c6_s_p4_0,
  128113. NULL,
  128114. 0
  128115. };
  128116. static long _vq_quantlist__44c6_s_p5_0[] = {
  128117. 1,
  128118. 0,
  128119. 2,
  128120. };
  128121. static long _vq_lengthlist__44c6_s_p5_0[] = {
  128122. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  128123. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  128124. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  128125. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128126. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  128127. 12,
  128128. };
  128129. static float _vq_quantthresh__44c6_s_p5_0[] = {
  128130. -5.5, 5.5,
  128131. };
  128132. static long _vq_quantmap__44c6_s_p5_0[] = {
  128133. 1, 0, 2,
  128134. };
  128135. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  128136. _vq_quantthresh__44c6_s_p5_0,
  128137. _vq_quantmap__44c6_s_p5_0,
  128138. 3,
  128139. 3
  128140. };
  128141. static static_codebook _44c6_s_p5_0 = {
  128142. 4, 81,
  128143. _vq_lengthlist__44c6_s_p5_0,
  128144. 1, -529137664, 1618345984, 2, 0,
  128145. _vq_quantlist__44c6_s_p5_0,
  128146. NULL,
  128147. &_vq_auxt__44c6_s_p5_0,
  128148. NULL,
  128149. 0
  128150. };
  128151. static long _vq_quantlist__44c6_s_p5_1[] = {
  128152. 5,
  128153. 4,
  128154. 6,
  128155. 3,
  128156. 7,
  128157. 2,
  128158. 8,
  128159. 1,
  128160. 9,
  128161. 0,
  128162. 10,
  128163. };
  128164. static long _vq_lengthlist__44c6_s_p5_1[] = {
  128165. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  128166. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  128167. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  128168. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  128169. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  128170. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  128171. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  128172. 11,10,10, 7, 7, 8, 8, 8, 8,
  128173. };
  128174. static float _vq_quantthresh__44c6_s_p5_1[] = {
  128175. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128176. 3.5, 4.5,
  128177. };
  128178. static long _vq_quantmap__44c6_s_p5_1[] = {
  128179. 9, 7, 5, 3, 1, 0, 2, 4,
  128180. 6, 8, 10,
  128181. };
  128182. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  128183. _vq_quantthresh__44c6_s_p5_1,
  128184. _vq_quantmap__44c6_s_p5_1,
  128185. 11,
  128186. 11
  128187. };
  128188. static static_codebook _44c6_s_p5_1 = {
  128189. 2, 121,
  128190. _vq_lengthlist__44c6_s_p5_1,
  128191. 1, -531365888, 1611661312, 4, 0,
  128192. _vq_quantlist__44c6_s_p5_1,
  128193. NULL,
  128194. &_vq_auxt__44c6_s_p5_1,
  128195. NULL,
  128196. 0
  128197. };
  128198. static long _vq_quantlist__44c6_s_p6_0[] = {
  128199. 6,
  128200. 5,
  128201. 7,
  128202. 4,
  128203. 8,
  128204. 3,
  128205. 9,
  128206. 2,
  128207. 10,
  128208. 1,
  128209. 11,
  128210. 0,
  128211. 12,
  128212. };
  128213. static long _vq_lengthlist__44c6_s_p6_0[] = {
  128214. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  128215. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  128216. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  128217. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128218. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  128219. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128224. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128225. };
  128226. static float _vq_quantthresh__44c6_s_p6_0[] = {
  128227. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128228. 12.5, 17.5, 22.5, 27.5,
  128229. };
  128230. static long _vq_quantmap__44c6_s_p6_0[] = {
  128231. 11, 9, 7, 5, 3, 1, 0, 2,
  128232. 4, 6, 8, 10, 12,
  128233. };
  128234. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  128235. _vq_quantthresh__44c6_s_p6_0,
  128236. _vq_quantmap__44c6_s_p6_0,
  128237. 13,
  128238. 13
  128239. };
  128240. static static_codebook _44c6_s_p6_0 = {
  128241. 2, 169,
  128242. _vq_lengthlist__44c6_s_p6_0,
  128243. 1, -526516224, 1616117760, 4, 0,
  128244. _vq_quantlist__44c6_s_p6_0,
  128245. NULL,
  128246. &_vq_auxt__44c6_s_p6_0,
  128247. NULL,
  128248. 0
  128249. };
  128250. static long _vq_quantlist__44c6_s_p6_1[] = {
  128251. 2,
  128252. 1,
  128253. 3,
  128254. 0,
  128255. 4,
  128256. };
  128257. static long _vq_lengthlist__44c6_s_p6_1[] = {
  128258. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  128259. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128260. };
  128261. static float _vq_quantthresh__44c6_s_p6_1[] = {
  128262. -1.5, -0.5, 0.5, 1.5,
  128263. };
  128264. static long _vq_quantmap__44c6_s_p6_1[] = {
  128265. 3, 1, 0, 2, 4,
  128266. };
  128267. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  128268. _vq_quantthresh__44c6_s_p6_1,
  128269. _vq_quantmap__44c6_s_p6_1,
  128270. 5,
  128271. 5
  128272. };
  128273. static static_codebook _44c6_s_p6_1 = {
  128274. 2, 25,
  128275. _vq_lengthlist__44c6_s_p6_1,
  128276. 1, -533725184, 1611661312, 3, 0,
  128277. _vq_quantlist__44c6_s_p6_1,
  128278. NULL,
  128279. &_vq_auxt__44c6_s_p6_1,
  128280. NULL,
  128281. 0
  128282. };
  128283. static long _vq_quantlist__44c6_s_p7_0[] = {
  128284. 6,
  128285. 5,
  128286. 7,
  128287. 4,
  128288. 8,
  128289. 3,
  128290. 9,
  128291. 2,
  128292. 10,
  128293. 1,
  128294. 11,
  128295. 0,
  128296. 12,
  128297. };
  128298. static long _vq_lengthlist__44c6_s_p7_0[] = {
  128299. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  128300. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  128301. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  128302. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  128303. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  128304. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  128305. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  128306. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  128307. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  128308. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  128309. 20,13,13,13,13,13,13,14,14,
  128310. };
  128311. static float _vq_quantthresh__44c6_s_p7_0[] = {
  128312. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128313. 27.5, 38.5, 49.5, 60.5,
  128314. };
  128315. static long _vq_quantmap__44c6_s_p7_0[] = {
  128316. 11, 9, 7, 5, 3, 1, 0, 2,
  128317. 4, 6, 8, 10, 12,
  128318. };
  128319. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  128320. _vq_quantthresh__44c6_s_p7_0,
  128321. _vq_quantmap__44c6_s_p7_0,
  128322. 13,
  128323. 13
  128324. };
  128325. static static_codebook _44c6_s_p7_0 = {
  128326. 2, 169,
  128327. _vq_lengthlist__44c6_s_p7_0,
  128328. 1, -523206656, 1618345984, 4, 0,
  128329. _vq_quantlist__44c6_s_p7_0,
  128330. NULL,
  128331. &_vq_auxt__44c6_s_p7_0,
  128332. NULL,
  128333. 0
  128334. };
  128335. static long _vq_quantlist__44c6_s_p7_1[] = {
  128336. 5,
  128337. 4,
  128338. 6,
  128339. 3,
  128340. 7,
  128341. 2,
  128342. 8,
  128343. 1,
  128344. 9,
  128345. 0,
  128346. 10,
  128347. };
  128348. static long _vq_lengthlist__44c6_s_p7_1[] = {
  128349. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  128350. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  128351. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  128352. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  128353. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  128354. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  128355. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  128356. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  128357. };
  128358. static float _vq_quantthresh__44c6_s_p7_1[] = {
  128359. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128360. 3.5, 4.5,
  128361. };
  128362. static long _vq_quantmap__44c6_s_p7_1[] = {
  128363. 9, 7, 5, 3, 1, 0, 2, 4,
  128364. 6, 8, 10,
  128365. };
  128366. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  128367. _vq_quantthresh__44c6_s_p7_1,
  128368. _vq_quantmap__44c6_s_p7_1,
  128369. 11,
  128370. 11
  128371. };
  128372. static static_codebook _44c6_s_p7_1 = {
  128373. 2, 121,
  128374. _vq_lengthlist__44c6_s_p7_1,
  128375. 1, -531365888, 1611661312, 4, 0,
  128376. _vq_quantlist__44c6_s_p7_1,
  128377. NULL,
  128378. &_vq_auxt__44c6_s_p7_1,
  128379. NULL,
  128380. 0
  128381. };
  128382. static long _vq_quantlist__44c6_s_p8_0[] = {
  128383. 7,
  128384. 6,
  128385. 8,
  128386. 5,
  128387. 9,
  128388. 4,
  128389. 10,
  128390. 3,
  128391. 11,
  128392. 2,
  128393. 12,
  128394. 1,
  128395. 13,
  128396. 0,
  128397. 14,
  128398. };
  128399. static long _vq_lengthlist__44c6_s_p8_0[] = {
  128400. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  128401. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  128402. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  128403. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  128404. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  128405. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  128406. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  128407. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  128408. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  128409. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  128410. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  128411. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  128412. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  128413. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  128414. 14,
  128415. };
  128416. static float _vq_quantthresh__44c6_s_p8_0[] = {
  128417. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128418. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128419. };
  128420. static long _vq_quantmap__44c6_s_p8_0[] = {
  128421. 13, 11, 9, 7, 5, 3, 1, 0,
  128422. 2, 4, 6, 8, 10, 12, 14,
  128423. };
  128424. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  128425. _vq_quantthresh__44c6_s_p8_0,
  128426. _vq_quantmap__44c6_s_p8_0,
  128427. 15,
  128428. 15
  128429. };
  128430. static static_codebook _44c6_s_p8_0 = {
  128431. 2, 225,
  128432. _vq_lengthlist__44c6_s_p8_0,
  128433. 1, -520986624, 1620377600, 4, 0,
  128434. _vq_quantlist__44c6_s_p8_0,
  128435. NULL,
  128436. &_vq_auxt__44c6_s_p8_0,
  128437. NULL,
  128438. 0
  128439. };
  128440. static long _vq_quantlist__44c6_s_p8_1[] = {
  128441. 10,
  128442. 9,
  128443. 11,
  128444. 8,
  128445. 12,
  128446. 7,
  128447. 13,
  128448. 6,
  128449. 14,
  128450. 5,
  128451. 15,
  128452. 4,
  128453. 16,
  128454. 3,
  128455. 17,
  128456. 2,
  128457. 18,
  128458. 1,
  128459. 19,
  128460. 0,
  128461. 20,
  128462. };
  128463. static long _vq_lengthlist__44c6_s_p8_1[] = {
  128464. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  128465. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  128466. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128467. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128468. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128469. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  128470. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  128471. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  128472. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128473. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128474. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  128475. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  128476. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  128477. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  128478. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  128479. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  128480. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  128481. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  128482. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  128483. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  128484. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  128485. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  128486. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  128487. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128488. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  128489. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  128490. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  128491. 10,10,10,10,10,10,10,10,10,
  128492. };
  128493. static float _vq_quantthresh__44c6_s_p8_1[] = {
  128494. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128495. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128496. 6.5, 7.5, 8.5, 9.5,
  128497. };
  128498. static long _vq_quantmap__44c6_s_p8_1[] = {
  128499. 19, 17, 15, 13, 11, 9, 7, 5,
  128500. 3, 1, 0, 2, 4, 6, 8, 10,
  128501. 12, 14, 16, 18, 20,
  128502. };
  128503. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  128504. _vq_quantthresh__44c6_s_p8_1,
  128505. _vq_quantmap__44c6_s_p8_1,
  128506. 21,
  128507. 21
  128508. };
  128509. static static_codebook _44c6_s_p8_1 = {
  128510. 2, 441,
  128511. _vq_lengthlist__44c6_s_p8_1,
  128512. 1, -529268736, 1611661312, 5, 0,
  128513. _vq_quantlist__44c6_s_p8_1,
  128514. NULL,
  128515. &_vq_auxt__44c6_s_p8_1,
  128516. NULL,
  128517. 0
  128518. };
  128519. static long _vq_quantlist__44c6_s_p9_0[] = {
  128520. 6,
  128521. 5,
  128522. 7,
  128523. 4,
  128524. 8,
  128525. 3,
  128526. 9,
  128527. 2,
  128528. 10,
  128529. 1,
  128530. 11,
  128531. 0,
  128532. 12,
  128533. };
  128534. static long _vq_lengthlist__44c6_s_p9_0[] = {
  128535. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  128536. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  128537. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128538. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  128539. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128540. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128541. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128542. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128543. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128544. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128545. 10,10,10,10,10,10,10,10,10,
  128546. };
  128547. static float _vq_quantthresh__44c6_s_p9_0[] = {
  128548. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  128549. 1592.5, 2229.5, 2866.5, 3503.5,
  128550. };
  128551. static long _vq_quantmap__44c6_s_p9_0[] = {
  128552. 11, 9, 7, 5, 3, 1, 0, 2,
  128553. 4, 6, 8, 10, 12,
  128554. };
  128555. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  128556. _vq_quantthresh__44c6_s_p9_0,
  128557. _vq_quantmap__44c6_s_p9_0,
  128558. 13,
  128559. 13
  128560. };
  128561. static static_codebook _44c6_s_p9_0 = {
  128562. 2, 169,
  128563. _vq_lengthlist__44c6_s_p9_0,
  128564. 1, -511845376, 1630791680, 4, 0,
  128565. _vq_quantlist__44c6_s_p9_0,
  128566. NULL,
  128567. &_vq_auxt__44c6_s_p9_0,
  128568. NULL,
  128569. 0
  128570. };
  128571. static long _vq_quantlist__44c6_s_p9_1[] = {
  128572. 6,
  128573. 5,
  128574. 7,
  128575. 4,
  128576. 8,
  128577. 3,
  128578. 9,
  128579. 2,
  128580. 10,
  128581. 1,
  128582. 11,
  128583. 0,
  128584. 12,
  128585. };
  128586. static long _vq_lengthlist__44c6_s_p9_1[] = {
  128587. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  128588. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  128589. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  128590. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  128591. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  128592. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  128593. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  128594. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  128595. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  128596. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  128597. 15,12,10,11,11,13,11,12,13,
  128598. };
  128599. static float _vq_quantthresh__44c6_s_p9_1[] = {
  128600. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  128601. 122.5, 171.5, 220.5, 269.5,
  128602. };
  128603. static long _vq_quantmap__44c6_s_p9_1[] = {
  128604. 11, 9, 7, 5, 3, 1, 0, 2,
  128605. 4, 6, 8, 10, 12,
  128606. };
  128607. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  128608. _vq_quantthresh__44c6_s_p9_1,
  128609. _vq_quantmap__44c6_s_p9_1,
  128610. 13,
  128611. 13
  128612. };
  128613. static static_codebook _44c6_s_p9_1 = {
  128614. 2, 169,
  128615. _vq_lengthlist__44c6_s_p9_1,
  128616. 1, -518889472, 1622704128, 4, 0,
  128617. _vq_quantlist__44c6_s_p9_1,
  128618. NULL,
  128619. &_vq_auxt__44c6_s_p9_1,
  128620. NULL,
  128621. 0
  128622. };
  128623. static long _vq_quantlist__44c6_s_p9_2[] = {
  128624. 24,
  128625. 23,
  128626. 25,
  128627. 22,
  128628. 26,
  128629. 21,
  128630. 27,
  128631. 20,
  128632. 28,
  128633. 19,
  128634. 29,
  128635. 18,
  128636. 30,
  128637. 17,
  128638. 31,
  128639. 16,
  128640. 32,
  128641. 15,
  128642. 33,
  128643. 14,
  128644. 34,
  128645. 13,
  128646. 35,
  128647. 12,
  128648. 36,
  128649. 11,
  128650. 37,
  128651. 10,
  128652. 38,
  128653. 9,
  128654. 39,
  128655. 8,
  128656. 40,
  128657. 7,
  128658. 41,
  128659. 6,
  128660. 42,
  128661. 5,
  128662. 43,
  128663. 4,
  128664. 44,
  128665. 3,
  128666. 45,
  128667. 2,
  128668. 46,
  128669. 1,
  128670. 47,
  128671. 0,
  128672. 48,
  128673. };
  128674. static long _vq_lengthlist__44c6_s_p9_2[] = {
  128675. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  128676. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128677. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128678. 7,
  128679. };
  128680. static float _vq_quantthresh__44c6_s_p9_2[] = {
  128681. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128682. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128683. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128684. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128685. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128686. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128687. };
  128688. static long _vq_quantmap__44c6_s_p9_2[] = {
  128689. 47, 45, 43, 41, 39, 37, 35, 33,
  128690. 31, 29, 27, 25, 23, 21, 19, 17,
  128691. 15, 13, 11, 9, 7, 5, 3, 1,
  128692. 0, 2, 4, 6, 8, 10, 12, 14,
  128693. 16, 18, 20, 22, 24, 26, 28, 30,
  128694. 32, 34, 36, 38, 40, 42, 44, 46,
  128695. 48,
  128696. };
  128697. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  128698. _vq_quantthresh__44c6_s_p9_2,
  128699. _vq_quantmap__44c6_s_p9_2,
  128700. 49,
  128701. 49
  128702. };
  128703. static static_codebook _44c6_s_p9_2 = {
  128704. 1, 49,
  128705. _vq_lengthlist__44c6_s_p9_2,
  128706. 1, -526909440, 1611661312, 6, 0,
  128707. _vq_quantlist__44c6_s_p9_2,
  128708. NULL,
  128709. &_vq_auxt__44c6_s_p9_2,
  128710. NULL,
  128711. 0
  128712. };
  128713. static long _huff_lengthlist__44c6_s_short[] = {
  128714. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  128715. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  128716. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  128717. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  128718. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  128719. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  128720. 9,10,17,18,
  128721. };
  128722. static static_codebook _huff_book__44c6_s_short = {
  128723. 2, 100,
  128724. _huff_lengthlist__44c6_s_short,
  128725. 0, 0, 0, 0, 0,
  128726. NULL,
  128727. NULL,
  128728. NULL,
  128729. NULL,
  128730. 0
  128731. };
  128732. static long _huff_lengthlist__44c7_s_long[] = {
  128733. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  128734. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  128735. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  128736. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  128737. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  128738. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  128739. 11,10,10,12,
  128740. };
  128741. static static_codebook _huff_book__44c7_s_long = {
  128742. 2, 100,
  128743. _huff_lengthlist__44c7_s_long,
  128744. 0, 0, 0, 0, 0,
  128745. NULL,
  128746. NULL,
  128747. NULL,
  128748. NULL,
  128749. 0
  128750. };
  128751. static long _vq_quantlist__44c7_s_p1_0[] = {
  128752. 1,
  128753. 0,
  128754. 2,
  128755. };
  128756. static long _vq_lengthlist__44c7_s_p1_0[] = {
  128757. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  128758. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  128760. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128761. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  128762. 8,
  128763. };
  128764. static float _vq_quantthresh__44c7_s_p1_0[] = {
  128765. -0.5, 0.5,
  128766. };
  128767. static long _vq_quantmap__44c7_s_p1_0[] = {
  128768. 1, 0, 2,
  128769. };
  128770. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  128771. _vq_quantthresh__44c7_s_p1_0,
  128772. _vq_quantmap__44c7_s_p1_0,
  128773. 3,
  128774. 3
  128775. };
  128776. static static_codebook _44c7_s_p1_0 = {
  128777. 4, 81,
  128778. _vq_lengthlist__44c7_s_p1_0,
  128779. 1, -535822336, 1611661312, 2, 0,
  128780. _vq_quantlist__44c7_s_p1_0,
  128781. NULL,
  128782. &_vq_auxt__44c7_s_p1_0,
  128783. NULL,
  128784. 0
  128785. };
  128786. static long _vq_quantlist__44c7_s_p2_0[] = {
  128787. 2,
  128788. 1,
  128789. 3,
  128790. 0,
  128791. 4,
  128792. };
  128793. static long _vq_lengthlist__44c7_s_p2_0[] = {
  128794. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128795. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  128796. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  128797. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  128798. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  128799. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  128800. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  128801. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  128804. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  128805. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  128806. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  128807. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  128808. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  128809. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  128812. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  128813. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  128814. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  128815. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  128816. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  128817. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  128820. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  128821. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  128822. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  128823. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  128824. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  128825. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128830. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  128831. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  128832. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  128833. 13,
  128834. };
  128835. static float _vq_quantthresh__44c7_s_p2_0[] = {
  128836. -1.5, -0.5, 0.5, 1.5,
  128837. };
  128838. static long _vq_quantmap__44c7_s_p2_0[] = {
  128839. 3, 1, 0, 2, 4,
  128840. };
  128841. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  128842. _vq_quantthresh__44c7_s_p2_0,
  128843. _vq_quantmap__44c7_s_p2_0,
  128844. 5,
  128845. 5
  128846. };
  128847. static static_codebook _44c7_s_p2_0 = {
  128848. 4, 625,
  128849. _vq_lengthlist__44c7_s_p2_0,
  128850. 1, -533725184, 1611661312, 3, 0,
  128851. _vq_quantlist__44c7_s_p2_0,
  128852. NULL,
  128853. &_vq_auxt__44c7_s_p2_0,
  128854. NULL,
  128855. 0
  128856. };
  128857. static long _vq_quantlist__44c7_s_p3_0[] = {
  128858. 4,
  128859. 3,
  128860. 5,
  128861. 2,
  128862. 6,
  128863. 1,
  128864. 7,
  128865. 0,
  128866. 8,
  128867. };
  128868. static long _vq_lengthlist__44c7_s_p3_0[] = {
  128869. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  128870. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  128871. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  128872. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0,
  128875. };
  128876. static float _vq_quantthresh__44c7_s_p3_0[] = {
  128877. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128878. };
  128879. static long _vq_quantmap__44c7_s_p3_0[] = {
  128880. 7, 5, 3, 1, 0, 2, 4, 6,
  128881. 8,
  128882. };
  128883. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  128884. _vq_quantthresh__44c7_s_p3_0,
  128885. _vq_quantmap__44c7_s_p3_0,
  128886. 9,
  128887. 9
  128888. };
  128889. static static_codebook _44c7_s_p3_0 = {
  128890. 2, 81,
  128891. _vq_lengthlist__44c7_s_p3_0,
  128892. 1, -531628032, 1611661312, 4, 0,
  128893. _vq_quantlist__44c7_s_p3_0,
  128894. NULL,
  128895. &_vq_auxt__44c7_s_p3_0,
  128896. NULL,
  128897. 0
  128898. };
  128899. static long _vq_quantlist__44c7_s_p4_0[] = {
  128900. 8,
  128901. 7,
  128902. 9,
  128903. 6,
  128904. 10,
  128905. 5,
  128906. 11,
  128907. 4,
  128908. 12,
  128909. 3,
  128910. 13,
  128911. 2,
  128912. 14,
  128913. 1,
  128914. 15,
  128915. 0,
  128916. 16,
  128917. };
  128918. static long _vq_lengthlist__44c7_s_p4_0[] = {
  128919. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  128920. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  128921. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128922. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  128923. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  128924. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  128925. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  128926. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128927. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128928. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0,
  128938. };
  128939. static float _vq_quantthresh__44c7_s_p4_0[] = {
  128940. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128941. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128942. };
  128943. static long _vq_quantmap__44c7_s_p4_0[] = {
  128944. 15, 13, 11, 9, 7, 5, 3, 1,
  128945. 0, 2, 4, 6, 8, 10, 12, 14,
  128946. 16,
  128947. };
  128948. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  128949. _vq_quantthresh__44c7_s_p4_0,
  128950. _vq_quantmap__44c7_s_p4_0,
  128951. 17,
  128952. 17
  128953. };
  128954. static static_codebook _44c7_s_p4_0 = {
  128955. 2, 289,
  128956. _vq_lengthlist__44c7_s_p4_0,
  128957. 1, -529530880, 1611661312, 5, 0,
  128958. _vq_quantlist__44c7_s_p4_0,
  128959. NULL,
  128960. &_vq_auxt__44c7_s_p4_0,
  128961. NULL,
  128962. 0
  128963. };
  128964. static long _vq_quantlist__44c7_s_p5_0[] = {
  128965. 1,
  128966. 0,
  128967. 2,
  128968. };
  128969. static long _vq_lengthlist__44c7_s_p5_0[] = {
  128970. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  128971. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  128972. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  128973. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  128974. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  128975. 12,
  128976. };
  128977. static float _vq_quantthresh__44c7_s_p5_0[] = {
  128978. -5.5, 5.5,
  128979. };
  128980. static long _vq_quantmap__44c7_s_p5_0[] = {
  128981. 1, 0, 2,
  128982. };
  128983. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  128984. _vq_quantthresh__44c7_s_p5_0,
  128985. _vq_quantmap__44c7_s_p5_0,
  128986. 3,
  128987. 3
  128988. };
  128989. static static_codebook _44c7_s_p5_0 = {
  128990. 4, 81,
  128991. _vq_lengthlist__44c7_s_p5_0,
  128992. 1, -529137664, 1618345984, 2, 0,
  128993. _vq_quantlist__44c7_s_p5_0,
  128994. NULL,
  128995. &_vq_auxt__44c7_s_p5_0,
  128996. NULL,
  128997. 0
  128998. };
  128999. static long _vq_quantlist__44c7_s_p5_1[] = {
  129000. 5,
  129001. 4,
  129002. 6,
  129003. 3,
  129004. 7,
  129005. 2,
  129006. 8,
  129007. 1,
  129008. 9,
  129009. 0,
  129010. 10,
  129011. };
  129012. static long _vq_lengthlist__44c7_s_p5_1[] = {
  129013. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  129014. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  129015. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  129016. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  129017. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  129018. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  129019. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  129020. 11,11,11, 7, 7, 8, 8, 8, 8,
  129021. };
  129022. static float _vq_quantthresh__44c7_s_p5_1[] = {
  129023. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129024. 3.5, 4.5,
  129025. };
  129026. static long _vq_quantmap__44c7_s_p5_1[] = {
  129027. 9, 7, 5, 3, 1, 0, 2, 4,
  129028. 6, 8, 10,
  129029. };
  129030. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  129031. _vq_quantthresh__44c7_s_p5_1,
  129032. _vq_quantmap__44c7_s_p5_1,
  129033. 11,
  129034. 11
  129035. };
  129036. static static_codebook _44c7_s_p5_1 = {
  129037. 2, 121,
  129038. _vq_lengthlist__44c7_s_p5_1,
  129039. 1, -531365888, 1611661312, 4, 0,
  129040. _vq_quantlist__44c7_s_p5_1,
  129041. NULL,
  129042. &_vq_auxt__44c7_s_p5_1,
  129043. NULL,
  129044. 0
  129045. };
  129046. static long _vq_quantlist__44c7_s_p6_0[] = {
  129047. 6,
  129048. 5,
  129049. 7,
  129050. 4,
  129051. 8,
  129052. 3,
  129053. 9,
  129054. 2,
  129055. 10,
  129056. 1,
  129057. 11,
  129058. 0,
  129059. 12,
  129060. };
  129061. static long _vq_lengthlist__44c7_s_p6_0[] = {
  129062. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  129063. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  129064. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  129065. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  129066. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  129067. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  129068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. };
  129074. static float _vq_quantthresh__44c7_s_p6_0[] = {
  129075. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129076. 12.5, 17.5, 22.5, 27.5,
  129077. };
  129078. static long _vq_quantmap__44c7_s_p6_0[] = {
  129079. 11, 9, 7, 5, 3, 1, 0, 2,
  129080. 4, 6, 8, 10, 12,
  129081. };
  129082. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  129083. _vq_quantthresh__44c7_s_p6_0,
  129084. _vq_quantmap__44c7_s_p6_0,
  129085. 13,
  129086. 13
  129087. };
  129088. static static_codebook _44c7_s_p6_0 = {
  129089. 2, 169,
  129090. _vq_lengthlist__44c7_s_p6_0,
  129091. 1, -526516224, 1616117760, 4, 0,
  129092. _vq_quantlist__44c7_s_p6_0,
  129093. NULL,
  129094. &_vq_auxt__44c7_s_p6_0,
  129095. NULL,
  129096. 0
  129097. };
  129098. static long _vq_quantlist__44c7_s_p6_1[] = {
  129099. 2,
  129100. 1,
  129101. 3,
  129102. 0,
  129103. 4,
  129104. };
  129105. static long _vq_lengthlist__44c7_s_p6_1[] = {
  129106. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129107. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129108. };
  129109. static float _vq_quantthresh__44c7_s_p6_1[] = {
  129110. -1.5, -0.5, 0.5, 1.5,
  129111. };
  129112. static long _vq_quantmap__44c7_s_p6_1[] = {
  129113. 3, 1, 0, 2, 4,
  129114. };
  129115. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  129116. _vq_quantthresh__44c7_s_p6_1,
  129117. _vq_quantmap__44c7_s_p6_1,
  129118. 5,
  129119. 5
  129120. };
  129121. static static_codebook _44c7_s_p6_1 = {
  129122. 2, 25,
  129123. _vq_lengthlist__44c7_s_p6_1,
  129124. 1, -533725184, 1611661312, 3, 0,
  129125. _vq_quantlist__44c7_s_p6_1,
  129126. NULL,
  129127. &_vq_auxt__44c7_s_p6_1,
  129128. NULL,
  129129. 0
  129130. };
  129131. static long _vq_quantlist__44c7_s_p7_0[] = {
  129132. 6,
  129133. 5,
  129134. 7,
  129135. 4,
  129136. 8,
  129137. 3,
  129138. 9,
  129139. 2,
  129140. 10,
  129141. 1,
  129142. 11,
  129143. 0,
  129144. 12,
  129145. };
  129146. static long _vq_lengthlist__44c7_s_p7_0[] = {
  129147. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  129148. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129149. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  129150. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  129151. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  129152. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  129153. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  129154. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  129155. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  129156. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  129157. 19,13,13,13,13,14,14,15,15,
  129158. };
  129159. static float _vq_quantthresh__44c7_s_p7_0[] = {
  129160. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  129161. 27.5, 38.5, 49.5, 60.5,
  129162. };
  129163. static long _vq_quantmap__44c7_s_p7_0[] = {
  129164. 11, 9, 7, 5, 3, 1, 0, 2,
  129165. 4, 6, 8, 10, 12,
  129166. };
  129167. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  129168. _vq_quantthresh__44c7_s_p7_0,
  129169. _vq_quantmap__44c7_s_p7_0,
  129170. 13,
  129171. 13
  129172. };
  129173. static static_codebook _44c7_s_p7_0 = {
  129174. 2, 169,
  129175. _vq_lengthlist__44c7_s_p7_0,
  129176. 1, -523206656, 1618345984, 4, 0,
  129177. _vq_quantlist__44c7_s_p7_0,
  129178. NULL,
  129179. &_vq_auxt__44c7_s_p7_0,
  129180. NULL,
  129181. 0
  129182. };
  129183. static long _vq_quantlist__44c7_s_p7_1[] = {
  129184. 5,
  129185. 4,
  129186. 6,
  129187. 3,
  129188. 7,
  129189. 2,
  129190. 8,
  129191. 1,
  129192. 9,
  129193. 0,
  129194. 10,
  129195. };
  129196. static long _vq_lengthlist__44c7_s_p7_1[] = {
  129197. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  129198. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  129199. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  129200. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129201. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  129202. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  129203. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  129204. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  129205. };
  129206. static float _vq_quantthresh__44c7_s_p7_1[] = {
  129207. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129208. 3.5, 4.5,
  129209. };
  129210. static long _vq_quantmap__44c7_s_p7_1[] = {
  129211. 9, 7, 5, 3, 1, 0, 2, 4,
  129212. 6, 8, 10,
  129213. };
  129214. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  129215. _vq_quantthresh__44c7_s_p7_1,
  129216. _vq_quantmap__44c7_s_p7_1,
  129217. 11,
  129218. 11
  129219. };
  129220. static static_codebook _44c7_s_p7_1 = {
  129221. 2, 121,
  129222. _vq_lengthlist__44c7_s_p7_1,
  129223. 1, -531365888, 1611661312, 4, 0,
  129224. _vq_quantlist__44c7_s_p7_1,
  129225. NULL,
  129226. &_vq_auxt__44c7_s_p7_1,
  129227. NULL,
  129228. 0
  129229. };
  129230. static long _vq_quantlist__44c7_s_p8_0[] = {
  129231. 7,
  129232. 6,
  129233. 8,
  129234. 5,
  129235. 9,
  129236. 4,
  129237. 10,
  129238. 3,
  129239. 11,
  129240. 2,
  129241. 12,
  129242. 1,
  129243. 13,
  129244. 0,
  129245. 14,
  129246. };
  129247. static long _vq_lengthlist__44c7_s_p8_0[] = {
  129248. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  129249. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  129250. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  129251. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  129252. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  129253. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  129254. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  129255. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  129256. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  129257. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  129258. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  129259. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  129260. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  129261. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  129262. 14,
  129263. };
  129264. static float _vq_quantthresh__44c7_s_p8_0[] = {
  129265. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  129266. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  129267. };
  129268. static long _vq_quantmap__44c7_s_p8_0[] = {
  129269. 13, 11, 9, 7, 5, 3, 1, 0,
  129270. 2, 4, 6, 8, 10, 12, 14,
  129271. };
  129272. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  129273. _vq_quantthresh__44c7_s_p8_0,
  129274. _vq_quantmap__44c7_s_p8_0,
  129275. 15,
  129276. 15
  129277. };
  129278. static static_codebook _44c7_s_p8_0 = {
  129279. 2, 225,
  129280. _vq_lengthlist__44c7_s_p8_0,
  129281. 1, -520986624, 1620377600, 4, 0,
  129282. _vq_quantlist__44c7_s_p8_0,
  129283. NULL,
  129284. &_vq_auxt__44c7_s_p8_0,
  129285. NULL,
  129286. 0
  129287. };
  129288. static long _vq_quantlist__44c7_s_p8_1[] = {
  129289. 10,
  129290. 9,
  129291. 11,
  129292. 8,
  129293. 12,
  129294. 7,
  129295. 13,
  129296. 6,
  129297. 14,
  129298. 5,
  129299. 15,
  129300. 4,
  129301. 16,
  129302. 3,
  129303. 17,
  129304. 2,
  129305. 18,
  129306. 1,
  129307. 19,
  129308. 0,
  129309. 20,
  129310. };
  129311. static long _vq_lengthlist__44c7_s_p8_1[] = {
  129312. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  129313. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  129314. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  129315. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  129316. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129317. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  129318. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  129319. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  129320. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129321. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  129322. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  129323. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  129324. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  129325. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  129326. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  129327. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  129328. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  129329. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  129330. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  129331. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  129332. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  129333. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  129334. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  129335. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  129336. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  129337. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  129338. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  129339. 10,10,10,10,10,10,10,10,10,
  129340. };
  129341. static float _vq_quantthresh__44c7_s_p8_1[] = {
  129342. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  129343. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  129344. 6.5, 7.5, 8.5, 9.5,
  129345. };
  129346. static long _vq_quantmap__44c7_s_p8_1[] = {
  129347. 19, 17, 15, 13, 11, 9, 7, 5,
  129348. 3, 1, 0, 2, 4, 6, 8, 10,
  129349. 12, 14, 16, 18, 20,
  129350. };
  129351. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  129352. _vq_quantthresh__44c7_s_p8_1,
  129353. _vq_quantmap__44c7_s_p8_1,
  129354. 21,
  129355. 21
  129356. };
  129357. static static_codebook _44c7_s_p8_1 = {
  129358. 2, 441,
  129359. _vq_lengthlist__44c7_s_p8_1,
  129360. 1, -529268736, 1611661312, 5, 0,
  129361. _vq_quantlist__44c7_s_p8_1,
  129362. NULL,
  129363. &_vq_auxt__44c7_s_p8_1,
  129364. NULL,
  129365. 0
  129366. };
  129367. static long _vq_quantlist__44c7_s_p9_0[] = {
  129368. 6,
  129369. 5,
  129370. 7,
  129371. 4,
  129372. 8,
  129373. 3,
  129374. 9,
  129375. 2,
  129376. 10,
  129377. 1,
  129378. 11,
  129379. 0,
  129380. 12,
  129381. };
  129382. static long _vq_lengthlist__44c7_s_p9_0[] = {
  129383. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  129384. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  129385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129393. 11,11,11,11,11,11,11,11,11,
  129394. };
  129395. static float _vq_quantthresh__44c7_s_p9_0[] = {
  129396. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  129397. 1592.5, 2229.5, 2866.5, 3503.5,
  129398. };
  129399. static long _vq_quantmap__44c7_s_p9_0[] = {
  129400. 11, 9, 7, 5, 3, 1, 0, 2,
  129401. 4, 6, 8, 10, 12,
  129402. };
  129403. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  129404. _vq_quantthresh__44c7_s_p9_0,
  129405. _vq_quantmap__44c7_s_p9_0,
  129406. 13,
  129407. 13
  129408. };
  129409. static static_codebook _44c7_s_p9_0 = {
  129410. 2, 169,
  129411. _vq_lengthlist__44c7_s_p9_0,
  129412. 1, -511845376, 1630791680, 4, 0,
  129413. _vq_quantlist__44c7_s_p9_0,
  129414. NULL,
  129415. &_vq_auxt__44c7_s_p9_0,
  129416. NULL,
  129417. 0
  129418. };
  129419. static long _vq_quantlist__44c7_s_p9_1[] = {
  129420. 6,
  129421. 5,
  129422. 7,
  129423. 4,
  129424. 8,
  129425. 3,
  129426. 9,
  129427. 2,
  129428. 10,
  129429. 1,
  129430. 11,
  129431. 0,
  129432. 12,
  129433. };
  129434. static long _vq_lengthlist__44c7_s_p9_1[] = {
  129435. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  129436. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  129437. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  129438. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  129439. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  129440. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  129441. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  129442. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  129443. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  129444. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  129445. 15,11,11,10,10,12,12,12,12,
  129446. };
  129447. static float _vq_quantthresh__44c7_s_p9_1[] = {
  129448. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  129449. 122.5, 171.5, 220.5, 269.5,
  129450. };
  129451. static long _vq_quantmap__44c7_s_p9_1[] = {
  129452. 11, 9, 7, 5, 3, 1, 0, 2,
  129453. 4, 6, 8, 10, 12,
  129454. };
  129455. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  129456. _vq_quantthresh__44c7_s_p9_1,
  129457. _vq_quantmap__44c7_s_p9_1,
  129458. 13,
  129459. 13
  129460. };
  129461. static static_codebook _44c7_s_p9_1 = {
  129462. 2, 169,
  129463. _vq_lengthlist__44c7_s_p9_1,
  129464. 1, -518889472, 1622704128, 4, 0,
  129465. _vq_quantlist__44c7_s_p9_1,
  129466. NULL,
  129467. &_vq_auxt__44c7_s_p9_1,
  129468. NULL,
  129469. 0
  129470. };
  129471. static long _vq_quantlist__44c7_s_p9_2[] = {
  129472. 24,
  129473. 23,
  129474. 25,
  129475. 22,
  129476. 26,
  129477. 21,
  129478. 27,
  129479. 20,
  129480. 28,
  129481. 19,
  129482. 29,
  129483. 18,
  129484. 30,
  129485. 17,
  129486. 31,
  129487. 16,
  129488. 32,
  129489. 15,
  129490. 33,
  129491. 14,
  129492. 34,
  129493. 13,
  129494. 35,
  129495. 12,
  129496. 36,
  129497. 11,
  129498. 37,
  129499. 10,
  129500. 38,
  129501. 9,
  129502. 39,
  129503. 8,
  129504. 40,
  129505. 7,
  129506. 41,
  129507. 6,
  129508. 42,
  129509. 5,
  129510. 43,
  129511. 4,
  129512. 44,
  129513. 3,
  129514. 45,
  129515. 2,
  129516. 46,
  129517. 1,
  129518. 47,
  129519. 0,
  129520. 48,
  129521. };
  129522. static long _vq_lengthlist__44c7_s_p9_2[] = {
  129523. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  129524. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129525. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129526. 7,
  129527. };
  129528. static float _vq_quantthresh__44c7_s_p9_2[] = {
  129529. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129530. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129531. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129532. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129533. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129534. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129535. };
  129536. static long _vq_quantmap__44c7_s_p9_2[] = {
  129537. 47, 45, 43, 41, 39, 37, 35, 33,
  129538. 31, 29, 27, 25, 23, 21, 19, 17,
  129539. 15, 13, 11, 9, 7, 5, 3, 1,
  129540. 0, 2, 4, 6, 8, 10, 12, 14,
  129541. 16, 18, 20, 22, 24, 26, 28, 30,
  129542. 32, 34, 36, 38, 40, 42, 44, 46,
  129543. 48,
  129544. };
  129545. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  129546. _vq_quantthresh__44c7_s_p9_2,
  129547. _vq_quantmap__44c7_s_p9_2,
  129548. 49,
  129549. 49
  129550. };
  129551. static static_codebook _44c7_s_p9_2 = {
  129552. 1, 49,
  129553. _vq_lengthlist__44c7_s_p9_2,
  129554. 1, -526909440, 1611661312, 6, 0,
  129555. _vq_quantlist__44c7_s_p9_2,
  129556. NULL,
  129557. &_vq_auxt__44c7_s_p9_2,
  129558. NULL,
  129559. 0
  129560. };
  129561. static long _huff_lengthlist__44c7_s_short[] = {
  129562. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  129563. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  129564. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  129565. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  129566. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  129567. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  129568. 10, 9,11,14,
  129569. };
  129570. static static_codebook _huff_book__44c7_s_short = {
  129571. 2, 100,
  129572. _huff_lengthlist__44c7_s_short,
  129573. 0, 0, 0, 0, 0,
  129574. NULL,
  129575. NULL,
  129576. NULL,
  129577. NULL,
  129578. 0
  129579. };
  129580. static long _huff_lengthlist__44c8_s_long[] = {
  129581. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  129582. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  129583. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  129584. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  129585. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  129586. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  129587. 11, 9, 9,10,
  129588. };
  129589. static static_codebook _huff_book__44c8_s_long = {
  129590. 2, 100,
  129591. _huff_lengthlist__44c8_s_long,
  129592. 0, 0, 0, 0, 0,
  129593. NULL,
  129594. NULL,
  129595. NULL,
  129596. NULL,
  129597. 0
  129598. };
  129599. static long _vq_quantlist__44c8_s_p1_0[] = {
  129600. 1,
  129601. 0,
  129602. 2,
  129603. };
  129604. static long _vq_lengthlist__44c8_s_p1_0[] = {
  129605. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  129606. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  129607. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  129608. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  129609. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  129610. 8,
  129611. };
  129612. static float _vq_quantthresh__44c8_s_p1_0[] = {
  129613. -0.5, 0.5,
  129614. };
  129615. static long _vq_quantmap__44c8_s_p1_0[] = {
  129616. 1, 0, 2,
  129617. };
  129618. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  129619. _vq_quantthresh__44c8_s_p1_0,
  129620. _vq_quantmap__44c8_s_p1_0,
  129621. 3,
  129622. 3
  129623. };
  129624. static static_codebook _44c8_s_p1_0 = {
  129625. 4, 81,
  129626. _vq_lengthlist__44c8_s_p1_0,
  129627. 1, -535822336, 1611661312, 2, 0,
  129628. _vq_quantlist__44c8_s_p1_0,
  129629. NULL,
  129630. &_vq_auxt__44c8_s_p1_0,
  129631. NULL,
  129632. 0
  129633. };
  129634. static long _vq_quantlist__44c8_s_p2_0[] = {
  129635. 2,
  129636. 1,
  129637. 3,
  129638. 0,
  129639. 4,
  129640. };
  129641. static long _vq_lengthlist__44c8_s_p2_0[] = {
  129642. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  129643. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  129644. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  129645. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  129646. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  129647. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  129648. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  129649. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  129652. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  129653. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  129654. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  129655. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  129656. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  129657. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  129658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129659. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  129660. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  129661. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  129662. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  129663. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  129664. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  129665. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129667. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  129668. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  129669. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  129670. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  129671. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  129672. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  129673. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  129678. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  129679. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  129680. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  129681. 13,
  129682. };
  129683. static float _vq_quantthresh__44c8_s_p2_0[] = {
  129684. -1.5, -0.5, 0.5, 1.5,
  129685. };
  129686. static long _vq_quantmap__44c8_s_p2_0[] = {
  129687. 3, 1, 0, 2, 4,
  129688. };
  129689. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  129690. _vq_quantthresh__44c8_s_p2_0,
  129691. _vq_quantmap__44c8_s_p2_0,
  129692. 5,
  129693. 5
  129694. };
  129695. static static_codebook _44c8_s_p2_0 = {
  129696. 4, 625,
  129697. _vq_lengthlist__44c8_s_p2_0,
  129698. 1, -533725184, 1611661312, 3, 0,
  129699. _vq_quantlist__44c8_s_p2_0,
  129700. NULL,
  129701. &_vq_auxt__44c8_s_p2_0,
  129702. NULL,
  129703. 0
  129704. };
  129705. static long _vq_quantlist__44c8_s_p3_0[] = {
  129706. 4,
  129707. 3,
  129708. 5,
  129709. 2,
  129710. 6,
  129711. 1,
  129712. 7,
  129713. 0,
  129714. 8,
  129715. };
  129716. static long _vq_lengthlist__44c8_s_p3_0[] = {
  129717. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  129718. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  129719. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  129720. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0,
  129723. };
  129724. static float _vq_quantthresh__44c8_s_p3_0[] = {
  129725. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129726. };
  129727. static long _vq_quantmap__44c8_s_p3_0[] = {
  129728. 7, 5, 3, 1, 0, 2, 4, 6,
  129729. 8,
  129730. };
  129731. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  129732. _vq_quantthresh__44c8_s_p3_0,
  129733. _vq_quantmap__44c8_s_p3_0,
  129734. 9,
  129735. 9
  129736. };
  129737. static static_codebook _44c8_s_p3_0 = {
  129738. 2, 81,
  129739. _vq_lengthlist__44c8_s_p3_0,
  129740. 1, -531628032, 1611661312, 4, 0,
  129741. _vq_quantlist__44c8_s_p3_0,
  129742. NULL,
  129743. &_vq_auxt__44c8_s_p3_0,
  129744. NULL,
  129745. 0
  129746. };
  129747. static long _vq_quantlist__44c8_s_p4_0[] = {
  129748. 8,
  129749. 7,
  129750. 9,
  129751. 6,
  129752. 10,
  129753. 5,
  129754. 11,
  129755. 4,
  129756. 12,
  129757. 3,
  129758. 13,
  129759. 2,
  129760. 14,
  129761. 1,
  129762. 15,
  129763. 0,
  129764. 16,
  129765. };
  129766. static long _vq_lengthlist__44c8_s_p4_0[] = {
  129767. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129768. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  129769. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  129770. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  129771. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  129772. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  129773. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  129774. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  129775. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  129776. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0,
  129786. };
  129787. static float _vq_quantthresh__44c8_s_p4_0[] = {
  129788. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129789. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129790. };
  129791. static long _vq_quantmap__44c8_s_p4_0[] = {
  129792. 15, 13, 11, 9, 7, 5, 3, 1,
  129793. 0, 2, 4, 6, 8, 10, 12, 14,
  129794. 16,
  129795. };
  129796. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  129797. _vq_quantthresh__44c8_s_p4_0,
  129798. _vq_quantmap__44c8_s_p4_0,
  129799. 17,
  129800. 17
  129801. };
  129802. static static_codebook _44c8_s_p4_0 = {
  129803. 2, 289,
  129804. _vq_lengthlist__44c8_s_p4_0,
  129805. 1, -529530880, 1611661312, 5, 0,
  129806. _vq_quantlist__44c8_s_p4_0,
  129807. NULL,
  129808. &_vq_auxt__44c8_s_p4_0,
  129809. NULL,
  129810. 0
  129811. };
  129812. static long _vq_quantlist__44c8_s_p5_0[] = {
  129813. 1,
  129814. 0,
  129815. 2,
  129816. };
  129817. static long _vq_lengthlist__44c8_s_p5_0[] = {
  129818. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  129819. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  129820. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  129821. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  129822. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  129823. 12,
  129824. };
  129825. static float _vq_quantthresh__44c8_s_p5_0[] = {
  129826. -5.5, 5.5,
  129827. };
  129828. static long _vq_quantmap__44c8_s_p5_0[] = {
  129829. 1, 0, 2,
  129830. };
  129831. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  129832. _vq_quantthresh__44c8_s_p5_0,
  129833. _vq_quantmap__44c8_s_p5_0,
  129834. 3,
  129835. 3
  129836. };
  129837. static static_codebook _44c8_s_p5_0 = {
  129838. 4, 81,
  129839. _vq_lengthlist__44c8_s_p5_0,
  129840. 1, -529137664, 1618345984, 2, 0,
  129841. _vq_quantlist__44c8_s_p5_0,
  129842. NULL,
  129843. &_vq_auxt__44c8_s_p5_0,
  129844. NULL,
  129845. 0
  129846. };
  129847. static long _vq_quantlist__44c8_s_p5_1[] = {
  129848. 5,
  129849. 4,
  129850. 6,
  129851. 3,
  129852. 7,
  129853. 2,
  129854. 8,
  129855. 1,
  129856. 9,
  129857. 0,
  129858. 10,
  129859. };
  129860. static long _vq_lengthlist__44c8_s_p5_1[] = {
  129861. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  129862. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129863. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  129864. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  129865. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  129866. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  129867. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  129868. 11,11,11, 7, 7, 7, 7, 8, 8,
  129869. };
  129870. static float _vq_quantthresh__44c8_s_p5_1[] = {
  129871. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129872. 3.5, 4.5,
  129873. };
  129874. static long _vq_quantmap__44c8_s_p5_1[] = {
  129875. 9, 7, 5, 3, 1, 0, 2, 4,
  129876. 6, 8, 10,
  129877. };
  129878. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  129879. _vq_quantthresh__44c8_s_p5_1,
  129880. _vq_quantmap__44c8_s_p5_1,
  129881. 11,
  129882. 11
  129883. };
  129884. static static_codebook _44c8_s_p5_1 = {
  129885. 2, 121,
  129886. _vq_lengthlist__44c8_s_p5_1,
  129887. 1, -531365888, 1611661312, 4, 0,
  129888. _vq_quantlist__44c8_s_p5_1,
  129889. NULL,
  129890. &_vq_auxt__44c8_s_p5_1,
  129891. NULL,
  129892. 0
  129893. };
  129894. static long _vq_quantlist__44c8_s_p6_0[] = {
  129895. 6,
  129896. 5,
  129897. 7,
  129898. 4,
  129899. 8,
  129900. 3,
  129901. 9,
  129902. 2,
  129903. 10,
  129904. 1,
  129905. 11,
  129906. 0,
  129907. 12,
  129908. };
  129909. static long _vq_lengthlist__44c8_s_p6_0[] = {
  129910. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129911. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  129912. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  129913. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  129914. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  129915. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. };
  129922. static float _vq_quantthresh__44c8_s_p6_0[] = {
  129923. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129924. 12.5, 17.5, 22.5, 27.5,
  129925. };
  129926. static long _vq_quantmap__44c8_s_p6_0[] = {
  129927. 11, 9, 7, 5, 3, 1, 0, 2,
  129928. 4, 6, 8, 10, 12,
  129929. };
  129930. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  129931. _vq_quantthresh__44c8_s_p6_0,
  129932. _vq_quantmap__44c8_s_p6_0,
  129933. 13,
  129934. 13
  129935. };
  129936. static static_codebook _44c8_s_p6_0 = {
  129937. 2, 169,
  129938. _vq_lengthlist__44c8_s_p6_0,
  129939. 1, -526516224, 1616117760, 4, 0,
  129940. _vq_quantlist__44c8_s_p6_0,
  129941. NULL,
  129942. &_vq_auxt__44c8_s_p6_0,
  129943. NULL,
  129944. 0
  129945. };
  129946. static long _vq_quantlist__44c8_s_p6_1[] = {
  129947. 2,
  129948. 1,
  129949. 3,
  129950. 0,
  129951. 4,
  129952. };
  129953. static long _vq_lengthlist__44c8_s_p6_1[] = {
  129954. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  129955. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129956. };
  129957. static float _vq_quantthresh__44c8_s_p6_1[] = {
  129958. -1.5, -0.5, 0.5, 1.5,
  129959. };
  129960. static long _vq_quantmap__44c8_s_p6_1[] = {
  129961. 3, 1, 0, 2, 4,
  129962. };
  129963. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  129964. _vq_quantthresh__44c8_s_p6_1,
  129965. _vq_quantmap__44c8_s_p6_1,
  129966. 5,
  129967. 5
  129968. };
  129969. static static_codebook _44c8_s_p6_1 = {
  129970. 2, 25,
  129971. _vq_lengthlist__44c8_s_p6_1,
  129972. 1, -533725184, 1611661312, 3, 0,
  129973. _vq_quantlist__44c8_s_p6_1,
  129974. NULL,
  129975. &_vq_auxt__44c8_s_p6_1,
  129976. NULL,
  129977. 0
  129978. };
  129979. static long _vq_quantlist__44c8_s_p7_0[] = {
  129980. 6,
  129981. 5,
  129982. 7,
  129983. 4,
  129984. 8,
  129985. 3,
  129986. 9,
  129987. 2,
  129988. 10,
  129989. 1,
  129990. 11,
  129991. 0,
  129992. 12,
  129993. };
  129994. static long _vq_lengthlist__44c8_s_p7_0[] = {
  129995. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  129996. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  129997. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  129998. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  129999. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  130000. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  130001. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  130002. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  130003. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  130004. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  130005. 20,13,13,13,13,14,13,15,15,
  130006. };
  130007. static float _vq_quantthresh__44c8_s_p7_0[] = {
  130008. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130009. 27.5, 38.5, 49.5, 60.5,
  130010. };
  130011. static long _vq_quantmap__44c8_s_p7_0[] = {
  130012. 11, 9, 7, 5, 3, 1, 0, 2,
  130013. 4, 6, 8, 10, 12,
  130014. };
  130015. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  130016. _vq_quantthresh__44c8_s_p7_0,
  130017. _vq_quantmap__44c8_s_p7_0,
  130018. 13,
  130019. 13
  130020. };
  130021. static static_codebook _44c8_s_p7_0 = {
  130022. 2, 169,
  130023. _vq_lengthlist__44c8_s_p7_0,
  130024. 1, -523206656, 1618345984, 4, 0,
  130025. _vq_quantlist__44c8_s_p7_0,
  130026. NULL,
  130027. &_vq_auxt__44c8_s_p7_0,
  130028. NULL,
  130029. 0
  130030. };
  130031. static long _vq_quantlist__44c8_s_p7_1[] = {
  130032. 5,
  130033. 4,
  130034. 6,
  130035. 3,
  130036. 7,
  130037. 2,
  130038. 8,
  130039. 1,
  130040. 9,
  130041. 0,
  130042. 10,
  130043. };
  130044. static long _vq_lengthlist__44c8_s_p7_1[] = {
  130045. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  130046. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130047. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  130048. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130049. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130050. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130051. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130052. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130053. };
  130054. static float _vq_quantthresh__44c8_s_p7_1[] = {
  130055. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130056. 3.5, 4.5,
  130057. };
  130058. static long _vq_quantmap__44c8_s_p7_1[] = {
  130059. 9, 7, 5, 3, 1, 0, 2, 4,
  130060. 6, 8, 10,
  130061. };
  130062. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  130063. _vq_quantthresh__44c8_s_p7_1,
  130064. _vq_quantmap__44c8_s_p7_1,
  130065. 11,
  130066. 11
  130067. };
  130068. static static_codebook _44c8_s_p7_1 = {
  130069. 2, 121,
  130070. _vq_lengthlist__44c8_s_p7_1,
  130071. 1, -531365888, 1611661312, 4, 0,
  130072. _vq_quantlist__44c8_s_p7_1,
  130073. NULL,
  130074. &_vq_auxt__44c8_s_p7_1,
  130075. NULL,
  130076. 0
  130077. };
  130078. static long _vq_quantlist__44c8_s_p8_0[] = {
  130079. 7,
  130080. 6,
  130081. 8,
  130082. 5,
  130083. 9,
  130084. 4,
  130085. 10,
  130086. 3,
  130087. 11,
  130088. 2,
  130089. 12,
  130090. 1,
  130091. 13,
  130092. 0,
  130093. 14,
  130094. };
  130095. static long _vq_lengthlist__44c8_s_p8_0[] = {
  130096. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  130097. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  130098. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  130099. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  130100. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  130101. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  130102. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  130103. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  130104. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  130105. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  130106. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  130107. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  130108. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  130109. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  130110. 15,
  130111. };
  130112. static float _vq_quantthresh__44c8_s_p8_0[] = {
  130113. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130114. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130115. };
  130116. static long _vq_quantmap__44c8_s_p8_0[] = {
  130117. 13, 11, 9, 7, 5, 3, 1, 0,
  130118. 2, 4, 6, 8, 10, 12, 14,
  130119. };
  130120. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  130121. _vq_quantthresh__44c8_s_p8_0,
  130122. _vq_quantmap__44c8_s_p8_0,
  130123. 15,
  130124. 15
  130125. };
  130126. static static_codebook _44c8_s_p8_0 = {
  130127. 2, 225,
  130128. _vq_lengthlist__44c8_s_p8_0,
  130129. 1, -520986624, 1620377600, 4, 0,
  130130. _vq_quantlist__44c8_s_p8_0,
  130131. NULL,
  130132. &_vq_auxt__44c8_s_p8_0,
  130133. NULL,
  130134. 0
  130135. };
  130136. static long _vq_quantlist__44c8_s_p8_1[] = {
  130137. 10,
  130138. 9,
  130139. 11,
  130140. 8,
  130141. 12,
  130142. 7,
  130143. 13,
  130144. 6,
  130145. 14,
  130146. 5,
  130147. 15,
  130148. 4,
  130149. 16,
  130150. 3,
  130151. 17,
  130152. 2,
  130153. 18,
  130154. 1,
  130155. 19,
  130156. 0,
  130157. 20,
  130158. };
  130159. static long _vq_lengthlist__44c8_s_p8_1[] = {
  130160. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  130161. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  130162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  130163. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  130164. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130165. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  130166. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  130167. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  130168. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130169. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130170. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  130171. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130172. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  130173. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  130174. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  130175. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  130176. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  130177. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  130178. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  130179. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  130180. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  130181. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  130182. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130183. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  130184. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  130185. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  130186. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  130187. 10, 9, 9,10,10, 9,10, 9, 9,
  130188. };
  130189. static float _vq_quantthresh__44c8_s_p8_1[] = {
  130190. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  130191. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  130192. 6.5, 7.5, 8.5, 9.5,
  130193. };
  130194. static long _vq_quantmap__44c8_s_p8_1[] = {
  130195. 19, 17, 15, 13, 11, 9, 7, 5,
  130196. 3, 1, 0, 2, 4, 6, 8, 10,
  130197. 12, 14, 16, 18, 20,
  130198. };
  130199. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  130200. _vq_quantthresh__44c8_s_p8_1,
  130201. _vq_quantmap__44c8_s_p8_1,
  130202. 21,
  130203. 21
  130204. };
  130205. static static_codebook _44c8_s_p8_1 = {
  130206. 2, 441,
  130207. _vq_lengthlist__44c8_s_p8_1,
  130208. 1, -529268736, 1611661312, 5, 0,
  130209. _vq_quantlist__44c8_s_p8_1,
  130210. NULL,
  130211. &_vq_auxt__44c8_s_p8_1,
  130212. NULL,
  130213. 0
  130214. };
  130215. static long _vq_quantlist__44c8_s_p9_0[] = {
  130216. 8,
  130217. 7,
  130218. 9,
  130219. 6,
  130220. 10,
  130221. 5,
  130222. 11,
  130223. 4,
  130224. 12,
  130225. 3,
  130226. 13,
  130227. 2,
  130228. 14,
  130229. 1,
  130230. 15,
  130231. 0,
  130232. 16,
  130233. };
  130234. static long _vq_lengthlist__44c8_s_p9_0[] = {
  130235. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130236. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  130237. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  130238. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130239. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130246. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130247. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130248. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130249. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130250. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130251. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130252. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130253. 10,
  130254. };
  130255. static float _vq_quantthresh__44c8_s_p9_0[] = {
  130256. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  130257. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  130258. };
  130259. static long _vq_quantmap__44c8_s_p9_0[] = {
  130260. 15, 13, 11, 9, 7, 5, 3, 1,
  130261. 0, 2, 4, 6, 8, 10, 12, 14,
  130262. 16,
  130263. };
  130264. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  130265. _vq_quantthresh__44c8_s_p9_0,
  130266. _vq_quantmap__44c8_s_p9_0,
  130267. 17,
  130268. 17
  130269. };
  130270. static static_codebook _44c8_s_p9_0 = {
  130271. 2, 289,
  130272. _vq_lengthlist__44c8_s_p9_0,
  130273. 1, -509798400, 1631393792, 5, 0,
  130274. _vq_quantlist__44c8_s_p9_0,
  130275. NULL,
  130276. &_vq_auxt__44c8_s_p9_0,
  130277. NULL,
  130278. 0
  130279. };
  130280. static long _vq_quantlist__44c8_s_p9_1[] = {
  130281. 9,
  130282. 8,
  130283. 10,
  130284. 7,
  130285. 11,
  130286. 6,
  130287. 12,
  130288. 5,
  130289. 13,
  130290. 4,
  130291. 14,
  130292. 3,
  130293. 15,
  130294. 2,
  130295. 16,
  130296. 1,
  130297. 17,
  130298. 0,
  130299. 18,
  130300. };
  130301. static long _vq_lengthlist__44c8_s_p9_1[] = {
  130302. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  130303. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  130304. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  130305. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  130306. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  130307. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  130308. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  130309. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  130310. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  130311. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  130312. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  130313. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  130314. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  130315. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  130316. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  130317. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  130318. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  130319. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  130320. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  130321. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  130322. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  130323. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  130324. 14,13,13,14,14,15,14,15,14,
  130325. };
  130326. static float _vq_quantthresh__44c8_s_p9_1[] = {
  130327. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  130328. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  130329. 367.5, 416.5,
  130330. };
  130331. static long _vq_quantmap__44c8_s_p9_1[] = {
  130332. 17, 15, 13, 11, 9, 7, 5, 3,
  130333. 1, 0, 2, 4, 6, 8, 10, 12,
  130334. 14, 16, 18,
  130335. };
  130336. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  130337. _vq_quantthresh__44c8_s_p9_1,
  130338. _vq_quantmap__44c8_s_p9_1,
  130339. 19,
  130340. 19
  130341. };
  130342. static static_codebook _44c8_s_p9_1 = {
  130343. 2, 361,
  130344. _vq_lengthlist__44c8_s_p9_1,
  130345. 1, -518287360, 1622704128, 5, 0,
  130346. _vq_quantlist__44c8_s_p9_1,
  130347. NULL,
  130348. &_vq_auxt__44c8_s_p9_1,
  130349. NULL,
  130350. 0
  130351. };
  130352. static long _vq_quantlist__44c8_s_p9_2[] = {
  130353. 24,
  130354. 23,
  130355. 25,
  130356. 22,
  130357. 26,
  130358. 21,
  130359. 27,
  130360. 20,
  130361. 28,
  130362. 19,
  130363. 29,
  130364. 18,
  130365. 30,
  130366. 17,
  130367. 31,
  130368. 16,
  130369. 32,
  130370. 15,
  130371. 33,
  130372. 14,
  130373. 34,
  130374. 13,
  130375. 35,
  130376. 12,
  130377. 36,
  130378. 11,
  130379. 37,
  130380. 10,
  130381. 38,
  130382. 9,
  130383. 39,
  130384. 8,
  130385. 40,
  130386. 7,
  130387. 41,
  130388. 6,
  130389. 42,
  130390. 5,
  130391. 43,
  130392. 4,
  130393. 44,
  130394. 3,
  130395. 45,
  130396. 2,
  130397. 46,
  130398. 1,
  130399. 47,
  130400. 0,
  130401. 48,
  130402. };
  130403. static long _vq_lengthlist__44c8_s_p9_2[] = {
  130404. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  130405. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  130407. 7,
  130408. };
  130409. static float _vq_quantthresh__44c8_s_p9_2[] = {
  130410. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  130411. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  130412. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130413. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130414. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  130415. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  130416. };
  130417. static long _vq_quantmap__44c8_s_p9_2[] = {
  130418. 47, 45, 43, 41, 39, 37, 35, 33,
  130419. 31, 29, 27, 25, 23, 21, 19, 17,
  130420. 15, 13, 11, 9, 7, 5, 3, 1,
  130421. 0, 2, 4, 6, 8, 10, 12, 14,
  130422. 16, 18, 20, 22, 24, 26, 28, 30,
  130423. 32, 34, 36, 38, 40, 42, 44, 46,
  130424. 48,
  130425. };
  130426. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  130427. _vq_quantthresh__44c8_s_p9_2,
  130428. _vq_quantmap__44c8_s_p9_2,
  130429. 49,
  130430. 49
  130431. };
  130432. static static_codebook _44c8_s_p9_2 = {
  130433. 1, 49,
  130434. _vq_lengthlist__44c8_s_p9_2,
  130435. 1, -526909440, 1611661312, 6, 0,
  130436. _vq_quantlist__44c8_s_p9_2,
  130437. NULL,
  130438. &_vq_auxt__44c8_s_p9_2,
  130439. NULL,
  130440. 0
  130441. };
  130442. static long _huff_lengthlist__44c8_s_short[] = {
  130443. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  130444. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  130445. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  130446. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  130447. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  130448. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  130449. 10, 9,11,14,
  130450. };
  130451. static static_codebook _huff_book__44c8_s_short = {
  130452. 2, 100,
  130453. _huff_lengthlist__44c8_s_short,
  130454. 0, 0, 0, 0, 0,
  130455. NULL,
  130456. NULL,
  130457. NULL,
  130458. NULL,
  130459. 0
  130460. };
  130461. static long _huff_lengthlist__44c9_s_long[] = {
  130462. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  130463. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  130464. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  130465. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  130466. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  130467. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  130468. 10, 9, 8, 9,
  130469. };
  130470. static static_codebook _huff_book__44c9_s_long = {
  130471. 2, 100,
  130472. _huff_lengthlist__44c9_s_long,
  130473. 0, 0, 0, 0, 0,
  130474. NULL,
  130475. NULL,
  130476. NULL,
  130477. NULL,
  130478. 0
  130479. };
  130480. static long _vq_quantlist__44c9_s_p1_0[] = {
  130481. 1,
  130482. 0,
  130483. 2,
  130484. };
  130485. static long _vq_lengthlist__44c9_s_p1_0[] = {
  130486. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  130487. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  130488. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  130489. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  130490. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  130491. 7,
  130492. };
  130493. static float _vq_quantthresh__44c9_s_p1_0[] = {
  130494. -0.5, 0.5,
  130495. };
  130496. static long _vq_quantmap__44c9_s_p1_0[] = {
  130497. 1, 0, 2,
  130498. };
  130499. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  130500. _vq_quantthresh__44c9_s_p1_0,
  130501. _vq_quantmap__44c9_s_p1_0,
  130502. 3,
  130503. 3
  130504. };
  130505. static static_codebook _44c9_s_p1_0 = {
  130506. 4, 81,
  130507. _vq_lengthlist__44c9_s_p1_0,
  130508. 1, -535822336, 1611661312, 2, 0,
  130509. _vq_quantlist__44c9_s_p1_0,
  130510. NULL,
  130511. &_vq_auxt__44c9_s_p1_0,
  130512. NULL,
  130513. 0
  130514. };
  130515. static long _vq_quantlist__44c9_s_p2_0[] = {
  130516. 2,
  130517. 1,
  130518. 3,
  130519. 0,
  130520. 4,
  130521. };
  130522. static long _vq_lengthlist__44c9_s_p2_0[] = {
  130523. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  130524. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  130525. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  130526. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  130527. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  130528. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  130529. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  130530. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  130531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130532. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  130533. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  130534. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  130535. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  130536. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  130537. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  130538. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  130539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130540. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  130541. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  130542. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  130543. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  130544. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  130545. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  130546. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130548. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  130549. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  130550. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  130551. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  130552. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  130553. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  130554. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  130559. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  130560. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  130561. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  130562. 12,
  130563. };
  130564. static float _vq_quantthresh__44c9_s_p2_0[] = {
  130565. -1.5, -0.5, 0.5, 1.5,
  130566. };
  130567. static long _vq_quantmap__44c9_s_p2_0[] = {
  130568. 3, 1, 0, 2, 4,
  130569. };
  130570. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  130571. _vq_quantthresh__44c9_s_p2_0,
  130572. _vq_quantmap__44c9_s_p2_0,
  130573. 5,
  130574. 5
  130575. };
  130576. static static_codebook _44c9_s_p2_0 = {
  130577. 4, 625,
  130578. _vq_lengthlist__44c9_s_p2_0,
  130579. 1, -533725184, 1611661312, 3, 0,
  130580. _vq_quantlist__44c9_s_p2_0,
  130581. NULL,
  130582. &_vq_auxt__44c9_s_p2_0,
  130583. NULL,
  130584. 0
  130585. };
  130586. static long _vq_quantlist__44c9_s_p3_0[] = {
  130587. 4,
  130588. 3,
  130589. 5,
  130590. 2,
  130591. 6,
  130592. 1,
  130593. 7,
  130594. 0,
  130595. 8,
  130596. };
  130597. static long _vq_lengthlist__44c9_s_p3_0[] = {
  130598. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  130599. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  130600. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  130601. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  130602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130603. 0,
  130604. };
  130605. static float _vq_quantthresh__44c9_s_p3_0[] = {
  130606. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130607. };
  130608. static long _vq_quantmap__44c9_s_p3_0[] = {
  130609. 7, 5, 3, 1, 0, 2, 4, 6,
  130610. 8,
  130611. };
  130612. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  130613. _vq_quantthresh__44c9_s_p3_0,
  130614. _vq_quantmap__44c9_s_p3_0,
  130615. 9,
  130616. 9
  130617. };
  130618. static static_codebook _44c9_s_p3_0 = {
  130619. 2, 81,
  130620. _vq_lengthlist__44c9_s_p3_0,
  130621. 1, -531628032, 1611661312, 4, 0,
  130622. _vq_quantlist__44c9_s_p3_0,
  130623. NULL,
  130624. &_vq_auxt__44c9_s_p3_0,
  130625. NULL,
  130626. 0
  130627. };
  130628. static long _vq_quantlist__44c9_s_p4_0[] = {
  130629. 8,
  130630. 7,
  130631. 9,
  130632. 6,
  130633. 10,
  130634. 5,
  130635. 11,
  130636. 4,
  130637. 12,
  130638. 3,
  130639. 13,
  130640. 2,
  130641. 14,
  130642. 1,
  130643. 15,
  130644. 0,
  130645. 16,
  130646. };
  130647. static long _vq_lengthlist__44c9_s_p4_0[] = {
  130648. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  130649. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  130650. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  130651. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  130652. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  130653. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  130654. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  130655. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  130656. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  130657. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130666. 0,
  130667. };
  130668. static float _vq_quantthresh__44c9_s_p4_0[] = {
  130669. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130670. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130671. };
  130672. static long _vq_quantmap__44c9_s_p4_0[] = {
  130673. 15, 13, 11, 9, 7, 5, 3, 1,
  130674. 0, 2, 4, 6, 8, 10, 12, 14,
  130675. 16,
  130676. };
  130677. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  130678. _vq_quantthresh__44c9_s_p4_0,
  130679. _vq_quantmap__44c9_s_p4_0,
  130680. 17,
  130681. 17
  130682. };
  130683. static static_codebook _44c9_s_p4_0 = {
  130684. 2, 289,
  130685. _vq_lengthlist__44c9_s_p4_0,
  130686. 1, -529530880, 1611661312, 5, 0,
  130687. _vq_quantlist__44c9_s_p4_0,
  130688. NULL,
  130689. &_vq_auxt__44c9_s_p4_0,
  130690. NULL,
  130691. 0
  130692. };
  130693. static long _vq_quantlist__44c9_s_p5_0[] = {
  130694. 1,
  130695. 0,
  130696. 2,
  130697. };
  130698. static long _vq_lengthlist__44c9_s_p5_0[] = {
  130699. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  130700. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  130701. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  130702. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  130703. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  130704. 12,
  130705. };
  130706. static float _vq_quantthresh__44c9_s_p5_0[] = {
  130707. -5.5, 5.5,
  130708. };
  130709. static long _vq_quantmap__44c9_s_p5_0[] = {
  130710. 1, 0, 2,
  130711. };
  130712. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  130713. _vq_quantthresh__44c9_s_p5_0,
  130714. _vq_quantmap__44c9_s_p5_0,
  130715. 3,
  130716. 3
  130717. };
  130718. static static_codebook _44c9_s_p5_0 = {
  130719. 4, 81,
  130720. _vq_lengthlist__44c9_s_p5_0,
  130721. 1, -529137664, 1618345984, 2, 0,
  130722. _vq_quantlist__44c9_s_p5_0,
  130723. NULL,
  130724. &_vq_auxt__44c9_s_p5_0,
  130725. NULL,
  130726. 0
  130727. };
  130728. static long _vq_quantlist__44c9_s_p5_1[] = {
  130729. 5,
  130730. 4,
  130731. 6,
  130732. 3,
  130733. 7,
  130734. 2,
  130735. 8,
  130736. 1,
  130737. 9,
  130738. 0,
  130739. 10,
  130740. };
  130741. static long _vq_lengthlist__44c9_s_p5_1[] = {
  130742. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  130743. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  130744. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  130745. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  130746. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  130747. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  130748. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  130749. 11,11,11, 7, 7, 7, 7, 7, 7,
  130750. };
  130751. static float _vq_quantthresh__44c9_s_p5_1[] = {
  130752. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130753. 3.5, 4.5,
  130754. };
  130755. static long _vq_quantmap__44c9_s_p5_1[] = {
  130756. 9, 7, 5, 3, 1, 0, 2, 4,
  130757. 6, 8, 10,
  130758. };
  130759. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  130760. _vq_quantthresh__44c9_s_p5_1,
  130761. _vq_quantmap__44c9_s_p5_1,
  130762. 11,
  130763. 11
  130764. };
  130765. static static_codebook _44c9_s_p5_1 = {
  130766. 2, 121,
  130767. _vq_lengthlist__44c9_s_p5_1,
  130768. 1, -531365888, 1611661312, 4, 0,
  130769. _vq_quantlist__44c9_s_p5_1,
  130770. NULL,
  130771. &_vq_auxt__44c9_s_p5_1,
  130772. NULL,
  130773. 0
  130774. };
  130775. static long _vq_quantlist__44c9_s_p6_0[] = {
  130776. 6,
  130777. 5,
  130778. 7,
  130779. 4,
  130780. 8,
  130781. 3,
  130782. 9,
  130783. 2,
  130784. 10,
  130785. 1,
  130786. 11,
  130787. 0,
  130788. 12,
  130789. };
  130790. static long _vq_lengthlist__44c9_s_p6_0[] = {
  130791. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  130792. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  130793. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  130794. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  130795. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  130796. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. };
  130803. static float _vq_quantthresh__44c9_s_p6_0[] = {
  130804. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130805. 12.5, 17.5, 22.5, 27.5,
  130806. };
  130807. static long _vq_quantmap__44c9_s_p6_0[] = {
  130808. 11, 9, 7, 5, 3, 1, 0, 2,
  130809. 4, 6, 8, 10, 12,
  130810. };
  130811. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  130812. _vq_quantthresh__44c9_s_p6_0,
  130813. _vq_quantmap__44c9_s_p6_0,
  130814. 13,
  130815. 13
  130816. };
  130817. static static_codebook _44c9_s_p6_0 = {
  130818. 2, 169,
  130819. _vq_lengthlist__44c9_s_p6_0,
  130820. 1, -526516224, 1616117760, 4, 0,
  130821. _vq_quantlist__44c9_s_p6_0,
  130822. NULL,
  130823. &_vq_auxt__44c9_s_p6_0,
  130824. NULL,
  130825. 0
  130826. };
  130827. static long _vq_quantlist__44c9_s_p6_1[] = {
  130828. 2,
  130829. 1,
  130830. 3,
  130831. 0,
  130832. 4,
  130833. };
  130834. static long _vq_lengthlist__44c9_s_p6_1[] = {
  130835. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  130836. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  130837. };
  130838. static float _vq_quantthresh__44c9_s_p6_1[] = {
  130839. -1.5, -0.5, 0.5, 1.5,
  130840. };
  130841. static long _vq_quantmap__44c9_s_p6_1[] = {
  130842. 3, 1, 0, 2, 4,
  130843. };
  130844. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  130845. _vq_quantthresh__44c9_s_p6_1,
  130846. _vq_quantmap__44c9_s_p6_1,
  130847. 5,
  130848. 5
  130849. };
  130850. static static_codebook _44c9_s_p6_1 = {
  130851. 2, 25,
  130852. _vq_lengthlist__44c9_s_p6_1,
  130853. 1, -533725184, 1611661312, 3, 0,
  130854. _vq_quantlist__44c9_s_p6_1,
  130855. NULL,
  130856. &_vq_auxt__44c9_s_p6_1,
  130857. NULL,
  130858. 0
  130859. };
  130860. static long _vq_quantlist__44c9_s_p7_0[] = {
  130861. 6,
  130862. 5,
  130863. 7,
  130864. 4,
  130865. 8,
  130866. 3,
  130867. 9,
  130868. 2,
  130869. 10,
  130870. 1,
  130871. 11,
  130872. 0,
  130873. 12,
  130874. };
  130875. static long _vq_lengthlist__44c9_s_p7_0[] = {
  130876. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  130877. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  130878. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  130879. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  130880. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  130881. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  130882. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  130883. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  130884. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  130885. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  130886. 19,12,12,12,12,13,13,14,14,
  130887. };
  130888. static float _vq_quantthresh__44c9_s_p7_0[] = {
  130889. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  130890. 27.5, 38.5, 49.5, 60.5,
  130891. };
  130892. static long _vq_quantmap__44c9_s_p7_0[] = {
  130893. 11, 9, 7, 5, 3, 1, 0, 2,
  130894. 4, 6, 8, 10, 12,
  130895. };
  130896. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  130897. _vq_quantthresh__44c9_s_p7_0,
  130898. _vq_quantmap__44c9_s_p7_0,
  130899. 13,
  130900. 13
  130901. };
  130902. static static_codebook _44c9_s_p7_0 = {
  130903. 2, 169,
  130904. _vq_lengthlist__44c9_s_p7_0,
  130905. 1, -523206656, 1618345984, 4, 0,
  130906. _vq_quantlist__44c9_s_p7_0,
  130907. NULL,
  130908. &_vq_auxt__44c9_s_p7_0,
  130909. NULL,
  130910. 0
  130911. };
  130912. static long _vq_quantlist__44c9_s_p7_1[] = {
  130913. 5,
  130914. 4,
  130915. 6,
  130916. 3,
  130917. 7,
  130918. 2,
  130919. 8,
  130920. 1,
  130921. 9,
  130922. 0,
  130923. 10,
  130924. };
  130925. static long _vq_lengthlist__44c9_s_p7_1[] = {
  130926. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  130927. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  130928. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  130929. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130930. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  130931. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  130932. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  130933. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  130934. };
  130935. static float _vq_quantthresh__44c9_s_p7_1[] = {
  130936. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130937. 3.5, 4.5,
  130938. };
  130939. static long _vq_quantmap__44c9_s_p7_1[] = {
  130940. 9, 7, 5, 3, 1, 0, 2, 4,
  130941. 6, 8, 10,
  130942. };
  130943. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  130944. _vq_quantthresh__44c9_s_p7_1,
  130945. _vq_quantmap__44c9_s_p7_1,
  130946. 11,
  130947. 11
  130948. };
  130949. static static_codebook _44c9_s_p7_1 = {
  130950. 2, 121,
  130951. _vq_lengthlist__44c9_s_p7_1,
  130952. 1, -531365888, 1611661312, 4, 0,
  130953. _vq_quantlist__44c9_s_p7_1,
  130954. NULL,
  130955. &_vq_auxt__44c9_s_p7_1,
  130956. NULL,
  130957. 0
  130958. };
  130959. static long _vq_quantlist__44c9_s_p8_0[] = {
  130960. 7,
  130961. 6,
  130962. 8,
  130963. 5,
  130964. 9,
  130965. 4,
  130966. 10,
  130967. 3,
  130968. 11,
  130969. 2,
  130970. 12,
  130971. 1,
  130972. 13,
  130973. 0,
  130974. 14,
  130975. };
  130976. static long _vq_lengthlist__44c9_s_p8_0[] = {
  130977. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  130978. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  130979. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  130980. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  130981. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  130982. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  130983. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  130984. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  130985. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  130986. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  130987. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  130988. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  130989. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  130990. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  130991. 14,
  130992. };
  130993. static float _vq_quantthresh__44c9_s_p8_0[] = {
  130994. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  130995. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  130996. };
  130997. static long _vq_quantmap__44c9_s_p8_0[] = {
  130998. 13, 11, 9, 7, 5, 3, 1, 0,
  130999. 2, 4, 6, 8, 10, 12, 14,
  131000. };
  131001. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  131002. _vq_quantthresh__44c9_s_p8_0,
  131003. _vq_quantmap__44c9_s_p8_0,
  131004. 15,
  131005. 15
  131006. };
  131007. static static_codebook _44c9_s_p8_0 = {
  131008. 2, 225,
  131009. _vq_lengthlist__44c9_s_p8_0,
  131010. 1, -520986624, 1620377600, 4, 0,
  131011. _vq_quantlist__44c9_s_p8_0,
  131012. NULL,
  131013. &_vq_auxt__44c9_s_p8_0,
  131014. NULL,
  131015. 0
  131016. };
  131017. static long _vq_quantlist__44c9_s_p8_1[] = {
  131018. 10,
  131019. 9,
  131020. 11,
  131021. 8,
  131022. 12,
  131023. 7,
  131024. 13,
  131025. 6,
  131026. 14,
  131027. 5,
  131028. 15,
  131029. 4,
  131030. 16,
  131031. 3,
  131032. 17,
  131033. 2,
  131034. 18,
  131035. 1,
  131036. 19,
  131037. 0,
  131038. 20,
  131039. };
  131040. static long _vq_lengthlist__44c9_s_p8_1[] = {
  131041. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  131042. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131043. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  131044. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  131045. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131046. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  131047. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  131048. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  131049. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131050. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131051. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  131052. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131053. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131054. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  131055. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  131056. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  131057. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  131058. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  131059. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  131060. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131061. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131062. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  131063. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131064. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  131065. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  131066. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  131067. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  131068. 9, 9, 9,10, 9, 9, 9, 9, 9,
  131069. };
  131070. static float _vq_quantthresh__44c9_s_p8_1[] = {
  131071. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131072. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131073. 6.5, 7.5, 8.5, 9.5,
  131074. };
  131075. static long _vq_quantmap__44c9_s_p8_1[] = {
  131076. 19, 17, 15, 13, 11, 9, 7, 5,
  131077. 3, 1, 0, 2, 4, 6, 8, 10,
  131078. 12, 14, 16, 18, 20,
  131079. };
  131080. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  131081. _vq_quantthresh__44c9_s_p8_1,
  131082. _vq_quantmap__44c9_s_p8_1,
  131083. 21,
  131084. 21
  131085. };
  131086. static static_codebook _44c9_s_p8_1 = {
  131087. 2, 441,
  131088. _vq_lengthlist__44c9_s_p8_1,
  131089. 1, -529268736, 1611661312, 5, 0,
  131090. _vq_quantlist__44c9_s_p8_1,
  131091. NULL,
  131092. &_vq_auxt__44c9_s_p8_1,
  131093. NULL,
  131094. 0
  131095. };
  131096. static long _vq_quantlist__44c9_s_p9_0[] = {
  131097. 9,
  131098. 8,
  131099. 10,
  131100. 7,
  131101. 11,
  131102. 6,
  131103. 12,
  131104. 5,
  131105. 13,
  131106. 4,
  131107. 14,
  131108. 3,
  131109. 15,
  131110. 2,
  131111. 16,
  131112. 1,
  131113. 17,
  131114. 0,
  131115. 18,
  131116. };
  131117. static long _vq_lengthlist__44c9_s_p9_0[] = {
  131118. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131119. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  131120. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  131121. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  131122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131126. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131127. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131128. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131129. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131130. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131131. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131132. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131133. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131134. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  131135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131140. 11,11,11,11,11,11,11,11,11,
  131141. };
  131142. static float _vq_quantthresh__44c9_s_p9_0[] = {
  131143. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  131144. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  131145. 6982.5, 7913.5,
  131146. };
  131147. static long _vq_quantmap__44c9_s_p9_0[] = {
  131148. 17, 15, 13, 11, 9, 7, 5, 3,
  131149. 1, 0, 2, 4, 6, 8, 10, 12,
  131150. 14, 16, 18,
  131151. };
  131152. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  131153. _vq_quantthresh__44c9_s_p9_0,
  131154. _vq_quantmap__44c9_s_p9_0,
  131155. 19,
  131156. 19
  131157. };
  131158. static static_codebook _44c9_s_p9_0 = {
  131159. 2, 361,
  131160. _vq_lengthlist__44c9_s_p9_0,
  131161. 1, -508535424, 1631393792, 5, 0,
  131162. _vq_quantlist__44c9_s_p9_0,
  131163. NULL,
  131164. &_vq_auxt__44c9_s_p9_0,
  131165. NULL,
  131166. 0
  131167. };
  131168. static long _vq_quantlist__44c9_s_p9_1[] = {
  131169. 9,
  131170. 8,
  131171. 10,
  131172. 7,
  131173. 11,
  131174. 6,
  131175. 12,
  131176. 5,
  131177. 13,
  131178. 4,
  131179. 14,
  131180. 3,
  131181. 15,
  131182. 2,
  131183. 16,
  131184. 1,
  131185. 17,
  131186. 0,
  131187. 18,
  131188. };
  131189. static long _vq_lengthlist__44c9_s_p9_1[] = {
  131190. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  131191. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  131192. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  131193. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  131194. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  131195. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  131196. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  131197. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  131198. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  131199. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  131200. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  131201. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  131202. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  131203. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  131204. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  131205. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  131206. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  131207. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  131208. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  131209. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  131210. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  131211. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  131212. 13,13,13,14,13,14,15,15,15,
  131213. };
  131214. static float _vq_quantthresh__44c9_s_p9_1[] = {
  131215. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  131216. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  131217. 367.5, 416.5,
  131218. };
  131219. static long _vq_quantmap__44c9_s_p9_1[] = {
  131220. 17, 15, 13, 11, 9, 7, 5, 3,
  131221. 1, 0, 2, 4, 6, 8, 10, 12,
  131222. 14, 16, 18,
  131223. };
  131224. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  131225. _vq_quantthresh__44c9_s_p9_1,
  131226. _vq_quantmap__44c9_s_p9_1,
  131227. 19,
  131228. 19
  131229. };
  131230. static static_codebook _44c9_s_p9_1 = {
  131231. 2, 361,
  131232. _vq_lengthlist__44c9_s_p9_1,
  131233. 1, -518287360, 1622704128, 5, 0,
  131234. _vq_quantlist__44c9_s_p9_1,
  131235. NULL,
  131236. &_vq_auxt__44c9_s_p9_1,
  131237. NULL,
  131238. 0
  131239. };
  131240. static long _vq_quantlist__44c9_s_p9_2[] = {
  131241. 24,
  131242. 23,
  131243. 25,
  131244. 22,
  131245. 26,
  131246. 21,
  131247. 27,
  131248. 20,
  131249. 28,
  131250. 19,
  131251. 29,
  131252. 18,
  131253. 30,
  131254. 17,
  131255. 31,
  131256. 16,
  131257. 32,
  131258. 15,
  131259. 33,
  131260. 14,
  131261. 34,
  131262. 13,
  131263. 35,
  131264. 12,
  131265. 36,
  131266. 11,
  131267. 37,
  131268. 10,
  131269. 38,
  131270. 9,
  131271. 39,
  131272. 8,
  131273. 40,
  131274. 7,
  131275. 41,
  131276. 6,
  131277. 42,
  131278. 5,
  131279. 43,
  131280. 4,
  131281. 44,
  131282. 3,
  131283. 45,
  131284. 2,
  131285. 46,
  131286. 1,
  131287. 47,
  131288. 0,
  131289. 48,
  131290. };
  131291. static long _vq_lengthlist__44c9_s_p9_2[] = {
  131292. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  131293. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  131294. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  131295. 7,
  131296. };
  131297. static float _vq_quantthresh__44c9_s_p9_2[] = {
  131298. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  131299. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  131300. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131301. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131302. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  131303. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  131304. };
  131305. static long _vq_quantmap__44c9_s_p9_2[] = {
  131306. 47, 45, 43, 41, 39, 37, 35, 33,
  131307. 31, 29, 27, 25, 23, 21, 19, 17,
  131308. 15, 13, 11, 9, 7, 5, 3, 1,
  131309. 0, 2, 4, 6, 8, 10, 12, 14,
  131310. 16, 18, 20, 22, 24, 26, 28, 30,
  131311. 32, 34, 36, 38, 40, 42, 44, 46,
  131312. 48,
  131313. };
  131314. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  131315. _vq_quantthresh__44c9_s_p9_2,
  131316. _vq_quantmap__44c9_s_p9_2,
  131317. 49,
  131318. 49
  131319. };
  131320. static static_codebook _44c9_s_p9_2 = {
  131321. 1, 49,
  131322. _vq_lengthlist__44c9_s_p9_2,
  131323. 1, -526909440, 1611661312, 6, 0,
  131324. _vq_quantlist__44c9_s_p9_2,
  131325. NULL,
  131326. &_vq_auxt__44c9_s_p9_2,
  131327. NULL,
  131328. 0
  131329. };
  131330. static long _huff_lengthlist__44c9_s_short[] = {
  131331. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  131332. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  131333. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  131334. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  131335. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  131336. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  131337. 9, 8,10,13,
  131338. };
  131339. static static_codebook _huff_book__44c9_s_short = {
  131340. 2, 100,
  131341. _huff_lengthlist__44c9_s_short,
  131342. 0, 0, 0, 0, 0,
  131343. NULL,
  131344. NULL,
  131345. NULL,
  131346. NULL,
  131347. 0
  131348. };
  131349. static long _huff_lengthlist__44c0_s_long[] = {
  131350. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  131351. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  131352. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  131353. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  131354. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  131355. 12,
  131356. };
  131357. static static_codebook _huff_book__44c0_s_long = {
  131358. 2, 81,
  131359. _huff_lengthlist__44c0_s_long,
  131360. 0, 0, 0, 0, 0,
  131361. NULL,
  131362. NULL,
  131363. NULL,
  131364. NULL,
  131365. 0
  131366. };
  131367. static long _vq_quantlist__44c0_s_p1_0[] = {
  131368. 1,
  131369. 0,
  131370. 2,
  131371. };
  131372. static long _vq_lengthlist__44c0_s_p1_0[] = {
  131373. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  131374. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131378. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131379. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131383. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131384. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131396. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131401. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131406. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  131419. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131424. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  131429. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  131441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131465. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131470. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  131475. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131784. };
  131785. static float _vq_quantthresh__44c0_s_p1_0[] = {
  131786. -0.5, 0.5,
  131787. };
  131788. static long _vq_quantmap__44c0_s_p1_0[] = {
  131789. 1, 0, 2,
  131790. };
  131791. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  131792. _vq_quantthresh__44c0_s_p1_0,
  131793. _vq_quantmap__44c0_s_p1_0,
  131794. 3,
  131795. 3
  131796. };
  131797. static static_codebook _44c0_s_p1_0 = {
  131798. 8, 6561,
  131799. _vq_lengthlist__44c0_s_p1_0,
  131800. 1, -535822336, 1611661312, 2, 0,
  131801. _vq_quantlist__44c0_s_p1_0,
  131802. NULL,
  131803. &_vq_auxt__44c0_s_p1_0,
  131804. NULL,
  131805. 0
  131806. };
  131807. static long _vq_quantlist__44c0_s_p2_0[] = {
  131808. 2,
  131809. 1,
  131810. 3,
  131811. 0,
  131812. 4,
  131813. };
  131814. static long _vq_lengthlist__44c0_s_p2_0[] = {
  131815. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  131817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131818. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  131820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131821. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  131822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131855. };
  131856. static float _vq_quantthresh__44c0_s_p2_0[] = {
  131857. -1.5, -0.5, 0.5, 1.5,
  131858. };
  131859. static long _vq_quantmap__44c0_s_p2_0[] = {
  131860. 3, 1, 0, 2, 4,
  131861. };
  131862. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  131863. _vq_quantthresh__44c0_s_p2_0,
  131864. _vq_quantmap__44c0_s_p2_0,
  131865. 5,
  131866. 5
  131867. };
  131868. static static_codebook _44c0_s_p2_0 = {
  131869. 4, 625,
  131870. _vq_lengthlist__44c0_s_p2_0,
  131871. 1, -533725184, 1611661312, 3, 0,
  131872. _vq_quantlist__44c0_s_p2_0,
  131873. NULL,
  131874. &_vq_auxt__44c0_s_p2_0,
  131875. NULL,
  131876. 0
  131877. };
  131878. static long _vq_quantlist__44c0_s_p3_0[] = {
  131879. 4,
  131880. 3,
  131881. 5,
  131882. 2,
  131883. 6,
  131884. 1,
  131885. 7,
  131886. 0,
  131887. 8,
  131888. };
  131889. static long _vq_lengthlist__44c0_s_p3_0[] = {
  131890. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  131891. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131892. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131893. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131894. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131895. 0,
  131896. };
  131897. static float _vq_quantthresh__44c0_s_p3_0[] = {
  131898. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131899. };
  131900. static long _vq_quantmap__44c0_s_p3_0[] = {
  131901. 7, 5, 3, 1, 0, 2, 4, 6,
  131902. 8,
  131903. };
  131904. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  131905. _vq_quantthresh__44c0_s_p3_0,
  131906. _vq_quantmap__44c0_s_p3_0,
  131907. 9,
  131908. 9
  131909. };
  131910. static static_codebook _44c0_s_p3_0 = {
  131911. 2, 81,
  131912. _vq_lengthlist__44c0_s_p3_0,
  131913. 1, -531628032, 1611661312, 4, 0,
  131914. _vq_quantlist__44c0_s_p3_0,
  131915. NULL,
  131916. &_vq_auxt__44c0_s_p3_0,
  131917. NULL,
  131918. 0
  131919. };
  131920. static long _vq_quantlist__44c0_s_p4_0[] = {
  131921. 4,
  131922. 3,
  131923. 5,
  131924. 2,
  131925. 6,
  131926. 1,
  131927. 7,
  131928. 0,
  131929. 8,
  131930. };
  131931. static long _vq_lengthlist__44c0_s_p4_0[] = {
  131932. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131933. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131934. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  131935. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  131936. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131937. 10,
  131938. };
  131939. static float _vq_quantthresh__44c0_s_p4_0[] = {
  131940. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131941. };
  131942. static long _vq_quantmap__44c0_s_p4_0[] = {
  131943. 7, 5, 3, 1, 0, 2, 4, 6,
  131944. 8,
  131945. };
  131946. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  131947. _vq_quantthresh__44c0_s_p4_0,
  131948. _vq_quantmap__44c0_s_p4_0,
  131949. 9,
  131950. 9
  131951. };
  131952. static static_codebook _44c0_s_p4_0 = {
  131953. 2, 81,
  131954. _vq_lengthlist__44c0_s_p4_0,
  131955. 1, -531628032, 1611661312, 4, 0,
  131956. _vq_quantlist__44c0_s_p4_0,
  131957. NULL,
  131958. &_vq_auxt__44c0_s_p4_0,
  131959. NULL,
  131960. 0
  131961. };
  131962. static long _vq_quantlist__44c0_s_p5_0[] = {
  131963. 8,
  131964. 7,
  131965. 9,
  131966. 6,
  131967. 10,
  131968. 5,
  131969. 11,
  131970. 4,
  131971. 12,
  131972. 3,
  131973. 13,
  131974. 2,
  131975. 14,
  131976. 1,
  131977. 15,
  131978. 0,
  131979. 16,
  131980. };
  131981. static long _vq_lengthlist__44c0_s_p5_0[] = {
  131982. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131983. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  131984. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131985. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131986. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131987. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  131988. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  131989. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131990. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131991. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131992. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131993. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131994. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131995. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131996. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  131997. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  131998. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132000. 14,
  132001. };
  132002. static float _vq_quantthresh__44c0_s_p5_0[] = {
  132003. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132004. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132005. };
  132006. static long _vq_quantmap__44c0_s_p5_0[] = {
  132007. 15, 13, 11, 9, 7, 5, 3, 1,
  132008. 0, 2, 4, 6, 8, 10, 12, 14,
  132009. 16,
  132010. };
  132011. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  132012. _vq_quantthresh__44c0_s_p5_0,
  132013. _vq_quantmap__44c0_s_p5_0,
  132014. 17,
  132015. 17
  132016. };
  132017. static static_codebook _44c0_s_p5_0 = {
  132018. 2, 289,
  132019. _vq_lengthlist__44c0_s_p5_0,
  132020. 1, -529530880, 1611661312, 5, 0,
  132021. _vq_quantlist__44c0_s_p5_0,
  132022. NULL,
  132023. &_vq_auxt__44c0_s_p5_0,
  132024. NULL,
  132025. 0
  132026. };
  132027. static long _vq_quantlist__44c0_s_p6_0[] = {
  132028. 1,
  132029. 0,
  132030. 2,
  132031. };
  132032. static long _vq_lengthlist__44c0_s_p6_0[] = {
  132033. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  132034. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132035. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  132036. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  132037. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  132038. 10,
  132039. };
  132040. static float _vq_quantthresh__44c0_s_p6_0[] = {
  132041. -5.5, 5.5,
  132042. };
  132043. static long _vq_quantmap__44c0_s_p6_0[] = {
  132044. 1, 0, 2,
  132045. };
  132046. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  132047. _vq_quantthresh__44c0_s_p6_0,
  132048. _vq_quantmap__44c0_s_p6_0,
  132049. 3,
  132050. 3
  132051. };
  132052. static static_codebook _44c0_s_p6_0 = {
  132053. 4, 81,
  132054. _vq_lengthlist__44c0_s_p6_0,
  132055. 1, -529137664, 1618345984, 2, 0,
  132056. _vq_quantlist__44c0_s_p6_0,
  132057. NULL,
  132058. &_vq_auxt__44c0_s_p6_0,
  132059. NULL,
  132060. 0
  132061. };
  132062. static long _vq_quantlist__44c0_s_p6_1[] = {
  132063. 5,
  132064. 4,
  132065. 6,
  132066. 3,
  132067. 7,
  132068. 2,
  132069. 8,
  132070. 1,
  132071. 9,
  132072. 0,
  132073. 10,
  132074. };
  132075. static long _vq_lengthlist__44c0_s_p6_1[] = {
  132076. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  132077. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  132078. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  132079. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  132080. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132081. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  132082. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132083. 10,10,10, 8, 8, 8, 8, 8, 8,
  132084. };
  132085. static float _vq_quantthresh__44c0_s_p6_1[] = {
  132086. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132087. 3.5, 4.5,
  132088. };
  132089. static long _vq_quantmap__44c0_s_p6_1[] = {
  132090. 9, 7, 5, 3, 1, 0, 2, 4,
  132091. 6, 8, 10,
  132092. };
  132093. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  132094. _vq_quantthresh__44c0_s_p6_1,
  132095. _vq_quantmap__44c0_s_p6_1,
  132096. 11,
  132097. 11
  132098. };
  132099. static static_codebook _44c0_s_p6_1 = {
  132100. 2, 121,
  132101. _vq_lengthlist__44c0_s_p6_1,
  132102. 1, -531365888, 1611661312, 4, 0,
  132103. _vq_quantlist__44c0_s_p6_1,
  132104. NULL,
  132105. &_vq_auxt__44c0_s_p6_1,
  132106. NULL,
  132107. 0
  132108. };
  132109. static long _vq_quantlist__44c0_s_p7_0[] = {
  132110. 6,
  132111. 5,
  132112. 7,
  132113. 4,
  132114. 8,
  132115. 3,
  132116. 9,
  132117. 2,
  132118. 10,
  132119. 1,
  132120. 11,
  132121. 0,
  132122. 12,
  132123. };
  132124. static long _vq_lengthlist__44c0_s_p7_0[] = {
  132125. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  132126. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  132127. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132128. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132129. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  132130. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  132131. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  132132. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132133. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132134. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  132135. 0,12,12,11,11,12,12,13,13,
  132136. };
  132137. static float _vq_quantthresh__44c0_s_p7_0[] = {
  132138. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132139. 12.5, 17.5, 22.5, 27.5,
  132140. };
  132141. static long _vq_quantmap__44c0_s_p7_0[] = {
  132142. 11, 9, 7, 5, 3, 1, 0, 2,
  132143. 4, 6, 8, 10, 12,
  132144. };
  132145. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  132146. _vq_quantthresh__44c0_s_p7_0,
  132147. _vq_quantmap__44c0_s_p7_0,
  132148. 13,
  132149. 13
  132150. };
  132151. static static_codebook _44c0_s_p7_0 = {
  132152. 2, 169,
  132153. _vq_lengthlist__44c0_s_p7_0,
  132154. 1, -526516224, 1616117760, 4, 0,
  132155. _vq_quantlist__44c0_s_p7_0,
  132156. NULL,
  132157. &_vq_auxt__44c0_s_p7_0,
  132158. NULL,
  132159. 0
  132160. };
  132161. static long _vq_quantlist__44c0_s_p7_1[] = {
  132162. 2,
  132163. 1,
  132164. 3,
  132165. 0,
  132166. 4,
  132167. };
  132168. static long _vq_lengthlist__44c0_s_p7_1[] = {
  132169. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132170. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132171. };
  132172. static float _vq_quantthresh__44c0_s_p7_1[] = {
  132173. -1.5, -0.5, 0.5, 1.5,
  132174. };
  132175. static long _vq_quantmap__44c0_s_p7_1[] = {
  132176. 3, 1, 0, 2, 4,
  132177. };
  132178. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  132179. _vq_quantthresh__44c0_s_p7_1,
  132180. _vq_quantmap__44c0_s_p7_1,
  132181. 5,
  132182. 5
  132183. };
  132184. static static_codebook _44c0_s_p7_1 = {
  132185. 2, 25,
  132186. _vq_lengthlist__44c0_s_p7_1,
  132187. 1, -533725184, 1611661312, 3, 0,
  132188. _vq_quantlist__44c0_s_p7_1,
  132189. NULL,
  132190. &_vq_auxt__44c0_s_p7_1,
  132191. NULL,
  132192. 0
  132193. };
  132194. static long _vq_quantlist__44c0_s_p8_0[] = {
  132195. 2,
  132196. 1,
  132197. 3,
  132198. 0,
  132199. 4,
  132200. };
  132201. static long _vq_lengthlist__44c0_s_p8_0[] = {
  132202. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  132203. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132204. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132205. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132206. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132207. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132208. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132209. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  132210. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132211. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132212. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132213. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132214. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  132215. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132216. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132217. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  132218. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132219. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132220. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132221. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132222. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132223. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132224. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132225. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132227. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132228. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132229. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132230. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132231. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132232. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132233. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132234. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132235. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132236. 11,11,11,11,11,11,11,11,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,11,11,11,11,11,11,
  132240. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  132241. 11,
  132242. };
  132243. static float _vq_quantthresh__44c0_s_p8_0[] = {
  132244. -331.5, -110.5, 110.5, 331.5,
  132245. };
  132246. static long _vq_quantmap__44c0_s_p8_0[] = {
  132247. 3, 1, 0, 2, 4,
  132248. };
  132249. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  132250. _vq_quantthresh__44c0_s_p8_0,
  132251. _vq_quantmap__44c0_s_p8_0,
  132252. 5,
  132253. 5
  132254. };
  132255. static static_codebook _44c0_s_p8_0 = {
  132256. 4, 625,
  132257. _vq_lengthlist__44c0_s_p8_0,
  132258. 1, -518283264, 1627103232, 3, 0,
  132259. _vq_quantlist__44c0_s_p8_0,
  132260. NULL,
  132261. &_vq_auxt__44c0_s_p8_0,
  132262. NULL,
  132263. 0
  132264. };
  132265. static long _vq_quantlist__44c0_s_p8_1[] = {
  132266. 6,
  132267. 5,
  132268. 7,
  132269. 4,
  132270. 8,
  132271. 3,
  132272. 9,
  132273. 2,
  132274. 10,
  132275. 1,
  132276. 11,
  132277. 0,
  132278. 12,
  132279. };
  132280. static long _vq_lengthlist__44c0_s_p8_1[] = {
  132281. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  132282. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  132283. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  132284. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  132285. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  132286. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  132287. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  132288. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  132289. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  132290. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  132291. 16,13,13,12,12,14,14,15,13,
  132292. };
  132293. static float _vq_quantthresh__44c0_s_p8_1[] = {
  132294. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132295. 42.5, 59.5, 76.5, 93.5,
  132296. };
  132297. static long _vq_quantmap__44c0_s_p8_1[] = {
  132298. 11, 9, 7, 5, 3, 1, 0, 2,
  132299. 4, 6, 8, 10, 12,
  132300. };
  132301. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  132302. _vq_quantthresh__44c0_s_p8_1,
  132303. _vq_quantmap__44c0_s_p8_1,
  132304. 13,
  132305. 13
  132306. };
  132307. static static_codebook _44c0_s_p8_1 = {
  132308. 2, 169,
  132309. _vq_lengthlist__44c0_s_p8_1,
  132310. 1, -522616832, 1620115456, 4, 0,
  132311. _vq_quantlist__44c0_s_p8_1,
  132312. NULL,
  132313. &_vq_auxt__44c0_s_p8_1,
  132314. NULL,
  132315. 0
  132316. };
  132317. static long _vq_quantlist__44c0_s_p8_2[] = {
  132318. 8,
  132319. 7,
  132320. 9,
  132321. 6,
  132322. 10,
  132323. 5,
  132324. 11,
  132325. 4,
  132326. 12,
  132327. 3,
  132328. 13,
  132329. 2,
  132330. 14,
  132331. 1,
  132332. 15,
  132333. 0,
  132334. 16,
  132335. };
  132336. static long _vq_lengthlist__44c0_s_p8_2[] = {
  132337. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132338. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  132339. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  132340. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  132341. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132342. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  132343. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  132344. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  132345. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  132346. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  132347. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  132348. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  132349. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  132350. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  132351. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  132352. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  132353. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  132354. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  132355. 10,
  132356. };
  132357. static float _vq_quantthresh__44c0_s_p8_2[] = {
  132358. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132359. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132360. };
  132361. static long _vq_quantmap__44c0_s_p8_2[] = {
  132362. 15, 13, 11, 9, 7, 5, 3, 1,
  132363. 0, 2, 4, 6, 8, 10, 12, 14,
  132364. 16,
  132365. };
  132366. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  132367. _vq_quantthresh__44c0_s_p8_2,
  132368. _vq_quantmap__44c0_s_p8_2,
  132369. 17,
  132370. 17
  132371. };
  132372. static static_codebook _44c0_s_p8_2 = {
  132373. 2, 289,
  132374. _vq_lengthlist__44c0_s_p8_2,
  132375. 1, -529530880, 1611661312, 5, 0,
  132376. _vq_quantlist__44c0_s_p8_2,
  132377. NULL,
  132378. &_vq_auxt__44c0_s_p8_2,
  132379. NULL,
  132380. 0
  132381. };
  132382. static long _huff_lengthlist__44c0_s_short[] = {
  132383. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  132384. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  132385. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  132386. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  132387. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  132388. 12,
  132389. };
  132390. static static_codebook _huff_book__44c0_s_short = {
  132391. 2, 81,
  132392. _huff_lengthlist__44c0_s_short,
  132393. 0, 0, 0, 0, 0,
  132394. NULL,
  132395. NULL,
  132396. NULL,
  132397. NULL,
  132398. 0
  132399. };
  132400. static long _huff_lengthlist__44c0_sm_long[] = {
  132401. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  132402. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  132403. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  132404. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  132405. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  132406. 13,
  132407. };
  132408. static static_codebook _huff_book__44c0_sm_long = {
  132409. 2, 81,
  132410. _huff_lengthlist__44c0_sm_long,
  132411. 0, 0, 0, 0, 0,
  132412. NULL,
  132413. NULL,
  132414. NULL,
  132415. NULL,
  132416. 0
  132417. };
  132418. static long _vq_quantlist__44c0_sm_p1_0[] = {
  132419. 1,
  132420. 0,
  132421. 2,
  132422. };
  132423. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  132424. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132425. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132429. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132430. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132434. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132435. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132447. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132452. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132457. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  132470. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  132475. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  132480. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  132492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  132497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  132502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  132516. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132521. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132526. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132538. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132543. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  132835. };
  132836. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  132837. -0.5, 0.5,
  132838. };
  132839. static long _vq_quantmap__44c0_sm_p1_0[] = {
  132840. 1, 0, 2,
  132841. };
  132842. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  132843. _vq_quantthresh__44c0_sm_p1_0,
  132844. _vq_quantmap__44c0_sm_p1_0,
  132845. 3,
  132846. 3
  132847. };
  132848. static static_codebook _44c0_sm_p1_0 = {
  132849. 8, 6561,
  132850. _vq_lengthlist__44c0_sm_p1_0,
  132851. 1, -535822336, 1611661312, 2, 0,
  132852. _vq_quantlist__44c0_sm_p1_0,
  132853. NULL,
  132854. &_vq_auxt__44c0_sm_p1_0,
  132855. NULL,
  132856. 0
  132857. };
  132858. static long _vq_quantlist__44c0_sm_p2_0[] = {
  132859. 2,
  132860. 1,
  132861. 3,
  132862. 0,
  132863. 4,
  132864. };
  132865. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  132866. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132869. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  132871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132872. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  132873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  132906. };
  132907. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  132908. -1.5, -0.5, 0.5, 1.5,
  132909. };
  132910. static long _vq_quantmap__44c0_sm_p2_0[] = {
  132911. 3, 1, 0, 2, 4,
  132912. };
  132913. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  132914. _vq_quantthresh__44c0_sm_p2_0,
  132915. _vq_quantmap__44c0_sm_p2_0,
  132916. 5,
  132917. 5
  132918. };
  132919. static static_codebook _44c0_sm_p2_0 = {
  132920. 4, 625,
  132921. _vq_lengthlist__44c0_sm_p2_0,
  132922. 1, -533725184, 1611661312, 3, 0,
  132923. _vq_quantlist__44c0_sm_p2_0,
  132924. NULL,
  132925. &_vq_auxt__44c0_sm_p2_0,
  132926. NULL,
  132927. 0
  132928. };
  132929. static long _vq_quantlist__44c0_sm_p3_0[] = {
  132930. 4,
  132931. 3,
  132932. 5,
  132933. 2,
  132934. 6,
  132935. 1,
  132936. 7,
  132937. 0,
  132938. 8,
  132939. };
  132940. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  132941. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  132942. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  132943. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  132944. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  132945. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132946. 0,
  132947. };
  132948. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  132949. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132950. };
  132951. static long _vq_quantmap__44c0_sm_p3_0[] = {
  132952. 7, 5, 3, 1, 0, 2, 4, 6,
  132953. 8,
  132954. };
  132955. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  132956. _vq_quantthresh__44c0_sm_p3_0,
  132957. _vq_quantmap__44c0_sm_p3_0,
  132958. 9,
  132959. 9
  132960. };
  132961. static static_codebook _44c0_sm_p3_0 = {
  132962. 2, 81,
  132963. _vq_lengthlist__44c0_sm_p3_0,
  132964. 1, -531628032, 1611661312, 4, 0,
  132965. _vq_quantlist__44c0_sm_p3_0,
  132966. NULL,
  132967. &_vq_auxt__44c0_sm_p3_0,
  132968. NULL,
  132969. 0
  132970. };
  132971. static long _vq_quantlist__44c0_sm_p4_0[] = {
  132972. 4,
  132973. 3,
  132974. 5,
  132975. 2,
  132976. 6,
  132977. 1,
  132978. 7,
  132979. 0,
  132980. 8,
  132981. };
  132982. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  132983. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  132984. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  132985. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  132986. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  132987. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132988. 11,
  132989. };
  132990. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  132991. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132992. };
  132993. static long _vq_quantmap__44c0_sm_p4_0[] = {
  132994. 7, 5, 3, 1, 0, 2, 4, 6,
  132995. 8,
  132996. };
  132997. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  132998. _vq_quantthresh__44c0_sm_p4_0,
  132999. _vq_quantmap__44c0_sm_p4_0,
  133000. 9,
  133001. 9
  133002. };
  133003. static static_codebook _44c0_sm_p4_0 = {
  133004. 2, 81,
  133005. _vq_lengthlist__44c0_sm_p4_0,
  133006. 1, -531628032, 1611661312, 4, 0,
  133007. _vq_quantlist__44c0_sm_p4_0,
  133008. NULL,
  133009. &_vq_auxt__44c0_sm_p4_0,
  133010. NULL,
  133011. 0
  133012. };
  133013. static long _vq_quantlist__44c0_sm_p5_0[] = {
  133014. 8,
  133015. 7,
  133016. 9,
  133017. 6,
  133018. 10,
  133019. 5,
  133020. 11,
  133021. 4,
  133022. 12,
  133023. 3,
  133024. 13,
  133025. 2,
  133026. 14,
  133027. 1,
  133028. 15,
  133029. 0,
  133030. 16,
  133031. };
  133032. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  133033. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  133034. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  133035. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133036. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  133037. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  133038. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  133039. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  133040. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  133041. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  133042. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  133043. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133044. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133045. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  133046. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  133047. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  133048. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  133049. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  133050. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  133051. 14,
  133052. };
  133053. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  133054. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133055. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133056. };
  133057. static long _vq_quantmap__44c0_sm_p5_0[] = {
  133058. 15, 13, 11, 9, 7, 5, 3, 1,
  133059. 0, 2, 4, 6, 8, 10, 12, 14,
  133060. 16,
  133061. };
  133062. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  133063. _vq_quantthresh__44c0_sm_p5_0,
  133064. _vq_quantmap__44c0_sm_p5_0,
  133065. 17,
  133066. 17
  133067. };
  133068. static static_codebook _44c0_sm_p5_0 = {
  133069. 2, 289,
  133070. _vq_lengthlist__44c0_sm_p5_0,
  133071. 1, -529530880, 1611661312, 5, 0,
  133072. _vq_quantlist__44c0_sm_p5_0,
  133073. NULL,
  133074. &_vq_auxt__44c0_sm_p5_0,
  133075. NULL,
  133076. 0
  133077. };
  133078. static long _vq_quantlist__44c0_sm_p6_0[] = {
  133079. 1,
  133080. 0,
  133081. 2,
  133082. };
  133083. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  133084. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  133085. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  133086. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  133087. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  133088. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  133089. 11,
  133090. };
  133091. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  133092. -5.5, 5.5,
  133093. };
  133094. static long _vq_quantmap__44c0_sm_p6_0[] = {
  133095. 1, 0, 2,
  133096. };
  133097. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  133098. _vq_quantthresh__44c0_sm_p6_0,
  133099. _vq_quantmap__44c0_sm_p6_0,
  133100. 3,
  133101. 3
  133102. };
  133103. static static_codebook _44c0_sm_p6_0 = {
  133104. 4, 81,
  133105. _vq_lengthlist__44c0_sm_p6_0,
  133106. 1, -529137664, 1618345984, 2, 0,
  133107. _vq_quantlist__44c0_sm_p6_0,
  133108. NULL,
  133109. &_vq_auxt__44c0_sm_p6_0,
  133110. NULL,
  133111. 0
  133112. };
  133113. static long _vq_quantlist__44c0_sm_p6_1[] = {
  133114. 5,
  133115. 4,
  133116. 6,
  133117. 3,
  133118. 7,
  133119. 2,
  133120. 8,
  133121. 1,
  133122. 9,
  133123. 0,
  133124. 10,
  133125. };
  133126. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  133127. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  133128. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  133129. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  133130. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  133131. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  133132. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  133133. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  133134. 10,10,10, 8, 8, 8, 8, 8, 8,
  133135. };
  133136. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  133137. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133138. 3.5, 4.5,
  133139. };
  133140. static long _vq_quantmap__44c0_sm_p6_1[] = {
  133141. 9, 7, 5, 3, 1, 0, 2, 4,
  133142. 6, 8, 10,
  133143. };
  133144. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  133145. _vq_quantthresh__44c0_sm_p6_1,
  133146. _vq_quantmap__44c0_sm_p6_1,
  133147. 11,
  133148. 11
  133149. };
  133150. static static_codebook _44c0_sm_p6_1 = {
  133151. 2, 121,
  133152. _vq_lengthlist__44c0_sm_p6_1,
  133153. 1, -531365888, 1611661312, 4, 0,
  133154. _vq_quantlist__44c0_sm_p6_1,
  133155. NULL,
  133156. &_vq_auxt__44c0_sm_p6_1,
  133157. NULL,
  133158. 0
  133159. };
  133160. static long _vq_quantlist__44c0_sm_p7_0[] = {
  133161. 6,
  133162. 5,
  133163. 7,
  133164. 4,
  133165. 8,
  133166. 3,
  133167. 9,
  133168. 2,
  133169. 10,
  133170. 1,
  133171. 11,
  133172. 0,
  133173. 12,
  133174. };
  133175. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  133176. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133177. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  133178. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133179. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133180. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133181. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  133182. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  133183. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133184. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133185. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  133186. 0,12,12,11,11,13,12,14,14,
  133187. };
  133188. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  133189. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133190. 12.5, 17.5, 22.5, 27.5,
  133191. };
  133192. static long _vq_quantmap__44c0_sm_p7_0[] = {
  133193. 11, 9, 7, 5, 3, 1, 0, 2,
  133194. 4, 6, 8, 10, 12,
  133195. };
  133196. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  133197. _vq_quantthresh__44c0_sm_p7_0,
  133198. _vq_quantmap__44c0_sm_p7_0,
  133199. 13,
  133200. 13
  133201. };
  133202. static static_codebook _44c0_sm_p7_0 = {
  133203. 2, 169,
  133204. _vq_lengthlist__44c0_sm_p7_0,
  133205. 1, -526516224, 1616117760, 4, 0,
  133206. _vq_quantlist__44c0_sm_p7_0,
  133207. NULL,
  133208. &_vq_auxt__44c0_sm_p7_0,
  133209. NULL,
  133210. 0
  133211. };
  133212. static long _vq_quantlist__44c0_sm_p7_1[] = {
  133213. 2,
  133214. 1,
  133215. 3,
  133216. 0,
  133217. 4,
  133218. };
  133219. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  133220. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133221. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  133222. };
  133223. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  133224. -1.5, -0.5, 0.5, 1.5,
  133225. };
  133226. static long _vq_quantmap__44c0_sm_p7_1[] = {
  133227. 3, 1, 0, 2, 4,
  133228. };
  133229. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  133230. _vq_quantthresh__44c0_sm_p7_1,
  133231. _vq_quantmap__44c0_sm_p7_1,
  133232. 5,
  133233. 5
  133234. };
  133235. static static_codebook _44c0_sm_p7_1 = {
  133236. 2, 25,
  133237. _vq_lengthlist__44c0_sm_p7_1,
  133238. 1, -533725184, 1611661312, 3, 0,
  133239. _vq_quantlist__44c0_sm_p7_1,
  133240. NULL,
  133241. &_vq_auxt__44c0_sm_p7_1,
  133242. NULL,
  133243. 0
  133244. };
  133245. static long _vq_quantlist__44c0_sm_p8_0[] = {
  133246. 4,
  133247. 3,
  133248. 5,
  133249. 2,
  133250. 6,
  133251. 1,
  133252. 7,
  133253. 0,
  133254. 8,
  133255. };
  133256. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  133257. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  133258. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  133259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133260. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133261. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  133262. 12,
  133263. };
  133264. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  133265. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  133266. };
  133267. static long _vq_quantmap__44c0_sm_p8_0[] = {
  133268. 7, 5, 3, 1, 0, 2, 4, 6,
  133269. 8,
  133270. };
  133271. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  133272. _vq_quantthresh__44c0_sm_p8_0,
  133273. _vq_quantmap__44c0_sm_p8_0,
  133274. 9,
  133275. 9
  133276. };
  133277. static static_codebook _44c0_sm_p8_0 = {
  133278. 2, 81,
  133279. _vq_lengthlist__44c0_sm_p8_0,
  133280. 1, -516186112, 1627103232, 4, 0,
  133281. _vq_quantlist__44c0_sm_p8_0,
  133282. NULL,
  133283. &_vq_auxt__44c0_sm_p8_0,
  133284. NULL,
  133285. 0
  133286. };
  133287. static long _vq_quantlist__44c0_sm_p8_1[] = {
  133288. 6,
  133289. 5,
  133290. 7,
  133291. 4,
  133292. 8,
  133293. 3,
  133294. 9,
  133295. 2,
  133296. 10,
  133297. 1,
  133298. 11,
  133299. 0,
  133300. 12,
  133301. };
  133302. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  133303. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133304. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  133305. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  133306. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  133307. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  133308. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  133309. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  133310. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  133311. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  133312. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  133313. 20,13,13,12,12,16,13,15,13,
  133314. };
  133315. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  133316. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133317. 42.5, 59.5, 76.5, 93.5,
  133318. };
  133319. static long _vq_quantmap__44c0_sm_p8_1[] = {
  133320. 11, 9, 7, 5, 3, 1, 0, 2,
  133321. 4, 6, 8, 10, 12,
  133322. };
  133323. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  133324. _vq_quantthresh__44c0_sm_p8_1,
  133325. _vq_quantmap__44c0_sm_p8_1,
  133326. 13,
  133327. 13
  133328. };
  133329. static static_codebook _44c0_sm_p8_1 = {
  133330. 2, 169,
  133331. _vq_lengthlist__44c0_sm_p8_1,
  133332. 1, -522616832, 1620115456, 4, 0,
  133333. _vq_quantlist__44c0_sm_p8_1,
  133334. NULL,
  133335. &_vq_auxt__44c0_sm_p8_1,
  133336. NULL,
  133337. 0
  133338. };
  133339. static long _vq_quantlist__44c0_sm_p8_2[] = {
  133340. 8,
  133341. 7,
  133342. 9,
  133343. 6,
  133344. 10,
  133345. 5,
  133346. 11,
  133347. 4,
  133348. 12,
  133349. 3,
  133350. 13,
  133351. 2,
  133352. 14,
  133353. 1,
  133354. 15,
  133355. 0,
  133356. 16,
  133357. };
  133358. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  133359. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133360. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133361. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  133362. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133363. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  133364. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133365. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133366. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133367. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  133368. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  133369. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  133370. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  133371. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  133372. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  133373. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133374. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  133375. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  133376. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  133377. 9,
  133378. };
  133379. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  133380. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133381. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133382. };
  133383. static long _vq_quantmap__44c0_sm_p8_2[] = {
  133384. 15, 13, 11, 9, 7, 5, 3, 1,
  133385. 0, 2, 4, 6, 8, 10, 12, 14,
  133386. 16,
  133387. };
  133388. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  133389. _vq_quantthresh__44c0_sm_p8_2,
  133390. _vq_quantmap__44c0_sm_p8_2,
  133391. 17,
  133392. 17
  133393. };
  133394. static static_codebook _44c0_sm_p8_2 = {
  133395. 2, 289,
  133396. _vq_lengthlist__44c0_sm_p8_2,
  133397. 1, -529530880, 1611661312, 5, 0,
  133398. _vq_quantlist__44c0_sm_p8_2,
  133399. NULL,
  133400. &_vq_auxt__44c0_sm_p8_2,
  133401. NULL,
  133402. 0
  133403. };
  133404. static long _huff_lengthlist__44c0_sm_short[] = {
  133405. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  133406. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  133407. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  133408. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  133409. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  133410. 12,
  133411. };
  133412. static static_codebook _huff_book__44c0_sm_short = {
  133413. 2, 81,
  133414. _huff_lengthlist__44c0_sm_short,
  133415. 0, 0, 0, 0, 0,
  133416. NULL,
  133417. NULL,
  133418. NULL,
  133419. NULL,
  133420. 0
  133421. };
  133422. static long _huff_lengthlist__44c1_s_long[] = {
  133423. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  133424. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  133425. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  133426. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  133427. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  133428. 11,
  133429. };
  133430. static static_codebook _huff_book__44c1_s_long = {
  133431. 2, 81,
  133432. _huff_lengthlist__44c1_s_long,
  133433. 0, 0, 0, 0, 0,
  133434. NULL,
  133435. NULL,
  133436. NULL,
  133437. NULL,
  133438. 0
  133439. };
  133440. static long _vq_quantlist__44c1_s_p1_0[] = {
  133441. 1,
  133442. 0,
  133443. 2,
  133444. };
  133445. static long _vq_lengthlist__44c1_s_p1_0[] = {
  133446. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  133447. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133451. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  133452. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133456. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133457. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133469. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133474. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133479. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  133492. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  133497. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  133502. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  133514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  133519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  133524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  133538. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  133543. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  133548. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133560. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133565. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  133857. };
  133858. static float _vq_quantthresh__44c1_s_p1_0[] = {
  133859. -0.5, 0.5,
  133860. };
  133861. static long _vq_quantmap__44c1_s_p1_0[] = {
  133862. 1, 0, 2,
  133863. };
  133864. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  133865. _vq_quantthresh__44c1_s_p1_0,
  133866. _vq_quantmap__44c1_s_p1_0,
  133867. 3,
  133868. 3
  133869. };
  133870. static static_codebook _44c1_s_p1_0 = {
  133871. 8, 6561,
  133872. _vq_lengthlist__44c1_s_p1_0,
  133873. 1, -535822336, 1611661312, 2, 0,
  133874. _vq_quantlist__44c1_s_p1_0,
  133875. NULL,
  133876. &_vq_auxt__44c1_s_p1_0,
  133877. NULL,
  133878. 0
  133879. };
  133880. static long _vq_quantlist__44c1_s_p2_0[] = {
  133881. 2,
  133882. 1,
  133883. 3,
  133884. 0,
  133885. 4,
  133886. };
  133887. static long _vq_lengthlist__44c1_s_p2_0[] = {
  133888. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  133890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133891. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  133893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133894. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  133895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  133928. };
  133929. static float _vq_quantthresh__44c1_s_p2_0[] = {
  133930. -1.5, -0.5, 0.5, 1.5,
  133931. };
  133932. static long _vq_quantmap__44c1_s_p2_0[] = {
  133933. 3, 1, 0, 2, 4,
  133934. };
  133935. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  133936. _vq_quantthresh__44c1_s_p2_0,
  133937. _vq_quantmap__44c1_s_p2_0,
  133938. 5,
  133939. 5
  133940. };
  133941. static static_codebook _44c1_s_p2_0 = {
  133942. 4, 625,
  133943. _vq_lengthlist__44c1_s_p2_0,
  133944. 1, -533725184, 1611661312, 3, 0,
  133945. _vq_quantlist__44c1_s_p2_0,
  133946. NULL,
  133947. &_vq_auxt__44c1_s_p2_0,
  133948. NULL,
  133949. 0
  133950. };
  133951. static long _vq_quantlist__44c1_s_p3_0[] = {
  133952. 4,
  133953. 3,
  133954. 5,
  133955. 2,
  133956. 6,
  133957. 1,
  133958. 7,
  133959. 0,
  133960. 8,
  133961. };
  133962. static long _vq_lengthlist__44c1_s_p3_0[] = {
  133963. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  133964. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133965. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133966. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133967. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133968. 0,
  133969. };
  133970. static float _vq_quantthresh__44c1_s_p3_0[] = {
  133971. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133972. };
  133973. static long _vq_quantmap__44c1_s_p3_0[] = {
  133974. 7, 5, 3, 1, 0, 2, 4, 6,
  133975. 8,
  133976. };
  133977. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  133978. _vq_quantthresh__44c1_s_p3_0,
  133979. _vq_quantmap__44c1_s_p3_0,
  133980. 9,
  133981. 9
  133982. };
  133983. static static_codebook _44c1_s_p3_0 = {
  133984. 2, 81,
  133985. _vq_lengthlist__44c1_s_p3_0,
  133986. 1, -531628032, 1611661312, 4, 0,
  133987. _vq_quantlist__44c1_s_p3_0,
  133988. NULL,
  133989. &_vq_auxt__44c1_s_p3_0,
  133990. NULL,
  133991. 0
  133992. };
  133993. static long _vq_quantlist__44c1_s_p4_0[] = {
  133994. 4,
  133995. 3,
  133996. 5,
  133997. 2,
  133998. 6,
  133999. 1,
  134000. 7,
  134001. 0,
  134002. 8,
  134003. };
  134004. static long _vq_lengthlist__44c1_s_p4_0[] = {
  134005. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  134006. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  134007. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  134008. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  134009. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  134010. 11,
  134011. };
  134012. static float _vq_quantthresh__44c1_s_p4_0[] = {
  134013. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134014. };
  134015. static long _vq_quantmap__44c1_s_p4_0[] = {
  134016. 7, 5, 3, 1, 0, 2, 4, 6,
  134017. 8,
  134018. };
  134019. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  134020. _vq_quantthresh__44c1_s_p4_0,
  134021. _vq_quantmap__44c1_s_p4_0,
  134022. 9,
  134023. 9
  134024. };
  134025. static static_codebook _44c1_s_p4_0 = {
  134026. 2, 81,
  134027. _vq_lengthlist__44c1_s_p4_0,
  134028. 1, -531628032, 1611661312, 4, 0,
  134029. _vq_quantlist__44c1_s_p4_0,
  134030. NULL,
  134031. &_vq_auxt__44c1_s_p4_0,
  134032. NULL,
  134033. 0
  134034. };
  134035. static long _vq_quantlist__44c1_s_p5_0[] = {
  134036. 8,
  134037. 7,
  134038. 9,
  134039. 6,
  134040. 10,
  134041. 5,
  134042. 11,
  134043. 4,
  134044. 12,
  134045. 3,
  134046. 13,
  134047. 2,
  134048. 14,
  134049. 1,
  134050. 15,
  134051. 0,
  134052. 16,
  134053. };
  134054. static long _vq_lengthlist__44c1_s_p5_0[] = {
  134055. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134056. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  134057. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  134058. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134059. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  134060. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  134061. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  134062. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134063. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  134064. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  134065. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  134066. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  134067. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  134068. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  134069. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  134070. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  134071. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  134072. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  134073. 14,
  134074. };
  134075. static float _vq_quantthresh__44c1_s_p5_0[] = {
  134076. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134077. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134078. };
  134079. static long _vq_quantmap__44c1_s_p5_0[] = {
  134080. 15, 13, 11, 9, 7, 5, 3, 1,
  134081. 0, 2, 4, 6, 8, 10, 12, 14,
  134082. 16,
  134083. };
  134084. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  134085. _vq_quantthresh__44c1_s_p5_0,
  134086. _vq_quantmap__44c1_s_p5_0,
  134087. 17,
  134088. 17
  134089. };
  134090. static static_codebook _44c1_s_p5_0 = {
  134091. 2, 289,
  134092. _vq_lengthlist__44c1_s_p5_0,
  134093. 1, -529530880, 1611661312, 5, 0,
  134094. _vq_quantlist__44c1_s_p5_0,
  134095. NULL,
  134096. &_vq_auxt__44c1_s_p5_0,
  134097. NULL,
  134098. 0
  134099. };
  134100. static long _vq_quantlist__44c1_s_p6_0[] = {
  134101. 1,
  134102. 0,
  134103. 2,
  134104. };
  134105. static long _vq_lengthlist__44c1_s_p6_0[] = {
  134106. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  134107. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  134108. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  134109. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  134110. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  134111. 11,
  134112. };
  134113. static float _vq_quantthresh__44c1_s_p6_0[] = {
  134114. -5.5, 5.5,
  134115. };
  134116. static long _vq_quantmap__44c1_s_p6_0[] = {
  134117. 1, 0, 2,
  134118. };
  134119. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  134120. _vq_quantthresh__44c1_s_p6_0,
  134121. _vq_quantmap__44c1_s_p6_0,
  134122. 3,
  134123. 3
  134124. };
  134125. static static_codebook _44c1_s_p6_0 = {
  134126. 4, 81,
  134127. _vq_lengthlist__44c1_s_p6_0,
  134128. 1, -529137664, 1618345984, 2, 0,
  134129. _vq_quantlist__44c1_s_p6_0,
  134130. NULL,
  134131. &_vq_auxt__44c1_s_p6_0,
  134132. NULL,
  134133. 0
  134134. };
  134135. static long _vq_quantlist__44c1_s_p6_1[] = {
  134136. 5,
  134137. 4,
  134138. 6,
  134139. 3,
  134140. 7,
  134141. 2,
  134142. 8,
  134143. 1,
  134144. 9,
  134145. 0,
  134146. 10,
  134147. };
  134148. static long _vq_lengthlist__44c1_s_p6_1[] = {
  134149. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  134150. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  134151. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  134152. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  134153. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  134154. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  134155. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  134156. 10,10,10, 8, 8, 8, 8, 8, 8,
  134157. };
  134158. static float _vq_quantthresh__44c1_s_p6_1[] = {
  134159. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134160. 3.5, 4.5,
  134161. };
  134162. static long _vq_quantmap__44c1_s_p6_1[] = {
  134163. 9, 7, 5, 3, 1, 0, 2, 4,
  134164. 6, 8, 10,
  134165. };
  134166. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  134167. _vq_quantthresh__44c1_s_p6_1,
  134168. _vq_quantmap__44c1_s_p6_1,
  134169. 11,
  134170. 11
  134171. };
  134172. static static_codebook _44c1_s_p6_1 = {
  134173. 2, 121,
  134174. _vq_lengthlist__44c1_s_p6_1,
  134175. 1, -531365888, 1611661312, 4, 0,
  134176. _vq_quantlist__44c1_s_p6_1,
  134177. NULL,
  134178. &_vq_auxt__44c1_s_p6_1,
  134179. NULL,
  134180. 0
  134181. };
  134182. static long _vq_quantlist__44c1_s_p7_0[] = {
  134183. 6,
  134184. 5,
  134185. 7,
  134186. 4,
  134187. 8,
  134188. 3,
  134189. 9,
  134190. 2,
  134191. 10,
  134192. 1,
  134193. 11,
  134194. 0,
  134195. 12,
  134196. };
  134197. static long _vq_lengthlist__44c1_s_p7_0[] = {
  134198. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  134199. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  134200. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134201. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134202. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  134203. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  134204. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  134205. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  134206. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  134207. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  134208. 0,12,11,11,11,13,10,14,13,
  134209. };
  134210. static float _vq_quantthresh__44c1_s_p7_0[] = {
  134211. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134212. 12.5, 17.5, 22.5, 27.5,
  134213. };
  134214. static long _vq_quantmap__44c1_s_p7_0[] = {
  134215. 11, 9, 7, 5, 3, 1, 0, 2,
  134216. 4, 6, 8, 10, 12,
  134217. };
  134218. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  134219. _vq_quantthresh__44c1_s_p7_0,
  134220. _vq_quantmap__44c1_s_p7_0,
  134221. 13,
  134222. 13
  134223. };
  134224. static static_codebook _44c1_s_p7_0 = {
  134225. 2, 169,
  134226. _vq_lengthlist__44c1_s_p7_0,
  134227. 1, -526516224, 1616117760, 4, 0,
  134228. _vq_quantlist__44c1_s_p7_0,
  134229. NULL,
  134230. &_vq_auxt__44c1_s_p7_0,
  134231. NULL,
  134232. 0
  134233. };
  134234. static long _vq_quantlist__44c1_s_p7_1[] = {
  134235. 2,
  134236. 1,
  134237. 3,
  134238. 0,
  134239. 4,
  134240. };
  134241. static long _vq_lengthlist__44c1_s_p7_1[] = {
  134242. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134243. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134244. };
  134245. static float _vq_quantthresh__44c1_s_p7_1[] = {
  134246. -1.5, -0.5, 0.5, 1.5,
  134247. };
  134248. static long _vq_quantmap__44c1_s_p7_1[] = {
  134249. 3, 1, 0, 2, 4,
  134250. };
  134251. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  134252. _vq_quantthresh__44c1_s_p7_1,
  134253. _vq_quantmap__44c1_s_p7_1,
  134254. 5,
  134255. 5
  134256. };
  134257. static static_codebook _44c1_s_p7_1 = {
  134258. 2, 25,
  134259. _vq_lengthlist__44c1_s_p7_1,
  134260. 1, -533725184, 1611661312, 3, 0,
  134261. _vq_quantlist__44c1_s_p7_1,
  134262. NULL,
  134263. &_vq_auxt__44c1_s_p7_1,
  134264. NULL,
  134265. 0
  134266. };
  134267. static long _vq_quantlist__44c1_s_p8_0[] = {
  134268. 6,
  134269. 5,
  134270. 7,
  134271. 4,
  134272. 8,
  134273. 3,
  134274. 9,
  134275. 2,
  134276. 10,
  134277. 1,
  134278. 11,
  134279. 0,
  134280. 12,
  134281. };
  134282. static long _vq_lengthlist__44c1_s_p8_0[] = {
  134283. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  134284. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  134285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134286. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134287. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134288. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134289. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134291. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134292. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134293. 10,10,10,10,10,10,10,10,10,
  134294. };
  134295. static float _vq_quantthresh__44c1_s_p8_0[] = {
  134296. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  134297. 552.5, 773.5, 994.5, 1215.5,
  134298. };
  134299. static long _vq_quantmap__44c1_s_p8_0[] = {
  134300. 11, 9, 7, 5, 3, 1, 0, 2,
  134301. 4, 6, 8, 10, 12,
  134302. };
  134303. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  134304. _vq_quantthresh__44c1_s_p8_0,
  134305. _vq_quantmap__44c1_s_p8_0,
  134306. 13,
  134307. 13
  134308. };
  134309. static static_codebook _44c1_s_p8_0 = {
  134310. 2, 169,
  134311. _vq_lengthlist__44c1_s_p8_0,
  134312. 1, -514541568, 1627103232, 4, 0,
  134313. _vq_quantlist__44c1_s_p8_0,
  134314. NULL,
  134315. &_vq_auxt__44c1_s_p8_0,
  134316. NULL,
  134317. 0
  134318. };
  134319. static long _vq_quantlist__44c1_s_p8_1[] = {
  134320. 6,
  134321. 5,
  134322. 7,
  134323. 4,
  134324. 8,
  134325. 3,
  134326. 9,
  134327. 2,
  134328. 10,
  134329. 1,
  134330. 11,
  134331. 0,
  134332. 12,
  134333. };
  134334. static long _vq_lengthlist__44c1_s_p8_1[] = {
  134335. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134336. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  134337. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  134338. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  134339. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  134340. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  134341. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  134342. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  134343. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  134344. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  134345. 16,13,12,12,11,14,12,15,13,
  134346. };
  134347. static float _vq_quantthresh__44c1_s_p8_1[] = {
  134348. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134349. 42.5, 59.5, 76.5, 93.5,
  134350. };
  134351. static long _vq_quantmap__44c1_s_p8_1[] = {
  134352. 11, 9, 7, 5, 3, 1, 0, 2,
  134353. 4, 6, 8, 10, 12,
  134354. };
  134355. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  134356. _vq_quantthresh__44c1_s_p8_1,
  134357. _vq_quantmap__44c1_s_p8_1,
  134358. 13,
  134359. 13
  134360. };
  134361. static static_codebook _44c1_s_p8_1 = {
  134362. 2, 169,
  134363. _vq_lengthlist__44c1_s_p8_1,
  134364. 1, -522616832, 1620115456, 4, 0,
  134365. _vq_quantlist__44c1_s_p8_1,
  134366. NULL,
  134367. &_vq_auxt__44c1_s_p8_1,
  134368. NULL,
  134369. 0
  134370. };
  134371. static long _vq_quantlist__44c1_s_p8_2[] = {
  134372. 8,
  134373. 7,
  134374. 9,
  134375. 6,
  134376. 10,
  134377. 5,
  134378. 11,
  134379. 4,
  134380. 12,
  134381. 3,
  134382. 13,
  134383. 2,
  134384. 14,
  134385. 1,
  134386. 15,
  134387. 0,
  134388. 16,
  134389. };
  134390. static long _vq_lengthlist__44c1_s_p8_2[] = {
  134391. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  134392. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134393. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  134394. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  134395. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  134396. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  134397. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  134398. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  134399. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  134400. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  134401. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  134402. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134403. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  134404. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  134405. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  134406. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  134407. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  134408. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  134409. 9,
  134410. };
  134411. static float _vq_quantthresh__44c1_s_p8_2[] = {
  134412. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134413. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134414. };
  134415. static long _vq_quantmap__44c1_s_p8_2[] = {
  134416. 15, 13, 11, 9, 7, 5, 3, 1,
  134417. 0, 2, 4, 6, 8, 10, 12, 14,
  134418. 16,
  134419. };
  134420. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  134421. _vq_quantthresh__44c1_s_p8_2,
  134422. _vq_quantmap__44c1_s_p8_2,
  134423. 17,
  134424. 17
  134425. };
  134426. static static_codebook _44c1_s_p8_2 = {
  134427. 2, 289,
  134428. _vq_lengthlist__44c1_s_p8_2,
  134429. 1, -529530880, 1611661312, 5, 0,
  134430. _vq_quantlist__44c1_s_p8_2,
  134431. NULL,
  134432. &_vq_auxt__44c1_s_p8_2,
  134433. NULL,
  134434. 0
  134435. };
  134436. static long _huff_lengthlist__44c1_s_short[] = {
  134437. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  134438. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  134439. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  134440. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  134441. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  134442. 11,
  134443. };
  134444. static static_codebook _huff_book__44c1_s_short = {
  134445. 2, 81,
  134446. _huff_lengthlist__44c1_s_short,
  134447. 0, 0, 0, 0, 0,
  134448. NULL,
  134449. NULL,
  134450. NULL,
  134451. NULL,
  134452. 0
  134453. };
  134454. static long _huff_lengthlist__44c1_sm_long[] = {
  134455. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  134456. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  134457. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  134458. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  134459. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  134460. 11,
  134461. };
  134462. static static_codebook _huff_book__44c1_sm_long = {
  134463. 2, 81,
  134464. _huff_lengthlist__44c1_sm_long,
  134465. 0, 0, 0, 0, 0,
  134466. NULL,
  134467. NULL,
  134468. NULL,
  134469. NULL,
  134470. 0
  134471. };
  134472. static long _vq_quantlist__44c1_sm_p1_0[] = {
  134473. 1,
  134474. 0,
  134475. 2,
  134476. };
  134477. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  134478. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134479. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134483. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  134484. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134488. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134489. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134501. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134506. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134511. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  134524. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  134529. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  134534. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  134546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  134551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  134556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134570. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134575. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  134580. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134592. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134597. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  134889. };
  134890. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  134891. -0.5, 0.5,
  134892. };
  134893. static long _vq_quantmap__44c1_sm_p1_0[] = {
  134894. 1, 0, 2,
  134895. };
  134896. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  134897. _vq_quantthresh__44c1_sm_p1_0,
  134898. _vq_quantmap__44c1_sm_p1_0,
  134899. 3,
  134900. 3
  134901. };
  134902. static static_codebook _44c1_sm_p1_0 = {
  134903. 8, 6561,
  134904. _vq_lengthlist__44c1_sm_p1_0,
  134905. 1, -535822336, 1611661312, 2, 0,
  134906. _vq_quantlist__44c1_sm_p1_0,
  134907. NULL,
  134908. &_vq_auxt__44c1_sm_p1_0,
  134909. NULL,
  134910. 0
  134911. };
  134912. static long _vq_quantlist__44c1_sm_p2_0[] = {
  134913. 2,
  134914. 1,
  134915. 3,
  134916. 0,
  134917. 4,
  134918. };
  134919. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  134920. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  134922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134923. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  134925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134926. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  134927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  134960. };
  134961. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  134962. -1.5, -0.5, 0.5, 1.5,
  134963. };
  134964. static long _vq_quantmap__44c1_sm_p2_0[] = {
  134965. 3, 1, 0, 2, 4,
  134966. };
  134967. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  134968. _vq_quantthresh__44c1_sm_p2_0,
  134969. _vq_quantmap__44c1_sm_p2_0,
  134970. 5,
  134971. 5
  134972. };
  134973. static static_codebook _44c1_sm_p2_0 = {
  134974. 4, 625,
  134975. _vq_lengthlist__44c1_sm_p2_0,
  134976. 1, -533725184, 1611661312, 3, 0,
  134977. _vq_quantlist__44c1_sm_p2_0,
  134978. NULL,
  134979. &_vq_auxt__44c1_sm_p2_0,
  134980. NULL,
  134981. 0
  134982. };
  134983. static long _vq_quantlist__44c1_sm_p3_0[] = {
  134984. 4,
  134985. 3,
  134986. 5,
  134987. 2,
  134988. 6,
  134989. 1,
  134990. 7,
  134991. 0,
  134992. 8,
  134993. };
  134994. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  134995. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  134996. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  134997. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  134998. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  134999. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135000. 0,
  135001. };
  135002. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  135003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135004. };
  135005. static long _vq_quantmap__44c1_sm_p3_0[] = {
  135006. 7, 5, 3, 1, 0, 2, 4, 6,
  135007. 8,
  135008. };
  135009. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  135010. _vq_quantthresh__44c1_sm_p3_0,
  135011. _vq_quantmap__44c1_sm_p3_0,
  135012. 9,
  135013. 9
  135014. };
  135015. static static_codebook _44c1_sm_p3_0 = {
  135016. 2, 81,
  135017. _vq_lengthlist__44c1_sm_p3_0,
  135018. 1, -531628032, 1611661312, 4, 0,
  135019. _vq_quantlist__44c1_sm_p3_0,
  135020. NULL,
  135021. &_vq_auxt__44c1_sm_p3_0,
  135022. NULL,
  135023. 0
  135024. };
  135025. static long _vq_quantlist__44c1_sm_p4_0[] = {
  135026. 4,
  135027. 3,
  135028. 5,
  135029. 2,
  135030. 6,
  135031. 1,
  135032. 7,
  135033. 0,
  135034. 8,
  135035. };
  135036. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  135037. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  135038. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  135039. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  135040. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  135041. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  135042. 11,
  135043. };
  135044. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  135045. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135046. };
  135047. static long _vq_quantmap__44c1_sm_p4_0[] = {
  135048. 7, 5, 3, 1, 0, 2, 4, 6,
  135049. 8,
  135050. };
  135051. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  135052. _vq_quantthresh__44c1_sm_p4_0,
  135053. _vq_quantmap__44c1_sm_p4_0,
  135054. 9,
  135055. 9
  135056. };
  135057. static static_codebook _44c1_sm_p4_0 = {
  135058. 2, 81,
  135059. _vq_lengthlist__44c1_sm_p4_0,
  135060. 1, -531628032, 1611661312, 4, 0,
  135061. _vq_quantlist__44c1_sm_p4_0,
  135062. NULL,
  135063. &_vq_auxt__44c1_sm_p4_0,
  135064. NULL,
  135065. 0
  135066. };
  135067. static long _vq_quantlist__44c1_sm_p5_0[] = {
  135068. 8,
  135069. 7,
  135070. 9,
  135071. 6,
  135072. 10,
  135073. 5,
  135074. 11,
  135075. 4,
  135076. 12,
  135077. 3,
  135078. 13,
  135079. 2,
  135080. 14,
  135081. 1,
  135082. 15,
  135083. 0,
  135084. 16,
  135085. };
  135086. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  135087. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  135088. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  135089. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  135090. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  135091. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  135092. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  135093. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  135094. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  135095. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  135096. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  135097. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  135098. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  135099. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  135100. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  135101. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  135102. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  135103. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  135104. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  135105. 14,
  135106. };
  135107. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  135108. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135109. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135110. };
  135111. static long _vq_quantmap__44c1_sm_p5_0[] = {
  135112. 15, 13, 11, 9, 7, 5, 3, 1,
  135113. 0, 2, 4, 6, 8, 10, 12, 14,
  135114. 16,
  135115. };
  135116. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  135117. _vq_quantthresh__44c1_sm_p5_0,
  135118. _vq_quantmap__44c1_sm_p5_0,
  135119. 17,
  135120. 17
  135121. };
  135122. static static_codebook _44c1_sm_p5_0 = {
  135123. 2, 289,
  135124. _vq_lengthlist__44c1_sm_p5_0,
  135125. 1, -529530880, 1611661312, 5, 0,
  135126. _vq_quantlist__44c1_sm_p5_0,
  135127. NULL,
  135128. &_vq_auxt__44c1_sm_p5_0,
  135129. NULL,
  135130. 0
  135131. };
  135132. static long _vq_quantlist__44c1_sm_p6_0[] = {
  135133. 1,
  135134. 0,
  135135. 2,
  135136. };
  135137. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  135138. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  135139. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135140. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  135141. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  135142. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  135143. 11,
  135144. };
  135145. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  135146. -5.5, 5.5,
  135147. };
  135148. static long _vq_quantmap__44c1_sm_p6_0[] = {
  135149. 1, 0, 2,
  135150. };
  135151. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  135152. _vq_quantthresh__44c1_sm_p6_0,
  135153. _vq_quantmap__44c1_sm_p6_0,
  135154. 3,
  135155. 3
  135156. };
  135157. static static_codebook _44c1_sm_p6_0 = {
  135158. 4, 81,
  135159. _vq_lengthlist__44c1_sm_p6_0,
  135160. 1, -529137664, 1618345984, 2, 0,
  135161. _vq_quantlist__44c1_sm_p6_0,
  135162. NULL,
  135163. &_vq_auxt__44c1_sm_p6_0,
  135164. NULL,
  135165. 0
  135166. };
  135167. static long _vq_quantlist__44c1_sm_p6_1[] = {
  135168. 5,
  135169. 4,
  135170. 6,
  135171. 3,
  135172. 7,
  135173. 2,
  135174. 8,
  135175. 1,
  135176. 9,
  135177. 0,
  135178. 10,
  135179. };
  135180. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  135181. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135182. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135183. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135184. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  135185. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  135186. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  135187. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  135188. 10,10,10, 8, 8, 8, 8, 8, 8,
  135189. };
  135190. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  135191. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135192. 3.5, 4.5,
  135193. };
  135194. static long _vq_quantmap__44c1_sm_p6_1[] = {
  135195. 9, 7, 5, 3, 1, 0, 2, 4,
  135196. 6, 8, 10,
  135197. };
  135198. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  135199. _vq_quantthresh__44c1_sm_p6_1,
  135200. _vq_quantmap__44c1_sm_p6_1,
  135201. 11,
  135202. 11
  135203. };
  135204. static static_codebook _44c1_sm_p6_1 = {
  135205. 2, 121,
  135206. _vq_lengthlist__44c1_sm_p6_1,
  135207. 1, -531365888, 1611661312, 4, 0,
  135208. _vq_quantlist__44c1_sm_p6_1,
  135209. NULL,
  135210. &_vq_auxt__44c1_sm_p6_1,
  135211. NULL,
  135212. 0
  135213. };
  135214. static long _vq_quantlist__44c1_sm_p7_0[] = {
  135215. 6,
  135216. 5,
  135217. 7,
  135218. 4,
  135219. 8,
  135220. 3,
  135221. 9,
  135222. 2,
  135223. 10,
  135224. 1,
  135225. 11,
  135226. 0,
  135227. 12,
  135228. };
  135229. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  135230. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  135231. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  135232. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135233. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135234. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  135235. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  135236. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  135237. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  135238. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  135239. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  135240. 0,12,12,11,11,13,12,14,13,
  135241. };
  135242. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  135243. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135244. 12.5, 17.5, 22.5, 27.5,
  135245. };
  135246. static long _vq_quantmap__44c1_sm_p7_0[] = {
  135247. 11, 9, 7, 5, 3, 1, 0, 2,
  135248. 4, 6, 8, 10, 12,
  135249. };
  135250. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  135251. _vq_quantthresh__44c1_sm_p7_0,
  135252. _vq_quantmap__44c1_sm_p7_0,
  135253. 13,
  135254. 13
  135255. };
  135256. static static_codebook _44c1_sm_p7_0 = {
  135257. 2, 169,
  135258. _vq_lengthlist__44c1_sm_p7_0,
  135259. 1, -526516224, 1616117760, 4, 0,
  135260. _vq_quantlist__44c1_sm_p7_0,
  135261. NULL,
  135262. &_vq_auxt__44c1_sm_p7_0,
  135263. NULL,
  135264. 0
  135265. };
  135266. static long _vq_quantlist__44c1_sm_p7_1[] = {
  135267. 2,
  135268. 1,
  135269. 3,
  135270. 0,
  135271. 4,
  135272. };
  135273. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  135274. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135275. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135276. };
  135277. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  135278. -1.5, -0.5, 0.5, 1.5,
  135279. };
  135280. static long _vq_quantmap__44c1_sm_p7_1[] = {
  135281. 3, 1, 0, 2, 4,
  135282. };
  135283. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  135284. _vq_quantthresh__44c1_sm_p7_1,
  135285. _vq_quantmap__44c1_sm_p7_1,
  135286. 5,
  135287. 5
  135288. };
  135289. static static_codebook _44c1_sm_p7_1 = {
  135290. 2, 25,
  135291. _vq_lengthlist__44c1_sm_p7_1,
  135292. 1, -533725184, 1611661312, 3, 0,
  135293. _vq_quantlist__44c1_sm_p7_1,
  135294. NULL,
  135295. &_vq_auxt__44c1_sm_p7_1,
  135296. NULL,
  135297. 0
  135298. };
  135299. static long _vq_quantlist__44c1_sm_p8_0[] = {
  135300. 6,
  135301. 5,
  135302. 7,
  135303. 4,
  135304. 8,
  135305. 3,
  135306. 9,
  135307. 2,
  135308. 10,
  135309. 1,
  135310. 11,
  135311. 0,
  135312. 12,
  135313. };
  135314. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  135315. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  135316. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  135317. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135318. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135319. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135320. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135321. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135322. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135323. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135324. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  135325. 13,13,13,13,13,13,13,13,13,
  135326. };
  135327. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  135328. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  135329. 552.5, 773.5, 994.5, 1215.5,
  135330. };
  135331. static long _vq_quantmap__44c1_sm_p8_0[] = {
  135332. 11, 9, 7, 5, 3, 1, 0, 2,
  135333. 4, 6, 8, 10, 12,
  135334. };
  135335. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  135336. _vq_quantthresh__44c1_sm_p8_0,
  135337. _vq_quantmap__44c1_sm_p8_0,
  135338. 13,
  135339. 13
  135340. };
  135341. static static_codebook _44c1_sm_p8_0 = {
  135342. 2, 169,
  135343. _vq_lengthlist__44c1_sm_p8_0,
  135344. 1, -514541568, 1627103232, 4, 0,
  135345. _vq_quantlist__44c1_sm_p8_0,
  135346. NULL,
  135347. &_vq_auxt__44c1_sm_p8_0,
  135348. NULL,
  135349. 0
  135350. };
  135351. static long _vq_quantlist__44c1_sm_p8_1[] = {
  135352. 6,
  135353. 5,
  135354. 7,
  135355. 4,
  135356. 8,
  135357. 3,
  135358. 9,
  135359. 2,
  135360. 10,
  135361. 1,
  135362. 11,
  135363. 0,
  135364. 12,
  135365. };
  135366. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  135367. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  135368. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  135369. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  135370. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  135371. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  135372. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  135373. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  135374. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  135375. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  135376. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  135377. 20,13,12,12,12,14,12,14,13,
  135378. };
  135379. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  135380. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135381. 42.5, 59.5, 76.5, 93.5,
  135382. };
  135383. static long _vq_quantmap__44c1_sm_p8_1[] = {
  135384. 11, 9, 7, 5, 3, 1, 0, 2,
  135385. 4, 6, 8, 10, 12,
  135386. };
  135387. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  135388. _vq_quantthresh__44c1_sm_p8_1,
  135389. _vq_quantmap__44c1_sm_p8_1,
  135390. 13,
  135391. 13
  135392. };
  135393. static static_codebook _44c1_sm_p8_1 = {
  135394. 2, 169,
  135395. _vq_lengthlist__44c1_sm_p8_1,
  135396. 1, -522616832, 1620115456, 4, 0,
  135397. _vq_quantlist__44c1_sm_p8_1,
  135398. NULL,
  135399. &_vq_auxt__44c1_sm_p8_1,
  135400. NULL,
  135401. 0
  135402. };
  135403. static long _vq_quantlist__44c1_sm_p8_2[] = {
  135404. 8,
  135405. 7,
  135406. 9,
  135407. 6,
  135408. 10,
  135409. 5,
  135410. 11,
  135411. 4,
  135412. 12,
  135413. 3,
  135414. 13,
  135415. 2,
  135416. 14,
  135417. 1,
  135418. 15,
  135419. 0,
  135420. 16,
  135421. };
  135422. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  135423. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  135424. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  135425. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135426. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135427. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  135428. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  135429. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  135430. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  135431. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  135432. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  135433. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  135434. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  135435. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  135436. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  135437. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  135438. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  135439. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  135440. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  135441. 9,
  135442. };
  135443. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  135444. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135445. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135446. };
  135447. static long _vq_quantmap__44c1_sm_p8_2[] = {
  135448. 15, 13, 11, 9, 7, 5, 3, 1,
  135449. 0, 2, 4, 6, 8, 10, 12, 14,
  135450. 16,
  135451. };
  135452. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  135453. _vq_quantthresh__44c1_sm_p8_2,
  135454. _vq_quantmap__44c1_sm_p8_2,
  135455. 17,
  135456. 17
  135457. };
  135458. static static_codebook _44c1_sm_p8_2 = {
  135459. 2, 289,
  135460. _vq_lengthlist__44c1_sm_p8_2,
  135461. 1, -529530880, 1611661312, 5, 0,
  135462. _vq_quantlist__44c1_sm_p8_2,
  135463. NULL,
  135464. &_vq_auxt__44c1_sm_p8_2,
  135465. NULL,
  135466. 0
  135467. };
  135468. static long _huff_lengthlist__44c1_sm_short[] = {
  135469. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  135470. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  135471. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  135472. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  135473. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  135474. 11,
  135475. };
  135476. static static_codebook _huff_book__44c1_sm_short = {
  135477. 2, 81,
  135478. _huff_lengthlist__44c1_sm_short,
  135479. 0, 0, 0, 0, 0,
  135480. NULL,
  135481. NULL,
  135482. NULL,
  135483. NULL,
  135484. 0
  135485. };
  135486. static long _huff_lengthlist__44cn1_s_long[] = {
  135487. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  135488. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  135489. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  135490. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  135491. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  135492. 20,
  135493. };
  135494. static static_codebook _huff_book__44cn1_s_long = {
  135495. 2, 81,
  135496. _huff_lengthlist__44cn1_s_long,
  135497. 0, 0, 0, 0, 0,
  135498. NULL,
  135499. NULL,
  135500. NULL,
  135501. NULL,
  135502. 0
  135503. };
  135504. static long _vq_quantlist__44cn1_s_p1_0[] = {
  135505. 1,
  135506. 0,
  135507. 2,
  135508. };
  135509. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  135510. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135511. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135515. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  135516. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135520. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  135521. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135533. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135538. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135543. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  135556. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  135561. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  135566. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  135578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  135583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  135588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  135602. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  135607. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  135612. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135624. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135629. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135921. };
  135922. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  135923. -0.5, 0.5,
  135924. };
  135925. static long _vq_quantmap__44cn1_s_p1_0[] = {
  135926. 1, 0, 2,
  135927. };
  135928. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  135929. _vq_quantthresh__44cn1_s_p1_0,
  135930. _vq_quantmap__44cn1_s_p1_0,
  135931. 3,
  135932. 3
  135933. };
  135934. static static_codebook _44cn1_s_p1_0 = {
  135935. 8, 6561,
  135936. _vq_lengthlist__44cn1_s_p1_0,
  135937. 1, -535822336, 1611661312, 2, 0,
  135938. _vq_quantlist__44cn1_s_p1_0,
  135939. NULL,
  135940. &_vq_auxt__44cn1_s_p1_0,
  135941. NULL,
  135942. 0
  135943. };
  135944. static long _vq_quantlist__44cn1_s_p2_0[] = {
  135945. 2,
  135946. 1,
  135947. 3,
  135948. 0,
  135949. 4,
  135950. };
  135951. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  135952. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  135992. };
  135993. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  135994. -1.5, -0.5, 0.5, 1.5,
  135995. };
  135996. static long _vq_quantmap__44cn1_s_p2_0[] = {
  135997. 3, 1, 0, 2, 4,
  135998. };
  135999. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  136000. _vq_quantthresh__44cn1_s_p2_0,
  136001. _vq_quantmap__44cn1_s_p2_0,
  136002. 5,
  136003. 5
  136004. };
  136005. static static_codebook _44cn1_s_p2_0 = {
  136006. 4, 625,
  136007. _vq_lengthlist__44cn1_s_p2_0,
  136008. 1, -533725184, 1611661312, 3, 0,
  136009. _vq_quantlist__44cn1_s_p2_0,
  136010. NULL,
  136011. &_vq_auxt__44cn1_s_p2_0,
  136012. NULL,
  136013. 0
  136014. };
  136015. static long _vq_quantlist__44cn1_s_p3_0[] = {
  136016. 4,
  136017. 3,
  136018. 5,
  136019. 2,
  136020. 6,
  136021. 1,
  136022. 7,
  136023. 0,
  136024. 8,
  136025. };
  136026. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  136027. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136028. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136029. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136030. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136031. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0,
  136033. };
  136034. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  136035. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136036. };
  136037. static long _vq_quantmap__44cn1_s_p3_0[] = {
  136038. 7, 5, 3, 1, 0, 2, 4, 6,
  136039. 8,
  136040. };
  136041. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  136042. _vq_quantthresh__44cn1_s_p3_0,
  136043. _vq_quantmap__44cn1_s_p3_0,
  136044. 9,
  136045. 9
  136046. };
  136047. static static_codebook _44cn1_s_p3_0 = {
  136048. 2, 81,
  136049. _vq_lengthlist__44cn1_s_p3_0,
  136050. 1, -531628032, 1611661312, 4, 0,
  136051. _vq_quantlist__44cn1_s_p3_0,
  136052. NULL,
  136053. &_vq_auxt__44cn1_s_p3_0,
  136054. NULL,
  136055. 0
  136056. };
  136057. static long _vq_quantlist__44cn1_s_p4_0[] = {
  136058. 4,
  136059. 3,
  136060. 5,
  136061. 2,
  136062. 6,
  136063. 1,
  136064. 7,
  136065. 0,
  136066. 8,
  136067. };
  136068. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  136069. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  136070. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136071. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  136072. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  136073. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  136074. 11,
  136075. };
  136076. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  136077. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136078. };
  136079. static long _vq_quantmap__44cn1_s_p4_0[] = {
  136080. 7, 5, 3, 1, 0, 2, 4, 6,
  136081. 8,
  136082. };
  136083. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  136084. _vq_quantthresh__44cn1_s_p4_0,
  136085. _vq_quantmap__44cn1_s_p4_0,
  136086. 9,
  136087. 9
  136088. };
  136089. static static_codebook _44cn1_s_p4_0 = {
  136090. 2, 81,
  136091. _vq_lengthlist__44cn1_s_p4_0,
  136092. 1, -531628032, 1611661312, 4, 0,
  136093. _vq_quantlist__44cn1_s_p4_0,
  136094. NULL,
  136095. &_vq_auxt__44cn1_s_p4_0,
  136096. NULL,
  136097. 0
  136098. };
  136099. static long _vq_quantlist__44cn1_s_p5_0[] = {
  136100. 8,
  136101. 7,
  136102. 9,
  136103. 6,
  136104. 10,
  136105. 5,
  136106. 11,
  136107. 4,
  136108. 12,
  136109. 3,
  136110. 13,
  136111. 2,
  136112. 14,
  136113. 1,
  136114. 15,
  136115. 0,
  136116. 16,
  136117. };
  136118. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  136119. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  136120. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  136121. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136122. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136123. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136124. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136125. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136126. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  136127. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136128. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  136129. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136130. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136131. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  136132. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  136133. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  136134. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  136135. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  136137. 14,
  136138. };
  136139. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  136140. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136141. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136142. };
  136143. static long _vq_quantmap__44cn1_s_p5_0[] = {
  136144. 15, 13, 11, 9, 7, 5, 3, 1,
  136145. 0, 2, 4, 6, 8, 10, 12, 14,
  136146. 16,
  136147. };
  136148. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  136149. _vq_quantthresh__44cn1_s_p5_0,
  136150. _vq_quantmap__44cn1_s_p5_0,
  136151. 17,
  136152. 17
  136153. };
  136154. static static_codebook _44cn1_s_p5_0 = {
  136155. 2, 289,
  136156. _vq_lengthlist__44cn1_s_p5_0,
  136157. 1, -529530880, 1611661312, 5, 0,
  136158. _vq_quantlist__44cn1_s_p5_0,
  136159. NULL,
  136160. &_vq_auxt__44cn1_s_p5_0,
  136161. NULL,
  136162. 0
  136163. };
  136164. static long _vq_quantlist__44cn1_s_p6_0[] = {
  136165. 1,
  136166. 0,
  136167. 2,
  136168. };
  136169. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  136170. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  136171. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  136172. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  136173. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  136174. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  136175. 10,
  136176. };
  136177. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  136178. -5.5, 5.5,
  136179. };
  136180. static long _vq_quantmap__44cn1_s_p6_0[] = {
  136181. 1, 0, 2,
  136182. };
  136183. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  136184. _vq_quantthresh__44cn1_s_p6_0,
  136185. _vq_quantmap__44cn1_s_p6_0,
  136186. 3,
  136187. 3
  136188. };
  136189. static static_codebook _44cn1_s_p6_0 = {
  136190. 4, 81,
  136191. _vq_lengthlist__44cn1_s_p6_0,
  136192. 1, -529137664, 1618345984, 2, 0,
  136193. _vq_quantlist__44cn1_s_p6_0,
  136194. NULL,
  136195. &_vq_auxt__44cn1_s_p6_0,
  136196. NULL,
  136197. 0
  136198. };
  136199. static long _vq_quantlist__44cn1_s_p6_1[] = {
  136200. 5,
  136201. 4,
  136202. 6,
  136203. 3,
  136204. 7,
  136205. 2,
  136206. 8,
  136207. 1,
  136208. 9,
  136209. 0,
  136210. 10,
  136211. };
  136212. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  136213. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  136214. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  136215. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  136216. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  136217. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  136218. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  136219. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  136220. 10,10,10, 9, 9, 9, 9, 9, 9,
  136221. };
  136222. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  136223. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136224. 3.5, 4.5,
  136225. };
  136226. static long _vq_quantmap__44cn1_s_p6_1[] = {
  136227. 9, 7, 5, 3, 1, 0, 2, 4,
  136228. 6, 8, 10,
  136229. };
  136230. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  136231. _vq_quantthresh__44cn1_s_p6_1,
  136232. _vq_quantmap__44cn1_s_p6_1,
  136233. 11,
  136234. 11
  136235. };
  136236. static static_codebook _44cn1_s_p6_1 = {
  136237. 2, 121,
  136238. _vq_lengthlist__44cn1_s_p6_1,
  136239. 1, -531365888, 1611661312, 4, 0,
  136240. _vq_quantlist__44cn1_s_p6_1,
  136241. NULL,
  136242. &_vq_auxt__44cn1_s_p6_1,
  136243. NULL,
  136244. 0
  136245. };
  136246. static long _vq_quantlist__44cn1_s_p7_0[] = {
  136247. 6,
  136248. 5,
  136249. 7,
  136250. 4,
  136251. 8,
  136252. 3,
  136253. 9,
  136254. 2,
  136255. 10,
  136256. 1,
  136257. 11,
  136258. 0,
  136259. 12,
  136260. };
  136261. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  136262. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  136263. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  136264. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136265. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136266. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  136267. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136268. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  136269. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  136270. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  136271. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  136272. 0,13,13,12,12,13,13,13,14,
  136273. };
  136274. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  136275. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136276. 12.5, 17.5, 22.5, 27.5,
  136277. };
  136278. static long _vq_quantmap__44cn1_s_p7_0[] = {
  136279. 11, 9, 7, 5, 3, 1, 0, 2,
  136280. 4, 6, 8, 10, 12,
  136281. };
  136282. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  136283. _vq_quantthresh__44cn1_s_p7_0,
  136284. _vq_quantmap__44cn1_s_p7_0,
  136285. 13,
  136286. 13
  136287. };
  136288. static static_codebook _44cn1_s_p7_0 = {
  136289. 2, 169,
  136290. _vq_lengthlist__44cn1_s_p7_0,
  136291. 1, -526516224, 1616117760, 4, 0,
  136292. _vq_quantlist__44cn1_s_p7_0,
  136293. NULL,
  136294. &_vq_auxt__44cn1_s_p7_0,
  136295. NULL,
  136296. 0
  136297. };
  136298. static long _vq_quantlist__44cn1_s_p7_1[] = {
  136299. 2,
  136300. 1,
  136301. 3,
  136302. 0,
  136303. 4,
  136304. };
  136305. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  136306. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136307. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136308. };
  136309. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  136310. -1.5, -0.5, 0.5, 1.5,
  136311. };
  136312. static long _vq_quantmap__44cn1_s_p7_1[] = {
  136313. 3, 1, 0, 2, 4,
  136314. };
  136315. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  136316. _vq_quantthresh__44cn1_s_p7_1,
  136317. _vq_quantmap__44cn1_s_p7_1,
  136318. 5,
  136319. 5
  136320. };
  136321. static static_codebook _44cn1_s_p7_1 = {
  136322. 2, 25,
  136323. _vq_lengthlist__44cn1_s_p7_1,
  136324. 1, -533725184, 1611661312, 3, 0,
  136325. _vq_quantlist__44cn1_s_p7_1,
  136326. NULL,
  136327. &_vq_auxt__44cn1_s_p7_1,
  136328. NULL,
  136329. 0
  136330. };
  136331. static long _vq_quantlist__44cn1_s_p8_0[] = {
  136332. 2,
  136333. 1,
  136334. 3,
  136335. 0,
  136336. 4,
  136337. };
  136338. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  136339. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  136340. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  136341. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136342. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  136343. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136346. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  136347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136348. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  136349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  136350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136353. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136354. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  136355. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136358. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136362. 11,11,11,11,11,11,11,11,11,11,11,11,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,11,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,11,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,11,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,11,
  136372. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  136373. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136374. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136375. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136376. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136377. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136378. 12,
  136379. };
  136380. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  136381. -331.5, -110.5, 110.5, 331.5,
  136382. };
  136383. static long _vq_quantmap__44cn1_s_p8_0[] = {
  136384. 3, 1, 0, 2, 4,
  136385. };
  136386. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  136387. _vq_quantthresh__44cn1_s_p8_0,
  136388. _vq_quantmap__44cn1_s_p8_0,
  136389. 5,
  136390. 5
  136391. };
  136392. static static_codebook _44cn1_s_p8_0 = {
  136393. 4, 625,
  136394. _vq_lengthlist__44cn1_s_p8_0,
  136395. 1, -518283264, 1627103232, 3, 0,
  136396. _vq_quantlist__44cn1_s_p8_0,
  136397. NULL,
  136398. &_vq_auxt__44cn1_s_p8_0,
  136399. NULL,
  136400. 0
  136401. };
  136402. static long _vq_quantlist__44cn1_s_p8_1[] = {
  136403. 6,
  136404. 5,
  136405. 7,
  136406. 4,
  136407. 8,
  136408. 3,
  136409. 9,
  136410. 2,
  136411. 10,
  136412. 1,
  136413. 11,
  136414. 0,
  136415. 12,
  136416. };
  136417. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  136418. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  136419. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  136420. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  136421. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  136422. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  136423. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  136424. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  136425. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  136426. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  136427. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  136428. 15,12,12,11,11,14,12,13,14,
  136429. };
  136430. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  136431. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136432. 42.5, 59.5, 76.5, 93.5,
  136433. };
  136434. static long _vq_quantmap__44cn1_s_p8_1[] = {
  136435. 11, 9, 7, 5, 3, 1, 0, 2,
  136436. 4, 6, 8, 10, 12,
  136437. };
  136438. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  136439. _vq_quantthresh__44cn1_s_p8_1,
  136440. _vq_quantmap__44cn1_s_p8_1,
  136441. 13,
  136442. 13
  136443. };
  136444. static static_codebook _44cn1_s_p8_1 = {
  136445. 2, 169,
  136446. _vq_lengthlist__44cn1_s_p8_1,
  136447. 1, -522616832, 1620115456, 4, 0,
  136448. _vq_quantlist__44cn1_s_p8_1,
  136449. NULL,
  136450. &_vq_auxt__44cn1_s_p8_1,
  136451. NULL,
  136452. 0
  136453. };
  136454. static long _vq_quantlist__44cn1_s_p8_2[] = {
  136455. 8,
  136456. 7,
  136457. 9,
  136458. 6,
  136459. 10,
  136460. 5,
  136461. 11,
  136462. 4,
  136463. 12,
  136464. 3,
  136465. 13,
  136466. 2,
  136467. 14,
  136468. 1,
  136469. 15,
  136470. 0,
  136471. 16,
  136472. };
  136473. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  136474. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  136475. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  136476. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136477. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  136478. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  136479. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  136480. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  136481. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  136482. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  136483. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  136484. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  136485. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  136486. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  136487. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  136488. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  136489. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  136490. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136491. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  136492. 9,
  136493. };
  136494. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  136495. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136496. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136497. };
  136498. static long _vq_quantmap__44cn1_s_p8_2[] = {
  136499. 15, 13, 11, 9, 7, 5, 3, 1,
  136500. 0, 2, 4, 6, 8, 10, 12, 14,
  136501. 16,
  136502. };
  136503. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  136504. _vq_quantthresh__44cn1_s_p8_2,
  136505. _vq_quantmap__44cn1_s_p8_2,
  136506. 17,
  136507. 17
  136508. };
  136509. static static_codebook _44cn1_s_p8_2 = {
  136510. 2, 289,
  136511. _vq_lengthlist__44cn1_s_p8_2,
  136512. 1, -529530880, 1611661312, 5, 0,
  136513. _vq_quantlist__44cn1_s_p8_2,
  136514. NULL,
  136515. &_vq_auxt__44cn1_s_p8_2,
  136516. NULL,
  136517. 0
  136518. };
  136519. static long _huff_lengthlist__44cn1_s_short[] = {
  136520. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  136521. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  136522. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  136523. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  136524. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  136525. 10,
  136526. };
  136527. static static_codebook _huff_book__44cn1_s_short = {
  136528. 2, 81,
  136529. _huff_lengthlist__44cn1_s_short,
  136530. 0, 0, 0, 0, 0,
  136531. NULL,
  136532. NULL,
  136533. NULL,
  136534. NULL,
  136535. 0
  136536. };
  136537. static long _huff_lengthlist__44cn1_sm_long[] = {
  136538. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  136539. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  136540. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  136541. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  136542. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  136543. 17,
  136544. };
  136545. static static_codebook _huff_book__44cn1_sm_long = {
  136546. 2, 81,
  136547. _huff_lengthlist__44cn1_sm_long,
  136548. 0, 0, 0, 0, 0,
  136549. NULL,
  136550. NULL,
  136551. NULL,
  136552. NULL,
  136553. 0
  136554. };
  136555. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  136556. 1,
  136557. 0,
  136558. 2,
  136559. };
  136560. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  136561. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136562. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  136567. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136572. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  136607. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  136612. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136617. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  136653. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136658. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  136663. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  136972. };
  136973. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  136974. -0.5, 0.5,
  136975. };
  136976. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  136977. 1, 0, 2,
  136978. };
  136979. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  136980. _vq_quantthresh__44cn1_sm_p1_0,
  136981. _vq_quantmap__44cn1_sm_p1_0,
  136982. 3,
  136983. 3
  136984. };
  136985. static static_codebook _44cn1_sm_p1_0 = {
  136986. 8, 6561,
  136987. _vq_lengthlist__44cn1_sm_p1_0,
  136988. 1, -535822336, 1611661312, 2, 0,
  136989. _vq_quantlist__44cn1_sm_p1_0,
  136990. NULL,
  136991. &_vq_auxt__44cn1_sm_p1_0,
  136992. NULL,
  136993. 0
  136994. };
  136995. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  136996. 2,
  136997. 1,
  136998. 3,
  136999. 0,
  137000. 4,
  137001. };
  137002. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  137003. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  137043. };
  137044. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  137045. -1.5, -0.5, 0.5, 1.5,
  137046. };
  137047. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  137048. 3, 1, 0, 2, 4,
  137049. };
  137050. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  137051. _vq_quantthresh__44cn1_sm_p2_0,
  137052. _vq_quantmap__44cn1_sm_p2_0,
  137053. 5,
  137054. 5
  137055. };
  137056. static static_codebook _44cn1_sm_p2_0 = {
  137057. 4, 625,
  137058. _vq_lengthlist__44cn1_sm_p2_0,
  137059. 1, -533725184, 1611661312, 3, 0,
  137060. _vq_quantlist__44cn1_sm_p2_0,
  137061. NULL,
  137062. &_vq_auxt__44cn1_sm_p2_0,
  137063. NULL,
  137064. 0
  137065. };
  137066. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  137067. 4,
  137068. 3,
  137069. 5,
  137070. 2,
  137071. 6,
  137072. 1,
  137073. 7,
  137074. 0,
  137075. 8,
  137076. };
  137077. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  137078. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  137079. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137080. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137081. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  137082. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0,
  137084. };
  137085. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  137086. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137087. };
  137088. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  137089. 7, 5, 3, 1, 0, 2, 4, 6,
  137090. 8,
  137091. };
  137092. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  137093. _vq_quantthresh__44cn1_sm_p3_0,
  137094. _vq_quantmap__44cn1_sm_p3_0,
  137095. 9,
  137096. 9
  137097. };
  137098. static static_codebook _44cn1_sm_p3_0 = {
  137099. 2, 81,
  137100. _vq_lengthlist__44cn1_sm_p3_0,
  137101. 1, -531628032, 1611661312, 4, 0,
  137102. _vq_quantlist__44cn1_sm_p3_0,
  137103. NULL,
  137104. &_vq_auxt__44cn1_sm_p3_0,
  137105. NULL,
  137106. 0
  137107. };
  137108. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  137109. 4,
  137110. 3,
  137111. 5,
  137112. 2,
  137113. 6,
  137114. 1,
  137115. 7,
  137116. 0,
  137117. 8,
  137118. };
  137119. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  137120. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137121. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137122. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137123. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  137124. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  137125. 11,
  137126. };
  137127. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  137128. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137129. };
  137130. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  137131. 7, 5, 3, 1, 0, 2, 4, 6,
  137132. 8,
  137133. };
  137134. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  137135. _vq_quantthresh__44cn1_sm_p4_0,
  137136. _vq_quantmap__44cn1_sm_p4_0,
  137137. 9,
  137138. 9
  137139. };
  137140. static static_codebook _44cn1_sm_p4_0 = {
  137141. 2, 81,
  137142. _vq_lengthlist__44cn1_sm_p4_0,
  137143. 1, -531628032, 1611661312, 4, 0,
  137144. _vq_quantlist__44cn1_sm_p4_0,
  137145. NULL,
  137146. &_vq_auxt__44cn1_sm_p4_0,
  137147. NULL,
  137148. 0
  137149. };
  137150. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  137151. 8,
  137152. 7,
  137153. 9,
  137154. 6,
  137155. 10,
  137156. 5,
  137157. 11,
  137158. 4,
  137159. 12,
  137160. 3,
  137161. 13,
  137162. 2,
  137163. 14,
  137164. 1,
  137165. 15,
  137166. 0,
  137167. 16,
  137168. };
  137169. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  137170. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  137171. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137172. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137173. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137174. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  137175. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137176. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137177. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137178. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  137179. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137180. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  137181. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  137182. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  137183. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  137184. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  137185. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  137186. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  137188. 14,
  137189. };
  137190. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  137191. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137192. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137193. };
  137194. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  137195. 15, 13, 11, 9, 7, 5, 3, 1,
  137196. 0, 2, 4, 6, 8, 10, 12, 14,
  137197. 16,
  137198. };
  137199. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  137200. _vq_quantthresh__44cn1_sm_p5_0,
  137201. _vq_quantmap__44cn1_sm_p5_0,
  137202. 17,
  137203. 17
  137204. };
  137205. static static_codebook _44cn1_sm_p5_0 = {
  137206. 2, 289,
  137207. _vq_lengthlist__44cn1_sm_p5_0,
  137208. 1, -529530880, 1611661312, 5, 0,
  137209. _vq_quantlist__44cn1_sm_p5_0,
  137210. NULL,
  137211. &_vq_auxt__44cn1_sm_p5_0,
  137212. NULL,
  137213. 0
  137214. };
  137215. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  137216. 1,
  137217. 0,
  137218. 2,
  137219. };
  137220. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  137221. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  137222. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137223. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  137224. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  137225. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  137226. 10,
  137227. };
  137228. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  137229. -5.5, 5.5,
  137230. };
  137231. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  137232. 1, 0, 2,
  137233. };
  137234. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  137235. _vq_quantthresh__44cn1_sm_p6_0,
  137236. _vq_quantmap__44cn1_sm_p6_0,
  137237. 3,
  137238. 3
  137239. };
  137240. static static_codebook _44cn1_sm_p6_0 = {
  137241. 4, 81,
  137242. _vq_lengthlist__44cn1_sm_p6_0,
  137243. 1, -529137664, 1618345984, 2, 0,
  137244. _vq_quantlist__44cn1_sm_p6_0,
  137245. NULL,
  137246. &_vq_auxt__44cn1_sm_p6_0,
  137247. NULL,
  137248. 0
  137249. };
  137250. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  137251. 5,
  137252. 4,
  137253. 6,
  137254. 3,
  137255. 7,
  137256. 2,
  137257. 8,
  137258. 1,
  137259. 9,
  137260. 0,
  137261. 10,
  137262. };
  137263. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  137264. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  137265. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137266. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  137267. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137268. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137269. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  137270. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  137271. 10,10,10, 8, 9, 8, 8, 9, 8,
  137272. };
  137273. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  137274. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137275. 3.5, 4.5,
  137276. };
  137277. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  137278. 9, 7, 5, 3, 1, 0, 2, 4,
  137279. 6, 8, 10,
  137280. };
  137281. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  137282. _vq_quantthresh__44cn1_sm_p6_1,
  137283. _vq_quantmap__44cn1_sm_p6_1,
  137284. 11,
  137285. 11
  137286. };
  137287. static static_codebook _44cn1_sm_p6_1 = {
  137288. 2, 121,
  137289. _vq_lengthlist__44cn1_sm_p6_1,
  137290. 1, -531365888, 1611661312, 4, 0,
  137291. _vq_quantlist__44cn1_sm_p6_1,
  137292. NULL,
  137293. &_vq_auxt__44cn1_sm_p6_1,
  137294. NULL,
  137295. 0
  137296. };
  137297. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  137298. 6,
  137299. 5,
  137300. 7,
  137301. 4,
  137302. 8,
  137303. 3,
  137304. 9,
  137305. 2,
  137306. 10,
  137307. 1,
  137308. 11,
  137309. 0,
  137310. 12,
  137311. };
  137312. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  137313. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  137314. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  137315. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137316. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137317. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  137318. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  137319. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  137320. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  137321. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  137322. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  137323. 0,13,12,12,12,13,13,13,14,
  137324. };
  137325. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  137326. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137327. 12.5, 17.5, 22.5, 27.5,
  137328. };
  137329. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  137330. 11, 9, 7, 5, 3, 1, 0, 2,
  137331. 4, 6, 8, 10, 12,
  137332. };
  137333. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  137334. _vq_quantthresh__44cn1_sm_p7_0,
  137335. _vq_quantmap__44cn1_sm_p7_0,
  137336. 13,
  137337. 13
  137338. };
  137339. static static_codebook _44cn1_sm_p7_0 = {
  137340. 2, 169,
  137341. _vq_lengthlist__44cn1_sm_p7_0,
  137342. 1, -526516224, 1616117760, 4, 0,
  137343. _vq_quantlist__44cn1_sm_p7_0,
  137344. NULL,
  137345. &_vq_auxt__44cn1_sm_p7_0,
  137346. NULL,
  137347. 0
  137348. };
  137349. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  137350. 2,
  137351. 1,
  137352. 3,
  137353. 0,
  137354. 4,
  137355. };
  137356. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  137357. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137358. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  137359. };
  137360. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  137361. -1.5, -0.5, 0.5, 1.5,
  137362. };
  137363. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  137364. 3, 1, 0, 2, 4,
  137365. };
  137366. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  137367. _vq_quantthresh__44cn1_sm_p7_1,
  137368. _vq_quantmap__44cn1_sm_p7_1,
  137369. 5,
  137370. 5
  137371. };
  137372. static static_codebook _44cn1_sm_p7_1 = {
  137373. 2, 25,
  137374. _vq_lengthlist__44cn1_sm_p7_1,
  137375. 1, -533725184, 1611661312, 3, 0,
  137376. _vq_quantlist__44cn1_sm_p7_1,
  137377. NULL,
  137378. &_vq_auxt__44cn1_sm_p7_1,
  137379. NULL,
  137380. 0
  137381. };
  137382. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  137383. 4,
  137384. 3,
  137385. 5,
  137386. 2,
  137387. 6,
  137388. 1,
  137389. 7,
  137390. 0,
  137391. 8,
  137392. };
  137393. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  137394. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  137395. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  137396. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  137397. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  137398. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  137399. 14,
  137400. };
  137401. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  137402. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137403. };
  137404. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  137405. 7, 5, 3, 1, 0, 2, 4, 6,
  137406. 8,
  137407. };
  137408. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  137409. _vq_quantthresh__44cn1_sm_p8_0,
  137410. _vq_quantmap__44cn1_sm_p8_0,
  137411. 9,
  137412. 9
  137413. };
  137414. static static_codebook _44cn1_sm_p8_0 = {
  137415. 2, 81,
  137416. _vq_lengthlist__44cn1_sm_p8_0,
  137417. 1, -516186112, 1627103232, 4, 0,
  137418. _vq_quantlist__44cn1_sm_p8_0,
  137419. NULL,
  137420. &_vq_auxt__44cn1_sm_p8_0,
  137421. NULL,
  137422. 0
  137423. };
  137424. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  137425. 6,
  137426. 5,
  137427. 7,
  137428. 4,
  137429. 8,
  137430. 3,
  137431. 9,
  137432. 2,
  137433. 10,
  137434. 1,
  137435. 11,
  137436. 0,
  137437. 12,
  137438. };
  137439. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  137440. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  137441. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  137442. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  137443. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  137444. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  137445. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  137446. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  137447. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  137448. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  137449. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  137450. 17,12,12,11,10,13,11,13,13,
  137451. };
  137452. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  137453. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137454. 42.5, 59.5, 76.5, 93.5,
  137455. };
  137456. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  137457. 11, 9, 7, 5, 3, 1, 0, 2,
  137458. 4, 6, 8, 10, 12,
  137459. };
  137460. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  137461. _vq_quantthresh__44cn1_sm_p8_1,
  137462. _vq_quantmap__44cn1_sm_p8_1,
  137463. 13,
  137464. 13
  137465. };
  137466. static static_codebook _44cn1_sm_p8_1 = {
  137467. 2, 169,
  137468. _vq_lengthlist__44cn1_sm_p8_1,
  137469. 1, -522616832, 1620115456, 4, 0,
  137470. _vq_quantlist__44cn1_sm_p8_1,
  137471. NULL,
  137472. &_vq_auxt__44cn1_sm_p8_1,
  137473. NULL,
  137474. 0
  137475. };
  137476. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  137477. 8,
  137478. 7,
  137479. 9,
  137480. 6,
  137481. 10,
  137482. 5,
  137483. 11,
  137484. 4,
  137485. 12,
  137486. 3,
  137487. 13,
  137488. 2,
  137489. 14,
  137490. 1,
  137491. 15,
  137492. 0,
  137493. 16,
  137494. };
  137495. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  137496. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  137497. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137498. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  137499. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137500. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  137501. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  137502. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  137503. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  137504. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  137505. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  137506. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  137507. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  137508. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  137509. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  137510. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  137511. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137512. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137513. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137514. 9,
  137515. };
  137516. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  137517. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137518. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137519. };
  137520. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  137521. 15, 13, 11, 9, 7, 5, 3, 1,
  137522. 0, 2, 4, 6, 8, 10, 12, 14,
  137523. 16,
  137524. };
  137525. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  137526. _vq_quantthresh__44cn1_sm_p8_2,
  137527. _vq_quantmap__44cn1_sm_p8_2,
  137528. 17,
  137529. 17
  137530. };
  137531. static static_codebook _44cn1_sm_p8_2 = {
  137532. 2, 289,
  137533. _vq_lengthlist__44cn1_sm_p8_2,
  137534. 1, -529530880, 1611661312, 5, 0,
  137535. _vq_quantlist__44cn1_sm_p8_2,
  137536. NULL,
  137537. &_vq_auxt__44cn1_sm_p8_2,
  137538. NULL,
  137539. 0
  137540. };
  137541. static long _huff_lengthlist__44cn1_sm_short[] = {
  137542. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  137543. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  137544. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  137545. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  137546. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  137547. 9,
  137548. };
  137549. static static_codebook _huff_book__44cn1_sm_short = {
  137550. 2, 81,
  137551. _huff_lengthlist__44cn1_sm_short,
  137552. 0, 0, 0, 0, 0,
  137553. NULL,
  137554. NULL,
  137555. NULL,
  137556. NULL,
  137557. 0
  137558. };
  137559. /********* End of inlined file: res_books_stereo.h *********/
  137560. /***** residue backends *********************************************/
  137561. static vorbis_info_residue0 _residue_44_low={
  137562. 0,-1, -1, 9,-1,
  137563. /* 0 1 2 3 4 5 6 7 */
  137564. {0},
  137565. {-1},
  137566. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137567. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  137568. };
  137569. static vorbis_info_residue0 _residue_44_mid={
  137570. 0,-1, -1, 10,-1,
  137571. /* 0 1 2 3 4 5 6 7 8 */
  137572. {0},
  137573. {-1},
  137574. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  137575. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  137576. };
  137577. static vorbis_info_residue0 _residue_44_high={
  137578. 0,-1, -1, 10,-1,
  137579. /* 0 1 2 3 4 5 6 7 8 */
  137580. {0},
  137581. {-1},
  137582. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  137583. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  137584. };
  137585. static static_bookblock _resbook_44s_n1={
  137586. {
  137587. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  137588. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  137589. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  137590. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  137591. }
  137592. };
  137593. static static_bookblock _resbook_44sm_n1={
  137594. {
  137595. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  137596. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  137597. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  137598. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  137599. }
  137600. };
  137601. static static_bookblock _resbook_44s_0={
  137602. {
  137603. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  137604. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  137605. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  137606. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  137607. }
  137608. };
  137609. static static_bookblock _resbook_44sm_0={
  137610. {
  137611. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  137612. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  137613. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  137614. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  137615. }
  137616. };
  137617. static static_bookblock _resbook_44s_1={
  137618. {
  137619. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  137620. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  137621. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  137622. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  137623. }
  137624. };
  137625. static static_bookblock _resbook_44sm_1={
  137626. {
  137627. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  137628. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  137629. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  137630. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  137631. }
  137632. };
  137633. static static_bookblock _resbook_44s_2={
  137634. {
  137635. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  137636. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  137637. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  137638. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  137639. }
  137640. };
  137641. static static_bookblock _resbook_44s_3={
  137642. {
  137643. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  137644. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  137645. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  137646. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  137647. }
  137648. };
  137649. static static_bookblock _resbook_44s_4={
  137650. {
  137651. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  137652. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  137653. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  137654. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  137655. }
  137656. };
  137657. static static_bookblock _resbook_44s_5={
  137658. {
  137659. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  137660. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  137661. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  137662. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  137663. }
  137664. };
  137665. static static_bookblock _resbook_44s_6={
  137666. {
  137667. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  137668. {0,0,&_44c6_s_p4_0},
  137669. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  137670. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  137671. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  137672. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  137673. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  137674. }
  137675. };
  137676. static static_bookblock _resbook_44s_7={
  137677. {
  137678. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  137679. {0,0,&_44c7_s_p4_0},
  137680. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  137681. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  137682. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  137683. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  137684. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  137685. }
  137686. };
  137687. static static_bookblock _resbook_44s_8={
  137688. {
  137689. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  137690. {0,0,&_44c8_s_p4_0},
  137691. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  137692. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  137693. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  137694. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  137695. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  137696. }
  137697. };
  137698. static static_bookblock _resbook_44s_9={
  137699. {
  137700. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  137701. {0,0,&_44c9_s_p4_0},
  137702. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  137703. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  137704. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  137705. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  137706. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  137707. }
  137708. };
  137709. static vorbis_residue_template _res_44s_n1[]={
  137710. {2,0, &_residue_44_low,
  137711. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  137712. &_resbook_44s_n1,&_resbook_44sm_n1},
  137713. {2,0, &_residue_44_low,
  137714. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  137715. &_resbook_44s_n1,&_resbook_44sm_n1}
  137716. };
  137717. static vorbis_residue_template _res_44s_0[]={
  137718. {2,0, &_residue_44_low,
  137719. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  137720. &_resbook_44s_0,&_resbook_44sm_0},
  137721. {2,0, &_residue_44_low,
  137722. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  137723. &_resbook_44s_0,&_resbook_44sm_0}
  137724. };
  137725. static vorbis_residue_template _res_44s_1[]={
  137726. {2,0, &_residue_44_low,
  137727. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  137728. &_resbook_44s_1,&_resbook_44sm_1},
  137729. {2,0, &_residue_44_low,
  137730. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  137731. &_resbook_44s_1,&_resbook_44sm_1}
  137732. };
  137733. static vorbis_residue_template _res_44s_2[]={
  137734. {2,0, &_residue_44_mid,
  137735. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  137736. &_resbook_44s_2,&_resbook_44s_2},
  137737. {2,0, &_residue_44_mid,
  137738. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  137739. &_resbook_44s_2,&_resbook_44s_2}
  137740. };
  137741. static vorbis_residue_template _res_44s_3[]={
  137742. {2,0, &_residue_44_mid,
  137743. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  137744. &_resbook_44s_3,&_resbook_44s_3},
  137745. {2,0, &_residue_44_mid,
  137746. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  137747. &_resbook_44s_3,&_resbook_44s_3}
  137748. };
  137749. static vorbis_residue_template _res_44s_4[]={
  137750. {2,0, &_residue_44_mid,
  137751. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  137752. &_resbook_44s_4,&_resbook_44s_4},
  137753. {2,0, &_residue_44_mid,
  137754. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  137755. &_resbook_44s_4,&_resbook_44s_4}
  137756. };
  137757. static vorbis_residue_template _res_44s_5[]={
  137758. {2,0, &_residue_44_mid,
  137759. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  137760. &_resbook_44s_5,&_resbook_44s_5},
  137761. {2,0, &_residue_44_mid,
  137762. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  137763. &_resbook_44s_5,&_resbook_44s_5}
  137764. };
  137765. static vorbis_residue_template _res_44s_6[]={
  137766. {2,0, &_residue_44_high,
  137767. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  137768. &_resbook_44s_6,&_resbook_44s_6},
  137769. {2,0, &_residue_44_high,
  137770. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  137771. &_resbook_44s_6,&_resbook_44s_6}
  137772. };
  137773. static vorbis_residue_template _res_44s_7[]={
  137774. {2,0, &_residue_44_high,
  137775. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  137776. &_resbook_44s_7,&_resbook_44s_7},
  137777. {2,0, &_residue_44_high,
  137778. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  137779. &_resbook_44s_7,&_resbook_44s_7}
  137780. };
  137781. static vorbis_residue_template _res_44s_8[]={
  137782. {2,0, &_residue_44_high,
  137783. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  137784. &_resbook_44s_8,&_resbook_44s_8},
  137785. {2,0, &_residue_44_high,
  137786. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  137787. &_resbook_44s_8,&_resbook_44s_8}
  137788. };
  137789. static vorbis_residue_template _res_44s_9[]={
  137790. {2,0, &_residue_44_high,
  137791. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  137792. &_resbook_44s_9,&_resbook_44s_9},
  137793. {2,0, &_residue_44_high,
  137794. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  137795. &_resbook_44s_9,&_resbook_44s_9}
  137796. };
  137797. static vorbis_mapping_template _mapres_template_44_stereo[]={
  137798. { _map_nominal, _res_44s_n1 }, /* -1 */
  137799. { _map_nominal, _res_44s_0 }, /* 0 */
  137800. { _map_nominal, _res_44s_1 }, /* 1 */
  137801. { _map_nominal, _res_44s_2 }, /* 2 */
  137802. { _map_nominal, _res_44s_3 }, /* 3 */
  137803. { _map_nominal, _res_44s_4 }, /* 4 */
  137804. { _map_nominal, _res_44s_5 }, /* 5 */
  137805. { _map_nominal, _res_44s_6 }, /* 6 */
  137806. { _map_nominal, _res_44s_7 }, /* 7 */
  137807. { _map_nominal, _res_44s_8 }, /* 8 */
  137808. { _map_nominal, _res_44s_9 }, /* 9 */
  137809. };
  137810. /********* End of inlined file: residue_44.h *********/
  137811. /********* Start of inlined file: psych_44.h *********/
  137812. /* preecho trigger settings *****************************************/
  137813. static vorbis_info_psy_global _psy_global_44[5]={
  137814. {8, /* lines per eighth octave */
  137815. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  137816. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  137817. -6.f,
  137818. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137819. },
  137820. {8, /* lines per eighth octave */
  137821. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137822. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  137823. -6.f,
  137824. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137825. },
  137826. {8, /* lines per eighth octave */
  137827. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  137828. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  137829. -6.f,
  137830. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137831. },
  137832. {8, /* lines per eighth octave */
  137833. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  137834. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  137835. -6.f,
  137836. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137837. },
  137838. {8, /* lines per eighth octave */
  137839. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  137840. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  137841. -6.f,
  137842. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  137843. },
  137844. };
  137845. /* noise compander lookups * low, mid, high quality ****************/
  137846. static compandblock _psy_compand_44[6]={
  137847. /* sub-mode Z short */
  137848. {{
  137849. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137850. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137851. 16,17,18,19,20,21,22, 23, /* 23dB */
  137852. 24,25,26,27,28,29,30, 31, /* 31dB */
  137853. 32,33,34,35,36,37,38, 39, /* 39dB */
  137854. }},
  137855. /* mode_Z nominal short */
  137856. {{
  137857. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  137858. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  137859. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  137860. 15,16,17,17,17,18,18, 19, /* 31dB */
  137861. 19,19,20,21,22,23,24, 25, /* 39dB */
  137862. }},
  137863. /* mode A short */
  137864. {{
  137865. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  137866. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  137867. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137868. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137869. 11,12,13,14,15,16,17, 18, /* 39dB */
  137870. }},
  137871. /* sub-mode Z long */
  137872. {{
  137873. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137874. 8, 9,10,11,12,13,14, 15, /* 15dB */
  137875. 16,17,18,19,20,21,22, 23, /* 23dB */
  137876. 24,25,26,27,28,29,30, 31, /* 31dB */
  137877. 32,33,34,35,36,37,38, 39, /* 39dB */
  137878. }},
  137879. /* mode_Z nominal long */
  137880. {{
  137881. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137882. 8, 9,10,11,12,12,13, 13, /* 15dB */
  137883. 13,14,14,14,15,15,15, 15, /* 23dB */
  137884. 16,16,17,17,17,18,18, 19, /* 31dB */
  137885. 19,19,20,21,22,23,24, 25, /* 39dB */
  137886. }},
  137887. /* mode A long */
  137888. {{
  137889. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  137890. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  137891. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  137892. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  137893. 11,12,13,14,15,16,17, 18, /* 39dB */
  137894. }}
  137895. };
  137896. /* tonal masking curve level adjustments *************************/
  137897. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  137898. /* 63 125 250 500 1 2 4 8 16 */
  137899. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  137900. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137901. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  137902. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137903. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  137904. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137905. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  137906. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137907. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  137908. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  137909. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137910. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137911. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137912. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137913. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137914. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137915. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137916. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137917. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137918. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137919. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137920. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137921. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137922. };
  137923. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  137924. /* 63 125 250 500 1 2 4 8 16 */
  137925. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  137926. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  137927. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  137928. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  137929. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  137930. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  137931. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  137932. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  137933. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  137934. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  137935. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  137936. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  137937. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  137938. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  137939. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  137940. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  137941. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  137942. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  137943. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  137944. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  137945. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  137946. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  137947. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  137948. };
  137949. /* noise bias (transition block) */
  137950. static noise3 _psy_noisebias_trans[12]={
  137951. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  137952. /* -1 */
  137953. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  137954. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  137955. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  137956. /* 0
  137957. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137958. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  137959. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  137960. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137961. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  137962. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  137963. /* 1
  137964. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137965. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  137966. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  137967. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  137968. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  137969. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  137970. /* 2
  137971. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137972. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  137973. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  137974. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  137975. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  137976. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  137977. /* 3
  137978. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137979. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  137980. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137981. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  137982. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  137983. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137984. /* 4
  137985. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137986. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  137987. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  137988. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137989. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  137990. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  137991. /* 5
  137992. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137993. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  137994. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  137995. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  137996. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  137997. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  137998. /* 6
  137999. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138000. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138001. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138002. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138003. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138004. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138005. /* 7
  138006. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138007. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  138008. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  138009. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  138010. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138011. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138012. /* 8
  138013. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138014. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  138015. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138016. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  138017. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138018. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138019. /* 9
  138020. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138021. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  138022. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138023. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138024. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  138025. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  138026. /* 10 */
  138027. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  138028. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  138029. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138030. };
  138031. /* noise bias (long block) */
  138032. static noise3 _psy_noisebias_long[12]={
  138033. /*63 125 250 500 1k 2k 4k 8k 16k*/
  138034. /* -1 */
  138035. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  138036. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  138037. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138038. /* 0 */
  138039. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138040. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  138041. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  138042. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  138043. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  138044. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  138045. /* 1 */
  138046. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138047. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  138048. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  138049. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  138050. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  138051. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  138052. /* 2 */
  138053. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138054. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  138055. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138056. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  138057. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  138058. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  138059. /* 3 */
  138060. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138061. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  138062. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138063. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  138064. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  138065. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  138066. /* 4 */
  138067. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138068. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  138069. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  138070. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138071. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  138072. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  138073. /* 5 */
  138074. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138075. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  138076. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  138077. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138078. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  138079. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  138080. /* 6 */
  138081. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138082. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  138083. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  138084. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138085. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  138086. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  138087. /* 7 */
  138088. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  138089. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  138090. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  138091. /* 8 */
  138092. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  138093. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  138094. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  138095. /* 9 */
  138096. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138097. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  138098. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138099. /* 10 */
  138100. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  138101. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  138102. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138103. };
  138104. /* noise bias (impulse block) */
  138105. static noise3 _psy_noisebias_impulse[12]={
  138106. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138107. /* -1 */
  138108. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138109. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138110. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138111. /* 0 */
  138112. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138113. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  138114. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  138115. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  138116. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  138117. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138118. /* 1 */
  138119. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138120. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  138121. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  138122. /* 2 */
  138123. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138124. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138125. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138126. /* 3 */
  138127. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138128. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138129. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138130. /* 4 */
  138131. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138132. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  138133. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  138134. /* 5 */
  138135. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138136. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  138137. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  138138. /* 6
  138139. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138140. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  138141. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  138142. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  138143. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  138144. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  138145. /* 7 */
  138146. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138147. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  138148. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  138149. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  138150. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  138151. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138152. /* 8 */
  138153. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138154. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  138155. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  138156. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  138157. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  138158. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  138159. /* 9 */
  138160. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138161. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  138162. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  138163. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  138164. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  138165. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  138166. /* 10 */
  138167. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  138168. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  138169. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138170. };
  138171. /* noise bias (padding block) */
  138172. static noise3 _psy_noisebias_padding[12]={
  138173. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  138174. /* -1 */
  138175. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138176. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  138177. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  138178. /* 0 */
  138179. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  138180. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  138181. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  138182. /* 1 */
  138183. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  138184. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138185. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  138186. /* 2 */
  138187. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138188. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  138189. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  138190. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  138191. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138192. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138193. /* 3 */
  138194. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  138195. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  138196. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138197. /* 4 */
  138198. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  138199. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  138200. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  138201. /* 5 */
  138202. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138203. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  138204. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  138205. /* 6 */
  138206. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138207. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  138208. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  138209. /* 7 */
  138210. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  138211. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  138212. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  138213. /* 8 */
  138214. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  138215. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  138216. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  138217. /* 9 */
  138218. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  138219. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  138220. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  138221. /* 10 */
  138222. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  138223. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  138224. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  138225. };
  138226. static noiseguard _psy_noiseguards_44[4]={
  138227. {3,3,15},
  138228. {3,3,15},
  138229. {10,10,100},
  138230. {10,10,100},
  138231. };
  138232. static int _psy_tone_suppress[12]={
  138233. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  138234. };
  138235. static int _psy_tone_0dB[12]={
  138236. 90,90,95,95,95,95,105,105,105,105,105,105,
  138237. };
  138238. static int _psy_noise_suppress[12]={
  138239. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  138240. };
  138241. static vorbis_info_psy _psy_info_template={
  138242. /* blockflag */
  138243. -1,
  138244. /* ath_adjatt, ath_maxatt */
  138245. -140.,-140.,
  138246. /* tonemask att boost/decay,suppr,curves */
  138247. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  138248. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  138249. 1, -0.f, .5f, .5f, 0,0,0,
  138250. /* noiseoffset*3, noisecompand, max_curve_dB */
  138251. {{-1},{-1},{-1}},{-1},105.f,
  138252. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  138253. 0,0,-1,-1,0.,
  138254. };
  138255. /* ath ****************/
  138256. static int _psy_ath_floater[12]={
  138257. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  138258. };
  138259. static int _psy_ath_abs[12]={
  138260. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  138261. };
  138262. /* stereo setup. These don't map directly to quality level, there's
  138263. an additional indirection as several of the below may be used in a
  138264. single bitmanaged stream
  138265. ****************/
  138266. /* various stereo possibilities */
  138267. /* stereo mode by base quality level */
  138268. static adj_stereo _psy_stereo_modes_44[12]={
  138269. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  138270. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138271. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138272. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  138273. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138274. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  138275. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  138276. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  138277. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  138278. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138279. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  138280. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138281. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138282. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  138283. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  138284. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  138285. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  138286. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138287. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138288. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  138289. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  138290. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  138291. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138292. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138293. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  138294. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138295. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  138296. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138297. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  138298. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  138299. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  138300. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  138301. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138302. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  138303. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138304. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  138305. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  138306. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138307. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  138308. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138309. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138310. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138311. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138312. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138313. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  138314. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  138315. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138316. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  138317. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138318. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138319. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138320. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  138321. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138322. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138323. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138324. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138325. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  138326. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138327. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138328. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138329. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138330. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138331. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138332. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138333. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138334. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  138335. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138336. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138337. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  138338. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  138339. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138340. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138341. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  138342. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138343. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  138344. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138345. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138346. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138347. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138348. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  138349. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138350. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  138351. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  138352. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  138353. };
  138354. /* tone master attenuation by base quality mode and bitrate tweak */
  138355. static att3 _psy_tone_masteratt_44[12]={
  138356. {{ 35, 21, 9}, 0, 0}, /* -1 */
  138357. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  138358. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  138359. {{ 25, 12, 2}, 0, 0}, /* 1 */
  138360. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  138361. {{ 20, 9, -3}, 0, 0}, /* 2 */
  138362. {{ 20, 9, -4}, 0, 0}, /* 3 */
  138363. {{ 20, 9, -4}, 0, 0}, /* 4 */
  138364. {{ 20, 6, -6}, 0, 0}, /* 5 */
  138365. {{ 20, 3, -10}, 0, 0}, /* 6 */
  138366. {{ 18, 1, -14}, 0, 0}, /* 7 */
  138367. {{ 18, 0, -16}, 0, 0}, /* 8 */
  138368. {{ 18, -2, -16}, 0, 0}, /* 9 */
  138369. {{ 12, -2, -20}, 0, 0}, /* 10 */
  138370. };
  138371. /* lowpass by mode **************/
  138372. static double _psy_lowpass_44[12]={
  138373. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  138374. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  138375. };
  138376. /* noise normalization **********/
  138377. static int _noise_start_short_44[11]={
  138378. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  138379. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  138380. };
  138381. static int _noise_start_long_44[11]={
  138382. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  138383. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  138384. };
  138385. static int _noise_part_short_44[11]={
  138386. 8,8,8,8,8,8,8,8,8,8,8
  138387. };
  138388. static int _noise_part_long_44[11]={
  138389. 32,32,32,32,32,32,32,32,32,32,32
  138390. };
  138391. static double _noise_thresh_44[11]={
  138392. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  138393. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  138394. };
  138395. static double _noise_thresh_5only[2]={
  138396. .5,.5,
  138397. };
  138398. /********* End of inlined file: psych_44.h *********/
  138399. static double rate_mapping_44_stereo[12]={
  138400. 22500.,32000.,40000.,48000.,56000.,64000.,
  138401. 80000.,96000.,112000.,128000.,160000.,250001.
  138402. };
  138403. static double quality_mapping_44[12]={
  138404. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  138405. };
  138406. static int blocksize_short_44[11]={
  138407. 512,256,256,256,256,256,256,256,256,256,256
  138408. };
  138409. static int blocksize_long_44[11]={
  138410. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  138411. };
  138412. static double _psy_compand_short_mapping[12]={
  138413. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  138414. };
  138415. static double _psy_compand_long_mapping[12]={
  138416. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  138417. };
  138418. static double _global_mapping_44[12]={
  138419. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  138420. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  138421. };
  138422. static int _floor_short_mapping_44[11]={
  138423. 1,0,0,2,2,4,5,5,5,5,5
  138424. };
  138425. static int _floor_long_mapping_44[11]={
  138426. 8,7,7,7,7,7,7,7,7,7,7
  138427. };
  138428. ve_setup_data_template ve_setup_44_stereo={
  138429. 11,
  138430. rate_mapping_44_stereo,
  138431. quality_mapping_44,
  138432. 2,
  138433. 40000,
  138434. 50000,
  138435. blocksize_short_44,
  138436. blocksize_long_44,
  138437. _psy_tone_masteratt_44,
  138438. _psy_tone_0dB,
  138439. _psy_tone_suppress,
  138440. _vp_tonemask_adj_otherblock,
  138441. _vp_tonemask_adj_longblock,
  138442. _vp_tonemask_adj_otherblock,
  138443. _psy_noiseguards_44,
  138444. _psy_noisebias_impulse,
  138445. _psy_noisebias_padding,
  138446. _psy_noisebias_trans,
  138447. _psy_noisebias_long,
  138448. _psy_noise_suppress,
  138449. _psy_compand_44,
  138450. _psy_compand_short_mapping,
  138451. _psy_compand_long_mapping,
  138452. {_noise_start_short_44,_noise_start_long_44},
  138453. {_noise_part_short_44,_noise_part_long_44},
  138454. _noise_thresh_44,
  138455. _psy_ath_floater,
  138456. _psy_ath_abs,
  138457. _psy_lowpass_44,
  138458. _psy_global_44,
  138459. _global_mapping_44,
  138460. _psy_stereo_modes_44,
  138461. _floor_books,
  138462. _floor,
  138463. _floor_short_mapping_44,
  138464. _floor_long_mapping_44,
  138465. _mapres_template_44_stereo
  138466. };
  138467. /********* End of inlined file: setup_44.h *********/
  138468. /********* Start of inlined file: setup_44u.h *********/
  138469. /********* Start of inlined file: residue_44u.h *********/
  138470. /********* Start of inlined file: res_books_uncoupled.h *********/
  138471. static long _vq_quantlist__16u0__p1_0[] = {
  138472. 1,
  138473. 0,
  138474. 2,
  138475. };
  138476. static long _vq_lengthlist__16u0__p1_0[] = {
  138477. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  138478. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  138479. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  138480. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  138481. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  138482. 12,
  138483. };
  138484. static float _vq_quantthresh__16u0__p1_0[] = {
  138485. -0.5, 0.5,
  138486. };
  138487. static long _vq_quantmap__16u0__p1_0[] = {
  138488. 1, 0, 2,
  138489. };
  138490. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  138491. _vq_quantthresh__16u0__p1_0,
  138492. _vq_quantmap__16u0__p1_0,
  138493. 3,
  138494. 3
  138495. };
  138496. static static_codebook _16u0__p1_0 = {
  138497. 4, 81,
  138498. _vq_lengthlist__16u0__p1_0,
  138499. 1, -535822336, 1611661312, 2, 0,
  138500. _vq_quantlist__16u0__p1_0,
  138501. NULL,
  138502. &_vq_auxt__16u0__p1_0,
  138503. NULL,
  138504. 0
  138505. };
  138506. static long _vq_quantlist__16u0__p2_0[] = {
  138507. 1,
  138508. 0,
  138509. 2,
  138510. };
  138511. static long _vq_lengthlist__16u0__p2_0[] = {
  138512. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  138513. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  138514. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  138515. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  138516. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  138517. 8,
  138518. };
  138519. static float _vq_quantthresh__16u0__p2_0[] = {
  138520. -0.5, 0.5,
  138521. };
  138522. static long _vq_quantmap__16u0__p2_0[] = {
  138523. 1, 0, 2,
  138524. };
  138525. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  138526. _vq_quantthresh__16u0__p2_0,
  138527. _vq_quantmap__16u0__p2_0,
  138528. 3,
  138529. 3
  138530. };
  138531. static static_codebook _16u0__p2_0 = {
  138532. 4, 81,
  138533. _vq_lengthlist__16u0__p2_0,
  138534. 1, -535822336, 1611661312, 2, 0,
  138535. _vq_quantlist__16u0__p2_0,
  138536. NULL,
  138537. &_vq_auxt__16u0__p2_0,
  138538. NULL,
  138539. 0
  138540. };
  138541. static long _vq_quantlist__16u0__p3_0[] = {
  138542. 2,
  138543. 1,
  138544. 3,
  138545. 0,
  138546. 4,
  138547. };
  138548. static long _vq_lengthlist__16u0__p3_0[] = {
  138549. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  138550. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  138551. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  138552. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  138553. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  138554. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  138555. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  138556. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  138557. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  138558. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  138559. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  138560. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  138561. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  138562. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  138563. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  138564. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  138565. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  138566. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  138567. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  138568. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  138569. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  138570. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  138571. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  138572. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  138573. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  138574. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  138575. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  138576. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  138577. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  138578. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  138579. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  138580. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  138581. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  138582. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  138583. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  138584. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  138585. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  138586. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  138587. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  138588. 18,
  138589. };
  138590. static float _vq_quantthresh__16u0__p3_0[] = {
  138591. -1.5, -0.5, 0.5, 1.5,
  138592. };
  138593. static long _vq_quantmap__16u0__p3_0[] = {
  138594. 3, 1, 0, 2, 4,
  138595. };
  138596. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  138597. _vq_quantthresh__16u0__p3_0,
  138598. _vq_quantmap__16u0__p3_0,
  138599. 5,
  138600. 5
  138601. };
  138602. static static_codebook _16u0__p3_0 = {
  138603. 4, 625,
  138604. _vq_lengthlist__16u0__p3_0,
  138605. 1, -533725184, 1611661312, 3, 0,
  138606. _vq_quantlist__16u0__p3_0,
  138607. NULL,
  138608. &_vq_auxt__16u0__p3_0,
  138609. NULL,
  138610. 0
  138611. };
  138612. static long _vq_quantlist__16u0__p4_0[] = {
  138613. 2,
  138614. 1,
  138615. 3,
  138616. 0,
  138617. 4,
  138618. };
  138619. static long _vq_lengthlist__16u0__p4_0[] = {
  138620. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  138621. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  138622. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  138623. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  138624. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  138625. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  138626. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  138627. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  138628. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  138629. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  138630. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  138631. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  138632. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  138633. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  138634. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  138635. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  138636. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  138637. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  138638. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  138639. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  138640. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  138641. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  138642. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  138643. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  138644. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  138645. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  138646. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  138647. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  138648. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  138649. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  138650. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  138651. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  138652. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  138653. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  138654. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  138655. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  138656. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  138657. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  138658. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  138659. 11,
  138660. };
  138661. static float _vq_quantthresh__16u0__p4_0[] = {
  138662. -1.5, -0.5, 0.5, 1.5,
  138663. };
  138664. static long _vq_quantmap__16u0__p4_0[] = {
  138665. 3, 1, 0, 2, 4,
  138666. };
  138667. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  138668. _vq_quantthresh__16u0__p4_0,
  138669. _vq_quantmap__16u0__p4_0,
  138670. 5,
  138671. 5
  138672. };
  138673. static static_codebook _16u0__p4_0 = {
  138674. 4, 625,
  138675. _vq_lengthlist__16u0__p4_0,
  138676. 1, -533725184, 1611661312, 3, 0,
  138677. _vq_quantlist__16u0__p4_0,
  138678. NULL,
  138679. &_vq_auxt__16u0__p4_0,
  138680. NULL,
  138681. 0
  138682. };
  138683. static long _vq_quantlist__16u0__p5_0[] = {
  138684. 4,
  138685. 3,
  138686. 5,
  138687. 2,
  138688. 6,
  138689. 1,
  138690. 7,
  138691. 0,
  138692. 8,
  138693. };
  138694. static long _vq_lengthlist__16u0__p5_0[] = {
  138695. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  138696. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  138697. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  138698. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138699. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  138700. 12,
  138701. };
  138702. static float _vq_quantthresh__16u0__p5_0[] = {
  138703. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138704. };
  138705. static long _vq_quantmap__16u0__p5_0[] = {
  138706. 7, 5, 3, 1, 0, 2, 4, 6,
  138707. 8,
  138708. };
  138709. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  138710. _vq_quantthresh__16u0__p5_0,
  138711. _vq_quantmap__16u0__p5_0,
  138712. 9,
  138713. 9
  138714. };
  138715. static static_codebook _16u0__p5_0 = {
  138716. 2, 81,
  138717. _vq_lengthlist__16u0__p5_0,
  138718. 1, -531628032, 1611661312, 4, 0,
  138719. _vq_quantlist__16u0__p5_0,
  138720. NULL,
  138721. &_vq_auxt__16u0__p5_0,
  138722. NULL,
  138723. 0
  138724. };
  138725. static long _vq_quantlist__16u0__p6_0[] = {
  138726. 6,
  138727. 5,
  138728. 7,
  138729. 4,
  138730. 8,
  138731. 3,
  138732. 9,
  138733. 2,
  138734. 10,
  138735. 1,
  138736. 11,
  138737. 0,
  138738. 12,
  138739. };
  138740. static long _vq_lengthlist__16u0__p6_0[] = {
  138741. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  138742. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  138743. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  138744. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  138745. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  138746. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  138747. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  138748. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  138749. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  138750. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  138751. 18, 0,19, 0, 0, 0, 0, 0, 0,
  138752. };
  138753. static float _vq_quantthresh__16u0__p6_0[] = {
  138754. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138755. 12.5, 17.5, 22.5, 27.5,
  138756. };
  138757. static long _vq_quantmap__16u0__p6_0[] = {
  138758. 11, 9, 7, 5, 3, 1, 0, 2,
  138759. 4, 6, 8, 10, 12,
  138760. };
  138761. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  138762. _vq_quantthresh__16u0__p6_0,
  138763. _vq_quantmap__16u0__p6_0,
  138764. 13,
  138765. 13
  138766. };
  138767. static static_codebook _16u0__p6_0 = {
  138768. 2, 169,
  138769. _vq_lengthlist__16u0__p6_0,
  138770. 1, -526516224, 1616117760, 4, 0,
  138771. _vq_quantlist__16u0__p6_0,
  138772. NULL,
  138773. &_vq_auxt__16u0__p6_0,
  138774. NULL,
  138775. 0
  138776. };
  138777. static long _vq_quantlist__16u0__p6_1[] = {
  138778. 2,
  138779. 1,
  138780. 3,
  138781. 0,
  138782. 4,
  138783. };
  138784. static long _vq_lengthlist__16u0__p6_1[] = {
  138785. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  138786. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  138787. };
  138788. static float _vq_quantthresh__16u0__p6_1[] = {
  138789. -1.5, -0.5, 0.5, 1.5,
  138790. };
  138791. static long _vq_quantmap__16u0__p6_1[] = {
  138792. 3, 1, 0, 2, 4,
  138793. };
  138794. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  138795. _vq_quantthresh__16u0__p6_1,
  138796. _vq_quantmap__16u0__p6_1,
  138797. 5,
  138798. 5
  138799. };
  138800. static static_codebook _16u0__p6_1 = {
  138801. 2, 25,
  138802. _vq_lengthlist__16u0__p6_1,
  138803. 1, -533725184, 1611661312, 3, 0,
  138804. _vq_quantlist__16u0__p6_1,
  138805. NULL,
  138806. &_vq_auxt__16u0__p6_1,
  138807. NULL,
  138808. 0
  138809. };
  138810. static long _vq_quantlist__16u0__p7_0[] = {
  138811. 1,
  138812. 0,
  138813. 2,
  138814. };
  138815. static long _vq_lengthlist__16u0__p7_0[] = {
  138816. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138817. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138818. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138819. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138820. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138821. 7,
  138822. };
  138823. static float _vq_quantthresh__16u0__p7_0[] = {
  138824. -157.5, 157.5,
  138825. };
  138826. static long _vq_quantmap__16u0__p7_0[] = {
  138827. 1, 0, 2,
  138828. };
  138829. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  138830. _vq_quantthresh__16u0__p7_0,
  138831. _vq_quantmap__16u0__p7_0,
  138832. 3,
  138833. 3
  138834. };
  138835. static static_codebook _16u0__p7_0 = {
  138836. 4, 81,
  138837. _vq_lengthlist__16u0__p7_0,
  138838. 1, -518803456, 1628680192, 2, 0,
  138839. _vq_quantlist__16u0__p7_0,
  138840. NULL,
  138841. &_vq_auxt__16u0__p7_0,
  138842. NULL,
  138843. 0
  138844. };
  138845. static long _vq_quantlist__16u0__p7_1[] = {
  138846. 7,
  138847. 6,
  138848. 8,
  138849. 5,
  138850. 9,
  138851. 4,
  138852. 10,
  138853. 3,
  138854. 11,
  138855. 2,
  138856. 12,
  138857. 1,
  138858. 13,
  138859. 0,
  138860. 14,
  138861. };
  138862. static long _vq_lengthlist__16u0__p7_1[] = {
  138863. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  138864. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  138865. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  138866. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  138867. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  138868. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  138869. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138871. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138872. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138873. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138874. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138875. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138876. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138877. 10,
  138878. };
  138879. static float _vq_quantthresh__16u0__p7_1[] = {
  138880. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138881. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138882. };
  138883. static long _vq_quantmap__16u0__p7_1[] = {
  138884. 13, 11, 9, 7, 5, 3, 1, 0,
  138885. 2, 4, 6, 8, 10, 12, 14,
  138886. };
  138887. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  138888. _vq_quantthresh__16u0__p7_1,
  138889. _vq_quantmap__16u0__p7_1,
  138890. 15,
  138891. 15
  138892. };
  138893. static static_codebook _16u0__p7_1 = {
  138894. 2, 225,
  138895. _vq_lengthlist__16u0__p7_1,
  138896. 1, -520986624, 1620377600, 4, 0,
  138897. _vq_quantlist__16u0__p7_1,
  138898. NULL,
  138899. &_vq_auxt__16u0__p7_1,
  138900. NULL,
  138901. 0
  138902. };
  138903. static long _vq_quantlist__16u0__p7_2[] = {
  138904. 10,
  138905. 9,
  138906. 11,
  138907. 8,
  138908. 12,
  138909. 7,
  138910. 13,
  138911. 6,
  138912. 14,
  138913. 5,
  138914. 15,
  138915. 4,
  138916. 16,
  138917. 3,
  138918. 17,
  138919. 2,
  138920. 18,
  138921. 1,
  138922. 19,
  138923. 0,
  138924. 20,
  138925. };
  138926. static long _vq_lengthlist__16u0__p7_2[] = {
  138927. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  138928. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  138929. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  138930. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  138931. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  138932. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  138933. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  138934. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  138935. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  138936. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  138937. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  138938. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  138939. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  138940. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  138941. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  138942. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  138943. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  138944. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  138945. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  138946. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  138947. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  138948. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  138949. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  138950. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  138951. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  138952. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  138953. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  138954. 10,10,12,11,10,11,11,11,10,
  138955. };
  138956. static float _vq_quantthresh__16u0__p7_2[] = {
  138957. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138958. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138959. 6.5, 7.5, 8.5, 9.5,
  138960. };
  138961. static long _vq_quantmap__16u0__p7_2[] = {
  138962. 19, 17, 15, 13, 11, 9, 7, 5,
  138963. 3, 1, 0, 2, 4, 6, 8, 10,
  138964. 12, 14, 16, 18, 20,
  138965. };
  138966. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  138967. _vq_quantthresh__16u0__p7_2,
  138968. _vq_quantmap__16u0__p7_2,
  138969. 21,
  138970. 21
  138971. };
  138972. static static_codebook _16u0__p7_2 = {
  138973. 2, 441,
  138974. _vq_lengthlist__16u0__p7_2,
  138975. 1, -529268736, 1611661312, 5, 0,
  138976. _vq_quantlist__16u0__p7_2,
  138977. NULL,
  138978. &_vq_auxt__16u0__p7_2,
  138979. NULL,
  138980. 0
  138981. };
  138982. static long _huff_lengthlist__16u0__single[] = {
  138983. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  138984. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  138985. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  138986. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  138987. };
  138988. static static_codebook _huff_book__16u0__single = {
  138989. 2, 64,
  138990. _huff_lengthlist__16u0__single,
  138991. 0, 0, 0, 0, 0,
  138992. NULL,
  138993. NULL,
  138994. NULL,
  138995. NULL,
  138996. 0
  138997. };
  138998. static long _huff_lengthlist__16u1__long[] = {
  138999. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  139000. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  139001. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  139002. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  139003. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  139004. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  139005. 16,13,16,18,
  139006. };
  139007. static static_codebook _huff_book__16u1__long = {
  139008. 2, 100,
  139009. _huff_lengthlist__16u1__long,
  139010. 0, 0, 0, 0, 0,
  139011. NULL,
  139012. NULL,
  139013. NULL,
  139014. NULL,
  139015. 0
  139016. };
  139017. static long _vq_quantlist__16u1__p1_0[] = {
  139018. 1,
  139019. 0,
  139020. 2,
  139021. };
  139022. static long _vq_lengthlist__16u1__p1_0[] = {
  139023. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  139024. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  139025. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  139026. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  139027. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  139028. 11,
  139029. };
  139030. static float _vq_quantthresh__16u1__p1_0[] = {
  139031. -0.5, 0.5,
  139032. };
  139033. static long _vq_quantmap__16u1__p1_0[] = {
  139034. 1, 0, 2,
  139035. };
  139036. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  139037. _vq_quantthresh__16u1__p1_0,
  139038. _vq_quantmap__16u1__p1_0,
  139039. 3,
  139040. 3
  139041. };
  139042. static static_codebook _16u1__p1_0 = {
  139043. 4, 81,
  139044. _vq_lengthlist__16u1__p1_0,
  139045. 1, -535822336, 1611661312, 2, 0,
  139046. _vq_quantlist__16u1__p1_0,
  139047. NULL,
  139048. &_vq_auxt__16u1__p1_0,
  139049. NULL,
  139050. 0
  139051. };
  139052. static long _vq_quantlist__16u1__p2_0[] = {
  139053. 1,
  139054. 0,
  139055. 2,
  139056. };
  139057. static long _vq_lengthlist__16u1__p2_0[] = {
  139058. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  139059. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  139060. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  139061. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  139062. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  139063. 8,
  139064. };
  139065. static float _vq_quantthresh__16u1__p2_0[] = {
  139066. -0.5, 0.5,
  139067. };
  139068. static long _vq_quantmap__16u1__p2_0[] = {
  139069. 1, 0, 2,
  139070. };
  139071. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  139072. _vq_quantthresh__16u1__p2_0,
  139073. _vq_quantmap__16u1__p2_0,
  139074. 3,
  139075. 3
  139076. };
  139077. static static_codebook _16u1__p2_0 = {
  139078. 4, 81,
  139079. _vq_lengthlist__16u1__p2_0,
  139080. 1, -535822336, 1611661312, 2, 0,
  139081. _vq_quantlist__16u1__p2_0,
  139082. NULL,
  139083. &_vq_auxt__16u1__p2_0,
  139084. NULL,
  139085. 0
  139086. };
  139087. static long _vq_quantlist__16u1__p3_0[] = {
  139088. 2,
  139089. 1,
  139090. 3,
  139091. 0,
  139092. 4,
  139093. };
  139094. static long _vq_lengthlist__16u1__p3_0[] = {
  139095. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139096. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  139097. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  139098. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  139099. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  139100. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  139101. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  139102. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  139103. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  139104. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  139105. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  139106. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  139107. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  139108. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  139109. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  139110. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  139111. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  139112. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  139113. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  139114. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  139115. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  139116. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  139117. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  139118. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  139119. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  139120. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  139121. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  139122. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  139123. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  139124. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  139125. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  139126. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  139127. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  139128. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  139129. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  139130. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  139131. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  139132. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  139133. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  139134. 16,
  139135. };
  139136. static float _vq_quantthresh__16u1__p3_0[] = {
  139137. -1.5, -0.5, 0.5, 1.5,
  139138. };
  139139. static long _vq_quantmap__16u1__p3_0[] = {
  139140. 3, 1, 0, 2, 4,
  139141. };
  139142. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  139143. _vq_quantthresh__16u1__p3_0,
  139144. _vq_quantmap__16u1__p3_0,
  139145. 5,
  139146. 5
  139147. };
  139148. static static_codebook _16u1__p3_0 = {
  139149. 4, 625,
  139150. _vq_lengthlist__16u1__p3_0,
  139151. 1, -533725184, 1611661312, 3, 0,
  139152. _vq_quantlist__16u1__p3_0,
  139153. NULL,
  139154. &_vq_auxt__16u1__p3_0,
  139155. NULL,
  139156. 0
  139157. };
  139158. static long _vq_quantlist__16u1__p4_0[] = {
  139159. 2,
  139160. 1,
  139161. 3,
  139162. 0,
  139163. 4,
  139164. };
  139165. static long _vq_lengthlist__16u1__p4_0[] = {
  139166. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  139167. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  139168. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  139169. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  139170. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139171. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  139172. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  139173. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  139174. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  139175. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  139176. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  139177. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  139178. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  139179. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  139180. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  139181. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  139182. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  139183. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139184. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  139185. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  139186. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  139187. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  139188. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  139189. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  139190. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  139191. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  139192. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  139193. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  139194. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  139195. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  139196. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  139197. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  139198. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  139199. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  139200. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  139201. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  139202. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  139203. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  139204. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  139205. 11,
  139206. };
  139207. static float _vq_quantthresh__16u1__p4_0[] = {
  139208. -1.5, -0.5, 0.5, 1.5,
  139209. };
  139210. static long _vq_quantmap__16u1__p4_0[] = {
  139211. 3, 1, 0, 2, 4,
  139212. };
  139213. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  139214. _vq_quantthresh__16u1__p4_0,
  139215. _vq_quantmap__16u1__p4_0,
  139216. 5,
  139217. 5
  139218. };
  139219. static static_codebook _16u1__p4_0 = {
  139220. 4, 625,
  139221. _vq_lengthlist__16u1__p4_0,
  139222. 1, -533725184, 1611661312, 3, 0,
  139223. _vq_quantlist__16u1__p4_0,
  139224. NULL,
  139225. &_vq_auxt__16u1__p4_0,
  139226. NULL,
  139227. 0
  139228. };
  139229. static long _vq_quantlist__16u1__p5_0[] = {
  139230. 4,
  139231. 3,
  139232. 5,
  139233. 2,
  139234. 6,
  139235. 1,
  139236. 7,
  139237. 0,
  139238. 8,
  139239. };
  139240. static long _vq_lengthlist__16u1__p5_0[] = {
  139241. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139242. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139243. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  139244. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  139245. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  139246. 13,
  139247. };
  139248. static float _vq_quantthresh__16u1__p5_0[] = {
  139249. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139250. };
  139251. static long _vq_quantmap__16u1__p5_0[] = {
  139252. 7, 5, 3, 1, 0, 2, 4, 6,
  139253. 8,
  139254. };
  139255. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  139256. _vq_quantthresh__16u1__p5_0,
  139257. _vq_quantmap__16u1__p5_0,
  139258. 9,
  139259. 9
  139260. };
  139261. static static_codebook _16u1__p5_0 = {
  139262. 2, 81,
  139263. _vq_lengthlist__16u1__p5_0,
  139264. 1, -531628032, 1611661312, 4, 0,
  139265. _vq_quantlist__16u1__p5_0,
  139266. NULL,
  139267. &_vq_auxt__16u1__p5_0,
  139268. NULL,
  139269. 0
  139270. };
  139271. static long _vq_quantlist__16u1__p6_0[] = {
  139272. 4,
  139273. 3,
  139274. 5,
  139275. 2,
  139276. 6,
  139277. 1,
  139278. 7,
  139279. 0,
  139280. 8,
  139281. };
  139282. static long _vq_lengthlist__16u1__p6_0[] = {
  139283. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  139284. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139285. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139286. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139287. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139288. 11,
  139289. };
  139290. static float _vq_quantthresh__16u1__p6_0[] = {
  139291. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139292. };
  139293. static long _vq_quantmap__16u1__p6_0[] = {
  139294. 7, 5, 3, 1, 0, 2, 4, 6,
  139295. 8,
  139296. };
  139297. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  139298. _vq_quantthresh__16u1__p6_0,
  139299. _vq_quantmap__16u1__p6_0,
  139300. 9,
  139301. 9
  139302. };
  139303. static static_codebook _16u1__p6_0 = {
  139304. 2, 81,
  139305. _vq_lengthlist__16u1__p6_0,
  139306. 1, -531628032, 1611661312, 4, 0,
  139307. _vq_quantlist__16u1__p6_0,
  139308. NULL,
  139309. &_vq_auxt__16u1__p6_0,
  139310. NULL,
  139311. 0
  139312. };
  139313. static long _vq_quantlist__16u1__p7_0[] = {
  139314. 1,
  139315. 0,
  139316. 2,
  139317. };
  139318. static long _vq_lengthlist__16u1__p7_0[] = {
  139319. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  139320. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  139321. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  139322. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  139323. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  139324. 13,
  139325. };
  139326. static float _vq_quantthresh__16u1__p7_0[] = {
  139327. -5.5, 5.5,
  139328. };
  139329. static long _vq_quantmap__16u1__p7_0[] = {
  139330. 1, 0, 2,
  139331. };
  139332. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  139333. _vq_quantthresh__16u1__p7_0,
  139334. _vq_quantmap__16u1__p7_0,
  139335. 3,
  139336. 3
  139337. };
  139338. static static_codebook _16u1__p7_0 = {
  139339. 4, 81,
  139340. _vq_lengthlist__16u1__p7_0,
  139341. 1, -529137664, 1618345984, 2, 0,
  139342. _vq_quantlist__16u1__p7_0,
  139343. NULL,
  139344. &_vq_auxt__16u1__p7_0,
  139345. NULL,
  139346. 0
  139347. };
  139348. static long _vq_quantlist__16u1__p7_1[] = {
  139349. 5,
  139350. 4,
  139351. 6,
  139352. 3,
  139353. 7,
  139354. 2,
  139355. 8,
  139356. 1,
  139357. 9,
  139358. 0,
  139359. 10,
  139360. };
  139361. static long _vq_lengthlist__16u1__p7_1[] = {
  139362. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  139363. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  139364. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139365. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  139366. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  139367. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  139368. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  139369. 8, 9, 9,10,10,10,10,10,10,
  139370. };
  139371. static float _vq_quantthresh__16u1__p7_1[] = {
  139372. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139373. 3.5, 4.5,
  139374. };
  139375. static long _vq_quantmap__16u1__p7_1[] = {
  139376. 9, 7, 5, 3, 1, 0, 2, 4,
  139377. 6, 8, 10,
  139378. };
  139379. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  139380. _vq_quantthresh__16u1__p7_1,
  139381. _vq_quantmap__16u1__p7_1,
  139382. 11,
  139383. 11
  139384. };
  139385. static static_codebook _16u1__p7_1 = {
  139386. 2, 121,
  139387. _vq_lengthlist__16u1__p7_1,
  139388. 1, -531365888, 1611661312, 4, 0,
  139389. _vq_quantlist__16u1__p7_1,
  139390. NULL,
  139391. &_vq_auxt__16u1__p7_1,
  139392. NULL,
  139393. 0
  139394. };
  139395. static long _vq_quantlist__16u1__p8_0[] = {
  139396. 5,
  139397. 4,
  139398. 6,
  139399. 3,
  139400. 7,
  139401. 2,
  139402. 8,
  139403. 1,
  139404. 9,
  139405. 0,
  139406. 10,
  139407. };
  139408. static long _vq_lengthlist__16u1__p8_0[] = {
  139409. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  139410. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  139411. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  139412. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  139413. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  139414. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  139415. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  139416. 13,14,14,15,15,16,16,15,16,
  139417. };
  139418. static float _vq_quantthresh__16u1__p8_0[] = {
  139419. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139420. 38.5, 49.5,
  139421. };
  139422. static long _vq_quantmap__16u1__p8_0[] = {
  139423. 9, 7, 5, 3, 1, 0, 2, 4,
  139424. 6, 8, 10,
  139425. };
  139426. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  139427. _vq_quantthresh__16u1__p8_0,
  139428. _vq_quantmap__16u1__p8_0,
  139429. 11,
  139430. 11
  139431. };
  139432. static static_codebook _16u1__p8_0 = {
  139433. 2, 121,
  139434. _vq_lengthlist__16u1__p8_0,
  139435. 1, -524582912, 1618345984, 4, 0,
  139436. _vq_quantlist__16u1__p8_0,
  139437. NULL,
  139438. &_vq_auxt__16u1__p8_0,
  139439. NULL,
  139440. 0
  139441. };
  139442. static long _vq_quantlist__16u1__p8_1[] = {
  139443. 5,
  139444. 4,
  139445. 6,
  139446. 3,
  139447. 7,
  139448. 2,
  139449. 8,
  139450. 1,
  139451. 9,
  139452. 0,
  139453. 10,
  139454. };
  139455. static long _vq_lengthlist__16u1__p8_1[] = {
  139456. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  139457. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139458. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  139459. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139460. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139461. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139462. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139463. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139464. };
  139465. static float _vq_quantthresh__16u1__p8_1[] = {
  139466. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139467. 3.5, 4.5,
  139468. };
  139469. static long _vq_quantmap__16u1__p8_1[] = {
  139470. 9, 7, 5, 3, 1, 0, 2, 4,
  139471. 6, 8, 10,
  139472. };
  139473. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  139474. _vq_quantthresh__16u1__p8_1,
  139475. _vq_quantmap__16u1__p8_1,
  139476. 11,
  139477. 11
  139478. };
  139479. static static_codebook _16u1__p8_1 = {
  139480. 2, 121,
  139481. _vq_lengthlist__16u1__p8_1,
  139482. 1, -531365888, 1611661312, 4, 0,
  139483. _vq_quantlist__16u1__p8_1,
  139484. NULL,
  139485. &_vq_auxt__16u1__p8_1,
  139486. NULL,
  139487. 0
  139488. };
  139489. static long _vq_quantlist__16u1__p9_0[] = {
  139490. 7,
  139491. 6,
  139492. 8,
  139493. 5,
  139494. 9,
  139495. 4,
  139496. 10,
  139497. 3,
  139498. 11,
  139499. 2,
  139500. 12,
  139501. 1,
  139502. 13,
  139503. 0,
  139504. 14,
  139505. };
  139506. static long _vq_lengthlist__16u1__p9_0[] = {
  139507. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139508. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139510. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139511. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139512. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139513. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139514. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139515. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139516. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139517. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139518. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139519. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139520. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139521. 8,
  139522. };
  139523. static float _vq_quantthresh__16u1__p9_0[] = {
  139524. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139525. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139526. };
  139527. static long _vq_quantmap__16u1__p9_0[] = {
  139528. 13, 11, 9, 7, 5, 3, 1, 0,
  139529. 2, 4, 6, 8, 10, 12, 14,
  139530. };
  139531. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  139532. _vq_quantthresh__16u1__p9_0,
  139533. _vq_quantmap__16u1__p9_0,
  139534. 15,
  139535. 15
  139536. };
  139537. static static_codebook _16u1__p9_0 = {
  139538. 2, 225,
  139539. _vq_lengthlist__16u1__p9_0,
  139540. 1, -514071552, 1627381760, 4, 0,
  139541. _vq_quantlist__16u1__p9_0,
  139542. NULL,
  139543. &_vq_auxt__16u1__p9_0,
  139544. NULL,
  139545. 0
  139546. };
  139547. static long _vq_quantlist__16u1__p9_1[] = {
  139548. 7,
  139549. 6,
  139550. 8,
  139551. 5,
  139552. 9,
  139553. 4,
  139554. 10,
  139555. 3,
  139556. 11,
  139557. 2,
  139558. 12,
  139559. 1,
  139560. 13,
  139561. 0,
  139562. 14,
  139563. };
  139564. static long _vq_lengthlist__16u1__p9_1[] = {
  139565. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  139566. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  139567. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  139568. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  139569. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  139570. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  139571. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  139572. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  139573. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  139574. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139575. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  139576. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139577. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139578. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  139579. 9,
  139580. };
  139581. static float _vq_quantthresh__16u1__p9_1[] = {
  139582. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139583. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139584. };
  139585. static long _vq_quantmap__16u1__p9_1[] = {
  139586. 13, 11, 9, 7, 5, 3, 1, 0,
  139587. 2, 4, 6, 8, 10, 12, 14,
  139588. };
  139589. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  139590. _vq_quantthresh__16u1__p9_1,
  139591. _vq_quantmap__16u1__p9_1,
  139592. 15,
  139593. 15
  139594. };
  139595. static static_codebook _16u1__p9_1 = {
  139596. 2, 225,
  139597. _vq_lengthlist__16u1__p9_1,
  139598. 1, -522338304, 1620115456, 4, 0,
  139599. _vq_quantlist__16u1__p9_1,
  139600. NULL,
  139601. &_vq_auxt__16u1__p9_1,
  139602. NULL,
  139603. 0
  139604. };
  139605. static long _vq_quantlist__16u1__p9_2[] = {
  139606. 8,
  139607. 7,
  139608. 9,
  139609. 6,
  139610. 10,
  139611. 5,
  139612. 11,
  139613. 4,
  139614. 12,
  139615. 3,
  139616. 13,
  139617. 2,
  139618. 14,
  139619. 1,
  139620. 15,
  139621. 0,
  139622. 16,
  139623. };
  139624. static long _vq_lengthlist__16u1__p9_2[] = {
  139625. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  139626. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  139627. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  139628. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  139629. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  139630. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  139631. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  139632. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  139633. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  139634. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  139635. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  139636. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  139637. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  139638. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  139639. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  139640. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  139641. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  139642. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  139643. 10,
  139644. };
  139645. static float _vq_quantthresh__16u1__p9_2[] = {
  139646. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139647. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139648. };
  139649. static long _vq_quantmap__16u1__p9_2[] = {
  139650. 15, 13, 11, 9, 7, 5, 3, 1,
  139651. 0, 2, 4, 6, 8, 10, 12, 14,
  139652. 16,
  139653. };
  139654. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  139655. _vq_quantthresh__16u1__p9_2,
  139656. _vq_quantmap__16u1__p9_2,
  139657. 17,
  139658. 17
  139659. };
  139660. static static_codebook _16u1__p9_2 = {
  139661. 2, 289,
  139662. _vq_lengthlist__16u1__p9_2,
  139663. 1, -529530880, 1611661312, 5, 0,
  139664. _vq_quantlist__16u1__p9_2,
  139665. NULL,
  139666. &_vq_auxt__16u1__p9_2,
  139667. NULL,
  139668. 0
  139669. };
  139670. static long _huff_lengthlist__16u1__short[] = {
  139671. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  139672. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  139673. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  139674. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  139675. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  139676. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  139677. 16,16,16,16,
  139678. };
  139679. static static_codebook _huff_book__16u1__short = {
  139680. 2, 100,
  139681. _huff_lengthlist__16u1__short,
  139682. 0, 0, 0, 0, 0,
  139683. NULL,
  139684. NULL,
  139685. NULL,
  139686. NULL,
  139687. 0
  139688. };
  139689. static long _huff_lengthlist__16u2__long[] = {
  139690. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  139691. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  139692. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  139693. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  139694. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  139695. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  139696. 13,14,18,18,
  139697. };
  139698. static static_codebook _huff_book__16u2__long = {
  139699. 2, 100,
  139700. _huff_lengthlist__16u2__long,
  139701. 0, 0, 0, 0, 0,
  139702. NULL,
  139703. NULL,
  139704. NULL,
  139705. NULL,
  139706. 0
  139707. };
  139708. static long _huff_lengthlist__16u2__short[] = {
  139709. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  139710. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  139711. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  139712. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  139713. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  139714. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  139715. 16,16,16,16,
  139716. };
  139717. static static_codebook _huff_book__16u2__short = {
  139718. 2, 100,
  139719. _huff_lengthlist__16u2__short,
  139720. 0, 0, 0, 0, 0,
  139721. NULL,
  139722. NULL,
  139723. NULL,
  139724. NULL,
  139725. 0
  139726. };
  139727. static long _vq_quantlist__16u2_p1_0[] = {
  139728. 1,
  139729. 0,
  139730. 2,
  139731. };
  139732. static long _vq_lengthlist__16u2_p1_0[] = {
  139733. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  139734. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  139735. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  139736. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  139737. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  139738. 10,
  139739. };
  139740. static float _vq_quantthresh__16u2_p1_0[] = {
  139741. -0.5, 0.5,
  139742. };
  139743. static long _vq_quantmap__16u2_p1_0[] = {
  139744. 1, 0, 2,
  139745. };
  139746. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  139747. _vq_quantthresh__16u2_p1_0,
  139748. _vq_quantmap__16u2_p1_0,
  139749. 3,
  139750. 3
  139751. };
  139752. static static_codebook _16u2_p1_0 = {
  139753. 4, 81,
  139754. _vq_lengthlist__16u2_p1_0,
  139755. 1, -535822336, 1611661312, 2, 0,
  139756. _vq_quantlist__16u2_p1_0,
  139757. NULL,
  139758. &_vq_auxt__16u2_p1_0,
  139759. NULL,
  139760. 0
  139761. };
  139762. static long _vq_quantlist__16u2_p2_0[] = {
  139763. 2,
  139764. 1,
  139765. 3,
  139766. 0,
  139767. 4,
  139768. };
  139769. static long _vq_lengthlist__16u2_p2_0[] = {
  139770. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  139771. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  139772. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  139773. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  139774. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  139775. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  139776. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  139777. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  139778. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  139779. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  139780. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  139781. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139782. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  139783. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  139784. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  139785. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  139786. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  139787. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  139788. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  139789. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  139790. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  139791. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  139792. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  139793. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  139794. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  139795. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  139796. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  139797. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  139798. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  139799. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  139800. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  139801. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  139802. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  139803. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  139804. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  139805. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  139806. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  139807. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  139808. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  139809. 13,
  139810. };
  139811. static float _vq_quantthresh__16u2_p2_0[] = {
  139812. -1.5, -0.5, 0.5, 1.5,
  139813. };
  139814. static long _vq_quantmap__16u2_p2_0[] = {
  139815. 3, 1, 0, 2, 4,
  139816. };
  139817. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  139818. _vq_quantthresh__16u2_p2_0,
  139819. _vq_quantmap__16u2_p2_0,
  139820. 5,
  139821. 5
  139822. };
  139823. static static_codebook _16u2_p2_0 = {
  139824. 4, 625,
  139825. _vq_lengthlist__16u2_p2_0,
  139826. 1, -533725184, 1611661312, 3, 0,
  139827. _vq_quantlist__16u2_p2_0,
  139828. NULL,
  139829. &_vq_auxt__16u2_p2_0,
  139830. NULL,
  139831. 0
  139832. };
  139833. static long _vq_quantlist__16u2_p3_0[] = {
  139834. 4,
  139835. 3,
  139836. 5,
  139837. 2,
  139838. 6,
  139839. 1,
  139840. 7,
  139841. 0,
  139842. 8,
  139843. };
  139844. static long _vq_lengthlist__16u2_p3_0[] = {
  139845. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  139846. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  139847. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  139848. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  139849. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  139850. 11,
  139851. };
  139852. static float _vq_quantthresh__16u2_p3_0[] = {
  139853. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139854. };
  139855. static long _vq_quantmap__16u2_p3_0[] = {
  139856. 7, 5, 3, 1, 0, 2, 4, 6,
  139857. 8,
  139858. };
  139859. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  139860. _vq_quantthresh__16u2_p3_0,
  139861. _vq_quantmap__16u2_p3_0,
  139862. 9,
  139863. 9
  139864. };
  139865. static static_codebook _16u2_p3_0 = {
  139866. 2, 81,
  139867. _vq_lengthlist__16u2_p3_0,
  139868. 1, -531628032, 1611661312, 4, 0,
  139869. _vq_quantlist__16u2_p3_0,
  139870. NULL,
  139871. &_vq_auxt__16u2_p3_0,
  139872. NULL,
  139873. 0
  139874. };
  139875. static long _vq_quantlist__16u2_p4_0[] = {
  139876. 8,
  139877. 7,
  139878. 9,
  139879. 6,
  139880. 10,
  139881. 5,
  139882. 11,
  139883. 4,
  139884. 12,
  139885. 3,
  139886. 13,
  139887. 2,
  139888. 14,
  139889. 1,
  139890. 15,
  139891. 0,
  139892. 16,
  139893. };
  139894. static long _vq_lengthlist__16u2_p4_0[] = {
  139895. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  139896. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  139897. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  139898. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139899. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139900. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  139901. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  139902. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  139903. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  139904. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  139905. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  139906. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  139907. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  139908. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  139909. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  139910. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  139911. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  139912. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  139913. 14,
  139914. };
  139915. static float _vq_quantthresh__16u2_p4_0[] = {
  139916. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139917. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139918. };
  139919. static long _vq_quantmap__16u2_p4_0[] = {
  139920. 15, 13, 11, 9, 7, 5, 3, 1,
  139921. 0, 2, 4, 6, 8, 10, 12, 14,
  139922. 16,
  139923. };
  139924. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  139925. _vq_quantthresh__16u2_p4_0,
  139926. _vq_quantmap__16u2_p4_0,
  139927. 17,
  139928. 17
  139929. };
  139930. static static_codebook _16u2_p4_0 = {
  139931. 2, 289,
  139932. _vq_lengthlist__16u2_p4_0,
  139933. 1, -529530880, 1611661312, 5, 0,
  139934. _vq_quantlist__16u2_p4_0,
  139935. NULL,
  139936. &_vq_auxt__16u2_p4_0,
  139937. NULL,
  139938. 0
  139939. };
  139940. static long _vq_quantlist__16u2_p5_0[] = {
  139941. 1,
  139942. 0,
  139943. 2,
  139944. };
  139945. static long _vq_lengthlist__16u2_p5_0[] = {
  139946. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  139947. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  139948. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  139949. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  139950. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  139951. 10,
  139952. };
  139953. static float _vq_quantthresh__16u2_p5_0[] = {
  139954. -5.5, 5.5,
  139955. };
  139956. static long _vq_quantmap__16u2_p5_0[] = {
  139957. 1, 0, 2,
  139958. };
  139959. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  139960. _vq_quantthresh__16u2_p5_0,
  139961. _vq_quantmap__16u2_p5_0,
  139962. 3,
  139963. 3
  139964. };
  139965. static static_codebook _16u2_p5_0 = {
  139966. 4, 81,
  139967. _vq_lengthlist__16u2_p5_0,
  139968. 1, -529137664, 1618345984, 2, 0,
  139969. _vq_quantlist__16u2_p5_0,
  139970. NULL,
  139971. &_vq_auxt__16u2_p5_0,
  139972. NULL,
  139973. 0
  139974. };
  139975. static long _vq_quantlist__16u2_p5_1[] = {
  139976. 5,
  139977. 4,
  139978. 6,
  139979. 3,
  139980. 7,
  139981. 2,
  139982. 8,
  139983. 1,
  139984. 9,
  139985. 0,
  139986. 10,
  139987. };
  139988. static long _vq_lengthlist__16u2_p5_1[] = {
  139989. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  139990. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  139991. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  139992. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  139993. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  139994. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  139995. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  139996. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139997. };
  139998. static float _vq_quantthresh__16u2_p5_1[] = {
  139999. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140000. 3.5, 4.5,
  140001. };
  140002. static long _vq_quantmap__16u2_p5_1[] = {
  140003. 9, 7, 5, 3, 1, 0, 2, 4,
  140004. 6, 8, 10,
  140005. };
  140006. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  140007. _vq_quantthresh__16u2_p5_1,
  140008. _vq_quantmap__16u2_p5_1,
  140009. 11,
  140010. 11
  140011. };
  140012. static static_codebook _16u2_p5_1 = {
  140013. 2, 121,
  140014. _vq_lengthlist__16u2_p5_1,
  140015. 1, -531365888, 1611661312, 4, 0,
  140016. _vq_quantlist__16u2_p5_1,
  140017. NULL,
  140018. &_vq_auxt__16u2_p5_1,
  140019. NULL,
  140020. 0
  140021. };
  140022. static long _vq_quantlist__16u2_p6_0[] = {
  140023. 6,
  140024. 5,
  140025. 7,
  140026. 4,
  140027. 8,
  140028. 3,
  140029. 9,
  140030. 2,
  140031. 10,
  140032. 1,
  140033. 11,
  140034. 0,
  140035. 12,
  140036. };
  140037. static long _vq_lengthlist__16u2_p6_0[] = {
  140038. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  140039. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  140040. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  140041. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  140042. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  140043. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  140044. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  140045. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  140046. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  140047. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  140048. 12,13,13,14,14,14,14,15,15,
  140049. };
  140050. static float _vq_quantthresh__16u2_p6_0[] = {
  140051. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140052. 12.5, 17.5, 22.5, 27.5,
  140053. };
  140054. static long _vq_quantmap__16u2_p6_0[] = {
  140055. 11, 9, 7, 5, 3, 1, 0, 2,
  140056. 4, 6, 8, 10, 12,
  140057. };
  140058. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  140059. _vq_quantthresh__16u2_p6_0,
  140060. _vq_quantmap__16u2_p6_0,
  140061. 13,
  140062. 13
  140063. };
  140064. static static_codebook _16u2_p6_0 = {
  140065. 2, 169,
  140066. _vq_lengthlist__16u2_p6_0,
  140067. 1, -526516224, 1616117760, 4, 0,
  140068. _vq_quantlist__16u2_p6_0,
  140069. NULL,
  140070. &_vq_auxt__16u2_p6_0,
  140071. NULL,
  140072. 0
  140073. };
  140074. static long _vq_quantlist__16u2_p6_1[] = {
  140075. 2,
  140076. 1,
  140077. 3,
  140078. 0,
  140079. 4,
  140080. };
  140081. static long _vq_lengthlist__16u2_p6_1[] = {
  140082. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  140083. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  140084. };
  140085. static float _vq_quantthresh__16u2_p6_1[] = {
  140086. -1.5, -0.5, 0.5, 1.5,
  140087. };
  140088. static long _vq_quantmap__16u2_p6_1[] = {
  140089. 3, 1, 0, 2, 4,
  140090. };
  140091. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  140092. _vq_quantthresh__16u2_p6_1,
  140093. _vq_quantmap__16u2_p6_1,
  140094. 5,
  140095. 5
  140096. };
  140097. static static_codebook _16u2_p6_1 = {
  140098. 2, 25,
  140099. _vq_lengthlist__16u2_p6_1,
  140100. 1, -533725184, 1611661312, 3, 0,
  140101. _vq_quantlist__16u2_p6_1,
  140102. NULL,
  140103. &_vq_auxt__16u2_p6_1,
  140104. NULL,
  140105. 0
  140106. };
  140107. static long _vq_quantlist__16u2_p7_0[] = {
  140108. 6,
  140109. 5,
  140110. 7,
  140111. 4,
  140112. 8,
  140113. 3,
  140114. 9,
  140115. 2,
  140116. 10,
  140117. 1,
  140118. 11,
  140119. 0,
  140120. 12,
  140121. };
  140122. static long _vq_lengthlist__16u2_p7_0[] = {
  140123. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  140124. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  140125. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  140126. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  140127. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  140128. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  140129. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  140130. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  140131. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  140132. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  140133. 12,13,13,13,14,14,14,15,14,
  140134. };
  140135. static float _vq_quantthresh__16u2_p7_0[] = {
  140136. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  140137. 27.5, 38.5, 49.5, 60.5,
  140138. };
  140139. static long _vq_quantmap__16u2_p7_0[] = {
  140140. 11, 9, 7, 5, 3, 1, 0, 2,
  140141. 4, 6, 8, 10, 12,
  140142. };
  140143. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  140144. _vq_quantthresh__16u2_p7_0,
  140145. _vq_quantmap__16u2_p7_0,
  140146. 13,
  140147. 13
  140148. };
  140149. static static_codebook _16u2_p7_0 = {
  140150. 2, 169,
  140151. _vq_lengthlist__16u2_p7_0,
  140152. 1, -523206656, 1618345984, 4, 0,
  140153. _vq_quantlist__16u2_p7_0,
  140154. NULL,
  140155. &_vq_auxt__16u2_p7_0,
  140156. NULL,
  140157. 0
  140158. };
  140159. static long _vq_quantlist__16u2_p7_1[] = {
  140160. 5,
  140161. 4,
  140162. 6,
  140163. 3,
  140164. 7,
  140165. 2,
  140166. 8,
  140167. 1,
  140168. 9,
  140169. 0,
  140170. 10,
  140171. };
  140172. static long _vq_lengthlist__16u2_p7_1[] = {
  140173. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  140174. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  140175. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  140176. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  140177. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  140178. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  140179. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  140180. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140181. };
  140182. static float _vq_quantthresh__16u2_p7_1[] = {
  140183. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140184. 3.5, 4.5,
  140185. };
  140186. static long _vq_quantmap__16u2_p7_1[] = {
  140187. 9, 7, 5, 3, 1, 0, 2, 4,
  140188. 6, 8, 10,
  140189. };
  140190. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  140191. _vq_quantthresh__16u2_p7_1,
  140192. _vq_quantmap__16u2_p7_1,
  140193. 11,
  140194. 11
  140195. };
  140196. static static_codebook _16u2_p7_1 = {
  140197. 2, 121,
  140198. _vq_lengthlist__16u2_p7_1,
  140199. 1, -531365888, 1611661312, 4, 0,
  140200. _vq_quantlist__16u2_p7_1,
  140201. NULL,
  140202. &_vq_auxt__16u2_p7_1,
  140203. NULL,
  140204. 0
  140205. };
  140206. static long _vq_quantlist__16u2_p8_0[] = {
  140207. 7,
  140208. 6,
  140209. 8,
  140210. 5,
  140211. 9,
  140212. 4,
  140213. 10,
  140214. 3,
  140215. 11,
  140216. 2,
  140217. 12,
  140218. 1,
  140219. 13,
  140220. 0,
  140221. 14,
  140222. };
  140223. static long _vq_lengthlist__16u2_p8_0[] = {
  140224. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  140225. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  140226. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  140227. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  140228. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  140229. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  140230. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  140231. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  140232. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  140233. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  140234. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  140235. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  140236. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  140237. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  140238. 14,
  140239. };
  140240. static float _vq_quantthresh__16u2_p8_0[] = {
  140241. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140242. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140243. };
  140244. static long _vq_quantmap__16u2_p8_0[] = {
  140245. 13, 11, 9, 7, 5, 3, 1, 0,
  140246. 2, 4, 6, 8, 10, 12, 14,
  140247. };
  140248. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  140249. _vq_quantthresh__16u2_p8_0,
  140250. _vq_quantmap__16u2_p8_0,
  140251. 15,
  140252. 15
  140253. };
  140254. static static_codebook _16u2_p8_0 = {
  140255. 2, 225,
  140256. _vq_lengthlist__16u2_p8_0,
  140257. 1, -520986624, 1620377600, 4, 0,
  140258. _vq_quantlist__16u2_p8_0,
  140259. NULL,
  140260. &_vq_auxt__16u2_p8_0,
  140261. NULL,
  140262. 0
  140263. };
  140264. static long _vq_quantlist__16u2_p8_1[] = {
  140265. 10,
  140266. 9,
  140267. 11,
  140268. 8,
  140269. 12,
  140270. 7,
  140271. 13,
  140272. 6,
  140273. 14,
  140274. 5,
  140275. 15,
  140276. 4,
  140277. 16,
  140278. 3,
  140279. 17,
  140280. 2,
  140281. 18,
  140282. 1,
  140283. 19,
  140284. 0,
  140285. 20,
  140286. };
  140287. static long _vq_lengthlist__16u2_p8_1[] = {
  140288. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  140289. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  140290. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  140291. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  140292. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  140293. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  140294. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  140295. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  140296. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  140297. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  140298. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  140299. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  140300. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  140301. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  140302. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  140303. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  140304. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  140305. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  140306. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  140307. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  140308. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  140309. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  140310. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  140311. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  140312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140313. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  140314. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  140315. 11,11,10,11,11,11,10,11,11,
  140316. };
  140317. static float _vq_quantthresh__16u2_p8_1[] = {
  140318. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  140319. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  140320. 6.5, 7.5, 8.5, 9.5,
  140321. };
  140322. static long _vq_quantmap__16u2_p8_1[] = {
  140323. 19, 17, 15, 13, 11, 9, 7, 5,
  140324. 3, 1, 0, 2, 4, 6, 8, 10,
  140325. 12, 14, 16, 18, 20,
  140326. };
  140327. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  140328. _vq_quantthresh__16u2_p8_1,
  140329. _vq_quantmap__16u2_p8_1,
  140330. 21,
  140331. 21
  140332. };
  140333. static static_codebook _16u2_p8_1 = {
  140334. 2, 441,
  140335. _vq_lengthlist__16u2_p8_1,
  140336. 1, -529268736, 1611661312, 5, 0,
  140337. _vq_quantlist__16u2_p8_1,
  140338. NULL,
  140339. &_vq_auxt__16u2_p8_1,
  140340. NULL,
  140341. 0
  140342. };
  140343. static long _vq_quantlist__16u2_p9_0[] = {
  140344. 5586,
  140345. 4655,
  140346. 6517,
  140347. 3724,
  140348. 7448,
  140349. 2793,
  140350. 8379,
  140351. 1862,
  140352. 9310,
  140353. 931,
  140354. 10241,
  140355. 0,
  140356. 11172,
  140357. 5521,
  140358. 5651,
  140359. };
  140360. static long _vq_lengthlist__16u2_p9_0[] = {
  140361. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  140362. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140363. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140364. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140365. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140366. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140367. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140368. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140369. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140370. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140371. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140373. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  140374. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  140375. 5,
  140376. };
  140377. static float _vq_quantthresh__16u2_p9_0[] = {
  140378. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  140379. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  140380. };
  140381. static long _vq_quantmap__16u2_p9_0[] = {
  140382. 11, 9, 7, 5, 3, 1, 13, 0,
  140383. 14, 2, 4, 6, 8, 10, 12,
  140384. };
  140385. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  140386. _vq_quantthresh__16u2_p9_0,
  140387. _vq_quantmap__16u2_p9_0,
  140388. 15,
  140389. 15
  140390. };
  140391. static static_codebook _16u2_p9_0 = {
  140392. 2, 225,
  140393. _vq_lengthlist__16u2_p9_0,
  140394. 1, -510275072, 1611661312, 14, 0,
  140395. _vq_quantlist__16u2_p9_0,
  140396. NULL,
  140397. &_vq_auxt__16u2_p9_0,
  140398. NULL,
  140399. 0
  140400. };
  140401. static long _vq_quantlist__16u2_p9_1[] = {
  140402. 392,
  140403. 343,
  140404. 441,
  140405. 294,
  140406. 490,
  140407. 245,
  140408. 539,
  140409. 196,
  140410. 588,
  140411. 147,
  140412. 637,
  140413. 98,
  140414. 686,
  140415. 49,
  140416. 735,
  140417. 0,
  140418. 784,
  140419. 388,
  140420. 396,
  140421. };
  140422. static long _vq_lengthlist__16u2_p9_1[] = {
  140423. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  140424. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  140425. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  140426. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  140427. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  140428. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  140429. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140430. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  140431. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  140432. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140433. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140434. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140435. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140436. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140437. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  140438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140439. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140440. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140441. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140442. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140443. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  140444. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  140445. 11,11,11,11,11,11,11, 5, 4,
  140446. };
  140447. static float _vq_quantthresh__16u2_p9_1[] = {
  140448. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  140449. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  140450. 318.5, 367.5,
  140451. };
  140452. static long _vq_quantmap__16u2_p9_1[] = {
  140453. 15, 13, 11, 9, 7, 5, 3, 1,
  140454. 17, 0, 18, 2, 4, 6, 8, 10,
  140455. 12, 14, 16,
  140456. };
  140457. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  140458. _vq_quantthresh__16u2_p9_1,
  140459. _vq_quantmap__16u2_p9_1,
  140460. 19,
  140461. 19
  140462. };
  140463. static static_codebook _16u2_p9_1 = {
  140464. 2, 361,
  140465. _vq_lengthlist__16u2_p9_1,
  140466. 1, -518488064, 1611661312, 10, 0,
  140467. _vq_quantlist__16u2_p9_1,
  140468. NULL,
  140469. &_vq_auxt__16u2_p9_1,
  140470. NULL,
  140471. 0
  140472. };
  140473. static long _vq_quantlist__16u2_p9_2[] = {
  140474. 24,
  140475. 23,
  140476. 25,
  140477. 22,
  140478. 26,
  140479. 21,
  140480. 27,
  140481. 20,
  140482. 28,
  140483. 19,
  140484. 29,
  140485. 18,
  140486. 30,
  140487. 17,
  140488. 31,
  140489. 16,
  140490. 32,
  140491. 15,
  140492. 33,
  140493. 14,
  140494. 34,
  140495. 13,
  140496. 35,
  140497. 12,
  140498. 36,
  140499. 11,
  140500. 37,
  140501. 10,
  140502. 38,
  140503. 9,
  140504. 39,
  140505. 8,
  140506. 40,
  140507. 7,
  140508. 41,
  140509. 6,
  140510. 42,
  140511. 5,
  140512. 43,
  140513. 4,
  140514. 44,
  140515. 3,
  140516. 45,
  140517. 2,
  140518. 46,
  140519. 1,
  140520. 47,
  140521. 0,
  140522. 48,
  140523. };
  140524. static long _vq_lengthlist__16u2_p9_2[] = {
  140525. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  140526. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  140527. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  140528. 11,
  140529. };
  140530. static float _vq_quantthresh__16u2_p9_2[] = {
  140531. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  140532. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  140533. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140534. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140535. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  140536. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  140537. };
  140538. static long _vq_quantmap__16u2_p9_2[] = {
  140539. 47, 45, 43, 41, 39, 37, 35, 33,
  140540. 31, 29, 27, 25, 23, 21, 19, 17,
  140541. 15, 13, 11, 9, 7, 5, 3, 1,
  140542. 0, 2, 4, 6, 8, 10, 12, 14,
  140543. 16, 18, 20, 22, 24, 26, 28, 30,
  140544. 32, 34, 36, 38, 40, 42, 44, 46,
  140545. 48,
  140546. };
  140547. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  140548. _vq_quantthresh__16u2_p9_2,
  140549. _vq_quantmap__16u2_p9_2,
  140550. 49,
  140551. 49
  140552. };
  140553. static static_codebook _16u2_p9_2 = {
  140554. 1, 49,
  140555. _vq_lengthlist__16u2_p9_2,
  140556. 1, -526909440, 1611661312, 6, 0,
  140557. _vq_quantlist__16u2_p9_2,
  140558. NULL,
  140559. &_vq_auxt__16u2_p9_2,
  140560. NULL,
  140561. 0
  140562. };
  140563. static long _vq_quantlist__8u0__p1_0[] = {
  140564. 1,
  140565. 0,
  140566. 2,
  140567. };
  140568. static long _vq_lengthlist__8u0__p1_0[] = {
  140569. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  140570. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  140571. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  140572. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  140573. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  140574. 11,
  140575. };
  140576. static float _vq_quantthresh__8u0__p1_0[] = {
  140577. -0.5, 0.5,
  140578. };
  140579. static long _vq_quantmap__8u0__p1_0[] = {
  140580. 1, 0, 2,
  140581. };
  140582. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  140583. _vq_quantthresh__8u0__p1_0,
  140584. _vq_quantmap__8u0__p1_0,
  140585. 3,
  140586. 3
  140587. };
  140588. static static_codebook _8u0__p1_0 = {
  140589. 4, 81,
  140590. _vq_lengthlist__8u0__p1_0,
  140591. 1, -535822336, 1611661312, 2, 0,
  140592. _vq_quantlist__8u0__p1_0,
  140593. NULL,
  140594. &_vq_auxt__8u0__p1_0,
  140595. NULL,
  140596. 0
  140597. };
  140598. static long _vq_quantlist__8u0__p2_0[] = {
  140599. 1,
  140600. 0,
  140601. 2,
  140602. };
  140603. static long _vq_lengthlist__8u0__p2_0[] = {
  140604. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  140605. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  140606. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  140607. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  140608. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  140609. 8,
  140610. };
  140611. static float _vq_quantthresh__8u0__p2_0[] = {
  140612. -0.5, 0.5,
  140613. };
  140614. static long _vq_quantmap__8u0__p2_0[] = {
  140615. 1, 0, 2,
  140616. };
  140617. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  140618. _vq_quantthresh__8u0__p2_0,
  140619. _vq_quantmap__8u0__p2_0,
  140620. 3,
  140621. 3
  140622. };
  140623. static static_codebook _8u0__p2_0 = {
  140624. 4, 81,
  140625. _vq_lengthlist__8u0__p2_0,
  140626. 1, -535822336, 1611661312, 2, 0,
  140627. _vq_quantlist__8u0__p2_0,
  140628. NULL,
  140629. &_vq_auxt__8u0__p2_0,
  140630. NULL,
  140631. 0
  140632. };
  140633. static long _vq_quantlist__8u0__p3_0[] = {
  140634. 2,
  140635. 1,
  140636. 3,
  140637. 0,
  140638. 4,
  140639. };
  140640. static long _vq_lengthlist__8u0__p3_0[] = {
  140641. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  140642. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  140643. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  140644. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140645. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  140646. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  140647. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  140648. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  140649. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  140650. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  140651. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  140652. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  140653. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  140654. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  140655. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  140656. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  140657. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  140658. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  140659. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  140660. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  140661. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  140662. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  140663. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  140664. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  140665. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  140666. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  140667. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  140668. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  140669. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  140670. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  140671. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  140672. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  140673. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  140674. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  140675. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  140676. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  140677. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  140678. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  140679. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  140680. 16,
  140681. };
  140682. static float _vq_quantthresh__8u0__p3_0[] = {
  140683. -1.5, -0.5, 0.5, 1.5,
  140684. };
  140685. static long _vq_quantmap__8u0__p3_0[] = {
  140686. 3, 1, 0, 2, 4,
  140687. };
  140688. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  140689. _vq_quantthresh__8u0__p3_0,
  140690. _vq_quantmap__8u0__p3_0,
  140691. 5,
  140692. 5
  140693. };
  140694. static static_codebook _8u0__p3_0 = {
  140695. 4, 625,
  140696. _vq_lengthlist__8u0__p3_0,
  140697. 1, -533725184, 1611661312, 3, 0,
  140698. _vq_quantlist__8u0__p3_0,
  140699. NULL,
  140700. &_vq_auxt__8u0__p3_0,
  140701. NULL,
  140702. 0
  140703. };
  140704. static long _vq_quantlist__8u0__p4_0[] = {
  140705. 2,
  140706. 1,
  140707. 3,
  140708. 0,
  140709. 4,
  140710. };
  140711. static long _vq_lengthlist__8u0__p4_0[] = {
  140712. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  140713. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  140714. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  140715. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  140716. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  140717. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  140718. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  140719. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  140720. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  140721. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  140722. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  140723. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  140724. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  140725. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  140726. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  140727. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  140728. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  140729. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  140730. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  140731. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  140732. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  140733. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  140734. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  140735. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  140736. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  140737. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  140738. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  140739. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  140740. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  140741. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  140742. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  140743. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  140744. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  140745. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  140746. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  140747. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  140748. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  140749. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  140750. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  140751. 12,
  140752. };
  140753. static float _vq_quantthresh__8u0__p4_0[] = {
  140754. -1.5, -0.5, 0.5, 1.5,
  140755. };
  140756. static long _vq_quantmap__8u0__p4_0[] = {
  140757. 3, 1, 0, 2, 4,
  140758. };
  140759. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  140760. _vq_quantthresh__8u0__p4_0,
  140761. _vq_quantmap__8u0__p4_0,
  140762. 5,
  140763. 5
  140764. };
  140765. static static_codebook _8u0__p4_0 = {
  140766. 4, 625,
  140767. _vq_lengthlist__8u0__p4_0,
  140768. 1, -533725184, 1611661312, 3, 0,
  140769. _vq_quantlist__8u0__p4_0,
  140770. NULL,
  140771. &_vq_auxt__8u0__p4_0,
  140772. NULL,
  140773. 0
  140774. };
  140775. static long _vq_quantlist__8u0__p5_0[] = {
  140776. 4,
  140777. 3,
  140778. 5,
  140779. 2,
  140780. 6,
  140781. 1,
  140782. 7,
  140783. 0,
  140784. 8,
  140785. };
  140786. static long _vq_lengthlist__8u0__p5_0[] = {
  140787. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  140788. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  140789. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  140790. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140791. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  140792. 12,
  140793. };
  140794. static float _vq_quantthresh__8u0__p5_0[] = {
  140795. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140796. };
  140797. static long _vq_quantmap__8u0__p5_0[] = {
  140798. 7, 5, 3, 1, 0, 2, 4, 6,
  140799. 8,
  140800. };
  140801. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  140802. _vq_quantthresh__8u0__p5_0,
  140803. _vq_quantmap__8u0__p5_0,
  140804. 9,
  140805. 9
  140806. };
  140807. static static_codebook _8u0__p5_0 = {
  140808. 2, 81,
  140809. _vq_lengthlist__8u0__p5_0,
  140810. 1, -531628032, 1611661312, 4, 0,
  140811. _vq_quantlist__8u0__p5_0,
  140812. NULL,
  140813. &_vq_auxt__8u0__p5_0,
  140814. NULL,
  140815. 0
  140816. };
  140817. static long _vq_quantlist__8u0__p6_0[] = {
  140818. 6,
  140819. 5,
  140820. 7,
  140821. 4,
  140822. 8,
  140823. 3,
  140824. 9,
  140825. 2,
  140826. 10,
  140827. 1,
  140828. 11,
  140829. 0,
  140830. 12,
  140831. };
  140832. static long _vq_lengthlist__8u0__p6_0[] = {
  140833. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  140834. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  140835. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  140836. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  140837. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  140838. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  140839. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  140840. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  140841. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  140842. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  140843. 16, 0,15, 0,17, 0, 0, 0, 0,
  140844. };
  140845. static float _vq_quantthresh__8u0__p6_0[] = {
  140846. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140847. 12.5, 17.5, 22.5, 27.5,
  140848. };
  140849. static long _vq_quantmap__8u0__p6_0[] = {
  140850. 11, 9, 7, 5, 3, 1, 0, 2,
  140851. 4, 6, 8, 10, 12,
  140852. };
  140853. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  140854. _vq_quantthresh__8u0__p6_0,
  140855. _vq_quantmap__8u0__p6_0,
  140856. 13,
  140857. 13
  140858. };
  140859. static static_codebook _8u0__p6_0 = {
  140860. 2, 169,
  140861. _vq_lengthlist__8u0__p6_0,
  140862. 1, -526516224, 1616117760, 4, 0,
  140863. _vq_quantlist__8u0__p6_0,
  140864. NULL,
  140865. &_vq_auxt__8u0__p6_0,
  140866. NULL,
  140867. 0
  140868. };
  140869. static long _vq_quantlist__8u0__p6_1[] = {
  140870. 2,
  140871. 1,
  140872. 3,
  140873. 0,
  140874. 4,
  140875. };
  140876. static long _vq_lengthlist__8u0__p6_1[] = {
  140877. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  140878. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  140879. };
  140880. static float _vq_quantthresh__8u0__p6_1[] = {
  140881. -1.5, -0.5, 0.5, 1.5,
  140882. };
  140883. static long _vq_quantmap__8u0__p6_1[] = {
  140884. 3, 1, 0, 2, 4,
  140885. };
  140886. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  140887. _vq_quantthresh__8u0__p6_1,
  140888. _vq_quantmap__8u0__p6_1,
  140889. 5,
  140890. 5
  140891. };
  140892. static static_codebook _8u0__p6_1 = {
  140893. 2, 25,
  140894. _vq_lengthlist__8u0__p6_1,
  140895. 1, -533725184, 1611661312, 3, 0,
  140896. _vq_quantlist__8u0__p6_1,
  140897. NULL,
  140898. &_vq_auxt__8u0__p6_1,
  140899. NULL,
  140900. 0
  140901. };
  140902. static long _vq_quantlist__8u0__p7_0[] = {
  140903. 1,
  140904. 0,
  140905. 2,
  140906. };
  140907. static long _vq_lengthlist__8u0__p7_0[] = {
  140908. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140909. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140910. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140911. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140912. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  140913. 7,
  140914. };
  140915. static float _vq_quantthresh__8u0__p7_0[] = {
  140916. -157.5, 157.5,
  140917. };
  140918. static long _vq_quantmap__8u0__p7_0[] = {
  140919. 1, 0, 2,
  140920. };
  140921. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  140922. _vq_quantthresh__8u0__p7_0,
  140923. _vq_quantmap__8u0__p7_0,
  140924. 3,
  140925. 3
  140926. };
  140927. static static_codebook _8u0__p7_0 = {
  140928. 4, 81,
  140929. _vq_lengthlist__8u0__p7_0,
  140930. 1, -518803456, 1628680192, 2, 0,
  140931. _vq_quantlist__8u0__p7_0,
  140932. NULL,
  140933. &_vq_auxt__8u0__p7_0,
  140934. NULL,
  140935. 0
  140936. };
  140937. static long _vq_quantlist__8u0__p7_1[] = {
  140938. 7,
  140939. 6,
  140940. 8,
  140941. 5,
  140942. 9,
  140943. 4,
  140944. 10,
  140945. 3,
  140946. 11,
  140947. 2,
  140948. 12,
  140949. 1,
  140950. 13,
  140951. 0,
  140952. 14,
  140953. };
  140954. static long _vq_lengthlist__8u0__p7_1[] = {
  140955. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  140956. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  140957. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  140958. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  140959. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  140960. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  140961. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140962. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140963. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140964. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140965. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140966. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140967. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  140968. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  140969. 10,
  140970. };
  140971. static float _vq_quantthresh__8u0__p7_1[] = {
  140972. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  140973. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  140974. };
  140975. static long _vq_quantmap__8u0__p7_1[] = {
  140976. 13, 11, 9, 7, 5, 3, 1, 0,
  140977. 2, 4, 6, 8, 10, 12, 14,
  140978. };
  140979. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  140980. _vq_quantthresh__8u0__p7_1,
  140981. _vq_quantmap__8u0__p7_1,
  140982. 15,
  140983. 15
  140984. };
  140985. static static_codebook _8u0__p7_1 = {
  140986. 2, 225,
  140987. _vq_lengthlist__8u0__p7_1,
  140988. 1, -520986624, 1620377600, 4, 0,
  140989. _vq_quantlist__8u0__p7_1,
  140990. NULL,
  140991. &_vq_auxt__8u0__p7_1,
  140992. NULL,
  140993. 0
  140994. };
  140995. static long _vq_quantlist__8u0__p7_2[] = {
  140996. 10,
  140997. 9,
  140998. 11,
  140999. 8,
  141000. 12,
  141001. 7,
  141002. 13,
  141003. 6,
  141004. 14,
  141005. 5,
  141006. 15,
  141007. 4,
  141008. 16,
  141009. 3,
  141010. 17,
  141011. 2,
  141012. 18,
  141013. 1,
  141014. 19,
  141015. 0,
  141016. 20,
  141017. };
  141018. static long _vq_lengthlist__8u0__p7_2[] = {
  141019. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  141020. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  141021. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  141022. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  141023. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  141024. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  141025. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  141026. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  141027. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  141028. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  141029. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  141030. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  141031. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  141032. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  141033. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  141034. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  141035. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  141036. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  141037. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  141038. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  141039. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  141040. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  141041. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  141042. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  141043. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  141044. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  141045. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  141046. 11,12,11,11,11,10,10,11,11,
  141047. };
  141048. static float _vq_quantthresh__8u0__p7_2[] = {
  141049. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  141050. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  141051. 6.5, 7.5, 8.5, 9.5,
  141052. };
  141053. static long _vq_quantmap__8u0__p7_2[] = {
  141054. 19, 17, 15, 13, 11, 9, 7, 5,
  141055. 3, 1, 0, 2, 4, 6, 8, 10,
  141056. 12, 14, 16, 18, 20,
  141057. };
  141058. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  141059. _vq_quantthresh__8u0__p7_2,
  141060. _vq_quantmap__8u0__p7_2,
  141061. 21,
  141062. 21
  141063. };
  141064. static static_codebook _8u0__p7_2 = {
  141065. 2, 441,
  141066. _vq_lengthlist__8u0__p7_2,
  141067. 1, -529268736, 1611661312, 5, 0,
  141068. _vq_quantlist__8u0__p7_2,
  141069. NULL,
  141070. &_vq_auxt__8u0__p7_2,
  141071. NULL,
  141072. 0
  141073. };
  141074. static long _huff_lengthlist__8u0__single[] = {
  141075. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  141076. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  141077. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  141078. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  141079. };
  141080. static static_codebook _huff_book__8u0__single = {
  141081. 2, 64,
  141082. _huff_lengthlist__8u0__single,
  141083. 0, 0, 0, 0, 0,
  141084. NULL,
  141085. NULL,
  141086. NULL,
  141087. NULL,
  141088. 0
  141089. };
  141090. static long _vq_quantlist__8u1__p1_0[] = {
  141091. 1,
  141092. 0,
  141093. 2,
  141094. };
  141095. static long _vq_lengthlist__8u1__p1_0[] = {
  141096. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  141097. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  141098. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  141099. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  141100. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  141101. 10,
  141102. };
  141103. static float _vq_quantthresh__8u1__p1_0[] = {
  141104. -0.5, 0.5,
  141105. };
  141106. static long _vq_quantmap__8u1__p1_0[] = {
  141107. 1, 0, 2,
  141108. };
  141109. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  141110. _vq_quantthresh__8u1__p1_0,
  141111. _vq_quantmap__8u1__p1_0,
  141112. 3,
  141113. 3
  141114. };
  141115. static static_codebook _8u1__p1_0 = {
  141116. 4, 81,
  141117. _vq_lengthlist__8u1__p1_0,
  141118. 1, -535822336, 1611661312, 2, 0,
  141119. _vq_quantlist__8u1__p1_0,
  141120. NULL,
  141121. &_vq_auxt__8u1__p1_0,
  141122. NULL,
  141123. 0
  141124. };
  141125. static long _vq_quantlist__8u1__p2_0[] = {
  141126. 1,
  141127. 0,
  141128. 2,
  141129. };
  141130. static long _vq_lengthlist__8u1__p2_0[] = {
  141131. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  141132. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  141133. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  141134. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  141135. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  141136. 7,
  141137. };
  141138. static float _vq_quantthresh__8u1__p2_0[] = {
  141139. -0.5, 0.5,
  141140. };
  141141. static long _vq_quantmap__8u1__p2_0[] = {
  141142. 1, 0, 2,
  141143. };
  141144. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  141145. _vq_quantthresh__8u1__p2_0,
  141146. _vq_quantmap__8u1__p2_0,
  141147. 3,
  141148. 3
  141149. };
  141150. static static_codebook _8u1__p2_0 = {
  141151. 4, 81,
  141152. _vq_lengthlist__8u1__p2_0,
  141153. 1, -535822336, 1611661312, 2, 0,
  141154. _vq_quantlist__8u1__p2_0,
  141155. NULL,
  141156. &_vq_auxt__8u1__p2_0,
  141157. NULL,
  141158. 0
  141159. };
  141160. static long _vq_quantlist__8u1__p3_0[] = {
  141161. 2,
  141162. 1,
  141163. 3,
  141164. 0,
  141165. 4,
  141166. };
  141167. static long _vq_lengthlist__8u1__p3_0[] = {
  141168. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  141169. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  141170. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  141171. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  141172. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  141173. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  141174. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  141175. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  141176. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  141177. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  141178. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  141179. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  141180. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  141181. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  141182. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  141183. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  141184. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  141185. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  141186. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  141187. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  141188. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  141189. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  141190. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  141191. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  141192. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  141193. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  141194. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  141195. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  141196. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  141197. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  141198. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  141199. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  141200. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  141201. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  141202. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  141203. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  141204. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  141205. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  141206. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  141207. 16,
  141208. };
  141209. static float _vq_quantthresh__8u1__p3_0[] = {
  141210. -1.5, -0.5, 0.5, 1.5,
  141211. };
  141212. static long _vq_quantmap__8u1__p3_0[] = {
  141213. 3, 1, 0, 2, 4,
  141214. };
  141215. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  141216. _vq_quantthresh__8u1__p3_0,
  141217. _vq_quantmap__8u1__p3_0,
  141218. 5,
  141219. 5
  141220. };
  141221. static static_codebook _8u1__p3_0 = {
  141222. 4, 625,
  141223. _vq_lengthlist__8u1__p3_0,
  141224. 1, -533725184, 1611661312, 3, 0,
  141225. _vq_quantlist__8u1__p3_0,
  141226. NULL,
  141227. &_vq_auxt__8u1__p3_0,
  141228. NULL,
  141229. 0
  141230. };
  141231. static long _vq_quantlist__8u1__p4_0[] = {
  141232. 2,
  141233. 1,
  141234. 3,
  141235. 0,
  141236. 4,
  141237. };
  141238. static long _vq_lengthlist__8u1__p4_0[] = {
  141239. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  141240. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  141241. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  141242. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  141243. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  141244. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  141245. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  141246. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  141247. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  141248. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  141249. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  141250. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  141251. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  141252. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  141253. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  141254. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  141255. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  141256. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  141257. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  141258. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  141259. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  141260. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  141261. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  141262. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  141263. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  141264. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  141265. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  141266. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  141267. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  141268. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  141269. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  141270. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  141271. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  141272. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  141273. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  141274. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  141275. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  141276. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  141277. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  141278. 10,
  141279. };
  141280. static float _vq_quantthresh__8u1__p4_0[] = {
  141281. -1.5, -0.5, 0.5, 1.5,
  141282. };
  141283. static long _vq_quantmap__8u1__p4_0[] = {
  141284. 3, 1, 0, 2, 4,
  141285. };
  141286. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  141287. _vq_quantthresh__8u1__p4_0,
  141288. _vq_quantmap__8u1__p4_0,
  141289. 5,
  141290. 5
  141291. };
  141292. static static_codebook _8u1__p4_0 = {
  141293. 4, 625,
  141294. _vq_lengthlist__8u1__p4_0,
  141295. 1, -533725184, 1611661312, 3, 0,
  141296. _vq_quantlist__8u1__p4_0,
  141297. NULL,
  141298. &_vq_auxt__8u1__p4_0,
  141299. NULL,
  141300. 0
  141301. };
  141302. static long _vq_quantlist__8u1__p5_0[] = {
  141303. 4,
  141304. 3,
  141305. 5,
  141306. 2,
  141307. 6,
  141308. 1,
  141309. 7,
  141310. 0,
  141311. 8,
  141312. };
  141313. static long _vq_lengthlist__8u1__p5_0[] = {
  141314. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  141315. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  141316. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  141317. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  141318. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  141319. 13,
  141320. };
  141321. static float _vq_quantthresh__8u1__p5_0[] = {
  141322. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141323. };
  141324. static long _vq_quantmap__8u1__p5_0[] = {
  141325. 7, 5, 3, 1, 0, 2, 4, 6,
  141326. 8,
  141327. };
  141328. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  141329. _vq_quantthresh__8u1__p5_0,
  141330. _vq_quantmap__8u1__p5_0,
  141331. 9,
  141332. 9
  141333. };
  141334. static static_codebook _8u1__p5_0 = {
  141335. 2, 81,
  141336. _vq_lengthlist__8u1__p5_0,
  141337. 1, -531628032, 1611661312, 4, 0,
  141338. _vq_quantlist__8u1__p5_0,
  141339. NULL,
  141340. &_vq_auxt__8u1__p5_0,
  141341. NULL,
  141342. 0
  141343. };
  141344. static long _vq_quantlist__8u1__p6_0[] = {
  141345. 4,
  141346. 3,
  141347. 5,
  141348. 2,
  141349. 6,
  141350. 1,
  141351. 7,
  141352. 0,
  141353. 8,
  141354. };
  141355. static long _vq_lengthlist__8u1__p6_0[] = {
  141356. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  141357. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  141358. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  141359. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  141360. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141361. 10,
  141362. };
  141363. static float _vq_quantthresh__8u1__p6_0[] = {
  141364. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141365. };
  141366. static long _vq_quantmap__8u1__p6_0[] = {
  141367. 7, 5, 3, 1, 0, 2, 4, 6,
  141368. 8,
  141369. };
  141370. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  141371. _vq_quantthresh__8u1__p6_0,
  141372. _vq_quantmap__8u1__p6_0,
  141373. 9,
  141374. 9
  141375. };
  141376. static static_codebook _8u1__p6_0 = {
  141377. 2, 81,
  141378. _vq_lengthlist__8u1__p6_0,
  141379. 1, -531628032, 1611661312, 4, 0,
  141380. _vq_quantlist__8u1__p6_0,
  141381. NULL,
  141382. &_vq_auxt__8u1__p6_0,
  141383. NULL,
  141384. 0
  141385. };
  141386. static long _vq_quantlist__8u1__p7_0[] = {
  141387. 1,
  141388. 0,
  141389. 2,
  141390. };
  141391. static long _vq_lengthlist__8u1__p7_0[] = {
  141392. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  141393. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  141394. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  141395. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  141396. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  141397. 11,
  141398. };
  141399. static float _vq_quantthresh__8u1__p7_0[] = {
  141400. -5.5, 5.5,
  141401. };
  141402. static long _vq_quantmap__8u1__p7_0[] = {
  141403. 1, 0, 2,
  141404. };
  141405. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  141406. _vq_quantthresh__8u1__p7_0,
  141407. _vq_quantmap__8u1__p7_0,
  141408. 3,
  141409. 3
  141410. };
  141411. static static_codebook _8u1__p7_0 = {
  141412. 4, 81,
  141413. _vq_lengthlist__8u1__p7_0,
  141414. 1, -529137664, 1618345984, 2, 0,
  141415. _vq_quantlist__8u1__p7_0,
  141416. NULL,
  141417. &_vq_auxt__8u1__p7_0,
  141418. NULL,
  141419. 0
  141420. };
  141421. static long _vq_quantlist__8u1__p7_1[] = {
  141422. 5,
  141423. 4,
  141424. 6,
  141425. 3,
  141426. 7,
  141427. 2,
  141428. 8,
  141429. 1,
  141430. 9,
  141431. 0,
  141432. 10,
  141433. };
  141434. static long _vq_lengthlist__8u1__p7_1[] = {
  141435. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  141436. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  141437. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  141438. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141439. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  141440. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  141441. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  141442. 9, 9, 9, 9, 9,10,10,10,10,
  141443. };
  141444. static float _vq_quantthresh__8u1__p7_1[] = {
  141445. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141446. 3.5, 4.5,
  141447. };
  141448. static long _vq_quantmap__8u1__p7_1[] = {
  141449. 9, 7, 5, 3, 1, 0, 2, 4,
  141450. 6, 8, 10,
  141451. };
  141452. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  141453. _vq_quantthresh__8u1__p7_1,
  141454. _vq_quantmap__8u1__p7_1,
  141455. 11,
  141456. 11
  141457. };
  141458. static static_codebook _8u1__p7_1 = {
  141459. 2, 121,
  141460. _vq_lengthlist__8u1__p7_1,
  141461. 1, -531365888, 1611661312, 4, 0,
  141462. _vq_quantlist__8u1__p7_1,
  141463. NULL,
  141464. &_vq_auxt__8u1__p7_1,
  141465. NULL,
  141466. 0
  141467. };
  141468. static long _vq_quantlist__8u1__p8_0[] = {
  141469. 5,
  141470. 4,
  141471. 6,
  141472. 3,
  141473. 7,
  141474. 2,
  141475. 8,
  141476. 1,
  141477. 9,
  141478. 0,
  141479. 10,
  141480. };
  141481. static long _vq_lengthlist__8u1__p8_0[] = {
  141482. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  141483. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  141484. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  141485. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  141486. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  141487. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  141488. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  141489. 12,13,13,14,14,15,15,15,15,
  141490. };
  141491. static float _vq_quantthresh__8u1__p8_0[] = {
  141492. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  141493. 38.5, 49.5,
  141494. };
  141495. static long _vq_quantmap__8u1__p8_0[] = {
  141496. 9, 7, 5, 3, 1, 0, 2, 4,
  141497. 6, 8, 10,
  141498. };
  141499. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  141500. _vq_quantthresh__8u1__p8_0,
  141501. _vq_quantmap__8u1__p8_0,
  141502. 11,
  141503. 11
  141504. };
  141505. static static_codebook _8u1__p8_0 = {
  141506. 2, 121,
  141507. _vq_lengthlist__8u1__p8_0,
  141508. 1, -524582912, 1618345984, 4, 0,
  141509. _vq_quantlist__8u1__p8_0,
  141510. NULL,
  141511. &_vq_auxt__8u1__p8_0,
  141512. NULL,
  141513. 0
  141514. };
  141515. static long _vq_quantlist__8u1__p8_1[] = {
  141516. 5,
  141517. 4,
  141518. 6,
  141519. 3,
  141520. 7,
  141521. 2,
  141522. 8,
  141523. 1,
  141524. 9,
  141525. 0,
  141526. 10,
  141527. };
  141528. static long _vq_lengthlist__8u1__p8_1[] = {
  141529. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  141530. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  141531. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  141532. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  141533. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  141534. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  141535. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  141536. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  141537. };
  141538. static float _vq_quantthresh__8u1__p8_1[] = {
  141539. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141540. 3.5, 4.5,
  141541. };
  141542. static long _vq_quantmap__8u1__p8_1[] = {
  141543. 9, 7, 5, 3, 1, 0, 2, 4,
  141544. 6, 8, 10,
  141545. };
  141546. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  141547. _vq_quantthresh__8u1__p8_1,
  141548. _vq_quantmap__8u1__p8_1,
  141549. 11,
  141550. 11
  141551. };
  141552. static static_codebook _8u1__p8_1 = {
  141553. 2, 121,
  141554. _vq_lengthlist__8u1__p8_1,
  141555. 1, -531365888, 1611661312, 4, 0,
  141556. _vq_quantlist__8u1__p8_1,
  141557. NULL,
  141558. &_vq_auxt__8u1__p8_1,
  141559. NULL,
  141560. 0
  141561. };
  141562. static long _vq_quantlist__8u1__p9_0[] = {
  141563. 7,
  141564. 6,
  141565. 8,
  141566. 5,
  141567. 9,
  141568. 4,
  141569. 10,
  141570. 3,
  141571. 11,
  141572. 2,
  141573. 12,
  141574. 1,
  141575. 13,
  141576. 0,
  141577. 14,
  141578. };
  141579. static long _vq_lengthlist__8u1__p9_0[] = {
  141580. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  141581. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  141582. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141583. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141584. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141585. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141586. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141587. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141588. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141590. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141592. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  141593. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141594. 10,
  141595. };
  141596. static float _vq_quantthresh__8u1__p9_0[] = {
  141597. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  141598. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  141599. };
  141600. static long _vq_quantmap__8u1__p9_0[] = {
  141601. 13, 11, 9, 7, 5, 3, 1, 0,
  141602. 2, 4, 6, 8, 10, 12, 14,
  141603. };
  141604. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  141605. _vq_quantthresh__8u1__p9_0,
  141606. _vq_quantmap__8u1__p9_0,
  141607. 15,
  141608. 15
  141609. };
  141610. static static_codebook _8u1__p9_0 = {
  141611. 2, 225,
  141612. _vq_lengthlist__8u1__p9_0,
  141613. 1, -514071552, 1627381760, 4, 0,
  141614. _vq_quantlist__8u1__p9_0,
  141615. NULL,
  141616. &_vq_auxt__8u1__p9_0,
  141617. NULL,
  141618. 0
  141619. };
  141620. static long _vq_quantlist__8u1__p9_1[] = {
  141621. 7,
  141622. 6,
  141623. 8,
  141624. 5,
  141625. 9,
  141626. 4,
  141627. 10,
  141628. 3,
  141629. 11,
  141630. 2,
  141631. 12,
  141632. 1,
  141633. 13,
  141634. 0,
  141635. 14,
  141636. };
  141637. static long _vq_lengthlist__8u1__p9_1[] = {
  141638. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  141639. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  141640. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  141641. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  141642. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  141643. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  141644. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  141645. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  141646. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  141647. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  141648. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  141649. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  141650. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  141651. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  141652. 13,
  141653. };
  141654. static float _vq_quantthresh__8u1__p9_1[] = {
  141655. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141656. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141657. };
  141658. static long _vq_quantmap__8u1__p9_1[] = {
  141659. 13, 11, 9, 7, 5, 3, 1, 0,
  141660. 2, 4, 6, 8, 10, 12, 14,
  141661. };
  141662. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  141663. _vq_quantthresh__8u1__p9_1,
  141664. _vq_quantmap__8u1__p9_1,
  141665. 15,
  141666. 15
  141667. };
  141668. static static_codebook _8u1__p9_1 = {
  141669. 2, 225,
  141670. _vq_lengthlist__8u1__p9_1,
  141671. 1, -522338304, 1620115456, 4, 0,
  141672. _vq_quantlist__8u1__p9_1,
  141673. NULL,
  141674. &_vq_auxt__8u1__p9_1,
  141675. NULL,
  141676. 0
  141677. };
  141678. static long _vq_quantlist__8u1__p9_2[] = {
  141679. 8,
  141680. 7,
  141681. 9,
  141682. 6,
  141683. 10,
  141684. 5,
  141685. 11,
  141686. 4,
  141687. 12,
  141688. 3,
  141689. 13,
  141690. 2,
  141691. 14,
  141692. 1,
  141693. 15,
  141694. 0,
  141695. 16,
  141696. };
  141697. static long _vq_lengthlist__8u1__p9_2[] = {
  141698. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141699. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  141700. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141701. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  141702. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141703. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  141704. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141705. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  141706. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  141707. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141708. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141709. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  141710. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  141711. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  141713. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  141714. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141715. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141716. 10,
  141717. };
  141718. static float _vq_quantthresh__8u1__p9_2[] = {
  141719. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141720. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141721. };
  141722. static long _vq_quantmap__8u1__p9_2[] = {
  141723. 15, 13, 11, 9, 7, 5, 3, 1,
  141724. 0, 2, 4, 6, 8, 10, 12, 14,
  141725. 16,
  141726. };
  141727. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  141728. _vq_quantthresh__8u1__p9_2,
  141729. _vq_quantmap__8u1__p9_2,
  141730. 17,
  141731. 17
  141732. };
  141733. static static_codebook _8u1__p9_2 = {
  141734. 2, 289,
  141735. _vq_lengthlist__8u1__p9_2,
  141736. 1, -529530880, 1611661312, 5, 0,
  141737. _vq_quantlist__8u1__p9_2,
  141738. NULL,
  141739. &_vq_auxt__8u1__p9_2,
  141740. NULL,
  141741. 0
  141742. };
  141743. static long _huff_lengthlist__8u1__single[] = {
  141744. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  141745. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  141746. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  141747. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  141748. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  141749. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  141750. 13, 8, 8,15,
  141751. };
  141752. static static_codebook _huff_book__8u1__single = {
  141753. 2, 100,
  141754. _huff_lengthlist__8u1__single,
  141755. 0, 0, 0, 0, 0,
  141756. NULL,
  141757. NULL,
  141758. NULL,
  141759. NULL,
  141760. 0
  141761. };
  141762. static long _huff_lengthlist__44u0__long[] = {
  141763. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  141764. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  141765. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  141766. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  141767. };
  141768. static static_codebook _huff_book__44u0__long = {
  141769. 2, 64,
  141770. _huff_lengthlist__44u0__long,
  141771. 0, 0, 0, 0, 0,
  141772. NULL,
  141773. NULL,
  141774. NULL,
  141775. NULL,
  141776. 0
  141777. };
  141778. static long _vq_quantlist__44u0__p1_0[] = {
  141779. 1,
  141780. 0,
  141781. 2,
  141782. };
  141783. static long _vq_lengthlist__44u0__p1_0[] = {
  141784. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  141785. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141786. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  141787. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  141788. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  141789. 13,
  141790. };
  141791. static float _vq_quantthresh__44u0__p1_0[] = {
  141792. -0.5, 0.5,
  141793. };
  141794. static long _vq_quantmap__44u0__p1_0[] = {
  141795. 1, 0, 2,
  141796. };
  141797. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  141798. _vq_quantthresh__44u0__p1_0,
  141799. _vq_quantmap__44u0__p1_0,
  141800. 3,
  141801. 3
  141802. };
  141803. static static_codebook _44u0__p1_0 = {
  141804. 4, 81,
  141805. _vq_lengthlist__44u0__p1_0,
  141806. 1, -535822336, 1611661312, 2, 0,
  141807. _vq_quantlist__44u0__p1_0,
  141808. NULL,
  141809. &_vq_auxt__44u0__p1_0,
  141810. NULL,
  141811. 0
  141812. };
  141813. static long _vq_quantlist__44u0__p2_0[] = {
  141814. 1,
  141815. 0,
  141816. 2,
  141817. };
  141818. static long _vq_lengthlist__44u0__p2_0[] = {
  141819. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  141820. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  141821. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141822. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  141823. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141824. 9,
  141825. };
  141826. static float _vq_quantthresh__44u0__p2_0[] = {
  141827. -0.5, 0.5,
  141828. };
  141829. static long _vq_quantmap__44u0__p2_0[] = {
  141830. 1, 0, 2,
  141831. };
  141832. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  141833. _vq_quantthresh__44u0__p2_0,
  141834. _vq_quantmap__44u0__p2_0,
  141835. 3,
  141836. 3
  141837. };
  141838. static static_codebook _44u0__p2_0 = {
  141839. 4, 81,
  141840. _vq_lengthlist__44u0__p2_0,
  141841. 1, -535822336, 1611661312, 2, 0,
  141842. _vq_quantlist__44u0__p2_0,
  141843. NULL,
  141844. &_vq_auxt__44u0__p2_0,
  141845. NULL,
  141846. 0
  141847. };
  141848. static long _vq_quantlist__44u0__p3_0[] = {
  141849. 2,
  141850. 1,
  141851. 3,
  141852. 0,
  141853. 4,
  141854. };
  141855. static long _vq_lengthlist__44u0__p3_0[] = {
  141856. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  141857. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  141858. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  141859. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  141860. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  141861. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  141862. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  141863. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  141864. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  141865. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  141866. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  141867. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  141868. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  141869. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  141870. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  141871. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  141872. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  141873. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  141874. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  141875. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  141876. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  141877. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  141878. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  141879. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  141880. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  141881. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  141882. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  141883. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  141884. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  141885. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  141886. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  141887. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  141888. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  141889. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  141890. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  141891. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  141892. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  141893. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  141894. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  141895. 19,
  141896. };
  141897. static float _vq_quantthresh__44u0__p3_0[] = {
  141898. -1.5, -0.5, 0.5, 1.5,
  141899. };
  141900. static long _vq_quantmap__44u0__p3_0[] = {
  141901. 3, 1, 0, 2, 4,
  141902. };
  141903. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  141904. _vq_quantthresh__44u0__p3_0,
  141905. _vq_quantmap__44u0__p3_0,
  141906. 5,
  141907. 5
  141908. };
  141909. static static_codebook _44u0__p3_0 = {
  141910. 4, 625,
  141911. _vq_lengthlist__44u0__p3_0,
  141912. 1, -533725184, 1611661312, 3, 0,
  141913. _vq_quantlist__44u0__p3_0,
  141914. NULL,
  141915. &_vq_auxt__44u0__p3_0,
  141916. NULL,
  141917. 0
  141918. };
  141919. static long _vq_quantlist__44u0__p4_0[] = {
  141920. 2,
  141921. 1,
  141922. 3,
  141923. 0,
  141924. 4,
  141925. };
  141926. static long _vq_lengthlist__44u0__p4_0[] = {
  141927. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  141928. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  141929. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  141930. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  141931. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  141932. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  141933. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  141934. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  141935. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  141936. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  141937. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  141938. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141939. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  141940. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  141941. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  141942. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  141943. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  141944. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  141945. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  141946. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  141947. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  141948. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  141949. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  141950. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  141951. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  141952. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  141953. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  141954. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  141955. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  141956. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  141957. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  141958. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  141959. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  141960. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  141961. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  141962. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  141963. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  141964. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  141965. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  141966. 12,
  141967. };
  141968. static float _vq_quantthresh__44u0__p4_0[] = {
  141969. -1.5, -0.5, 0.5, 1.5,
  141970. };
  141971. static long _vq_quantmap__44u0__p4_0[] = {
  141972. 3, 1, 0, 2, 4,
  141973. };
  141974. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  141975. _vq_quantthresh__44u0__p4_0,
  141976. _vq_quantmap__44u0__p4_0,
  141977. 5,
  141978. 5
  141979. };
  141980. static static_codebook _44u0__p4_0 = {
  141981. 4, 625,
  141982. _vq_lengthlist__44u0__p4_0,
  141983. 1, -533725184, 1611661312, 3, 0,
  141984. _vq_quantlist__44u0__p4_0,
  141985. NULL,
  141986. &_vq_auxt__44u0__p4_0,
  141987. NULL,
  141988. 0
  141989. };
  141990. static long _vq_quantlist__44u0__p5_0[] = {
  141991. 4,
  141992. 3,
  141993. 5,
  141994. 2,
  141995. 6,
  141996. 1,
  141997. 7,
  141998. 0,
  141999. 8,
  142000. };
  142001. static long _vq_lengthlist__44u0__p5_0[] = {
  142002. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142003. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142004. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142005. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142006. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142007. 12,
  142008. };
  142009. static float _vq_quantthresh__44u0__p5_0[] = {
  142010. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142011. };
  142012. static long _vq_quantmap__44u0__p5_0[] = {
  142013. 7, 5, 3, 1, 0, 2, 4, 6,
  142014. 8,
  142015. };
  142016. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  142017. _vq_quantthresh__44u0__p5_0,
  142018. _vq_quantmap__44u0__p5_0,
  142019. 9,
  142020. 9
  142021. };
  142022. static static_codebook _44u0__p5_0 = {
  142023. 2, 81,
  142024. _vq_lengthlist__44u0__p5_0,
  142025. 1, -531628032, 1611661312, 4, 0,
  142026. _vq_quantlist__44u0__p5_0,
  142027. NULL,
  142028. &_vq_auxt__44u0__p5_0,
  142029. NULL,
  142030. 0
  142031. };
  142032. static long _vq_quantlist__44u0__p6_0[] = {
  142033. 6,
  142034. 5,
  142035. 7,
  142036. 4,
  142037. 8,
  142038. 3,
  142039. 9,
  142040. 2,
  142041. 10,
  142042. 1,
  142043. 11,
  142044. 0,
  142045. 12,
  142046. };
  142047. static long _vq_lengthlist__44u0__p6_0[] = {
  142048. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142049. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142050. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142051. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142052. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142053. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142054. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142055. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142056. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142057. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142058. 15,17,16,17,18,17,17,18, 0,
  142059. };
  142060. static float _vq_quantthresh__44u0__p6_0[] = {
  142061. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142062. 12.5, 17.5, 22.5, 27.5,
  142063. };
  142064. static long _vq_quantmap__44u0__p6_0[] = {
  142065. 11, 9, 7, 5, 3, 1, 0, 2,
  142066. 4, 6, 8, 10, 12,
  142067. };
  142068. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  142069. _vq_quantthresh__44u0__p6_0,
  142070. _vq_quantmap__44u0__p6_0,
  142071. 13,
  142072. 13
  142073. };
  142074. static static_codebook _44u0__p6_0 = {
  142075. 2, 169,
  142076. _vq_lengthlist__44u0__p6_0,
  142077. 1, -526516224, 1616117760, 4, 0,
  142078. _vq_quantlist__44u0__p6_0,
  142079. NULL,
  142080. &_vq_auxt__44u0__p6_0,
  142081. NULL,
  142082. 0
  142083. };
  142084. static long _vq_quantlist__44u0__p6_1[] = {
  142085. 2,
  142086. 1,
  142087. 3,
  142088. 0,
  142089. 4,
  142090. };
  142091. static long _vq_lengthlist__44u0__p6_1[] = {
  142092. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142093. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142094. };
  142095. static float _vq_quantthresh__44u0__p6_1[] = {
  142096. -1.5, -0.5, 0.5, 1.5,
  142097. };
  142098. static long _vq_quantmap__44u0__p6_1[] = {
  142099. 3, 1, 0, 2, 4,
  142100. };
  142101. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  142102. _vq_quantthresh__44u0__p6_1,
  142103. _vq_quantmap__44u0__p6_1,
  142104. 5,
  142105. 5
  142106. };
  142107. static static_codebook _44u0__p6_1 = {
  142108. 2, 25,
  142109. _vq_lengthlist__44u0__p6_1,
  142110. 1, -533725184, 1611661312, 3, 0,
  142111. _vq_quantlist__44u0__p6_1,
  142112. NULL,
  142113. &_vq_auxt__44u0__p6_1,
  142114. NULL,
  142115. 0
  142116. };
  142117. static long _vq_quantlist__44u0__p7_0[] = {
  142118. 2,
  142119. 1,
  142120. 3,
  142121. 0,
  142122. 4,
  142123. };
  142124. static long _vq_lengthlist__44u0__p7_0[] = {
  142125. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  142126. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142128. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142132. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  142133. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142134. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142135. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142136. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142137. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142138. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142139. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142140. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142142. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142144. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142147. 11,11,11,11,11,11,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,11,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,11,11,11,
  142155. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  142156. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142157. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142158. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142159. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142160. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142161. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142162. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142164. 10,
  142165. };
  142166. static float _vq_quantthresh__44u0__p7_0[] = {
  142167. -253.5, -84.5, 84.5, 253.5,
  142168. };
  142169. static long _vq_quantmap__44u0__p7_0[] = {
  142170. 3, 1, 0, 2, 4,
  142171. };
  142172. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  142173. _vq_quantthresh__44u0__p7_0,
  142174. _vq_quantmap__44u0__p7_0,
  142175. 5,
  142176. 5
  142177. };
  142178. static static_codebook _44u0__p7_0 = {
  142179. 4, 625,
  142180. _vq_lengthlist__44u0__p7_0,
  142181. 1, -518709248, 1626677248, 3, 0,
  142182. _vq_quantlist__44u0__p7_0,
  142183. NULL,
  142184. &_vq_auxt__44u0__p7_0,
  142185. NULL,
  142186. 0
  142187. };
  142188. static long _vq_quantlist__44u0__p7_1[] = {
  142189. 6,
  142190. 5,
  142191. 7,
  142192. 4,
  142193. 8,
  142194. 3,
  142195. 9,
  142196. 2,
  142197. 10,
  142198. 1,
  142199. 11,
  142200. 0,
  142201. 12,
  142202. };
  142203. static long _vq_lengthlist__44u0__p7_1[] = {
  142204. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142205. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142206. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142207. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142208. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142209. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142210. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142211. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142212. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142213. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142214. 15,15,15,15,15,15,15,15,15,
  142215. };
  142216. static float _vq_quantthresh__44u0__p7_1[] = {
  142217. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142218. 32.5, 45.5, 58.5, 71.5,
  142219. };
  142220. static long _vq_quantmap__44u0__p7_1[] = {
  142221. 11, 9, 7, 5, 3, 1, 0, 2,
  142222. 4, 6, 8, 10, 12,
  142223. };
  142224. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  142225. _vq_quantthresh__44u0__p7_1,
  142226. _vq_quantmap__44u0__p7_1,
  142227. 13,
  142228. 13
  142229. };
  142230. static static_codebook _44u0__p7_1 = {
  142231. 2, 169,
  142232. _vq_lengthlist__44u0__p7_1,
  142233. 1, -523010048, 1618608128, 4, 0,
  142234. _vq_quantlist__44u0__p7_1,
  142235. NULL,
  142236. &_vq_auxt__44u0__p7_1,
  142237. NULL,
  142238. 0
  142239. };
  142240. static long _vq_quantlist__44u0__p7_2[] = {
  142241. 6,
  142242. 5,
  142243. 7,
  142244. 4,
  142245. 8,
  142246. 3,
  142247. 9,
  142248. 2,
  142249. 10,
  142250. 1,
  142251. 11,
  142252. 0,
  142253. 12,
  142254. };
  142255. static long _vq_lengthlist__44u0__p7_2[] = {
  142256. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142257. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142258. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142259. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142260. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142261. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142262. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142263. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142264. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142265. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142266. 9, 9, 9,10, 9, 9,10,10, 9,
  142267. };
  142268. static float _vq_quantthresh__44u0__p7_2[] = {
  142269. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142270. 2.5, 3.5, 4.5, 5.5,
  142271. };
  142272. static long _vq_quantmap__44u0__p7_2[] = {
  142273. 11, 9, 7, 5, 3, 1, 0, 2,
  142274. 4, 6, 8, 10, 12,
  142275. };
  142276. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  142277. _vq_quantthresh__44u0__p7_2,
  142278. _vq_quantmap__44u0__p7_2,
  142279. 13,
  142280. 13
  142281. };
  142282. static static_codebook _44u0__p7_2 = {
  142283. 2, 169,
  142284. _vq_lengthlist__44u0__p7_2,
  142285. 1, -531103744, 1611661312, 4, 0,
  142286. _vq_quantlist__44u0__p7_2,
  142287. NULL,
  142288. &_vq_auxt__44u0__p7_2,
  142289. NULL,
  142290. 0
  142291. };
  142292. static long _huff_lengthlist__44u0__short[] = {
  142293. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142294. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142295. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142296. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142297. };
  142298. static static_codebook _huff_book__44u0__short = {
  142299. 2, 64,
  142300. _huff_lengthlist__44u0__short,
  142301. 0, 0, 0, 0, 0,
  142302. NULL,
  142303. NULL,
  142304. NULL,
  142305. NULL,
  142306. 0
  142307. };
  142308. static long _huff_lengthlist__44u1__long[] = {
  142309. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  142310. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  142311. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  142312. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  142313. };
  142314. static static_codebook _huff_book__44u1__long = {
  142315. 2, 64,
  142316. _huff_lengthlist__44u1__long,
  142317. 0, 0, 0, 0, 0,
  142318. NULL,
  142319. NULL,
  142320. NULL,
  142321. NULL,
  142322. 0
  142323. };
  142324. static long _vq_quantlist__44u1__p1_0[] = {
  142325. 1,
  142326. 0,
  142327. 2,
  142328. };
  142329. static long _vq_lengthlist__44u1__p1_0[] = {
  142330. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142331. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142332. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  142333. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  142334. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  142335. 13,
  142336. };
  142337. static float _vq_quantthresh__44u1__p1_0[] = {
  142338. -0.5, 0.5,
  142339. };
  142340. static long _vq_quantmap__44u1__p1_0[] = {
  142341. 1, 0, 2,
  142342. };
  142343. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  142344. _vq_quantthresh__44u1__p1_0,
  142345. _vq_quantmap__44u1__p1_0,
  142346. 3,
  142347. 3
  142348. };
  142349. static static_codebook _44u1__p1_0 = {
  142350. 4, 81,
  142351. _vq_lengthlist__44u1__p1_0,
  142352. 1, -535822336, 1611661312, 2, 0,
  142353. _vq_quantlist__44u1__p1_0,
  142354. NULL,
  142355. &_vq_auxt__44u1__p1_0,
  142356. NULL,
  142357. 0
  142358. };
  142359. static long _vq_quantlist__44u1__p2_0[] = {
  142360. 1,
  142361. 0,
  142362. 2,
  142363. };
  142364. static long _vq_lengthlist__44u1__p2_0[] = {
  142365. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  142366. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  142367. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142368. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  142369. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142370. 9,
  142371. };
  142372. static float _vq_quantthresh__44u1__p2_0[] = {
  142373. -0.5, 0.5,
  142374. };
  142375. static long _vq_quantmap__44u1__p2_0[] = {
  142376. 1, 0, 2,
  142377. };
  142378. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  142379. _vq_quantthresh__44u1__p2_0,
  142380. _vq_quantmap__44u1__p2_0,
  142381. 3,
  142382. 3
  142383. };
  142384. static static_codebook _44u1__p2_0 = {
  142385. 4, 81,
  142386. _vq_lengthlist__44u1__p2_0,
  142387. 1, -535822336, 1611661312, 2, 0,
  142388. _vq_quantlist__44u1__p2_0,
  142389. NULL,
  142390. &_vq_auxt__44u1__p2_0,
  142391. NULL,
  142392. 0
  142393. };
  142394. static long _vq_quantlist__44u1__p3_0[] = {
  142395. 2,
  142396. 1,
  142397. 3,
  142398. 0,
  142399. 4,
  142400. };
  142401. static long _vq_lengthlist__44u1__p3_0[] = {
  142402. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  142403. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  142404. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  142405. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  142406. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  142407. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  142408. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  142409. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  142410. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  142411. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  142412. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  142413. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  142414. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  142415. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  142416. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  142417. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  142418. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  142419. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  142420. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  142421. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  142422. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  142423. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  142424. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  142425. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  142426. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  142427. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  142428. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  142429. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  142430. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  142431. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  142432. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  142433. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  142434. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  142435. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  142436. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  142437. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  142438. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  142439. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  142440. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  142441. 19,
  142442. };
  142443. static float _vq_quantthresh__44u1__p3_0[] = {
  142444. -1.5, -0.5, 0.5, 1.5,
  142445. };
  142446. static long _vq_quantmap__44u1__p3_0[] = {
  142447. 3, 1, 0, 2, 4,
  142448. };
  142449. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  142450. _vq_quantthresh__44u1__p3_0,
  142451. _vq_quantmap__44u1__p3_0,
  142452. 5,
  142453. 5
  142454. };
  142455. static static_codebook _44u1__p3_0 = {
  142456. 4, 625,
  142457. _vq_lengthlist__44u1__p3_0,
  142458. 1, -533725184, 1611661312, 3, 0,
  142459. _vq_quantlist__44u1__p3_0,
  142460. NULL,
  142461. &_vq_auxt__44u1__p3_0,
  142462. NULL,
  142463. 0
  142464. };
  142465. static long _vq_quantlist__44u1__p4_0[] = {
  142466. 2,
  142467. 1,
  142468. 3,
  142469. 0,
  142470. 4,
  142471. };
  142472. static long _vq_lengthlist__44u1__p4_0[] = {
  142473. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  142474. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  142475. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  142476. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  142477. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  142478. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  142479. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  142480. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  142481. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  142482. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  142483. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  142484. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142485. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  142486. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  142487. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  142488. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  142489. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  142490. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  142491. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  142492. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  142493. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  142494. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  142495. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  142496. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  142497. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  142498. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  142499. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  142500. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  142501. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  142502. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  142503. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  142504. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  142505. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  142506. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  142507. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  142508. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  142509. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  142510. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  142511. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  142512. 12,
  142513. };
  142514. static float _vq_quantthresh__44u1__p4_0[] = {
  142515. -1.5, -0.5, 0.5, 1.5,
  142516. };
  142517. static long _vq_quantmap__44u1__p4_0[] = {
  142518. 3, 1, 0, 2, 4,
  142519. };
  142520. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  142521. _vq_quantthresh__44u1__p4_0,
  142522. _vq_quantmap__44u1__p4_0,
  142523. 5,
  142524. 5
  142525. };
  142526. static static_codebook _44u1__p4_0 = {
  142527. 4, 625,
  142528. _vq_lengthlist__44u1__p4_0,
  142529. 1, -533725184, 1611661312, 3, 0,
  142530. _vq_quantlist__44u1__p4_0,
  142531. NULL,
  142532. &_vq_auxt__44u1__p4_0,
  142533. NULL,
  142534. 0
  142535. };
  142536. static long _vq_quantlist__44u1__p5_0[] = {
  142537. 4,
  142538. 3,
  142539. 5,
  142540. 2,
  142541. 6,
  142542. 1,
  142543. 7,
  142544. 0,
  142545. 8,
  142546. };
  142547. static long _vq_lengthlist__44u1__p5_0[] = {
  142548. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  142549. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  142550. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  142551. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  142552. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  142553. 12,
  142554. };
  142555. static float _vq_quantthresh__44u1__p5_0[] = {
  142556. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142557. };
  142558. static long _vq_quantmap__44u1__p5_0[] = {
  142559. 7, 5, 3, 1, 0, 2, 4, 6,
  142560. 8,
  142561. };
  142562. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  142563. _vq_quantthresh__44u1__p5_0,
  142564. _vq_quantmap__44u1__p5_0,
  142565. 9,
  142566. 9
  142567. };
  142568. static static_codebook _44u1__p5_0 = {
  142569. 2, 81,
  142570. _vq_lengthlist__44u1__p5_0,
  142571. 1, -531628032, 1611661312, 4, 0,
  142572. _vq_quantlist__44u1__p5_0,
  142573. NULL,
  142574. &_vq_auxt__44u1__p5_0,
  142575. NULL,
  142576. 0
  142577. };
  142578. static long _vq_quantlist__44u1__p6_0[] = {
  142579. 6,
  142580. 5,
  142581. 7,
  142582. 4,
  142583. 8,
  142584. 3,
  142585. 9,
  142586. 2,
  142587. 10,
  142588. 1,
  142589. 11,
  142590. 0,
  142591. 12,
  142592. };
  142593. static long _vq_lengthlist__44u1__p6_0[] = {
  142594. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  142595. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  142596. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  142597. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  142598. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  142599. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  142600. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  142601. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  142602. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  142603. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  142604. 15,17,16,17,18,17,17,18, 0,
  142605. };
  142606. static float _vq_quantthresh__44u1__p6_0[] = {
  142607. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142608. 12.5, 17.5, 22.5, 27.5,
  142609. };
  142610. static long _vq_quantmap__44u1__p6_0[] = {
  142611. 11, 9, 7, 5, 3, 1, 0, 2,
  142612. 4, 6, 8, 10, 12,
  142613. };
  142614. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  142615. _vq_quantthresh__44u1__p6_0,
  142616. _vq_quantmap__44u1__p6_0,
  142617. 13,
  142618. 13
  142619. };
  142620. static static_codebook _44u1__p6_0 = {
  142621. 2, 169,
  142622. _vq_lengthlist__44u1__p6_0,
  142623. 1, -526516224, 1616117760, 4, 0,
  142624. _vq_quantlist__44u1__p6_0,
  142625. NULL,
  142626. &_vq_auxt__44u1__p6_0,
  142627. NULL,
  142628. 0
  142629. };
  142630. static long _vq_quantlist__44u1__p6_1[] = {
  142631. 2,
  142632. 1,
  142633. 3,
  142634. 0,
  142635. 4,
  142636. };
  142637. static long _vq_lengthlist__44u1__p6_1[] = {
  142638. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  142639. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  142640. };
  142641. static float _vq_quantthresh__44u1__p6_1[] = {
  142642. -1.5, -0.5, 0.5, 1.5,
  142643. };
  142644. static long _vq_quantmap__44u1__p6_1[] = {
  142645. 3, 1, 0, 2, 4,
  142646. };
  142647. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  142648. _vq_quantthresh__44u1__p6_1,
  142649. _vq_quantmap__44u1__p6_1,
  142650. 5,
  142651. 5
  142652. };
  142653. static static_codebook _44u1__p6_1 = {
  142654. 2, 25,
  142655. _vq_lengthlist__44u1__p6_1,
  142656. 1, -533725184, 1611661312, 3, 0,
  142657. _vq_quantlist__44u1__p6_1,
  142658. NULL,
  142659. &_vq_auxt__44u1__p6_1,
  142660. NULL,
  142661. 0
  142662. };
  142663. static long _vq_quantlist__44u1__p7_0[] = {
  142664. 3,
  142665. 2,
  142666. 4,
  142667. 1,
  142668. 5,
  142669. 0,
  142670. 6,
  142671. };
  142672. static long _vq_lengthlist__44u1__p7_0[] = {
  142673. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142674. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142675. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142676. 8,
  142677. };
  142678. static float _vq_quantthresh__44u1__p7_0[] = {
  142679. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  142680. };
  142681. static long _vq_quantmap__44u1__p7_0[] = {
  142682. 5, 3, 1, 0, 2, 4, 6,
  142683. };
  142684. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  142685. _vq_quantthresh__44u1__p7_0,
  142686. _vq_quantmap__44u1__p7_0,
  142687. 7,
  142688. 7
  142689. };
  142690. static static_codebook _44u1__p7_0 = {
  142691. 2, 49,
  142692. _vq_lengthlist__44u1__p7_0,
  142693. 1, -518017024, 1626677248, 3, 0,
  142694. _vq_quantlist__44u1__p7_0,
  142695. NULL,
  142696. &_vq_auxt__44u1__p7_0,
  142697. NULL,
  142698. 0
  142699. };
  142700. static long _vq_quantlist__44u1__p7_1[] = {
  142701. 6,
  142702. 5,
  142703. 7,
  142704. 4,
  142705. 8,
  142706. 3,
  142707. 9,
  142708. 2,
  142709. 10,
  142710. 1,
  142711. 11,
  142712. 0,
  142713. 12,
  142714. };
  142715. static long _vq_lengthlist__44u1__p7_1[] = {
  142716. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  142717. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  142718. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  142719. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  142720. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  142721. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  142722. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  142723. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  142724. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  142725. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  142726. 15,15,15,15,15,15,15,15,15,
  142727. };
  142728. static float _vq_quantthresh__44u1__p7_1[] = {
  142729. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  142730. 32.5, 45.5, 58.5, 71.5,
  142731. };
  142732. static long _vq_quantmap__44u1__p7_1[] = {
  142733. 11, 9, 7, 5, 3, 1, 0, 2,
  142734. 4, 6, 8, 10, 12,
  142735. };
  142736. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  142737. _vq_quantthresh__44u1__p7_1,
  142738. _vq_quantmap__44u1__p7_1,
  142739. 13,
  142740. 13
  142741. };
  142742. static static_codebook _44u1__p7_1 = {
  142743. 2, 169,
  142744. _vq_lengthlist__44u1__p7_1,
  142745. 1, -523010048, 1618608128, 4, 0,
  142746. _vq_quantlist__44u1__p7_1,
  142747. NULL,
  142748. &_vq_auxt__44u1__p7_1,
  142749. NULL,
  142750. 0
  142751. };
  142752. static long _vq_quantlist__44u1__p7_2[] = {
  142753. 6,
  142754. 5,
  142755. 7,
  142756. 4,
  142757. 8,
  142758. 3,
  142759. 9,
  142760. 2,
  142761. 10,
  142762. 1,
  142763. 11,
  142764. 0,
  142765. 12,
  142766. };
  142767. static long _vq_lengthlist__44u1__p7_2[] = {
  142768. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  142769. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  142770. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  142771. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  142772. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  142773. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  142774. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  142775. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142776. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  142777. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  142778. 9, 9, 9,10, 9, 9,10,10, 9,
  142779. };
  142780. static float _vq_quantthresh__44u1__p7_2[] = {
  142781. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  142782. 2.5, 3.5, 4.5, 5.5,
  142783. };
  142784. static long _vq_quantmap__44u1__p7_2[] = {
  142785. 11, 9, 7, 5, 3, 1, 0, 2,
  142786. 4, 6, 8, 10, 12,
  142787. };
  142788. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  142789. _vq_quantthresh__44u1__p7_2,
  142790. _vq_quantmap__44u1__p7_2,
  142791. 13,
  142792. 13
  142793. };
  142794. static static_codebook _44u1__p7_2 = {
  142795. 2, 169,
  142796. _vq_lengthlist__44u1__p7_2,
  142797. 1, -531103744, 1611661312, 4, 0,
  142798. _vq_quantlist__44u1__p7_2,
  142799. NULL,
  142800. &_vq_auxt__44u1__p7_2,
  142801. NULL,
  142802. 0
  142803. };
  142804. static long _huff_lengthlist__44u1__short[] = {
  142805. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  142806. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  142807. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  142808. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  142809. };
  142810. static static_codebook _huff_book__44u1__short = {
  142811. 2, 64,
  142812. _huff_lengthlist__44u1__short,
  142813. 0, 0, 0, 0, 0,
  142814. NULL,
  142815. NULL,
  142816. NULL,
  142817. NULL,
  142818. 0
  142819. };
  142820. static long _huff_lengthlist__44u2__long[] = {
  142821. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  142822. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  142823. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  142824. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  142825. };
  142826. static static_codebook _huff_book__44u2__long = {
  142827. 2, 64,
  142828. _huff_lengthlist__44u2__long,
  142829. 0, 0, 0, 0, 0,
  142830. NULL,
  142831. NULL,
  142832. NULL,
  142833. NULL,
  142834. 0
  142835. };
  142836. static long _vq_quantlist__44u2__p1_0[] = {
  142837. 1,
  142838. 0,
  142839. 2,
  142840. };
  142841. static long _vq_lengthlist__44u2__p1_0[] = {
  142842. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  142843. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  142844. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  142845. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  142846. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  142847. 13,
  142848. };
  142849. static float _vq_quantthresh__44u2__p1_0[] = {
  142850. -0.5, 0.5,
  142851. };
  142852. static long _vq_quantmap__44u2__p1_0[] = {
  142853. 1, 0, 2,
  142854. };
  142855. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  142856. _vq_quantthresh__44u2__p1_0,
  142857. _vq_quantmap__44u2__p1_0,
  142858. 3,
  142859. 3
  142860. };
  142861. static static_codebook _44u2__p1_0 = {
  142862. 4, 81,
  142863. _vq_lengthlist__44u2__p1_0,
  142864. 1, -535822336, 1611661312, 2, 0,
  142865. _vq_quantlist__44u2__p1_0,
  142866. NULL,
  142867. &_vq_auxt__44u2__p1_0,
  142868. NULL,
  142869. 0
  142870. };
  142871. static long _vq_quantlist__44u2__p2_0[] = {
  142872. 1,
  142873. 0,
  142874. 2,
  142875. };
  142876. static long _vq_lengthlist__44u2__p2_0[] = {
  142877. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  142878. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  142879. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  142880. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  142881. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  142882. 9,
  142883. };
  142884. static float _vq_quantthresh__44u2__p2_0[] = {
  142885. -0.5, 0.5,
  142886. };
  142887. static long _vq_quantmap__44u2__p2_0[] = {
  142888. 1, 0, 2,
  142889. };
  142890. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  142891. _vq_quantthresh__44u2__p2_0,
  142892. _vq_quantmap__44u2__p2_0,
  142893. 3,
  142894. 3
  142895. };
  142896. static static_codebook _44u2__p2_0 = {
  142897. 4, 81,
  142898. _vq_lengthlist__44u2__p2_0,
  142899. 1, -535822336, 1611661312, 2, 0,
  142900. _vq_quantlist__44u2__p2_0,
  142901. NULL,
  142902. &_vq_auxt__44u2__p2_0,
  142903. NULL,
  142904. 0
  142905. };
  142906. static long _vq_quantlist__44u2__p3_0[] = {
  142907. 2,
  142908. 1,
  142909. 3,
  142910. 0,
  142911. 4,
  142912. };
  142913. static long _vq_lengthlist__44u2__p3_0[] = {
  142914. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  142915. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  142916. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  142917. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  142918. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  142919. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  142920. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  142921. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  142922. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  142923. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  142924. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  142925. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  142926. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  142927. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  142928. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  142929. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  142930. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142931. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  142932. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  142933. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  142934. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  142935. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  142936. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  142937. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  142938. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  142939. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  142940. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  142941. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  142942. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  142943. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  142944. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  142945. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  142946. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  142947. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  142948. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  142949. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  142950. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  142951. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  142952. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  142953. 0,
  142954. };
  142955. static float _vq_quantthresh__44u2__p3_0[] = {
  142956. -1.5, -0.5, 0.5, 1.5,
  142957. };
  142958. static long _vq_quantmap__44u2__p3_0[] = {
  142959. 3, 1, 0, 2, 4,
  142960. };
  142961. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  142962. _vq_quantthresh__44u2__p3_0,
  142963. _vq_quantmap__44u2__p3_0,
  142964. 5,
  142965. 5
  142966. };
  142967. static static_codebook _44u2__p3_0 = {
  142968. 4, 625,
  142969. _vq_lengthlist__44u2__p3_0,
  142970. 1, -533725184, 1611661312, 3, 0,
  142971. _vq_quantlist__44u2__p3_0,
  142972. NULL,
  142973. &_vq_auxt__44u2__p3_0,
  142974. NULL,
  142975. 0
  142976. };
  142977. static long _vq_quantlist__44u2__p4_0[] = {
  142978. 2,
  142979. 1,
  142980. 3,
  142981. 0,
  142982. 4,
  142983. };
  142984. static long _vq_lengthlist__44u2__p4_0[] = {
  142985. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  142986. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  142987. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  142988. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  142989. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  142990. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  142991. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  142992. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  142993. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  142994. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  142995. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  142996. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142997. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  142998. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  142999. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  143000. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  143001. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  143002. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143003. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143004. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  143005. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143006. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  143007. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  143008. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143009. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  143010. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  143011. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  143012. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  143013. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143014. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  143015. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  143016. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  143017. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  143018. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143019. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  143020. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  143021. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  143022. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  143023. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  143024. 13,
  143025. };
  143026. static float _vq_quantthresh__44u2__p4_0[] = {
  143027. -1.5, -0.5, 0.5, 1.5,
  143028. };
  143029. static long _vq_quantmap__44u2__p4_0[] = {
  143030. 3, 1, 0, 2, 4,
  143031. };
  143032. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  143033. _vq_quantthresh__44u2__p4_0,
  143034. _vq_quantmap__44u2__p4_0,
  143035. 5,
  143036. 5
  143037. };
  143038. static static_codebook _44u2__p4_0 = {
  143039. 4, 625,
  143040. _vq_lengthlist__44u2__p4_0,
  143041. 1, -533725184, 1611661312, 3, 0,
  143042. _vq_quantlist__44u2__p4_0,
  143043. NULL,
  143044. &_vq_auxt__44u2__p4_0,
  143045. NULL,
  143046. 0
  143047. };
  143048. static long _vq_quantlist__44u2__p5_0[] = {
  143049. 4,
  143050. 3,
  143051. 5,
  143052. 2,
  143053. 6,
  143054. 1,
  143055. 7,
  143056. 0,
  143057. 8,
  143058. };
  143059. static long _vq_lengthlist__44u2__p5_0[] = {
  143060. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  143061. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143062. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  143063. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  143064. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  143065. 13,
  143066. };
  143067. static float _vq_quantthresh__44u2__p5_0[] = {
  143068. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143069. };
  143070. static long _vq_quantmap__44u2__p5_0[] = {
  143071. 7, 5, 3, 1, 0, 2, 4, 6,
  143072. 8,
  143073. };
  143074. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  143075. _vq_quantthresh__44u2__p5_0,
  143076. _vq_quantmap__44u2__p5_0,
  143077. 9,
  143078. 9
  143079. };
  143080. static static_codebook _44u2__p5_0 = {
  143081. 2, 81,
  143082. _vq_lengthlist__44u2__p5_0,
  143083. 1, -531628032, 1611661312, 4, 0,
  143084. _vq_quantlist__44u2__p5_0,
  143085. NULL,
  143086. &_vq_auxt__44u2__p5_0,
  143087. NULL,
  143088. 0
  143089. };
  143090. static long _vq_quantlist__44u2__p6_0[] = {
  143091. 6,
  143092. 5,
  143093. 7,
  143094. 4,
  143095. 8,
  143096. 3,
  143097. 9,
  143098. 2,
  143099. 10,
  143100. 1,
  143101. 11,
  143102. 0,
  143103. 12,
  143104. };
  143105. static long _vq_lengthlist__44u2__p6_0[] = {
  143106. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  143107. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  143108. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  143109. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  143110. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  143111. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  143112. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  143113. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  143114. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  143115. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  143116. 15,17,17,16,18,17,18, 0, 0,
  143117. };
  143118. static float _vq_quantthresh__44u2__p6_0[] = {
  143119. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143120. 12.5, 17.5, 22.5, 27.5,
  143121. };
  143122. static long _vq_quantmap__44u2__p6_0[] = {
  143123. 11, 9, 7, 5, 3, 1, 0, 2,
  143124. 4, 6, 8, 10, 12,
  143125. };
  143126. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  143127. _vq_quantthresh__44u2__p6_0,
  143128. _vq_quantmap__44u2__p6_0,
  143129. 13,
  143130. 13
  143131. };
  143132. static static_codebook _44u2__p6_0 = {
  143133. 2, 169,
  143134. _vq_lengthlist__44u2__p6_0,
  143135. 1, -526516224, 1616117760, 4, 0,
  143136. _vq_quantlist__44u2__p6_0,
  143137. NULL,
  143138. &_vq_auxt__44u2__p6_0,
  143139. NULL,
  143140. 0
  143141. };
  143142. static long _vq_quantlist__44u2__p6_1[] = {
  143143. 2,
  143144. 1,
  143145. 3,
  143146. 0,
  143147. 4,
  143148. };
  143149. static long _vq_lengthlist__44u2__p6_1[] = {
  143150. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143151. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143152. };
  143153. static float _vq_quantthresh__44u2__p6_1[] = {
  143154. -1.5, -0.5, 0.5, 1.5,
  143155. };
  143156. static long _vq_quantmap__44u2__p6_1[] = {
  143157. 3, 1, 0, 2, 4,
  143158. };
  143159. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  143160. _vq_quantthresh__44u2__p6_1,
  143161. _vq_quantmap__44u2__p6_1,
  143162. 5,
  143163. 5
  143164. };
  143165. static static_codebook _44u2__p6_1 = {
  143166. 2, 25,
  143167. _vq_lengthlist__44u2__p6_1,
  143168. 1, -533725184, 1611661312, 3, 0,
  143169. _vq_quantlist__44u2__p6_1,
  143170. NULL,
  143171. &_vq_auxt__44u2__p6_1,
  143172. NULL,
  143173. 0
  143174. };
  143175. static long _vq_quantlist__44u2__p7_0[] = {
  143176. 4,
  143177. 3,
  143178. 5,
  143179. 2,
  143180. 6,
  143181. 1,
  143182. 7,
  143183. 0,
  143184. 8,
  143185. };
  143186. static long _vq_lengthlist__44u2__p7_0[] = {
  143187. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  143188. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  143189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  143192. 11,
  143193. };
  143194. static float _vq_quantthresh__44u2__p7_0[] = {
  143195. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  143196. };
  143197. static long _vq_quantmap__44u2__p7_0[] = {
  143198. 7, 5, 3, 1, 0, 2, 4, 6,
  143199. 8,
  143200. };
  143201. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  143202. _vq_quantthresh__44u2__p7_0,
  143203. _vq_quantmap__44u2__p7_0,
  143204. 9,
  143205. 9
  143206. };
  143207. static static_codebook _44u2__p7_0 = {
  143208. 2, 81,
  143209. _vq_lengthlist__44u2__p7_0,
  143210. 1, -516612096, 1626677248, 4, 0,
  143211. _vq_quantlist__44u2__p7_0,
  143212. NULL,
  143213. &_vq_auxt__44u2__p7_0,
  143214. NULL,
  143215. 0
  143216. };
  143217. static long _vq_quantlist__44u2__p7_1[] = {
  143218. 6,
  143219. 5,
  143220. 7,
  143221. 4,
  143222. 8,
  143223. 3,
  143224. 9,
  143225. 2,
  143226. 10,
  143227. 1,
  143228. 11,
  143229. 0,
  143230. 12,
  143231. };
  143232. static long _vq_lengthlist__44u2__p7_1[] = {
  143233. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  143234. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  143235. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  143236. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  143237. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  143238. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  143239. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  143240. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  143241. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  143242. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  143243. 14,14,14,17,15,17,17,17,17,
  143244. };
  143245. static float _vq_quantthresh__44u2__p7_1[] = {
  143246. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  143247. 32.5, 45.5, 58.5, 71.5,
  143248. };
  143249. static long _vq_quantmap__44u2__p7_1[] = {
  143250. 11, 9, 7, 5, 3, 1, 0, 2,
  143251. 4, 6, 8, 10, 12,
  143252. };
  143253. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  143254. _vq_quantthresh__44u2__p7_1,
  143255. _vq_quantmap__44u2__p7_1,
  143256. 13,
  143257. 13
  143258. };
  143259. static static_codebook _44u2__p7_1 = {
  143260. 2, 169,
  143261. _vq_lengthlist__44u2__p7_1,
  143262. 1, -523010048, 1618608128, 4, 0,
  143263. _vq_quantlist__44u2__p7_1,
  143264. NULL,
  143265. &_vq_auxt__44u2__p7_1,
  143266. NULL,
  143267. 0
  143268. };
  143269. static long _vq_quantlist__44u2__p7_2[] = {
  143270. 6,
  143271. 5,
  143272. 7,
  143273. 4,
  143274. 8,
  143275. 3,
  143276. 9,
  143277. 2,
  143278. 10,
  143279. 1,
  143280. 11,
  143281. 0,
  143282. 12,
  143283. };
  143284. static long _vq_lengthlist__44u2__p7_2[] = {
  143285. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  143286. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  143287. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  143288. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  143289. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  143290. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  143291. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143292. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143293. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  143294. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  143295. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143296. };
  143297. static float _vq_quantthresh__44u2__p7_2[] = {
  143298. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  143299. 2.5, 3.5, 4.5, 5.5,
  143300. };
  143301. static long _vq_quantmap__44u2__p7_2[] = {
  143302. 11, 9, 7, 5, 3, 1, 0, 2,
  143303. 4, 6, 8, 10, 12,
  143304. };
  143305. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  143306. _vq_quantthresh__44u2__p7_2,
  143307. _vq_quantmap__44u2__p7_2,
  143308. 13,
  143309. 13
  143310. };
  143311. static static_codebook _44u2__p7_2 = {
  143312. 2, 169,
  143313. _vq_lengthlist__44u2__p7_2,
  143314. 1, -531103744, 1611661312, 4, 0,
  143315. _vq_quantlist__44u2__p7_2,
  143316. NULL,
  143317. &_vq_auxt__44u2__p7_2,
  143318. NULL,
  143319. 0
  143320. };
  143321. static long _huff_lengthlist__44u2__short[] = {
  143322. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  143323. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  143324. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  143325. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  143326. };
  143327. static static_codebook _huff_book__44u2__short = {
  143328. 2, 64,
  143329. _huff_lengthlist__44u2__short,
  143330. 0, 0, 0, 0, 0,
  143331. NULL,
  143332. NULL,
  143333. NULL,
  143334. NULL,
  143335. 0
  143336. };
  143337. static long _huff_lengthlist__44u3__long[] = {
  143338. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  143339. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  143340. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  143341. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  143342. };
  143343. static static_codebook _huff_book__44u3__long = {
  143344. 2, 64,
  143345. _huff_lengthlist__44u3__long,
  143346. 0, 0, 0, 0, 0,
  143347. NULL,
  143348. NULL,
  143349. NULL,
  143350. NULL,
  143351. 0
  143352. };
  143353. static long _vq_quantlist__44u3__p1_0[] = {
  143354. 1,
  143355. 0,
  143356. 2,
  143357. };
  143358. static long _vq_lengthlist__44u3__p1_0[] = {
  143359. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143360. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143361. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  143362. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143363. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  143364. 13,
  143365. };
  143366. static float _vq_quantthresh__44u3__p1_0[] = {
  143367. -0.5, 0.5,
  143368. };
  143369. static long _vq_quantmap__44u3__p1_0[] = {
  143370. 1, 0, 2,
  143371. };
  143372. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  143373. _vq_quantthresh__44u3__p1_0,
  143374. _vq_quantmap__44u3__p1_0,
  143375. 3,
  143376. 3
  143377. };
  143378. static static_codebook _44u3__p1_0 = {
  143379. 4, 81,
  143380. _vq_lengthlist__44u3__p1_0,
  143381. 1, -535822336, 1611661312, 2, 0,
  143382. _vq_quantlist__44u3__p1_0,
  143383. NULL,
  143384. &_vq_auxt__44u3__p1_0,
  143385. NULL,
  143386. 0
  143387. };
  143388. static long _vq_quantlist__44u3__p2_0[] = {
  143389. 1,
  143390. 0,
  143391. 2,
  143392. };
  143393. static long _vq_lengthlist__44u3__p2_0[] = {
  143394. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143395. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  143396. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143397. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143398. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  143399. 9,
  143400. };
  143401. static float _vq_quantthresh__44u3__p2_0[] = {
  143402. -0.5, 0.5,
  143403. };
  143404. static long _vq_quantmap__44u3__p2_0[] = {
  143405. 1, 0, 2,
  143406. };
  143407. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  143408. _vq_quantthresh__44u3__p2_0,
  143409. _vq_quantmap__44u3__p2_0,
  143410. 3,
  143411. 3
  143412. };
  143413. static static_codebook _44u3__p2_0 = {
  143414. 4, 81,
  143415. _vq_lengthlist__44u3__p2_0,
  143416. 1, -535822336, 1611661312, 2, 0,
  143417. _vq_quantlist__44u3__p2_0,
  143418. NULL,
  143419. &_vq_auxt__44u3__p2_0,
  143420. NULL,
  143421. 0
  143422. };
  143423. static long _vq_quantlist__44u3__p3_0[] = {
  143424. 2,
  143425. 1,
  143426. 3,
  143427. 0,
  143428. 4,
  143429. };
  143430. static long _vq_lengthlist__44u3__p3_0[] = {
  143431. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143432. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  143433. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  143434. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  143435. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  143436. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  143437. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  143438. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  143439. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  143440. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143441. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  143442. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143443. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  143444. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  143445. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  143446. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  143447. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  143448. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  143449. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  143450. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  143451. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  143452. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  143453. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  143454. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  143455. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  143456. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  143457. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  143458. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  143459. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  143460. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  143461. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  143462. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  143463. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  143464. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  143465. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  143466. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  143467. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  143468. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  143469. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  143470. 0,
  143471. };
  143472. static float _vq_quantthresh__44u3__p3_0[] = {
  143473. -1.5, -0.5, 0.5, 1.5,
  143474. };
  143475. static long _vq_quantmap__44u3__p3_0[] = {
  143476. 3, 1, 0, 2, 4,
  143477. };
  143478. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  143479. _vq_quantthresh__44u3__p3_0,
  143480. _vq_quantmap__44u3__p3_0,
  143481. 5,
  143482. 5
  143483. };
  143484. static static_codebook _44u3__p3_0 = {
  143485. 4, 625,
  143486. _vq_lengthlist__44u3__p3_0,
  143487. 1, -533725184, 1611661312, 3, 0,
  143488. _vq_quantlist__44u3__p3_0,
  143489. NULL,
  143490. &_vq_auxt__44u3__p3_0,
  143491. NULL,
  143492. 0
  143493. };
  143494. static long _vq_quantlist__44u3__p4_0[] = {
  143495. 2,
  143496. 1,
  143497. 3,
  143498. 0,
  143499. 4,
  143500. };
  143501. static long _vq_lengthlist__44u3__p4_0[] = {
  143502. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  143503. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  143504. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  143505. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  143506. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  143507. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  143508. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  143509. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  143510. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  143511. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  143512. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  143513. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  143514. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  143515. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  143516. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  143517. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  143518. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  143519. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  143520. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  143521. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  143522. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  143523. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  143524. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  143525. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  143526. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  143527. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  143528. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  143529. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  143530. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  143531. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  143532. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  143533. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  143534. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  143535. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  143536. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  143537. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  143538. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  143539. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  143540. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  143541. 13,
  143542. };
  143543. static float _vq_quantthresh__44u3__p4_0[] = {
  143544. -1.5, -0.5, 0.5, 1.5,
  143545. };
  143546. static long _vq_quantmap__44u3__p4_0[] = {
  143547. 3, 1, 0, 2, 4,
  143548. };
  143549. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  143550. _vq_quantthresh__44u3__p4_0,
  143551. _vq_quantmap__44u3__p4_0,
  143552. 5,
  143553. 5
  143554. };
  143555. static static_codebook _44u3__p4_0 = {
  143556. 4, 625,
  143557. _vq_lengthlist__44u3__p4_0,
  143558. 1, -533725184, 1611661312, 3, 0,
  143559. _vq_quantlist__44u3__p4_0,
  143560. NULL,
  143561. &_vq_auxt__44u3__p4_0,
  143562. NULL,
  143563. 0
  143564. };
  143565. static long _vq_quantlist__44u3__p5_0[] = {
  143566. 4,
  143567. 3,
  143568. 5,
  143569. 2,
  143570. 6,
  143571. 1,
  143572. 7,
  143573. 0,
  143574. 8,
  143575. };
  143576. static long _vq_lengthlist__44u3__p5_0[] = {
  143577. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  143578. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  143579. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  143580. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143581. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  143582. 12,
  143583. };
  143584. static float _vq_quantthresh__44u3__p5_0[] = {
  143585. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143586. };
  143587. static long _vq_quantmap__44u3__p5_0[] = {
  143588. 7, 5, 3, 1, 0, 2, 4, 6,
  143589. 8,
  143590. };
  143591. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  143592. _vq_quantthresh__44u3__p5_0,
  143593. _vq_quantmap__44u3__p5_0,
  143594. 9,
  143595. 9
  143596. };
  143597. static static_codebook _44u3__p5_0 = {
  143598. 2, 81,
  143599. _vq_lengthlist__44u3__p5_0,
  143600. 1, -531628032, 1611661312, 4, 0,
  143601. _vq_quantlist__44u3__p5_0,
  143602. NULL,
  143603. &_vq_auxt__44u3__p5_0,
  143604. NULL,
  143605. 0
  143606. };
  143607. static long _vq_quantlist__44u3__p6_0[] = {
  143608. 6,
  143609. 5,
  143610. 7,
  143611. 4,
  143612. 8,
  143613. 3,
  143614. 9,
  143615. 2,
  143616. 10,
  143617. 1,
  143618. 11,
  143619. 0,
  143620. 12,
  143621. };
  143622. static long _vq_lengthlist__44u3__p6_0[] = {
  143623. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  143624. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  143625. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  143626. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  143627. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  143628. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  143629. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  143630. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  143631. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  143632. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  143633. 15,16,16,16,17,18,16,20,18,
  143634. };
  143635. static float _vq_quantthresh__44u3__p6_0[] = {
  143636. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143637. 12.5, 17.5, 22.5, 27.5,
  143638. };
  143639. static long _vq_quantmap__44u3__p6_0[] = {
  143640. 11, 9, 7, 5, 3, 1, 0, 2,
  143641. 4, 6, 8, 10, 12,
  143642. };
  143643. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  143644. _vq_quantthresh__44u3__p6_0,
  143645. _vq_quantmap__44u3__p6_0,
  143646. 13,
  143647. 13
  143648. };
  143649. static static_codebook _44u3__p6_0 = {
  143650. 2, 169,
  143651. _vq_lengthlist__44u3__p6_0,
  143652. 1, -526516224, 1616117760, 4, 0,
  143653. _vq_quantlist__44u3__p6_0,
  143654. NULL,
  143655. &_vq_auxt__44u3__p6_0,
  143656. NULL,
  143657. 0
  143658. };
  143659. static long _vq_quantlist__44u3__p6_1[] = {
  143660. 2,
  143661. 1,
  143662. 3,
  143663. 0,
  143664. 4,
  143665. };
  143666. static long _vq_lengthlist__44u3__p6_1[] = {
  143667. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  143668. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  143669. };
  143670. static float _vq_quantthresh__44u3__p6_1[] = {
  143671. -1.5, -0.5, 0.5, 1.5,
  143672. };
  143673. static long _vq_quantmap__44u3__p6_1[] = {
  143674. 3, 1, 0, 2, 4,
  143675. };
  143676. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  143677. _vq_quantthresh__44u3__p6_1,
  143678. _vq_quantmap__44u3__p6_1,
  143679. 5,
  143680. 5
  143681. };
  143682. static static_codebook _44u3__p6_1 = {
  143683. 2, 25,
  143684. _vq_lengthlist__44u3__p6_1,
  143685. 1, -533725184, 1611661312, 3, 0,
  143686. _vq_quantlist__44u3__p6_1,
  143687. NULL,
  143688. &_vq_auxt__44u3__p6_1,
  143689. NULL,
  143690. 0
  143691. };
  143692. static long _vq_quantlist__44u3__p7_0[] = {
  143693. 4,
  143694. 3,
  143695. 5,
  143696. 2,
  143697. 6,
  143698. 1,
  143699. 7,
  143700. 0,
  143701. 8,
  143702. };
  143703. static long _vq_lengthlist__44u3__p7_0[] = {
  143704. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  143705. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143706. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143707. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143708. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143709. 9,
  143710. };
  143711. static float _vq_quantthresh__44u3__p7_0[] = {
  143712. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  143713. };
  143714. static long _vq_quantmap__44u3__p7_0[] = {
  143715. 7, 5, 3, 1, 0, 2, 4, 6,
  143716. 8,
  143717. };
  143718. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  143719. _vq_quantthresh__44u3__p7_0,
  143720. _vq_quantmap__44u3__p7_0,
  143721. 9,
  143722. 9
  143723. };
  143724. static static_codebook _44u3__p7_0 = {
  143725. 2, 81,
  143726. _vq_lengthlist__44u3__p7_0,
  143727. 1, -515907584, 1627381760, 4, 0,
  143728. _vq_quantlist__44u3__p7_0,
  143729. NULL,
  143730. &_vq_auxt__44u3__p7_0,
  143731. NULL,
  143732. 0
  143733. };
  143734. static long _vq_quantlist__44u3__p7_1[] = {
  143735. 7,
  143736. 6,
  143737. 8,
  143738. 5,
  143739. 9,
  143740. 4,
  143741. 10,
  143742. 3,
  143743. 11,
  143744. 2,
  143745. 12,
  143746. 1,
  143747. 13,
  143748. 0,
  143749. 14,
  143750. };
  143751. static long _vq_lengthlist__44u3__p7_1[] = {
  143752. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  143753. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  143754. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  143755. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  143756. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  143757. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  143758. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  143759. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  143760. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  143761. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  143762. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  143763. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  143764. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  143765. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  143766. 17,
  143767. };
  143768. static float _vq_quantthresh__44u3__p7_1[] = {
  143769. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143770. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143771. };
  143772. static long _vq_quantmap__44u3__p7_1[] = {
  143773. 13, 11, 9, 7, 5, 3, 1, 0,
  143774. 2, 4, 6, 8, 10, 12, 14,
  143775. };
  143776. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  143777. _vq_quantthresh__44u3__p7_1,
  143778. _vq_quantmap__44u3__p7_1,
  143779. 15,
  143780. 15
  143781. };
  143782. static static_codebook _44u3__p7_1 = {
  143783. 2, 225,
  143784. _vq_lengthlist__44u3__p7_1,
  143785. 1, -522338304, 1620115456, 4, 0,
  143786. _vq_quantlist__44u3__p7_1,
  143787. NULL,
  143788. &_vq_auxt__44u3__p7_1,
  143789. NULL,
  143790. 0
  143791. };
  143792. static long _vq_quantlist__44u3__p7_2[] = {
  143793. 8,
  143794. 7,
  143795. 9,
  143796. 6,
  143797. 10,
  143798. 5,
  143799. 11,
  143800. 4,
  143801. 12,
  143802. 3,
  143803. 13,
  143804. 2,
  143805. 14,
  143806. 1,
  143807. 15,
  143808. 0,
  143809. 16,
  143810. };
  143811. static long _vq_lengthlist__44u3__p7_2[] = {
  143812. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143813. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143814. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  143815. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143816. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  143817. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143818. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  143819. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143820. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  143821. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  143822. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  143823. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  143824. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  143825. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  143826. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  143827. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  143828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143829. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  143830. 11,
  143831. };
  143832. static float _vq_quantthresh__44u3__p7_2[] = {
  143833. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143834. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143835. };
  143836. static long _vq_quantmap__44u3__p7_2[] = {
  143837. 15, 13, 11, 9, 7, 5, 3, 1,
  143838. 0, 2, 4, 6, 8, 10, 12, 14,
  143839. 16,
  143840. };
  143841. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  143842. _vq_quantthresh__44u3__p7_2,
  143843. _vq_quantmap__44u3__p7_2,
  143844. 17,
  143845. 17
  143846. };
  143847. static static_codebook _44u3__p7_2 = {
  143848. 2, 289,
  143849. _vq_lengthlist__44u3__p7_2,
  143850. 1, -529530880, 1611661312, 5, 0,
  143851. _vq_quantlist__44u3__p7_2,
  143852. NULL,
  143853. &_vq_auxt__44u3__p7_2,
  143854. NULL,
  143855. 0
  143856. };
  143857. static long _huff_lengthlist__44u3__short[] = {
  143858. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  143859. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  143860. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  143861. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  143862. };
  143863. static static_codebook _huff_book__44u3__short = {
  143864. 2, 64,
  143865. _huff_lengthlist__44u3__short,
  143866. 0, 0, 0, 0, 0,
  143867. NULL,
  143868. NULL,
  143869. NULL,
  143870. NULL,
  143871. 0
  143872. };
  143873. static long _huff_lengthlist__44u4__long[] = {
  143874. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  143875. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  143876. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  143877. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  143878. };
  143879. static static_codebook _huff_book__44u4__long = {
  143880. 2, 64,
  143881. _huff_lengthlist__44u4__long,
  143882. 0, 0, 0, 0, 0,
  143883. NULL,
  143884. NULL,
  143885. NULL,
  143886. NULL,
  143887. 0
  143888. };
  143889. static long _vq_quantlist__44u4__p1_0[] = {
  143890. 1,
  143891. 0,
  143892. 2,
  143893. };
  143894. static long _vq_lengthlist__44u4__p1_0[] = {
  143895. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  143896. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  143897. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  143898. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  143899. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  143900. 13,
  143901. };
  143902. static float _vq_quantthresh__44u4__p1_0[] = {
  143903. -0.5, 0.5,
  143904. };
  143905. static long _vq_quantmap__44u4__p1_0[] = {
  143906. 1, 0, 2,
  143907. };
  143908. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  143909. _vq_quantthresh__44u4__p1_0,
  143910. _vq_quantmap__44u4__p1_0,
  143911. 3,
  143912. 3
  143913. };
  143914. static static_codebook _44u4__p1_0 = {
  143915. 4, 81,
  143916. _vq_lengthlist__44u4__p1_0,
  143917. 1, -535822336, 1611661312, 2, 0,
  143918. _vq_quantlist__44u4__p1_0,
  143919. NULL,
  143920. &_vq_auxt__44u4__p1_0,
  143921. NULL,
  143922. 0
  143923. };
  143924. static long _vq_quantlist__44u4__p2_0[] = {
  143925. 1,
  143926. 0,
  143927. 2,
  143928. };
  143929. static long _vq_lengthlist__44u4__p2_0[] = {
  143930. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  143931. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  143932. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  143933. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  143934. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  143935. 9,
  143936. };
  143937. static float _vq_quantthresh__44u4__p2_0[] = {
  143938. -0.5, 0.5,
  143939. };
  143940. static long _vq_quantmap__44u4__p2_0[] = {
  143941. 1, 0, 2,
  143942. };
  143943. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  143944. _vq_quantthresh__44u4__p2_0,
  143945. _vq_quantmap__44u4__p2_0,
  143946. 3,
  143947. 3
  143948. };
  143949. static static_codebook _44u4__p2_0 = {
  143950. 4, 81,
  143951. _vq_lengthlist__44u4__p2_0,
  143952. 1, -535822336, 1611661312, 2, 0,
  143953. _vq_quantlist__44u4__p2_0,
  143954. NULL,
  143955. &_vq_auxt__44u4__p2_0,
  143956. NULL,
  143957. 0
  143958. };
  143959. static long _vq_quantlist__44u4__p3_0[] = {
  143960. 2,
  143961. 1,
  143962. 3,
  143963. 0,
  143964. 4,
  143965. };
  143966. static long _vq_lengthlist__44u4__p3_0[] = {
  143967. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  143968. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  143969. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  143970. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  143971. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143972. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  143973. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  143974. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  143975. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  143976. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  143977. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  143978. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  143979. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  143980. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  143981. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  143982. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  143983. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  143984. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  143985. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  143986. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  143987. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  143988. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  143989. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  143990. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  143991. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  143992. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  143993. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  143994. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  143995. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  143996. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  143997. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  143998. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  143999. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  144000. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  144001. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  144002. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  144003. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  144004. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  144005. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  144006. 0,
  144007. };
  144008. static float _vq_quantthresh__44u4__p3_0[] = {
  144009. -1.5, -0.5, 0.5, 1.5,
  144010. };
  144011. static long _vq_quantmap__44u4__p3_0[] = {
  144012. 3, 1, 0, 2, 4,
  144013. };
  144014. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  144015. _vq_quantthresh__44u4__p3_0,
  144016. _vq_quantmap__44u4__p3_0,
  144017. 5,
  144018. 5
  144019. };
  144020. static static_codebook _44u4__p3_0 = {
  144021. 4, 625,
  144022. _vq_lengthlist__44u4__p3_0,
  144023. 1, -533725184, 1611661312, 3, 0,
  144024. _vq_quantlist__44u4__p3_0,
  144025. NULL,
  144026. &_vq_auxt__44u4__p3_0,
  144027. NULL,
  144028. 0
  144029. };
  144030. static long _vq_quantlist__44u4__p4_0[] = {
  144031. 2,
  144032. 1,
  144033. 3,
  144034. 0,
  144035. 4,
  144036. };
  144037. static long _vq_lengthlist__44u4__p4_0[] = {
  144038. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  144039. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144040. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  144041. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144042. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  144043. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144044. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  144045. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  144046. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  144047. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  144048. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  144049. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144050. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  144051. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  144052. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  144053. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144054. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  144055. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144056. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  144057. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  144058. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  144059. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  144060. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  144061. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  144062. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  144063. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  144064. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  144065. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  144066. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  144067. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  144068. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  144069. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  144070. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  144071. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  144072. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  144073. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  144074. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  144075. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  144076. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  144077. 13,
  144078. };
  144079. static float _vq_quantthresh__44u4__p4_0[] = {
  144080. -1.5, -0.5, 0.5, 1.5,
  144081. };
  144082. static long _vq_quantmap__44u4__p4_0[] = {
  144083. 3, 1, 0, 2, 4,
  144084. };
  144085. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  144086. _vq_quantthresh__44u4__p4_0,
  144087. _vq_quantmap__44u4__p4_0,
  144088. 5,
  144089. 5
  144090. };
  144091. static static_codebook _44u4__p4_0 = {
  144092. 4, 625,
  144093. _vq_lengthlist__44u4__p4_0,
  144094. 1, -533725184, 1611661312, 3, 0,
  144095. _vq_quantlist__44u4__p4_0,
  144096. NULL,
  144097. &_vq_auxt__44u4__p4_0,
  144098. NULL,
  144099. 0
  144100. };
  144101. static long _vq_quantlist__44u4__p5_0[] = {
  144102. 4,
  144103. 3,
  144104. 5,
  144105. 2,
  144106. 6,
  144107. 1,
  144108. 7,
  144109. 0,
  144110. 8,
  144111. };
  144112. static long _vq_lengthlist__44u4__p5_0[] = {
  144113. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  144114. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  144115. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  144116. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  144117. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  144118. 12,
  144119. };
  144120. static float _vq_quantthresh__44u4__p5_0[] = {
  144121. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144122. };
  144123. static long _vq_quantmap__44u4__p5_0[] = {
  144124. 7, 5, 3, 1, 0, 2, 4, 6,
  144125. 8,
  144126. };
  144127. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  144128. _vq_quantthresh__44u4__p5_0,
  144129. _vq_quantmap__44u4__p5_0,
  144130. 9,
  144131. 9
  144132. };
  144133. static static_codebook _44u4__p5_0 = {
  144134. 2, 81,
  144135. _vq_lengthlist__44u4__p5_0,
  144136. 1, -531628032, 1611661312, 4, 0,
  144137. _vq_quantlist__44u4__p5_0,
  144138. NULL,
  144139. &_vq_auxt__44u4__p5_0,
  144140. NULL,
  144141. 0
  144142. };
  144143. static long _vq_quantlist__44u4__p6_0[] = {
  144144. 6,
  144145. 5,
  144146. 7,
  144147. 4,
  144148. 8,
  144149. 3,
  144150. 9,
  144151. 2,
  144152. 10,
  144153. 1,
  144154. 11,
  144155. 0,
  144156. 12,
  144157. };
  144158. static long _vq_lengthlist__44u4__p6_0[] = {
  144159. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  144160. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  144161. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  144162. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  144163. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  144164. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  144165. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  144166. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  144167. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  144168. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  144169. 16,16,16,17,17,18,17,20,21,
  144170. };
  144171. static float _vq_quantthresh__44u4__p6_0[] = {
  144172. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144173. 12.5, 17.5, 22.5, 27.5,
  144174. };
  144175. static long _vq_quantmap__44u4__p6_0[] = {
  144176. 11, 9, 7, 5, 3, 1, 0, 2,
  144177. 4, 6, 8, 10, 12,
  144178. };
  144179. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  144180. _vq_quantthresh__44u4__p6_0,
  144181. _vq_quantmap__44u4__p6_0,
  144182. 13,
  144183. 13
  144184. };
  144185. static static_codebook _44u4__p6_0 = {
  144186. 2, 169,
  144187. _vq_lengthlist__44u4__p6_0,
  144188. 1, -526516224, 1616117760, 4, 0,
  144189. _vq_quantlist__44u4__p6_0,
  144190. NULL,
  144191. &_vq_auxt__44u4__p6_0,
  144192. NULL,
  144193. 0
  144194. };
  144195. static long _vq_quantlist__44u4__p6_1[] = {
  144196. 2,
  144197. 1,
  144198. 3,
  144199. 0,
  144200. 4,
  144201. };
  144202. static long _vq_lengthlist__44u4__p6_1[] = {
  144203. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  144204. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  144205. };
  144206. static float _vq_quantthresh__44u4__p6_1[] = {
  144207. -1.5, -0.5, 0.5, 1.5,
  144208. };
  144209. static long _vq_quantmap__44u4__p6_1[] = {
  144210. 3, 1, 0, 2, 4,
  144211. };
  144212. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  144213. _vq_quantthresh__44u4__p6_1,
  144214. _vq_quantmap__44u4__p6_1,
  144215. 5,
  144216. 5
  144217. };
  144218. static static_codebook _44u4__p6_1 = {
  144219. 2, 25,
  144220. _vq_lengthlist__44u4__p6_1,
  144221. 1, -533725184, 1611661312, 3, 0,
  144222. _vq_quantlist__44u4__p6_1,
  144223. NULL,
  144224. &_vq_auxt__44u4__p6_1,
  144225. NULL,
  144226. 0
  144227. };
  144228. static long _vq_quantlist__44u4__p7_0[] = {
  144229. 6,
  144230. 5,
  144231. 7,
  144232. 4,
  144233. 8,
  144234. 3,
  144235. 9,
  144236. 2,
  144237. 10,
  144238. 1,
  144239. 11,
  144240. 0,
  144241. 12,
  144242. };
  144243. static long _vq_lengthlist__44u4__p7_0[] = {
  144244. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  144245. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  144246. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144247. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144249. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144250. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144251. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144254. 11,11,11,11,11,11,11,11,11,
  144255. };
  144256. static float _vq_quantthresh__44u4__p7_0[] = {
  144257. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144258. 637.5, 892.5, 1147.5, 1402.5,
  144259. };
  144260. static long _vq_quantmap__44u4__p7_0[] = {
  144261. 11, 9, 7, 5, 3, 1, 0, 2,
  144262. 4, 6, 8, 10, 12,
  144263. };
  144264. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  144265. _vq_quantthresh__44u4__p7_0,
  144266. _vq_quantmap__44u4__p7_0,
  144267. 13,
  144268. 13
  144269. };
  144270. static static_codebook _44u4__p7_0 = {
  144271. 2, 169,
  144272. _vq_lengthlist__44u4__p7_0,
  144273. 1, -514332672, 1627381760, 4, 0,
  144274. _vq_quantlist__44u4__p7_0,
  144275. NULL,
  144276. &_vq_auxt__44u4__p7_0,
  144277. NULL,
  144278. 0
  144279. };
  144280. static long _vq_quantlist__44u4__p7_1[] = {
  144281. 7,
  144282. 6,
  144283. 8,
  144284. 5,
  144285. 9,
  144286. 4,
  144287. 10,
  144288. 3,
  144289. 11,
  144290. 2,
  144291. 12,
  144292. 1,
  144293. 13,
  144294. 0,
  144295. 14,
  144296. };
  144297. static long _vq_lengthlist__44u4__p7_1[] = {
  144298. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  144299. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  144300. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  144301. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  144302. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  144303. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  144304. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  144305. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  144306. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  144307. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  144308. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  144309. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  144310. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  144311. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  144312. 16,
  144313. };
  144314. static float _vq_quantthresh__44u4__p7_1[] = {
  144315. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144316. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144317. };
  144318. static long _vq_quantmap__44u4__p7_1[] = {
  144319. 13, 11, 9, 7, 5, 3, 1, 0,
  144320. 2, 4, 6, 8, 10, 12, 14,
  144321. };
  144322. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  144323. _vq_quantthresh__44u4__p7_1,
  144324. _vq_quantmap__44u4__p7_1,
  144325. 15,
  144326. 15
  144327. };
  144328. static static_codebook _44u4__p7_1 = {
  144329. 2, 225,
  144330. _vq_lengthlist__44u4__p7_1,
  144331. 1, -522338304, 1620115456, 4, 0,
  144332. _vq_quantlist__44u4__p7_1,
  144333. NULL,
  144334. &_vq_auxt__44u4__p7_1,
  144335. NULL,
  144336. 0
  144337. };
  144338. static long _vq_quantlist__44u4__p7_2[] = {
  144339. 8,
  144340. 7,
  144341. 9,
  144342. 6,
  144343. 10,
  144344. 5,
  144345. 11,
  144346. 4,
  144347. 12,
  144348. 3,
  144349. 13,
  144350. 2,
  144351. 14,
  144352. 1,
  144353. 15,
  144354. 0,
  144355. 16,
  144356. };
  144357. static long _vq_lengthlist__44u4__p7_2[] = {
  144358. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144359. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144360. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144361. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144362. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144363. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144364. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144365. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  144366. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  144367. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  144368. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144369. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  144370. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144371. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  144372. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  144373. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144374. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144375. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  144376. 10,
  144377. };
  144378. static float _vq_quantthresh__44u4__p7_2[] = {
  144379. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144380. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144381. };
  144382. static long _vq_quantmap__44u4__p7_2[] = {
  144383. 15, 13, 11, 9, 7, 5, 3, 1,
  144384. 0, 2, 4, 6, 8, 10, 12, 14,
  144385. 16,
  144386. };
  144387. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  144388. _vq_quantthresh__44u4__p7_2,
  144389. _vq_quantmap__44u4__p7_2,
  144390. 17,
  144391. 17
  144392. };
  144393. static static_codebook _44u4__p7_2 = {
  144394. 2, 289,
  144395. _vq_lengthlist__44u4__p7_2,
  144396. 1, -529530880, 1611661312, 5, 0,
  144397. _vq_quantlist__44u4__p7_2,
  144398. NULL,
  144399. &_vq_auxt__44u4__p7_2,
  144400. NULL,
  144401. 0
  144402. };
  144403. static long _huff_lengthlist__44u4__short[] = {
  144404. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  144405. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  144406. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  144407. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  144408. };
  144409. static static_codebook _huff_book__44u4__short = {
  144410. 2, 64,
  144411. _huff_lengthlist__44u4__short,
  144412. 0, 0, 0, 0, 0,
  144413. NULL,
  144414. NULL,
  144415. NULL,
  144416. NULL,
  144417. 0
  144418. };
  144419. static long _huff_lengthlist__44u5__long[] = {
  144420. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  144421. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  144422. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  144423. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  144424. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  144425. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  144426. 14, 8, 7, 8,
  144427. };
  144428. static static_codebook _huff_book__44u5__long = {
  144429. 2, 100,
  144430. _huff_lengthlist__44u5__long,
  144431. 0, 0, 0, 0, 0,
  144432. NULL,
  144433. NULL,
  144434. NULL,
  144435. NULL,
  144436. 0
  144437. };
  144438. static long _vq_quantlist__44u5__p1_0[] = {
  144439. 1,
  144440. 0,
  144441. 2,
  144442. };
  144443. static long _vq_lengthlist__44u5__p1_0[] = {
  144444. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  144445. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  144446. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  144447. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  144448. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  144449. 12,
  144450. };
  144451. static float _vq_quantthresh__44u5__p1_0[] = {
  144452. -0.5, 0.5,
  144453. };
  144454. static long _vq_quantmap__44u5__p1_0[] = {
  144455. 1, 0, 2,
  144456. };
  144457. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  144458. _vq_quantthresh__44u5__p1_0,
  144459. _vq_quantmap__44u5__p1_0,
  144460. 3,
  144461. 3
  144462. };
  144463. static static_codebook _44u5__p1_0 = {
  144464. 4, 81,
  144465. _vq_lengthlist__44u5__p1_0,
  144466. 1, -535822336, 1611661312, 2, 0,
  144467. _vq_quantlist__44u5__p1_0,
  144468. NULL,
  144469. &_vq_auxt__44u5__p1_0,
  144470. NULL,
  144471. 0
  144472. };
  144473. static long _vq_quantlist__44u5__p2_0[] = {
  144474. 1,
  144475. 0,
  144476. 2,
  144477. };
  144478. static long _vq_lengthlist__44u5__p2_0[] = {
  144479. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  144480. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  144481. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  144482. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  144483. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  144484. 9,
  144485. };
  144486. static float _vq_quantthresh__44u5__p2_0[] = {
  144487. -0.5, 0.5,
  144488. };
  144489. static long _vq_quantmap__44u5__p2_0[] = {
  144490. 1, 0, 2,
  144491. };
  144492. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  144493. _vq_quantthresh__44u5__p2_0,
  144494. _vq_quantmap__44u5__p2_0,
  144495. 3,
  144496. 3
  144497. };
  144498. static static_codebook _44u5__p2_0 = {
  144499. 4, 81,
  144500. _vq_lengthlist__44u5__p2_0,
  144501. 1, -535822336, 1611661312, 2, 0,
  144502. _vq_quantlist__44u5__p2_0,
  144503. NULL,
  144504. &_vq_auxt__44u5__p2_0,
  144505. NULL,
  144506. 0
  144507. };
  144508. static long _vq_quantlist__44u5__p3_0[] = {
  144509. 2,
  144510. 1,
  144511. 3,
  144512. 0,
  144513. 4,
  144514. };
  144515. static long _vq_lengthlist__44u5__p3_0[] = {
  144516. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144517. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  144518. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  144519. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  144520. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  144521. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  144522. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  144523. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  144524. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  144525. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  144526. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  144527. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  144528. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  144529. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  144530. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  144531. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  144532. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  144533. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  144534. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  144535. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  144536. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  144537. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  144538. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  144539. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  144540. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  144541. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  144542. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  144543. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  144544. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  144545. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  144546. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  144547. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  144548. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  144549. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  144550. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  144551. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  144552. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  144553. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  144554. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  144555. 0,
  144556. };
  144557. static float _vq_quantthresh__44u5__p3_0[] = {
  144558. -1.5, -0.5, 0.5, 1.5,
  144559. };
  144560. static long _vq_quantmap__44u5__p3_0[] = {
  144561. 3, 1, 0, 2, 4,
  144562. };
  144563. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  144564. _vq_quantthresh__44u5__p3_0,
  144565. _vq_quantmap__44u5__p3_0,
  144566. 5,
  144567. 5
  144568. };
  144569. static static_codebook _44u5__p3_0 = {
  144570. 4, 625,
  144571. _vq_lengthlist__44u5__p3_0,
  144572. 1, -533725184, 1611661312, 3, 0,
  144573. _vq_quantlist__44u5__p3_0,
  144574. NULL,
  144575. &_vq_auxt__44u5__p3_0,
  144576. NULL,
  144577. 0
  144578. };
  144579. static long _vq_quantlist__44u5__p4_0[] = {
  144580. 2,
  144581. 1,
  144582. 3,
  144583. 0,
  144584. 4,
  144585. };
  144586. static long _vq_lengthlist__44u5__p4_0[] = {
  144587. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  144588. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  144589. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  144590. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  144591. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  144592. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  144593. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144594. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  144595. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144596. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  144597. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  144598. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144599. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  144600. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  144601. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  144602. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  144603. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144604. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  144605. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  144606. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  144607. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  144608. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  144609. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  144610. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  144611. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  144612. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  144613. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  144614. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  144615. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  144616. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  144617. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  144618. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  144619. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  144620. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  144621. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  144622. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  144623. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  144624. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  144625. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  144626. 12,
  144627. };
  144628. static float _vq_quantthresh__44u5__p4_0[] = {
  144629. -1.5, -0.5, 0.5, 1.5,
  144630. };
  144631. static long _vq_quantmap__44u5__p4_0[] = {
  144632. 3, 1, 0, 2, 4,
  144633. };
  144634. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  144635. _vq_quantthresh__44u5__p4_0,
  144636. _vq_quantmap__44u5__p4_0,
  144637. 5,
  144638. 5
  144639. };
  144640. static static_codebook _44u5__p4_0 = {
  144641. 4, 625,
  144642. _vq_lengthlist__44u5__p4_0,
  144643. 1, -533725184, 1611661312, 3, 0,
  144644. _vq_quantlist__44u5__p4_0,
  144645. NULL,
  144646. &_vq_auxt__44u5__p4_0,
  144647. NULL,
  144648. 0
  144649. };
  144650. static long _vq_quantlist__44u5__p5_0[] = {
  144651. 4,
  144652. 3,
  144653. 5,
  144654. 2,
  144655. 6,
  144656. 1,
  144657. 7,
  144658. 0,
  144659. 8,
  144660. };
  144661. static long _vq_lengthlist__44u5__p5_0[] = {
  144662. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  144663. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  144664. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  144665. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  144666. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  144667. 14,
  144668. };
  144669. static float _vq_quantthresh__44u5__p5_0[] = {
  144670. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144671. };
  144672. static long _vq_quantmap__44u5__p5_0[] = {
  144673. 7, 5, 3, 1, 0, 2, 4, 6,
  144674. 8,
  144675. };
  144676. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  144677. _vq_quantthresh__44u5__p5_0,
  144678. _vq_quantmap__44u5__p5_0,
  144679. 9,
  144680. 9
  144681. };
  144682. static static_codebook _44u5__p5_0 = {
  144683. 2, 81,
  144684. _vq_lengthlist__44u5__p5_0,
  144685. 1, -531628032, 1611661312, 4, 0,
  144686. _vq_quantlist__44u5__p5_0,
  144687. NULL,
  144688. &_vq_auxt__44u5__p5_0,
  144689. NULL,
  144690. 0
  144691. };
  144692. static long _vq_quantlist__44u5__p6_0[] = {
  144693. 4,
  144694. 3,
  144695. 5,
  144696. 2,
  144697. 6,
  144698. 1,
  144699. 7,
  144700. 0,
  144701. 8,
  144702. };
  144703. static long _vq_lengthlist__44u5__p6_0[] = {
  144704. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144705. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144706. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144707. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144708. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  144709. 11,
  144710. };
  144711. static float _vq_quantthresh__44u5__p6_0[] = {
  144712. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144713. };
  144714. static long _vq_quantmap__44u5__p6_0[] = {
  144715. 7, 5, 3, 1, 0, 2, 4, 6,
  144716. 8,
  144717. };
  144718. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  144719. _vq_quantthresh__44u5__p6_0,
  144720. _vq_quantmap__44u5__p6_0,
  144721. 9,
  144722. 9
  144723. };
  144724. static static_codebook _44u5__p6_0 = {
  144725. 2, 81,
  144726. _vq_lengthlist__44u5__p6_0,
  144727. 1, -531628032, 1611661312, 4, 0,
  144728. _vq_quantlist__44u5__p6_0,
  144729. NULL,
  144730. &_vq_auxt__44u5__p6_0,
  144731. NULL,
  144732. 0
  144733. };
  144734. static long _vq_quantlist__44u5__p7_0[] = {
  144735. 1,
  144736. 0,
  144737. 2,
  144738. };
  144739. static long _vq_lengthlist__44u5__p7_0[] = {
  144740. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  144741. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  144742. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  144743. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  144744. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  144745. 12,
  144746. };
  144747. static float _vq_quantthresh__44u5__p7_0[] = {
  144748. -5.5, 5.5,
  144749. };
  144750. static long _vq_quantmap__44u5__p7_0[] = {
  144751. 1, 0, 2,
  144752. };
  144753. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  144754. _vq_quantthresh__44u5__p7_0,
  144755. _vq_quantmap__44u5__p7_0,
  144756. 3,
  144757. 3
  144758. };
  144759. static static_codebook _44u5__p7_0 = {
  144760. 4, 81,
  144761. _vq_lengthlist__44u5__p7_0,
  144762. 1, -529137664, 1618345984, 2, 0,
  144763. _vq_quantlist__44u5__p7_0,
  144764. NULL,
  144765. &_vq_auxt__44u5__p7_0,
  144766. NULL,
  144767. 0
  144768. };
  144769. static long _vq_quantlist__44u5__p7_1[] = {
  144770. 5,
  144771. 4,
  144772. 6,
  144773. 3,
  144774. 7,
  144775. 2,
  144776. 8,
  144777. 1,
  144778. 9,
  144779. 0,
  144780. 10,
  144781. };
  144782. static long _vq_lengthlist__44u5__p7_1[] = {
  144783. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  144784. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  144785. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144786. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  144787. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  144788. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  144789. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  144790. 9, 9, 9, 9, 9,10,10,10,10,
  144791. };
  144792. static float _vq_quantthresh__44u5__p7_1[] = {
  144793. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144794. 3.5, 4.5,
  144795. };
  144796. static long _vq_quantmap__44u5__p7_1[] = {
  144797. 9, 7, 5, 3, 1, 0, 2, 4,
  144798. 6, 8, 10,
  144799. };
  144800. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  144801. _vq_quantthresh__44u5__p7_1,
  144802. _vq_quantmap__44u5__p7_1,
  144803. 11,
  144804. 11
  144805. };
  144806. static static_codebook _44u5__p7_1 = {
  144807. 2, 121,
  144808. _vq_lengthlist__44u5__p7_1,
  144809. 1, -531365888, 1611661312, 4, 0,
  144810. _vq_quantlist__44u5__p7_1,
  144811. NULL,
  144812. &_vq_auxt__44u5__p7_1,
  144813. NULL,
  144814. 0
  144815. };
  144816. static long _vq_quantlist__44u5__p8_0[] = {
  144817. 5,
  144818. 4,
  144819. 6,
  144820. 3,
  144821. 7,
  144822. 2,
  144823. 8,
  144824. 1,
  144825. 9,
  144826. 0,
  144827. 10,
  144828. };
  144829. static long _vq_lengthlist__44u5__p8_0[] = {
  144830. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  144831. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  144832. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  144833. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  144834. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  144835. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  144836. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  144837. 12,13,13,14,14,14,14,15,15,
  144838. };
  144839. static float _vq_quantthresh__44u5__p8_0[] = {
  144840. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144841. 38.5, 49.5,
  144842. };
  144843. static long _vq_quantmap__44u5__p8_0[] = {
  144844. 9, 7, 5, 3, 1, 0, 2, 4,
  144845. 6, 8, 10,
  144846. };
  144847. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  144848. _vq_quantthresh__44u5__p8_0,
  144849. _vq_quantmap__44u5__p8_0,
  144850. 11,
  144851. 11
  144852. };
  144853. static static_codebook _44u5__p8_0 = {
  144854. 2, 121,
  144855. _vq_lengthlist__44u5__p8_0,
  144856. 1, -524582912, 1618345984, 4, 0,
  144857. _vq_quantlist__44u5__p8_0,
  144858. NULL,
  144859. &_vq_auxt__44u5__p8_0,
  144860. NULL,
  144861. 0
  144862. };
  144863. static long _vq_quantlist__44u5__p8_1[] = {
  144864. 5,
  144865. 4,
  144866. 6,
  144867. 3,
  144868. 7,
  144869. 2,
  144870. 8,
  144871. 1,
  144872. 9,
  144873. 0,
  144874. 10,
  144875. };
  144876. static long _vq_lengthlist__44u5__p8_1[] = {
  144877. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  144878. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  144879. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  144880. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  144881. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  144882. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144883. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144884. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144885. };
  144886. static float _vq_quantthresh__44u5__p8_1[] = {
  144887. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144888. 3.5, 4.5,
  144889. };
  144890. static long _vq_quantmap__44u5__p8_1[] = {
  144891. 9, 7, 5, 3, 1, 0, 2, 4,
  144892. 6, 8, 10,
  144893. };
  144894. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  144895. _vq_quantthresh__44u5__p8_1,
  144896. _vq_quantmap__44u5__p8_1,
  144897. 11,
  144898. 11
  144899. };
  144900. static static_codebook _44u5__p8_1 = {
  144901. 2, 121,
  144902. _vq_lengthlist__44u5__p8_1,
  144903. 1, -531365888, 1611661312, 4, 0,
  144904. _vq_quantlist__44u5__p8_1,
  144905. NULL,
  144906. &_vq_auxt__44u5__p8_1,
  144907. NULL,
  144908. 0
  144909. };
  144910. static long _vq_quantlist__44u5__p9_0[] = {
  144911. 6,
  144912. 5,
  144913. 7,
  144914. 4,
  144915. 8,
  144916. 3,
  144917. 9,
  144918. 2,
  144919. 10,
  144920. 1,
  144921. 11,
  144922. 0,
  144923. 12,
  144924. };
  144925. static long _vq_lengthlist__44u5__p9_0[] = {
  144926. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  144927. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  144928. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  144929. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  144930. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144931. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144932. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144933. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  144934. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  144935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144936. 12,12,12,12,12,12,12,12,12,
  144937. };
  144938. static float _vq_quantthresh__44u5__p9_0[] = {
  144939. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  144940. 637.5, 892.5, 1147.5, 1402.5,
  144941. };
  144942. static long _vq_quantmap__44u5__p9_0[] = {
  144943. 11, 9, 7, 5, 3, 1, 0, 2,
  144944. 4, 6, 8, 10, 12,
  144945. };
  144946. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  144947. _vq_quantthresh__44u5__p9_0,
  144948. _vq_quantmap__44u5__p9_0,
  144949. 13,
  144950. 13
  144951. };
  144952. static static_codebook _44u5__p9_0 = {
  144953. 2, 169,
  144954. _vq_lengthlist__44u5__p9_0,
  144955. 1, -514332672, 1627381760, 4, 0,
  144956. _vq_quantlist__44u5__p9_0,
  144957. NULL,
  144958. &_vq_auxt__44u5__p9_0,
  144959. NULL,
  144960. 0
  144961. };
  144962. static long _vq_quantlist__44u5__p9_1[] = {
  144963. 7,
  144964. 6,
  144965. 8,
  144966. 5,
  144967. 9,
  144968. 4,
  144969. 10,
  144970. 3,
  144971. 11,
  144972. 2,
  144973. 12,
  144974. 1,
  144975. 13,
  144976. 0,
  144977. 14,
  144978. };
  144979. static long _vq_lengthlist__44u5__p9_1[] = {
  144980. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  144981. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  144982. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  144983. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  144984. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  144985. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  144986. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  144987. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  144988. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  144989. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  144990. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  144991. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  144992. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  144993. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  144994. 14,
  144995. };
  144996. static float _vq_quantthresh__44u5__p9_1[] = {
  144997. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144998. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144999. };
  145000. static long _vq_quantmap__44u5__p9_1[] = {
  145001. 13, 11, 9, 7, 5, 3, 1, 0,
  145002. 2, 4, 6, 8, 10, 12, 14,
  145003. };
  145004. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  145005. _vq_quantthresh__44u5__p9_1,
  145006. _vq_quantmap__44u5__p9_1,
  145007. 15,
  145008. 15
  145009. };
  145010. static static_codebook _44u5__p9_1 = {
  145011. 2, 225,
  145012. _vq_lengthlist__44u5__p9_1,
  145013. 1, -522338304, 1620115456, 4, 0,
  145014. _vq_quantlist__44u5__p9_1,
  145015. NULL,
  145016. &_vq_auxt__44u5__p9_1,
  145017. NULL,
  145018. 0
  145019. };
  145020. static long _vq_quantlist__44u5__p9_2[] = {
  145021. 8,
  145022. 7,
  145023. 9,
  145024. 6,
  145025. 10,
  145026. 5,
  145027. 11,
  145028. 4,
  145029. 12,
  145030. 3,
  145031. 13,
  145032. 2,
  145033. 14,
  145034. 1,
  145035. 15,
  145036. 0,
  145037. 16,
  145038. };
  145039. static long _vq_lengthlist__44u5__p9_2[] = {
  145040. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145041. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145042. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145043. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  145044. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145045. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145046. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  145047. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145048. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145049. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  145050. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  145051. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145052. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145053. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  145054. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  145055. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145056. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145057. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  145058. 10,
  145059. };
  145060. static float _vq_quantthresh__44u5__p9_2[] = {
  145061. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145062. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145063. };
  145064. static long _vq_quantmap__44u5__p9_2[] = {
  145065. 15, 13, 11, 9, 7, 5, 3, 1,
  145066. 0, 2, 4, 6, 8, 10, 12, 14,
  145067. 16,
  145068. };
  145069. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  145070. _vq_quantthresh__44u5__p9_2,
  145071. _vq_quantmap__44u5__p9_2,
  145072. 17,
  145073. 17
  145074. };
  145075. static static_codebook _44u5__p9_2 = {
  145076. 2, 289,
  145077. _vq_lengthlist__44u5__p9_2,
  145078. 1, -529530880, 1611661312, 5, 0,
  145079. _vq_quantlist__44u5__p9_2,
  145080. NULL,
  145081. &_vq_auxt__44u5__p9_2,
  145082. NULL,
  145083. 0
  145084. };
  145085. static long _huff_lengthlist__44u5__short[] = {
  145086. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  145087. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  145088. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  145089. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  145090. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  145091. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  145092. 6, 8,15,17,
  145093. };
  145094. static static_codebook _huff_book__44u5__short = {
  145095. 2, 100,
  145096. _huff_lengthlist__44u5__short,
  145097. 0, 0, 0, 0, 0,
  145098. NULL,
  145099. NULL,
  145100. NULL,
  145101. NULL,
  145102. 0
  145103. };
  145104. static long _huff_lengthlist__44u6__long[] = {
  145105. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  145106. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  145107. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  145108. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  145109. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  145110. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  145111. 13, 8, 7, 7,
  145112. };
  145113. static static_codebook _huff_book__44u6__long = {
  145114. 2, 100,
  145115. _huff_lengthlist__44u6__long,
  145116. 0, 0, 0, 0, 0,
  145117. NULL,
  145118. NULL,
  145119. NULL,
  145120. NULL,
  145121. 0
  145122. };
  145123. static long _vq_quantlist__44u6__p1_0[] = {
  145124. 1,
  145125. 0,
  145126. 2,
  145127. };
  145128. static long _vq_lengthlist__44u6__p1_0[] = {
  145129. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145130. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  145131. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145132. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  145133. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  145134. 12,
  145135. };
  145136. static float _vq_quantthresh__44u6__p1_0[] = {
  145137. -0.5, 0.5,
  145138. };
  145139. static long _vq_quantmap__44u6__p1_0[] = {
  145140. 1, 0, 2,
  145141. };
  145142. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  145143. _vq_quantthresh__44u6__p1_0,
  145144. _vq_quantmap__44u6__p1_0,
  145145. 3,
  145146. 3
  145147. };
  145148. static static_codebook _44u6__p1_0 = {
  145149. 4, 81,
  145150. _vq_lengthlist__44u6__p1_0,
  145151. 1, -535822336, 1611661312, 2, 0,
  145152. _vq_quantlist__44u6__p1_0,
  145153. NULL,
  145154. &_vq_auxt__44u6__p1_0,
  145155. NULL,
  145156. 0
  145157. };
  145158. static long _vq_quantlist__44u6__p2_0[] = {
  145159. 1,
  145160. 0,
  145161. 2,
  145162. };
  145163. static long _vq_lengthlist__44u6__p2_0[] = {
  145164. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145165. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145166. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  145167. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145168. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145169. 9,
  145170. };
  145171. static float _vq_quantthresh__44u6__p2_0[] = {
  145172. -0.5, 0.5,
  145173. };
  145174. static long _vq_quantmap__44u6__p2_0[] = {
  145175. 1, 0, 2,
  145176. };
  145177. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  145178. _vq_quantthresh__44u6__p2_0,
  145179. _vq_quantmap__44u6__p2_0,
  145180. 3,
  145181. 3
  145182. };
  145183. static static_codebook _44u6__p2_0 = {
  145184. 4, 81,
  145185. _vq_lengthlist__44u6__p2_0,
  145186. 1, -535822336, 1611661312, 2, 0,
  145187. _vq_quantlist__44u6__p2_0,
  145188. NULL,
  145189. &_vq_auxt__44u6__p2_0,
  145190. NULL,
  145191. 0
  145192. };
  145193. static long _vq_quantlist__44u6__p3_0[] = {
  145194. 2,
  145195. 1,
  145196. 3,
  145197. 0,
  145198. 4,
  145199. };
  145200. static long _vq_lengthlist__44u6__p3_0[] = {
  145201. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145202. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145203. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145204. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  145205. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  145206. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  145207. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  145208. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  145209. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  145210. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  145211. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  145212. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  145213. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  145214. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  145215. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  145216. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  145217. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  145218. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145219. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  145220. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  145221. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  145222. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  145223. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  145224. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  145225. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  145226. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  145227. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  145228. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  145229. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  145230. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  145231. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  145232. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  145233. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  145234. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  145235. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  145236. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  145237. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  145238. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  145239. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  145240. 19,
  145241. };
  145242. static float _vq_quantthresh__44u6__p3_0[] = {
  145243. -1.5, -0.5, 0.5, 1.5,
  145244. };
  145245. static long _vq_quantmap__44u6__p3_0[] = {
  145246. 3, 1, 0, 2, 4,
  145247. };
  145248. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  145249. _vq_quantthresh__44u6__p3_0,
  145250. _vq_quantmap__44u6__p3_0,
  145251. 5,
  145252. 5
  145253. };
  145254. static static_codebook _44u6__p3_0 = {
  145255. 4, 625,
  145256. _vq_lengthlist__44u6__p3_0,
  145257. 1, -533725184, 1611661312, 3, 0,
  145258. _vq_quantlist__44u6__p3_0,
  145259. NULL,
  145260. &_vq_auxt__44u6__p3_0,
  145261. NULL,
  145262. 0
  145263. };
  145264. static long _vq_quantlist__44u6__p4_0[] = {
  145265. 2,
  145266. 1,
  145267. 3,
  145268. 0,
  145269. 4,
  145270. };
  145271. static long _vq_lengthlist__44u6__p4_0[] = {
  145272. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145273. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145274. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145275. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  145276. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145277. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  145278. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145279. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  145280. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145281. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145282. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  145283. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145284. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145285. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  145286. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  145287. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145288. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  145289. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145290. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  145291. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  145292. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145293. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145294. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  145295. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145296. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  145297. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  145298. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145299. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  145300. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  145301. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  145302. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  145303. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145304. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  145305. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145306. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  145307. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145308. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  145309. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  145310. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  145311. 13,
  145312. };
  145313. static float _vq_quantthresh__44u6__p4_0[] = {
  145314. -1.5, -0.5, 0.5, 1.5,
  145315. };
  145316. static long _vq_quantmap__44u6__p4_0[] = {
  145317. 3, 1, 0, 2, 4,
  145318. };
  145319. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  145320. _vq_quantthresh__44u6__p4_0,
  145321. _vq_quantmap__44u6__p4_0,
  145322. 5,
  145323. 5
  145324. };
  145325. static static_codebook _44u6__p4_0 = {
  145326. 4, 625,
  145327. _vq_lengthlist__44u6__p4_0,
  145328. 1, -533725184, 1611661312, 3, 0,
  145329. _vq_quantlist__44u6__p4_0,
  145330. NULL,
  145331. &_vq_auxt__44u6__p4_0,
  145332. NULL,
  145333. 0
  145334. };
  145335. static long _vq_quantlist__44u6__p5_0[] = {
  145336. 4,
  145337. 3,
  145338. 5,
  145339. 2,
  145340. 6,
  145341. 1,
  145342. 7,
  145343. 0,
  145344. 8,
  145345. };
  145346. static long _vq_lengthlist__44u6__p5_0[] = {
  145347. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  145348. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  145349. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  145350. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  145351. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  145352. 14,
  145353. };
  145354. static float _vq_quantthresh__44u6__p5_0[] = {
  145355. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145356. };
  145357. static long _vq_quantmap__44u6__p5_0[] = {
  145358. 7, 5, 3, 1, 0, 2, 4, 6,
  145359. 8,
  145360. };
  145361. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  145362. _vq_quantthresh__44u6__p5_0,
  145363. _vq_quantmap__44u6__p5_0,
  145364. 9,
  145365. 9
  145366. };
  145367. static static_codebook _44u6__p5_0 = {
  145368. 2, 81,
  145369. _vq_lengthlist__44u6__p5_0,
  145370. 1, -531628032, 1611661312, 4, 0,
  145371. _vq_quantlist__44u6__p5_0,
  145372. NULL,
  145373. &_vq_auxt__44u6__p5_0,
  145374. NULL,
  145375. 0
  145376. };
  145377. static long _vq_quantlist__44u6__p6_0[] = {
  145378. 4,
  145379. 3,
  145380. 5,
  145381. 2,
  145382. 6,
  145383. 1,
  145384. 7,
  145385. 0,
  145386. 8,
  145387. };
  145388. static long _vq_lengthlist__44u6__p6_0[] = {
  145389. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  145390. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  145391. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  145392. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  145393. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  145394. 12,
  145395. };
  145396. static float _vq_quantthresh__44u6__p6_0[] = {
  145397. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145398. };
  145399. static long _vq_quantmap__44u6__p6_0[] = {
  145400. 7, 5, 3, 1, 0, 2, 4, 6,
  145401. 8,
  145402. };
  145403. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  145404. _vq_quantthresh__44u6__p6_0,
  145405. _vq_quantmap__44u6__p6_0,
  145406. 9,
  145407. 9
  145408. };
  145409. static static_codebook _44u6__p6_0 = {
  145410. 2, 81,
  145411. _vq_lengthlist__44u6__p6_0,
  145412. 1, -531628032, 1611661312, 4, 0,
  145413. _vq_quantlist__44u6__p6_0,
  145414. NULL,
  145415. &_vq_auxt__44u6__p6_0,
  145416. NULL,
  145417. 0
  145418. };
  145419. static long _vq_quantlist__44u6__p7_0[] = {
  145420. 1,
  145421. 0,
  145422. 2,
  145423. };
  145424. static long _vq_lengthlist__44u6__p7_0[] = {
  145425. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  145426. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  145427. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  145428. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  145429. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  145430. 10,
  145431. };
  145432. static float _vq_quantthresh__44u6__p7_0[] = {
  145433. -5.5, 5.5,
  145434. };
  145435. static long _vq_quantmap__44u6__p7_0[] = {
  145436. 1, 0, 2,
  145437. };
  145438. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  145439. _vq_quantthresh__44u6__p7_0,
  145440. _vq_quantmap__44u6__p7_0,
  145441. 3,
  145442. 3
  145443. };
  145444. static static_codebook _44u6__p7_0 = {
  145445. 4, 81,
  145446. _vq_lengthlist__44u6__p7_0,
  145447. 1, -529137664, 1618345984, 2, 0,
  145448. _vq_quantlist__44u6__p7_0,
  145449. NULL,
  145450. &_vq_auxt__44u6__p7_0,
  145451. NULL,
  145452. 0
  145453. };
  145454. static long _vq_quantlist__44u6__p7_1[] = {
  145455. 5,
  145456. 4,
  145457. 6,
  145458. 3,
  145459. 7,
  145460. 2,
  145461. 8,
  145462. 1,
  145463. 9,
  145464. 0,
  145465. 10,
  145466. };
  145467. static long _vq_lengthlist__44u6__p7_1[] = {
  145468. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  145469. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  145470. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145471. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  145472. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  145473. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  145474. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  145475. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145476. };
  145477. static float _vq_quantthresh__44u6__p7_1[] = {
  145478. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145479. 3.5, 4.5,
  145480. };
  145481. static long _vq_quantmap__44u6__p7_1[] = {
  145482. 9, 7, 5, 3, 1, 0, 2, 4,
  145483. 6, 8, 10,
  145484. };
  145485. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  145486. _vq_quantthresh__44u6__p7_1,
  145487. _vq_quantmap__44u6__p7_1,
  145488. 11,
  145489. 11
  145490. };
  145491. static static_codebook _44u6__p7_1 = {
  145492. 2, 121,
  145493. _vq_lengthlist__44u6__p7_1,
  145494. 1, -531365888, 1611661312, 4, 0,
  145495. _vq_quantlist__44u6__p7_1,
  145496. NULL,
  145497. &_vq_auxt__44u6__p7_1,
  145498. NULL,
  145499. 0
  145500. };
  145501. static long _vq_quantlist__44u6__p8_0[] = {
  145502. 5,
  145503. 4,
  145504. 6,
  145505. 3,
  145506. 7,
  145507. 2,
  145508. 8,
  145509. 1,
  145510. 9,
  145511. 0,
  145512. 10,
  145513. };
  145514. static long _vq_lengthlist__44u6__p8_0[] = {
  145515. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  145516. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  145517. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  145518. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  145519. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  145520. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  145521. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  145522. 12,13,13,14,14,14,15,15,15,
  145523. };
  145524. static float _vq_quantthresh__44u6__p8_0[] = {
  145525. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145526. 38.5, 49.5,
  145527. };
  145528. static long _vq_quantmap__44u6__p8_0[] = {
  145529. 9, 7, 5, 3, 1, 0, 2, 4,
  145530. 6, 8, 10,
  145531. };
  145532. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  145533. _vq_quantthresh__44u6__p8_0,
  145534. _vq_quantmap__44u6__p8_0,
  145535. 11,
  145536. 11
  145537. };
  145538. static static_codebook _44u6__p8_0 = {
  145539. 2, 121,
  145540. _vq_lengthlist__44u6__p8_0,
  145541. 1, -524582912, 1618345984, 4, 0,
  145542. _vq_quantlist__44u6__p8_0,
  145543. NULL,
  145544. &_vq_auxt__44u6__p8_0,
  145545. NULL,
  145546. 0
  145547. };
  145548. static long _vq_quantlist__44u6__p8_1[] = {
  145549. 5,
  145550. 4,
  145551. 6,
  145552. 3,
  145553. 7,
  145554. 2,
  145555. 8,
  145556. 1,
  145557. 9,
  145558. 0,
  145559. 10,
  145560. };
  145561. static long _vq_lengthlist__44u6__p8_1[] = {
  145562. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  145563. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  145564. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  145565. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145566. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145567. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  145568. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145569. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145570. };
  145571. static float _vq_quantthresh__44u6__p8_1[] = {
  145572. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145573. 3.5, 4.5,
  145574. };
  145575. static long _vq_quantmap__44u6__p8_1[] = {
  145576. 9, 7, 5, 3, 1, 0, 2, 4,
  145577. 6, 8, 10,
  145578. };
  145579. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  145580. _vq_quantthresh__44u6__p8_1,
  145581. _vq_quantmap__44u6__p8_1,
  145582. 11,
  145583. 11
  145584. };
  145585. static static_codebook _44u6__p8_1 = {
  145586. 2, 121,
  145587. _vq_lengthlist__44u6__p8_1,
  145588. 1, -531365888, 1611661312, 4, 0,
  145589. _vq_quantlist__44u6__p8_1,
  145590. NULL,
  145591. &_vq_auxt__44u6__p8_1,
  145592. NULL,
  145593. 0
  145594. };
  145595. static long _vq_quantlist__44u6__p9_0[] = {
  145596. 7,
  145597. 6,
  145598. 8,
  145599. 5,
  145600. 9,
  145601. 4,
  145602. 10,
  145603. 3,
  145604. 11,
  145605. 2,
  145606. 12,
  145607. 1,
  145608. 13,
  145609. 0,
  145610. 14,
  145611. };
  145612. static long _vq_lengthlist__44u6__p9_0[] = {
  145613. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  145614. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  145615. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  145616. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  145617. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145618. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145619. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145620. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145621. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145622. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145623. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145624. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145625. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145626. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  145627. 14,
  145628. };
  145629. static float _vq_quantthresh__44u6__p9_0[] = {
  145630. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  145631. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  145632. };
  145633. static long _vq_quantmap__44u6__p9_0[] = {
  145634. 13, 11, 9, 7, 5, 3, 1, 0,
  145635. 2, 4, 6, 8, 10, 12, 14,
  145636. };
  145637. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  145638. _vq_quantthresh__44u6__p9_0,
  145639. _vq_quantmap__44u6__p9_0,
  145640. 15,
  145641. 15
  145642. };
  145643. static static_codebook _44u6__p9_0 = {
  145644. 2, 225,
  145645. _vq_lengthlist__44u6__p9_0,
  145646. 1, -514071552, 1627381760, 4, 0,
  145647. _vq_quantlist__44u6__p9_0,
  145648. NULL,
  145649. &_vq_auxt__44u6__p9_0,
  145650. NULL,
  145651. 0
  145652. };
  145653. static long _vq_quantlist__44u6__p9_1[] = {
  145654. 7,
  145655. 6,
  145656. 8,
  145657. 5,
  145658. 9,
  145659. 4,
  145660. 10,
  145661. 3,
  145662. 11,
  145663. 2,
  145664. 12,
  145665. 1,
  145666. 13,
  145667. 0,
  145668. 14,
  145669. };
  145670. static long _vq_lengthlist__44u6__p9_1[] = {
  145671. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  145672. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  145673. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  145674. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  145675. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  145676. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  145677. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  145678. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  145679. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  145680. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  145681. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  145682. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  145683. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  145684. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  145685. 13,
  145686. };
  145687. static float _vq_quantthresh__44u6__p9_1[] = {
  145688. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  145689. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  145690. };
  145691. static long _vq_quantmap__44u6__p9_1[] = {
  145692. 13, 11, 9, 7, 5, 3, 1, 0,
  145693. 2, 4, 6, 8, 10, 12, 14,
  145694. };
  145695. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  145696. _vq_quantthresh__44u6__p9_1,
  145697. _vq_quantmap__44u6__p9_1,
  145698. 15,
  145699. 15
  145700. };
  145701. static static_codebook _44u6__p9_1 = {
  145702. 2, 225,
  145703. _vq_lengthlist__44u6__p9_1,
  145704. 1, -522338304, 1620115456, 4, 0,
  145705. _vq_quantlist__44u6__p9_1,
  145706. NULL,
  145707. &_vq_auxt__44u6__p9_1,
  145708. NULL,
  145709. 0
  145710. };
  145711. static long _vq_quantlist__44u6__p9_2[] = {
  145712. 8,
  145713. 7,
  145714. 9,
  145715. 6,
  145716. 10,
  145717. 5,
  145718. 11,
  145719. 4,
  145720. 12,
  145721. 3,
  145722. 13,
  145723. 2,
  145724. 14,
  145725. 1,
  145726. 15,
  145727. 0,
  145728. 16,
  145729. };
  145730. static long _vq_lengthlist__44u6__p9_2[] = {
  145731. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  145732. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145733. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  145734. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145735. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145736. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145737. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145738. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145739. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  145740. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  145741. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  145742. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145743. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  145744. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  145745. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  145746. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  145747. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  145748. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  145749. 10,
  145750. };
  145751. static float _vq_quantthresh__44u6__p9_2[] = {
  145752. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145753. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145754. };
  145755. static long _vq_quantmap__44u6__p9_2[] = {
  145756. 15, 13, 11, 9, 7, 5, 3, 1,
  145757. 0, 2, 4, 6, 8, 10, 12, 14,
  145758. 16,
  145759. };
  145760. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  145761. _vq_quantthresh__44u6__p9_2,
  145762. _vq_quantmap__44u6__p9_2,
  145763. 17,
  145764. 17
  145765. };
  145766. static static_codebook _44u6__p9_2 = {
  145767. 2, 289,
  145768. _vq_lengthlist__44u6__p9_2,
  145769. 1, -529530880, 1611661312, 5, 0,
  145770. _vq_quantlist__44u6__p9_2,
  145771. NULL,
  145772. &_vq_auxt__44u6__p9_2,
  145773. NULL,
  145774. 0
  145775. };
  145776. static long _huff_lengthlist__44u6__short[] = {
  145777. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  145778. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  145779. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  145780. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  145781. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  145782. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  145783. 7, 6, 9,16,
  145784. };
  145785. static static_codebook _huff_book__44u6__short = {
  145786. 2, 100,
  145787. _huff_lengthlist__44u6__short,
  145788. 0, 0, 0, 0, 0,
  145789. NULL,
  145790. NULL,
  145791. NULL,
  145792. NULL,
  145793. 0
  145794. };
  145795. static long _huff_lengthlist__44u7__long[] = {
  145796. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  145797. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  145798. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  145799. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  145800. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  145801. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  145802. 12, 8, 6, 7,
  145803. };
  145804. static static_codebook _huff_book__44u7__long = {
  145805. 2, 100,
  145806. _huff_lengthlist__44u7__long,
  145807. 0, 0, 0, 0, 0,
  145808. NULL,
  145809. NULL,
  145810. NULL,
  145811. NULL,
  145812. 0
  145813. };
  145814. static long _vq_quantlist__44u7__p1_0[] = {
  145815. 1,
  145816. 0,
  145817. 2,
  145818. };
  145819. static long _vq_lengthlist__44u7__p1_0[] = {
  145820. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145821. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  145822. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  145823. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  145824. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  145825. 12,
  145826. };
  145827. static float _vq_quantthresh__44u7__p1_0[] = {
  145828. -0.5, 0.5,
  145829. };
  145830. static long _vq_quantmap__44u7__p1_0[] = {
  145831. 1, 0, 2,
  145832. };
  145833. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  145834. _vq_quantthresh__44u7__p1_0,
  145835. _vq_quantmap__44u7__p1_0,
  145836. 3,
  145837. 3
  145838. };
  145839. static static_codebook _44u7__p1_0 = {
  145840. 4, 81,
  145841. _vq_lengthlist__44u7__p1_0,
  145842. 1, -535822336, 1611661312, 2, 0,
  145843. _vq_quantlist__44u7__p1_0,
  145844. NULL,
  145845. &_vq_auxt__44u7__p1_0,
  145846. NULL,
  145847. 0
  145848. };
  145849. static long _vq_quantlist__44u7__p2_0[] = {
  145850. 1,
  145851. 0,
  145852. 2,
  145853. };
  145854. static long _vq_lengthlist__44u7__p2_0[] = {
  145855. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  145856. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  145857. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  145858. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  145859. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  145860. 9,
  145861. };
  145862. static float _vq_quantthresh__44u7__p2_0[] = {
  145863. -0.5, 0.5,
  145864. };
  145865. static long _vq_quantmap__44u7__p2_0[] = {
  145866. 1, 0, 2,
  145867. };
  145868. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  145869. _vq_quantthresh__44u7__p2_0,
  145870. _vq_quantmap__44u7__p2_0,
  145871. 3,
  145872. 3
  145873. };
  145874. static static_codebook _44u7__p2_0 = {
  145875. 4, 81,
  145876. _vq_lengthlist__44u7__p2_0,
  145877. 1, -535822336, 1611661312, 2, 0,
  145878. _vq_quantlist__44u7__p2_0,
  145879. NULL,
  145880. &_vq_auxt__44u7__p2_0,
  145881. NULL,
  145882. 0
  145883. };
  145884. static long _vq_quantlist__44u7__p3_0[] = {
  145885. 2,
  145886. 1,
  145887. 3,
  145888. 0,
  145889. 4,
  145890. };
  145891. static long _vq_lengthlist__44u7__p3_0[] = {
  145892. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  145893. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  145894. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  145895. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  145896. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  145897. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  145898. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  145899. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  145900. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  145901. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  145902. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  145903. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  145904. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  145905. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  145906. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  145907. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  145908. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  145909. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  145910. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  145911. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  145912. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  145913. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  145914. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  145915. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  145916. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  145917. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  145918. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  145919. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  145920. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  145921. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  145922. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  145923. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  145924. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  145925. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  145926. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  145927. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  145928. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  145929. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  145930. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  145931. 0,
  145932. };
  145933. static float _vq_quantthresh__44u7__p3_0[] = {
  145934. -1.5, -0.5, 0.5, 1.5,
  145935. };
  145936. static long _vq_quantmap__44u7__p3_0[] = {
  145937. 3, 1, 0, 2, 4,
  145938. };
  145939. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  145940. _vq_quantthresh__44u7__p3_0,
  145941. _vq_quantmap__44u7__p3_0,
  145942. 5,
  145943. 5
  145944. };
  145945. static static_codebook _44u7__p3_0 = {
  145946. 4, 625,
  145947. _vq_lengthlist__44u7__p3_0,
  145948. 1, -533725184, 1611661312, 3, 0,
  145949. _vq_quantlist__44u7__p3_0,
  145950. NULL,
  145951. &_vq_auxt__44u7__p3_0,
  145952. NULL,
  145953. 0
  145954. };
  145955. static long _vq_quantlist__44u7__p4_0[] = {
  145956. 2,
  145957. 1,
  145958. 3,
  145959. 0,
  145960. 4,
  145961. };
  145962. static long _vq_lengthlist__44u7__p4_0[] = {
  145963. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  145964. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  145965. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  145966. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  145967. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  145968. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  145969. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  145970. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  145971. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  145972. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  145973. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  145974. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  145975. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  145976. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  145977. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  145978. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  145979. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  145980. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145981. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  145982. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  145983. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  145984. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  145985. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  145986. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  145987. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  145988. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  145989. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  145990. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  145991. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  145992. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  145993. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  145994. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  145995. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  145996. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  145997. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  145998. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  145999. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  146000. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  146001. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  146002. 14,
  146003. };
  146004. static float _vq_quantthresh__44u7__p4_0[] = {
  146005. -1.5, -0.5, 0.5, 1.5,
  146006. };
  146007. static long _vq_quantmap__44u7__p4_0[] = {
  146008. 3, 1, 0, 2, 4,
  146009. };
  146010. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  146011. _vq_quantthresh__44u7__p4_0,
  146012. _vq_quantmap__44u7__p4_0,
  146013. 5,
  146014. 5
  146015. };
  146016. static static_codebook _44u7__p4_0 = {
  146017. 4, 625,
  146018. _vq_lengthlist__44u7__p4_0,
  146019. 1, -533725184, 1611661312, 3, 0,
  146020. _vq_quantlist__44u7__p4_0,
  146021. NULL,
  146022. &_vq_auxt__44u7__p4_0,
  146023. NULL,
  146024. 0
  146025. };
  146026. static long _vq_quantlist__44u7__p5_0[] = {
  146027. 4,
  146028. 3,
  146029. 5,
  146030. 2,
  146031. 6,
  146032. 1,
  146033. 7,
  146034. 0,
  146035. 8,
  146036. };
  146037. static long _vq_lengthlist__44u7__p5_0[] = {
  146038. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  146039. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  146040. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  146041. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  146042. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  146043. 14,
  146044. };
  146045. static float _vq_quantthresh__44u7__p5_0[] = {
  146046. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146047. };
  146048. static long _vq_quantmap__44u7__p5_0[] = {
  146049. 7, 5, 3, 1, 0, 2, 4, 6,
  146050. 8,
  146051. };
  146052. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  146053. _vq_quantthresh__44u7__p5_0,
  146054. _vq_quantmap__44u7__p5_0,
  146055. 9,
  146056. 9
  146057. };
  146058. static static_codebook _44u7__p5_0 = {
  146059. 2, 81,
  146060. _vq_lengthlist__44u7__p5_0,
  146061. 1, -531628032, 1611661312, 4, 0,
  146062. _vq_quantlist__44u7__p5_0,
  146063. NULL,
  146064. &_vq_auxt__44u7__p5_0,
  146065. NULL,
  146066. 0
  146067. };
  146068. static long _vq_quantlist__44u7__p6_0[] = {
  146069. 4,
  146070. 3,
  146071. 5,
  146072. 2,
  146073. 6,
  146074. 1,
  146075. 7,
  146076. 0,
  146077. 8,
  146078. };
  146079. static long _vq_lengthlist__44u7__p6_0[] = {
  146080. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  146081. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146082. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  146083. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  146084. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  146085. 12,
  146086. };
  146087. static float _vq_quantthresh__44u7__p6_0[] = {
  146088. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146089. };
  146090. static long _vq_quantmap__44u7__p6_0[] = {
  146091. 7, 5, 3, 1, 0, 2, 4, 6,
  146092. 8,
  146093. };
  146094. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  146095. _vq_quantthresh__44u7__p6_0,
  146096. _vq_quantmap__44u7__p6_0,
  146097. 9,
  146098. 9
  146099. };
  146100. static static_codebook _44u7__p6_0 = {
  146101. 2, 81,
  146102. _vq_lengthlist__44u7__p6_0,
  146103. 1, -531628032, 1611661312, 4, 0,
  146104. _vq_quantlist__44u7__p6_0,
  146105. NULL,
  146106. &_vq_auxt__44u7__p6_0,
  146107. NULL,
  146108. 0
  146109. };
  146110. static long _vq_quantlist__44u7__p7_0[] = {
  146111. 1,
  146112. 0,
  146113. 2,
  146114. };
  146115. static long _vq_lengthlist__44u7__p7_0[] = {
  146116. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  146117. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  146118. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  146119. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  146120. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  146121. 10,
  146122. };
  146123. static float _vq_quantthresh__44u7__p7_0[] = {
  146124. -5.5, 5.5,
  146125. };
  146126. static long _vq_quantmap__44u7__p7_0[] = {
  146127. 1, 0, 2,
  146128. };
  146129. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  146130. _vq_quantthresh__44u7__p7_0,
  146131. _vq_quantmap__44u7__p7_0,
  146132. 3,
  146133. 3
  146134. };
  146135. static static_codebook _44u7__p7_0 = {
  146136. 4, 81,
  146137. _vq_lengthlist__44u7__p7_0,
  146138. 1, -529137664, 1618345984, 2, 0,
  146139. _vq_quantlist__44u7__p7_0,
  146140. NULL,
  146141. &_vq_auxt__44u7__p7_0,
  146142. NULL,
  146143. 0
  146144. };
  146145. static long _vq_quantlist__44u7__p7_1[] = {
  146146. 5,
  146147. 4,
  146148. 6,
  146149. 3,
  146150. 7,
  146151. 2,
  146152. 8,
  146153. 1,
  146154. 9,
  146155. 0,
  146156. 10,
  146157. };
  146158. static long _vq_lengthlist__44u7__p7_1[] = {
  146159. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  146160. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  146161. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  146162. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  146163. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  146164. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  146165. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  146166. 8, 9, 9, 9, 9, 9,10,10,10,
  146167. };
  146168. static float _vq_quantthresh__44u7__p7_1[] = {
  146169. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146170. 3.5, 4.5,
  146171. };
  146172. static long _vq_quantmap__44u7__p7_1[] = {
  146173. 9, 7, 5, 3, 1, 0, 2, 4,
  146174. 6, 8, 10,
  146175. };
  146176. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  146177. _vq_quantthresh__44u7__p7_1,
  146178. _vq_quantmap__44u7__p7_1,
  146179. 11,
  146180. 11
  146181. };
  146182. static static_codebook _44u7__p7_1 = {
  146183. 2, 121,
  146184. _vq_lengthlist__44u7__p7_1,
  146185. 1, -531365888, 1611661312, 4, 0,
  146186. _vq_quantlist__44u7__p7_1,
  146187. NULL,
  146188. &_vq_auxt__44u7__p7_1,
  146189. NULL,
  146190. 0
  146191. };
  146192. static long _vq_quantlist__44u7__p8_0[] = {
  146193. 5,
  146194. 4,
  146195. 6,
  146196. 3,
  146197. 7,
  146198. 2,
  146199. 8,
  146200. 1,
  146201. 9,
  146202. 0,
  146203. 10,
  146204. };
  146205. static long _vq_lengthlist__44u7__p8_0[] = {
  146206. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146207. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  146208. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  146209. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  146210. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  146211. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  146212. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  146213. 12,13,13,14,14,15,15,15,16,
  146214. };
  146215. static float _vq_quantthresh__44u7__p8_0[] = {
  146216. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146217. 38.5, 49.5,
  146218. };
  146219. static long _vq_quantmap__44u7__p8_0[] = {
  146220. 9, 7, 5, 3, 1, 0, 2, 4,
  146221. 6, 8, 10,
  146222. };
  146223. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  146224. _vq_quantthresh__44u7__p8_0,
  146225. _vq_quantmap__44u7__p8_0,
  146226. 11,
  146227. 11
  146228. };
  146229. static static_codebook _44u7__p8_0 = {
  146230. 2, 121,
  146231. _vq_lengthlist__44u7__p8_0,
  146232. 1, -524582912, 1618345984, 4, 0,
  146233. _vq_quantlist__44u7__p8_0,
  146234. NULL,
  146235. &_vq_auxt__44u7__p8_0,
  146236. NULL,
  146237. 0
  146238. };
  146239. static long _vq_quantlist__44u7__p8_1[] = {
  146240. 5,
  146241. 4,
  146242. 6,
  146243. 3,
  146244. 7,
  146245. 2,
  146246. 8,
  146247. 1,
  146248. 9,
  146249. 0,
  146250. 10,
  146251. };
  146252. static long _vq_lengthlist__44u7__p8_1[] = {
  146253. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146254. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  146255. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146256. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  146257. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  146258. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146259. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146260. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146261. };
  146262. static float _vq_quantthresh__44u7__p8_1[] = {
  146263. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146264. 3.5, 4.5,
  146265. };
  146266. static long _vq_quantmap__44u7__p8_1[] = {
  146267. 9, 7, 5, 3, 1, 0, 2, 4,
  146268. 6, 8, 10,
  146269. };
  146270. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  146271. _vq_quantthresh__44u7__p8_1,
  146272. _vq_quantmap__44u7__p8_1,
  146273. 11,
  146274. 11
  146275. };
  146276. static static_codebook _44u7__p8_1 = {
  146277. 2, 121,
  146278. _vq_lengthlist__44u7__p8_1,
  146279. 1, -531365888, 1611661312, 4, 0,
  146280. _vq_quantlist__44u7__p8_1,
  146281. NULL,
  146282. &_vq_auxt__44u7__p8_1,
  146283. NULL,
  146284. 0
  146285. };
  146286. static long _vq_quantlist__44u7__p9_0[] = {
  146287. 5,
  146288. 4,
  146289. 6,
  146290. 3,
  146291. 7,
  146292. 2,
  146293. 8,
  146294. 1,
  146295. 9,
  146296. 0,
  146297. 10,
  146298. };
  146299. static long _vq_lengthlist__44u7__p9_0[] = {
  146300. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  146301. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  146302. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146303. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146304. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146305. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146306. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146307. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146308. };
  146309. static float _vq_quantthresh__44u7__p9_0[] = {
  146310. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  146311. 2229.5, 2866.5,
  146312. };
  146313. static long _vq_quantmap__44u7__p9_0[] = {
  146314. 9, 7, 5, 3, 1, 0, 2, 4,
  146315. 6, 8, 10,
  146316. };
  146317. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  146318. _vq_quantthresh__44u7__p9_0,
  146319. _vq_quantmap__44u7__p9_0,
  146320. 11,
  146321. 11
  146322. };
  146323. static static_codebook _44u7__p9_0 = {
  146324. 2, 121,
  146325. _vq_lengthlist__44u7__p9_0,
  146326. 1, -512171520, 1630791680, 4, 0,
  146327. _vq_quantlist__44u7__p9_0,
  146328. NULL,
  146329. &_vq_auxt__44u7__p9_0,
  146330. NULL,
  146331. 0
  146332. };
  146333. static long _vq_quantlist__44u7__p9_1[] = {
  146334. 6,
  146335. 5,
  146336. 7,
  146337. 4,
  146338. 8,
  146339. 3,
  146340. 9,
  146341. 2,
  146342. 10,
  146343. 1,
  146344. 11,
  146345. 0,
  146346. 12,
  146347. };
  146348. static long _vq_lengthlist__44u7__p9_1[] = {
  146349. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  146350. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  146351. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  146352. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  146353. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  146354. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  146355. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  146356. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  146357. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  146358. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  146359. 15,15,15,15,17,17,16,17,16,
  146360. };
  146361. static float _vq_quantthresh__44u7__p9_1[] = {
  146362. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  146363. 122.5, 171.5, 220.5, 269.5,
  146364. };
  146365. static long _vq_quantmap__44u7__p9_1[] = {
  146366. 11, 9, 7, 5, 3, 1, 0, 2,
  146367. 4, 6, 8, 10, 12,
  146368. };
  146369. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  146370. _vq_quantthresh__44u7__p9_1,
  146371. _vq_quantmap__44u7__p9_1,
  146372. 13,
  146373. 13
  146374. };
  146375. static static_codebook _44u7__p9_1 = {
  146376. 2, 169,
  146377. _vq_lengthlist__44u7__p9_1,
  146378. 1, -518889472, 1622704128, 4, 0,
  146379. _vq_quantlist__44u7__p9_1,
  146380. NULL,
  146381. &_vq_auxt__44u7__p9_1,
  146382. NULL,
  146383. 0
  146384. };
  146385. static long _vq_quantlist__44u7__p9_2[] = {
  146386. 24,
  146387. 23,
  146388. 25,
  146389. 22,
  146390. 26,
  146391. 21,
  146392. 27,
  146393. 20,
  146394. 28,
  146395. 19,
  146396. 29,
  146397. 18,
  146398. 30,
  146399. 17,
  146400. 31,
  146401. 16,
  146402. 32,
  146403. 15,
  146404. 33,
  146405. 14,
  146406. 34,
  146407. 13,
  146408. 35,
  146409. 12,
  146410. 36,
  146411. 11,
  146412. 37,
  146413. 10,
  146414. 38,
  146415. 9,
  146416. 39,
  146417. 8,
  146418. 40,
  146419. 7,
  146420. 41,
  146421. 6,
  146422. 42,
  146423. 5,
  146424. 43,
  146425. 4,
  146426. 44,
  146427. 3,
  146428. 45,
  146429. 2,
  146430. 46,
  146431. 1,
  146432. 47,
  146433. 0,
  146434. 48,
  146435. };
  146436. static long _vq_lengthlist__44u7__p9_2[] = {
  146437. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  146438. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146439. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  146440. 8,
  146441. };
  146442. static float _vq_quantthresh__44u7__p9_2[] = {
  146443. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  146444. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  146445. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146446. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146447. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146448. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146449. };
  146450. static long _vq_quantmap__44u7__p9_2[] = {
  146451. 47, 45, 43, 41, 39, 37, 35, 33,
  146452. 31, 29, 27, 25, 23, 21, 19, 17,
  146453. 15, 13, 11, 9, 7, 5, 3, 1,
  146454. 0, 2, 4, 6, 8, 10, 12, 14,
  146455. 16, 18, 20, 22, 24, 26, 28, 30,
  146456. 32, 34, 36, 38, 40, 42, 44, 46,
  146457. 48,
  146458. };
  146459. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  146460. _vq_quantthresh__44u7__p9_2,
  146461. _vq_quantmap__44u7__p9_2,
  146462. 49,
  146463. 49
  146464. };
  146465. static static_codebook _44u7__p9_2 = {
  146466. 1, 49,
  146467. _vq_lengthlist__44u7__p9_2,
  146468. 1, -526909440, 1611661312, 6, 0,
  146469. _vq_quantlist__44u7__p9_2,
  146470. NULL,
  146471. &_vq_auxt__44u7__p9_2,
  146472. NULL,
  146473. 0
  146474. };
  146475. static long _huff_lengthlist__44u7__short[] = {
  146476. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  146477. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  146478. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  146479. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  146480. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  146481. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  146482. 6, 8, 5, 9,
  146483. };
  146484. static static_codebook _huff_book__44u7__short = {
  146485. 2, 100,
  146486. _huff_lengthlist__44u7__short,
  146487. 0, 0, 0, 0, 0,
  146488. NULL,
  146489. NULL,
  146490. NULL,
  146491. NULL,
  146492. 0
  146493. };
  146494. static long _huff_lengthlist__44u8__long[] = {
  146495. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  146496. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  146497. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  146498. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  146499. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  146500. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  146501. 10, 8, 8, 9,
  146502. };
  146503. static static_codebook _huff_book__44u8__long = {
  146504. 2, 100,
  146505. _huff_lengthlist__44u8__long,
  146506. 0, 0, 0, 0, 0,
  146507. NULL,
  146508. NULL,
  146509. NULL,
  146510. NULL,
  146511. 0
  146512. };
  146513. static long _huff_lengthlist__44u8__short[] = {
  146514. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  146515. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  146516. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  146517. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  146518. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  146519. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  146520. 10,10,15,17,
  146521. };
  146522. static static_codebook _huff_book__44u8__short = {
  146523. 2, 100,
  146524. _huff_lengthlist__44u8__short,
  146525. 0, 0, 0, 0, 0,
  146526. NULL,
  146527. NULL,
  146528. NULL,
  146529. NULL,
  146530. 0
  146531. };
  146532. static long _vq_quantlist__44u8_p1_0[] = {
  146533. 1,
  146534. 0,
  146535. 2,
  146536. };
  146537. static long _vq_lengthlist__44u8_p1_0[] = {
  146538. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  146539. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  146540. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  146541. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  146542. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  146543. 10,
  146544. };
  146545. static float _vq_quantthresh__44u8_p1_0[] = {
  146546. -0.5, 0.5,
  146547. };
  146548. static long _vq_quantmap__44u8_p1_0[] = {
  146549. 1, 0, 2,
  146550. };
  146551. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  146552. _vq_quantthresh__44u8_p1_0,
  146553. _vq_quantmap__44u8_p1_0,
  146554. 3,
  146555. 3
  146556. };
  146557. static static_codebook _44u8_p1_0 = {
  146558. 4, 81,
  146559. _vq_lengthlist__44u8_p1_0,
  146560. 1, -535822336, 1611661312, 2, 0,
  146561. _vq_quantlist__44u8_p1_0,
  146562. NULL,
  146563. &_vq_auxt__44u8_p1_0,
  146564. NULL,
  146565. 0
  146566. };
  146567. static long _vq_quantlist__44u8_p2_0[] = {
  146568. 2,
  146569. 1,
  146570. 3,
  146571. 0,
  146572. 4,
  146573. };
  146574. static long _vq_lengthlist__44u8_p2_0[] = {
  146575. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  146576. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  146577. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  146578. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  146579. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  146580. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  146581. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146582. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  146583. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  146584. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  146585. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  146586. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146587. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  146588. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  146589. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  146590. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  146591. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  146592. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  146593. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  146594. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  146595. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  146596. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  146597. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  146598. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  146599. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  146600. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  146601. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  146602. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  146603. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  146604. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  146605. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  146606. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  146607. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  146608. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  146609. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  146610. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  146611. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  146612. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  146613. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  146614. 14,
  146615. };
  146616. static float _vq_quantthresh__44u8_p2_0[] = {
  146617. -1.5, -0.5, 0.5, 1.5,
  146618. };
  146619. static long _vq_quantmap__44u8_p2_0[] = {
  146620. 3, 1, 0, 2, 4,
  146621. };
  146622. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  146623. _vq_quantthresh__44u8_p2_0,
  146624. _vq_quantmap__44u8_p2_0,
  146625. 5,
  146626. 5
  146627. };
  146628. static static_codebook _44u8_p2_0 = {
  146629. 4, 625,
  146630. _vq_lengthlist__44u8_p2_0,
  146631. 1, -533725184, 1611661312, 3, 0,
  146632. _vq_quantlist__44u8_p2_0,
  146633. NULL,
  146634. &_vq_auxt__44u8_p2_0,
  146635. NULL,
  146636. 0
  146637. };
  146638. static long _vq_quantlist__44u8_p3_0[] = {
  146639. 4,
  146640. 3,
  146641. 5,
  146642. 2,
  146643. 6,
  146644. 1,
  146645. 7,
  146646. 0,
  146647. 8,
  146648. };
  146649. static long _vq_lengthlist__44u8_p3_0[] = {
  146650. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  146651. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  146652. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  146653. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  146654. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  146655. 12,
  146656. };
  146657. static float _vq_quantthresh__44u8_p3_0[] = {
  146658. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146659. };
  146660. static long _vq_quantmap__44u8_p3_0[] = {
  146661. 7, 5, 3, 1, 0, 2, 4, 6,
  146662. 8,
  146663. };
  146664. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  146665. _vq_quantthresh__44u8_p3_0,
  146666. _vq_quantmap__44u8_p3_0,
  146667. 9,
  146668. 9
  146669. };
  146670. static static_codebook _44u8_p3_0 = {
  146671. 2, 81,
  146672. _vq_lengthlist__44u8_p3_0,
  146673. 1, -531628032, 1611661312, 4, 0,
  146674. _vq_quantlist__44u8_p3_0,
  146675. NULL,
  146676. &_vq_auxt__44u8_p3_0,
  146677. NULL,
  146678. 0
  146679. };
  146680. static long _vq_quantlist__44u8_p4_0[] = {
  146681. 8,
  146682. 7,
  146683. 9,
  146684. 6,
  146685. 10,
  146686. 5,
  146687. 11,
  146688. 4,
  146689. 12,
  146690. 3,
  146691. 13,
  146692. 2,
  146693. 14,
  146694. 1,
  146695. 15,
  146696. 0,
  146697. 16,
  146698. };
  146699. static long _vq_lengthlist__44u8_p4_0[] = {
  146700. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  146701. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  146702. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  146703. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  146704. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  146705. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  146706. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  146707. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  146708. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  146709. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  146710. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  146711. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  146712. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  146713. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  146714. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  146715. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  146716. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  146717. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  146718. 14,
  146719. };
  146720. static float _vq_quantthresh__44u8_p4_0[] = {
  146721. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146722. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146723. };
  146724. static long _vq_quantmap__44u8_p4_0[] = {
  146725. 15, 13, 11, 9, 7, 5, 3, 1,
  146726. 0, 2, 4, 6, 8, 10, 12, 14,
  146727. 16,
  146728. };
  146729. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  146730. _vq_quantthresh__44u8_p4_0,
  146731. _vq_quantmap__44u8_p4_0,
  146732. 17,
  146733. 17
  146734. };
  146735. static static_codebook _44u8_p4_0 = {
  146736. 2, 289,
  146737. _vq_lengthlist__44u8_p4_0,
  146738. 1, -529530880, 1611661312, 5, 0,
  146739. _vq_quantlist__44u8_p4_0,
  146740. NULL,
  146741. &_vq_auxt__44u8_p4_0,
  146742. NULL,
  146743. 0
  146744. };
  146745. static long _vq_quantlist__44u8_p5_0[] = {
  146746. 1,
  146747. 0,
  146748. 2,
  146749. };
  146750. static long _vq_lengthlist__44u8_p5_0[] = {
  146751. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  146752. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  146753. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  146754. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146755. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  146756. 10,
  146757. };
  146758. static float _vq_quantthresh__44u8_p5_0[] = {
  146759. -5.5, 5.5,
  146760. };
  146761. static long _vq_quantmap__44u8_p5_0[] = {
  146762. 1, 0, 2,
  146763. };
  146764. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  146765. _vq_quantthresh__44u8_p5_0,
  146766. _vq_quantmap__44u8_p5_0,
  146767. 3,
  146768. 3
  146769. };
  146770. static static_codebook _44u8_p5_0 = {
  146771. 4, 81,
  146772. _vq_lengthlist__44u8_p5_0,
  146773. 1, -529137664, 1618345984, 2, 0,
  146774. _vq_quantlist__44u8_p5_0,
  146775. NULL,
  146776. &_vq_auxt__44u8_p5_0,
  146777. NULL,
  146778. 0
  146779. };
  146780. static long _vq_quantlist__44u8_p5_1[] = {
  146781. 5,
  146782. 4,
  146783. 6,
  146784. 3,
  146785. 7,
  146786. 2,
  146787. 8,
  146788. 1,
  146789. 9,
  146790. 0,
  146791. 10,
  146792. };
  146793. static long _vq_lengthlist__44u8_p5_1[] = {
  146794. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  146795. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  146796. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  146797. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  146798. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  146799. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  146800. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  146801. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  146802. };
  146803. static float _vq_quantthresh__44u8_p5_1[] = {
  146804. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146805. 3.5, 4.5,
  146806. };
  146807. static long _vq_quantmap__44u8_p5_1[] = {
  146808. 9, 7, 5, 3, 1, 0, 2, 4,
  146809. 6, 8, 10,
  146810. };
  146811. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  146812. _vq_quantthresh__44u8_p5_1,
  146813. _vq_quantmap__44u8_p5_1,
  146814. 11,
  146815. 11
  146816. };
  146817. static static_codebook _44u8_p5_1 = {
  146818. 2, 121,
  146819. _vq_lengthlist__44u8_p5_1,
  146820. 1, -531365888, 1611661312, 4, 0,
  146821. _vq_quantlist__44u8_p5_1,
  146822. NULL,
  146823. &_vq_auxt__44u8_p5_1,
  146824. NULL,
  146825. 0
  146826. };
  146827. static long _vq_quantlist__44u8_p6_0[] = {
  146828. 6,
  146829. 5,
  146830. 7,
  146831. 4,
  146832. 8,
  146833. 3,
  146834. 9,
  146835. 2,
  146836. 10,
  146837. 1,
  146838. 11,
  146839. 0,
  146840. 12,
  146841. };
  146842. static long _vq_lengthlist__44u8_p6_0[] = {
  146843. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  146844. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  146845. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  146846. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  146847. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  146848. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  146849. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  146850. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  146851. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  146852. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  146853. 11,11,11,11,11,12,11,12,12,
  146854. };
  146855. static float _vq_quantthresh__44u8_p6_0[] = {
  146856. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146857. 12.5, 17.5, 22.5, 27.5,
  146858. };
  146859. static long _vq_quantmap__44u8_p6_0[] = {
  146860. 11, 9, 7, 5, 3, 1, 0, 2,
  146861. 4, 6, 8, 10, 12,
  146862. };
  146863. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  146864. _vq_quantthresh__44u8_p6_0,
  146865. _vq_quantmap__44u8_p6_0,
  146866. 13,
  146867. 13
  146868. };
  146869. static static_codebook _44u8_p6_0 = {
  146870. 2, 169,
  146871. _vq_lengthlist__44u8_p6_0,
  146872. 1, -526516224, 1616117760, 4, 0,
  146873. _vq_quantlist__44u8_p6_0,
  146874. NULL,
  146875. &_vq_auxt__44u8_p6_0,
  146876. NULL,
  146877. 0
  146878. };
  146879. static long _vq_quantlist__44u8_p6_1[] = {
  146880. 2,
  146881. 1,
  146882. 3,
  146883. 0,
  146884. 4,
  146885. };
  146886. static long _vq_lengthlist__44u8_p6_1[] = {
  146887. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146888. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  146889. };
  146890. static float _vq_quantthresh__44u8_p6_1[] = {
  146891. -1.5, -0.5, 0.5, 1.5,
  146892. };
  146893. static long _vq_quantmap__44u8_p6_1[] = {
  146894. 3, 1, 0, 2, 4,
  146895. };
  146896. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  146897. _vq_quantthresh__44u8_p6_1,
  146898. _vq_quantmap__44u8_p6_1,
  146899. 5,
  146900. 5
  146901. };
  146902. static static_codebook _44u8_p6_1 = {
  146903. 2, 25,
  146904. _vq_lengthlist__44u8_p6_1,
  146905. 1, -533725184, 1611661312, 3, 0,
  146906. _vq_quantlist__44u8_p6_1,
  146907. NULL,
  146908. &_vq_auxt__44u8_p6_1,
  146909. NULL,
  146910. 0
  146911. };
  146912. static long _vq_quantlist__44u8_p7_0[] = {
  146913. 6,
  146914. 5,
  146915. 7,
  146916. 4,
  146917. 8,
  146918. 3,
  146919. 9,
  146920. 2,
  146921. 10,
  146922. 1,
  146923. 11,
  146924. 0,
  146925. 12,
  146926. };
  146927. static long _vq_lengthlist__44u8_p7_0[] = {
  146928. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  146929. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  146930. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  146931. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  146932. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  146933. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  146934. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  146935. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  146936. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  146937. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  146938. 13,13,14,14,14,15,15,15,16,
  146939. };
  146940. static float _vq_quantthresh__44u8_p7_0[] = {
  146941. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  146942. 27.5, 38.5, 49.5, 60.5,
  146943. };
  146944. static long _vq_quantmap__44u8_p7_0[] = {
  146945. 11, 9, 7, 5, 3, 1, 0, 2,
  146946. 4, 6, 8, 10, 12,
  146947. };
  146948. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  146949. _vq_quantthresh__44u8_p7_0,
  146950. _vq_quantmap__44u8_p7_0,
  146951. 13,
  146952. 13
  146953. };
  146954. static static_codebook _44u8_p7_0 = {
  146955. 2, 169,
  146956. _vq_lengthlist__44u8_p7_0,
  146957. 1, -523206656, 1618345984, 4, 0,
  146958. _vq_quantlist__44u8_p7_0,
  146959. NULL,
  146960. &_vq_auxt__44u8_p7_0,
  146961. NULL,
  146962. 0
  146963. };
  146964. static long _vq_quantlist__44u8_p7_1[] = {
  146965. 5,
  146966. 4,
  146967. 6,
  146968. 3,
  146969. 7,
  146970. 2,
  146971. 8,
  146972. 1,
  146973. 9,
  146974. 0,
  146975. 10,
  146976. };
  146977. static long _vq_lengthlist__44u8_p7_1[] = {
  146978. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  146979. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  146980. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  146981. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  146982. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  146983. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  146984. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  146985. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  146986. };
  146987. static float _vq_quantthresh__44u8_p7_1[] = {
  146988. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146989. 3.5, 4.5,
  146990. };
  146991. static long _vq_quantmap__44u8_p7_1[] = {
  146992. 9, 7, 5, 3, 1, 0, 2, 4,
  146993. 6, 8, 10,
  146994. };
  146995. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  146996. _vq_quantthresh__44u8_p7_1,
  146997. _vq_quantmap__44u8_p7_1,
  146998. 11,
  146999. 11
  147000. };
  147001. static static_codebook _44u8_p7_1 = {
  147002. 2, 121,
  147003. _vq_lengthlist__44u8_p7_1,
  147004. 1, -531365888, 1611661312, 4, 0,
  147005. _vq_quantlist__44u8_p7_1,
  147006. NULL,
  147007. &_vq_auxt__44u8_p7_1,
  147008. NULL,
  147009. 0
  147010. };
  147011. static long _vq_quantlist__44u8_p8_0[] = {
  147012. 7,
  147013. 6,
  147014. 8,
  147015. 5,
  147016. 9,
  147017. 4,
  147018. 10,
  147019. 3,
  147020. 11,
  147021. 2,
  147022. 12,
  147023. 1,
  147024. 13,
  147025. 0,
  147026. 14,
  147027. };
  147028. static long _vq_lengthlist__44u8_p8_0[] = {
  147029. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  147030. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147031. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  147032. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  147033. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  147034. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  147035. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  147036. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  147037. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  147038. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  147039. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  147040. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  147041. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  147042. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  147043. 17,
  147044. };
  147045. static float _vq_quantthresh__44u8_p8_0[] = {
  147046. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147047. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147048. };
  147049. static long _vq_quantmap__44u8_p8_0[] = {
  147050. 13, 11, 9, 7, 5, 3, 1, 0,
  147051. 2, 4, 6, 8, 10, 12, 14,
  147052. };
  147053. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  147054. _vq_quantthresh__44u8_p8_0,
  147055. _vq_quantmap__44u8_p8_0,
  147056. 15,
  147057. 15
  147058. };
  147059. static static_codebook _44u8_p8_0 = {
  147060. 2, 225,
  147061. _vq_lengthlist__44u8_p8_0,
  147062. 1, -520986624, 1620377600, 4, 0,
  147063. _vq_quantlist__44u8_p8_0,
  147064. NULL,
  147065. &_vq_auxt__44u8_p8_0,
  147066. NULL,
  147067. 0
  147068. };
  147069. static long _vq_quantlist__44u8_p8_1[] = {
  147070. 10,
  147071. 9,
  147072. 11,
  147073. 8,
  147074. 12,
  147075. 7,
  147076. 13,
  147077. 6,
  147078. 14,
  147079. 5,
  147080. 15,
  147081. 4,
  147082. 16,
  147083. 3,
  147084. 17,
  147085. 2,
  147086. 18,
  147087. 1,
  147088. 19,
  147089. 0,
  147090. 20,
  147091. };
  147092. static long _vq_lengthlist__44u8_p8_1[] = {
  147093. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147094. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147095. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  147096. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147097. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147098. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147099. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147100. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  147101. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147102. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147103. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  147104. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  147105. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147106. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  147107. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  147108. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147109. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  147110. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147111. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147112. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147113. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147114. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147115. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147116. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  147117. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147118. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  147119. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  147120. 10,10,10,10,10,10,10,10,10,
  147121. };
  147122. static float _vq_quantthresh__44u8_p8_1[] = {
  147123. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147124. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147125. 6.5, 7.5, 8.5, 9.5,
  147126. };
  147127. static long _vq_quantmap__44u8_p8_1[] = {
  147128. 19, 17, 15, 13, 11, 9, 7, 5,
  147129. 3, 1, 0, 2, 4, 6, 8, 10,
  147130. 12, 14, 16, 18, 20,
  147131. };
  147132. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  147133. _vq_quantthresh__44u8_p8_1,
  147134. _vq_quantmap__44u8_p8_1,
  147135. 21,
  147136. 21
  147137. };
  147138. static static_codebook _44u8_p8_1 = {
  147139. 2, 441,
  147140. _vq_lengthlist__44u8_p8_1,
  147141. 1, -529268736, 1611661312, 5, 0,
  147142. _vq_quantlist__44u8_p8_1,
  147143. NULL,
  147144. &_vq_auxt__44u8_p8_1,
  147145. NULL,
  147146. 0
  147147. };
  147148. static long _vq_quantlist__44u8_p9_0[] = {
  147149. 4,
  147150. 3,
  147151. 5,
  147152. 2,
  147153. 6,
  147154. 1,
  147155. 7,
  147156. 0,
  147157. 8,
  147158. };
  147159. static long _vq_lengthlist__44u8_p9_0[] = {
  147160. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  147161. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147162. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147163. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  147165. 8,
  147166. };
  147167. static float _vq_quantthresh__44u8_p9_0[] = {
  147168. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  147169. };
  147170. static long _vq_quantmap__44u8_p9_0[] = {
  147171. 7, 5, 3, 1, 0, 2, 4, 6,
  147172. 8,
  147173. };
  147174. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  147175. _vq_quantthresh__44u8_p9_0,
  147176. _vq_quantmap__44u8_p9_0,
  147177. 9,
  147178. 9
  147179. };
  147180. static static_codebook _44u8_p9_0 = {
  147181. 2, 81,
  147182. _vq_lengthlist__44u8_p9_0,
  147183. 1, -511895552, 1631393792, 4, 0,
  147184. _vq_quantlist__44u8_p9_0,
  147185. NULL,
  147186. &_vq_auxt__44u8_p9_0,
  147187. NULL,
  147188. 0
  147189. };
  147190. static long _vq_quantlist__44u8_p9_1[] = {
  147191. 9,
  147192. 8,
  147193. 10,
  147194. 7,
  147195. 11,
  147196. 6,
  147197. 12,
  147198. 5,
  147199. 13,
  147200. 4,
  147201. 14,
  147202. 3,
  147203. 15,
  147204. 2,
  147205. 16,
  147206. 1,
  147207. 17,
  147208. 0,
  147209. 18,
  147210. };
  147211. static long _vq_lengthlist__44u8_p9_1[] = {
  147212. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  147213. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  147214. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  147215. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  147216. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  147217. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  147218. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  147219. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  147220. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  147221. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  147222. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  147223. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  147224. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  147225. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  147226. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  147227. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  147228. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  147229. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  147230. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  147231. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  147232. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  147233. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  147234. 16,15,16,16,16,16,16,16,16,
  147235. };
  147236. static float _vq_quantthresh__44u8_p9_1[] = {
  147237. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  147238. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  147239. 367.5, 416.5,
  147240. };
  147241. static long _vq_quantmap__44u8_p9_1[] = {
  147242. 17, 15, 13, 11, 9, 7, 5, 3,
  147243. 1, 0, 2, 4, 6, 8, 10, 12,
  147244. 14, 16, 18,
  147245. };
  147246. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  147247. _vq_quantthresh__44u8_p9_1,
  147248. _vq_quantmap__44u8_p9_1,
  147249. 19,
  147250. 19
  147251. };
  147252. static static_codebook _44u8_p9_1 = {
  147253. 2, 361,
  147254. _vq_lengthlist__44u8_p9_1,
  147255. 1, -518287360, 1622704128, 5, 0,
  147256. _vq_quantlist__44u8_p9_1,
  147257. NULL,
  147258. &_vq_auxt__44u8_p9_1,
  147259. NULL,
  147260. 0
  147261. };
  147262. static long _vq_quantlist__44u8_p9_2[] = {
  147263. 24,
  147264. 23,
  147265. 25,
  147266. 22,
  147267. 26,
  147268. 21,
  147269. 27,
  147270. 20,
  147271. 28,
  147272. 19,
  147273. 29,
  147274. 18,
  147275. 30,
  147276. 17,
  147277. 31,
  147278. 16,
  147279. 32,
  147280. 15,
  147281. 33,
  147282. 14,
  147283. 34,
  147284. 13,
  147285. 35,
  147286. 12,
  147287. 36,
  147288. 11,
  147289. 37,
  147290. 10,
  147291. 38,
  147292. 9,
  147293. 39,
  147294. 8,
  147295. 40,
  147296. 7,
  147297. 41,
  147298. 6,
  147299. 42,
  147300. 5,
  147301. 43,
  147302. 4,
  147303. 44,
  147304. 3,
  147305. 45,
  147306. 2,
  147307. 46,
  147308. 1,
  147309. 47,
  147310. 0,
  147311. 48,
  147312. };
  147313. static long _vq_lengthlist__44u8_p9_2[] = {
  147314. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  147315. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147316. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147317. 7,
  147318. };
  147319. static float _vq_quantthresh__44u8_p9_2[] = {
  147320. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  147321. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  147322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147324. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  147325. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  147326. };
  147327. static long _vq_quantmap__44u8_p9_2[] = {
  147328. 47, 45, 43, 41, 39, 37, 35, 33,
  147329. 31, 29, 27, 25, 23, 21, 19, 17,
  147330. 15, 13, 11, 9, 7, 5, 3, 1,
  147331. 0, 2, 4, 6, 8, 10, 12, 14,
  147332. 16, 18, 20, 22, 24, 26, 28, 30,
  147333. 32, 34, 36, 38, 40, 42, 44, 46,
  147334. 48,
  147335. };
  147336. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  147337. _vq_quantthresh__44u8_p9_2,
  147338. _vq_quantmap__44u8_p9_2,
  147339. 49,
  147340. 49
  147341. };
  147342. static static_codebook _44u8_p9_2 = {
  147343. 1, 49,
  147344. _vq_lengthlist__44u8_p9_2,
  147345. 1, -526909440, 1611661312, 6, 0,
  147346. _vq_quantlist__44u8_p9_2,
  147347. NULL,
  147348. &_vq_auxt__44u8_p9_2,
  147349. NULL,
  147350. 0
  147351. };
  147352. static long _huff_lengthlist__44u9__long[] = {
  147353. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  147354. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  147355. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  147356. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  147357. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  147358. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  147359. 10, 8, 8, 9,
  147360. };
  147361. static static_codebook _huff_book__44u9__long = {
  147362. 2, 100,
  147363. _huff_lengthlist__44u9__long,
  147364. 0, 0, 0, 0, 0,
  147365. NULL,
  147366. NULL,
  147367. NULL,
  147368. NULL,
  147369. 0
  147370. };
  147371. static long _huff_lengthlist__44u9__short[] = {
  147372. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  147373. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  147374. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  147375. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  147376. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  147377. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  147378. 9, 9,12,15,
  147379. };
  147380. static static_codebook _huff_book__44u9__short = {
  147381. 2, 100,
  147382. _huff_lengthlist__44u9__short,
  147383. 0, 0, 0, 0, 0,
  147384. NULL,
  147385. NULL,
  147386. NULL,
  147387. NULL,
  147388. 0
  147389. };
  147390. static long _vq_quantlist__44u9_p1_0[] = {
  147391. 1,
  147392. 0,
  147393. 2,
  147394. };
  147395. static long _vq_lengthlist__44u9_p1_0[] = {
  147396. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  147397. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  147398. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  147399. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  147400. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  147401. 10,
  147402. };
  147403. static float _vq_quantthresh__44u9_p1_0[] = {
  147404. -0.5, 0.5,
  147405. };
  147406. static long _vq_quantmap__44u9_p1_0[] = {
  147407. 1, 0, 2,
  147408. };
  147409. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  147410. _vq_quantthresh__44u9_p1_0,
  147411. _vq_quantmap__44u9_p1_0,
  147412. 3,
  147413. 3
  147414. };
  147415. static static_codebook _44u9_p1_0 = {
  147416. 4, 81,
  147417. _vq_lengthlist__44u9_p1_0,
  147418. 1, -535822336, 1611661312, 2, 0,
  147419. _vq_quantlist__44u9_p1_0,
  147420. NULL,
  147421. &_vq_auxt__44u9_p1_0,
  147422. NULL,
  147423. 0
  147424. };
  147425. static long _vq_quantlist__44u9_p2_0[] = {
  147426. 2,
  147427. 1,
  147428. 3,
  147429. 0,
  147430. 4,
  147431. };
  147432. static long _vq_lengthlist__44u9_p2_0[] = {
  147433. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  147434. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  147435. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  147436. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  147437. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  147438. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  147439. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  147440. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  147441. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  147442. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  147443. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  147444. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  147445. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  147446. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  147447. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  147448. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  147449. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  147450. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  147451. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  147452. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  147453. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  147454. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  147455. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  147456. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  147457. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  147458. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  147459. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  147460. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  147461. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  147462. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  147463. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  147464. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  147465. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  147466. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  147467. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  147468. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  147469. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  147470. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  147471. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  147472. 14,
  147473. };
  147474. static float _vq_quantthresh__44u9_p2_0[] = {
  147475. -1.5, -0.5, 0.5, 1.5,
  147476. };
  147477. static long _vq_quantmap__44u9_p2_0[] = {
  147478. 3, 1, 0, 2, 4,
  147479. };
  147480. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  147481. _vq_quantthresh__44u9_p2_0,
  147482. _vq_quantmap__44u9_p2_0,
  147483. 5,
  147484. 5
  147485. };
  147486. static static_codebook _44u9_p2_0 = {
  147487. 4, 625,
  147488. _vq_lengthlist__44u9_p2_0,
  147489. 1, -533725184, 1611661312, 3, 0,
  147490. _vq_quantlist__44u9_p2_0,
  147491. NULL,
  147492. &_vq_auxt__44u9_p2_0,
  147493. NULL,
  147494. 0
  147495. };
  147496. static long _vq_quantlist__44u9_p3_0[] = {
  147497. 4,
  147498. 3,
  147499. 5,
  147500. 2,
  147501. 6,
  147502. 1,
  147503. 7,
  147504. 0,
  147505. 8,
  147506. };
  147507. static long _vq_lengthlist__44u9_p3_0[] = {
  147508. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  147509. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  147510. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  147511. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  147512. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  147513. 11,
  147514. };
  147515. static float _vq_quantthresh__44u9_p3_0[] = {
  147516. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147517. };
  147518. static long _vq_quantmap__44u9_p3_0[] = {
  147519. 7, 5, 3, 1, 0, 2, 4, 6,
  147520. 8,
  147521. };
  147522. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  147523. _vq_quantthresh__44u9_p3_0,
  147524. _vq_quantmap__44u9_p3_0,
  147525. 9,
  147526. 9
  147527. };
  147528. static static_codebook _44u9_p3_0 = {
  147529. 2, 81,
  147530. _vq_lengthlist__44u9_p3_0,
  147531. 1, -531628032, 1611661312, 4, 0,
  147532. _vq_quantlist__44u9_p3_0,
  147533. NULL,
  147534. &_vq_auxt__44u9_p3_0,
  147535. NULL,
  147536. 0
  147537. };
  147538. static long _vq_quantlist__44u9_p4_0[] = {
  147539. 8,
  147540. 7,
  147541. 9,
  147542. 6,
  147543. 10,
  147544. 5,
  147545. 11,
  147546. 4,
  147547. 12,
  147548. 3,
  147549. 13,
  147550. 2,
  147551. 14,
  147552. 1,
  147553. 15,
  147554. 0,
  147555. 16,
  147556. };
  147557. static long _vq_lengthlist__44u9_p4_0[] = {
  147558. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  147559. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  147560. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  147561. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  147562. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  147563. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  147564. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  147565. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  147566. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  147567. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  147568. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  147569. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  147570. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  147571. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  147572. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  147573. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  147574. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  147575. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  147576. 14,
  147577. };
  147578. static float _vq_quantthresh__44u9_p4_0[] = {
  147579. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  147580. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  147581. };
  147582. static long _vq_quantmap__44u9_p4_0[] = {
  147583. 15, 13, 11, 9, 7, 5, 3, 1,
  147584. 0, 2, 4, 6, 8, 10, 12, 14,
  147585. 16,
  147586. };
  147587. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  147588. _vq_quantthresh__44u9_p4_0,
  147589. _vq_quantmap__44u9_p4_0,
  147590. 17,
  147591. 17
  147592. };
  147593. static static_codebook _44u9_p4_0 = {
  147594. 2, 289,
  147595. _vq_lengthlist__44u9_p4_0,
  147596. 1, -529530880, 1611661312, 5, 0,
  147597. _vq_quantlist__44u9_p4_0,
  147598. NULL,
  147599. &_vq_auxt__44u9_p4_0,
  147600. NULL,
  147601. 0
  147602. };
  147603. static long _vq_quantlist__44u9_p5_0[] = {
  147604. 1,
  147605. 0,
  147606. 2,
  147607. };
  147608. static long _vq_lengthlist__44u9_p5_0[] = {
  147609. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  147610. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  147611. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  147612. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  147613. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  147614. 10,
  147615. };
  147616. static float _vq_quantthresh__44u9_p5_0[] = {
  147617. -5.5, 5.5,
  147618. };
  147619. static long _vq_quantmap__44u9_p5_0[] = {
  147620. 1, 0, 2,
  147621. };
  147622. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  147623. _vq_quantthresh__44u9_p5_0,
  147624. _vq_quantmap__44u9_p5_0,
  147625. 3,
  147626. 3
  147627. };
  147628. static static_codebook _44u9_p5_0 = {
  147629. 4, 81,
  147630. _vq_lengthlist__44u9_p5_0,
  147631. 1, -529137664, 1618345984, 2, 0,
  147632. _vq_quantlist__44u9_p5_0,
  147633. NULL,
  147634. &_vq_auxt__44u9_p5_0,
  147635. NULL,
  147636. 0
  147637. };
  147638. static long _vq_quantlist__44u9_p5_1[] = {
  147639. 5,
  147640. 4,
  147641. 6,
  147642. 3,
  147643. 7,
  147644. 2,
  147645. 8,
  147646. 1,
  147647. 9,
  147648. 0,
  147649. 10,
  147650. };
  147651. static long _vq_lengthlist__44u9_p5_1[] = {
  147652. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  147653. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  147654. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  147655. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  147656. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  147657. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  147658. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  147659. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147660. };
  147661. static float _vq_quantthresh__44u9_p5_1[] = {
  147662. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147663. 3.5, 4.5,
  147664. };
  147665. static long _vq_quantmap__44u9_p5_1[] = {
  147666. 9, 7, 5, 3, 1, 0, 2, 4,
  147667. 6, 8, 10,
  147668. };
  147669. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  147670. _vq_quantthresh__44u9_p5_1,
  147671. _vq_quantmap__44u9_p5_1,
  147672. 11,
  147673. 11
  147674. };
  147675. static static_codebook _44u9_p5_1 = {
  147676. 2, 121,
  147677. _vq_lengthlist__44u9_p5_1,
  147678. 1, -531365888, 1611661312, 4, 0,
  147679. _vq_quantlist__44u9_p5_1,
  147680. NULL,
  147681. &_vq_auxt__44u9_p5_1,
  147682. NULL,
  147683. 0
  147684. };
  147685. static long _vq_quantlist__44u9_p6_0[] = {
  147686. 6,
  147687. 5,
  147688. 7,
  147689. 4,
  147690. 8,
  147691. 3,
  147692. 9,
  147693. 2,
  147694. 10,
  147695. 1,
  147696. 11,
  147697. 0,
  147698. 12,
  147699. };
  147700. static long _vq_lengthlist__44u9_p6_0[] = {
  147701. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  147702. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  147703. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147704. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  147705. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  147706. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  147707. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  147708. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  147709. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  147710. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  147711. 10,11,11,11,11,12,11,12,12,
  147712. };
  147713. static float _vq_quantthresh__44u9_p6_0[] = {
  147714. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147715. 12.5, 17.5, 22.5, 27.5,
  147716. };
  147717. static long _vq_quantmap__44u9_p6_0[] = {
  147718. 11, 9, 7, 5, 3, 1, 0, 2,
  147719. 4, 6, 8, 10, 12,
  147720. };
  147721. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  147722. _vq_quantthresh__44u9_p6_0,
  147723. _vq_quantmap__44u9_p6_0,
  147724. 13,
  147725. 13
  147726. };
  147727. static static_codebook _44u9_p6_0 = {
  147728. 2, 169,
  147729. _vq_lengthlist__44u9_p6_0,
  147730. 1, -526516224, 1616117760, 4, 0,
  147731. _vq_quantlist__44u9_p6_0,
  147732. NULL,
  147733. &_vq_auxt__44u9_p6_0,
  147734. NULL,
  147735. 0
  147736. };
  147737. static long _vq_quantlist__44u9_p6_1[] = {
  147738. 2,
  147739. 1,
  147740. 3,
  147741. 0,
  147742. 4,
  147743. };
  147744. static long _vq_lengthlist__44u9_p6_1[] = {
  147745. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  147746. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  147747. };
  147748. static float _vq_quantthresh__44u9_p6_1[] = {
  147749. -1.5, -0.5, 0.5, 1.5,
  147750. };
  147751. static long _vq_quantmap__44u9_p6_1[] = {
  147752. 3, 1, 0, 2, 4,
  147753. };
  147754. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  147755. _vq_quantthresh__44u9_p6_1,
  147756. _vq_quantmap__44u9_p6_1,
  147757. 5,
  147758. 5
  147759. };
  147760. static static_codebook _44u9_p6_1 = {
  147761. 2, 25,
  147762. _vq_lengthlist__44u9_p6_1,
  147763. 1, -533725184, 1611661312, 3, 0,
  147764. _vq_quantlist__44u9_p6_1,
  147765. NULL,
  147766. &_vq_auxt__44u9_p6_1,
  147767. NULL,
  147768. 0
  147769. };
  147770. static long _vq_quantlist__44u9_p7_0[] = {
  147771. 6,
  147772. 5,
  147773. 7,
  147774. 4,
  147775. 8,
  147776. 3,
  147777. 9,
  147778. 2,
  147779. 10,
  147780. 1,
  147781. 11,
  147782. 0,
  147783. 12,
  147784. };
  147785. static long _vq_lengthlist__44u9_p7_0[] = {
  147786. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  147787. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  147788. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  147789. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  147790. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  147791. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  147792. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  147793. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  147794. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  147795. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  147796. 12,13,13,14,14,14,15,15,15,
  147797. };
  147798. static float _vq_quantthresh__44u9_p7_0[] = {
  147799. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  147800. 27.5, 38.5, 49.5, 60.5,
  147801. };
  147802. static long _vq_quantmap__44u9_p7_0[] = {
  147803. 11, 9, 7, 5, 3, 1, 0, 2,
  147804. 4, 6, 8, 10, 12,
  147805. };
  147806. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  147807. _vq_quantthresh__44u9_p7_0,
  147808. _vq_quantmap__44u9_p7_0,
  147809. 13,
  147810. 13
  147811. };
  147812. static static_codebook _44u9_p7_0 = {
  147813. 2, 169,
  147814. _vq_lengthlist__44u9_p7_0,
  147815. 1, -523206656, 1618345984, 4, 0,
  147816. _vq_quantlist__44u9_p7_0,
  147817. NULL,
  147818. &_vq_auxt__44u9_p7_0,
  147819. NULL,
  147820. 0
  147821. };
  147822. static long _vq_quantlist__44u9_p7_1[] = {
  147823. 5,
  147824. 4,
  147825. 6,
  147826. 3,
  147827. 7,
  147828. 2,
  147829. 8,
  147830. 1,
  147831. 9,
  147832. 0,
  147833. 10,
  147834. };
  147835. static long _vq_lengthlist__44u9_p7_1[] = {
  147836. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  147837. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  147838. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  147839. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147840. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147841. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147842. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  147843. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  147844. };
  147845. static float _vq_quantthresh__44u9_p7_1[] = {
  147846. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  147847. 3.5, 4.5,
  147848. };
  147849. static long _vq_quantmap__44u9_p7_1[] = {
  147850. 9, 7, 5, 3, 1, 0, 2, 4,
  147851. 6, 8, 10,
  147852. };
  147853. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  147854. _vq_quantthresh__44u9_p7_1,
  147855. _vq_quantmap__44u9_p7_1,
  147856. 11,
  147857. 11
  147858. };
  147859. static static_codebook _44u9_p7_1 = {
  147860. 2, 121,
  147861. _vq_lengthlist__44u9_p7_1,
  147862. 1, -531365888, 1611661312, 4, 0,
  147863. _vq_quantlist__44u9_p7_1,
  147864. NULL,
  147865. &_vq_auxt__44u9_p7_1,
  147866. NULL,
  147867. 0
  147868. };
  147869. static long _vq_quantlist__44u9_p8_0[] = {
  147870. 7,
  147871. 6,
  147872. 8,
  147873. 5,
  147874. 9,
  147875. 4,
  147876. 10,
  147877. 3,
  147878. 11,
  147879. 2,
  147880. 12,
  147881. 1,
  147882. 13,
  147883. 0,
  147884. 14,
  147885. };
  147886. static long _vq_lengthlist__44u9_p8_0[] = {
  147887. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  147888. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  147889. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  147890. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  147891. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  147892. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  147893. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  147894. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  147895. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  147896. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  147897. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  147898. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  147899. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  147900. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  147901. 15,
  147902. };
  147903. static float _vq_quantthresh__44u9_p8_0[] = {
  147904. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  147905. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  147906. };
  147907. static long _vq_quantmap__44u9_p8_0[] = {
  147908. 13, 11, 9, 7, 5, 3, 1, 0,
  147909. 2, 4, 6, 8, 10, 12, 14,
  147910. };
  147911. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  147912. _vq_quantthresh__44u9_p8_0,
  147913. _vq_quantmap__44u9_p8_0,
  147914. 15,
  147915. 15
  147916. };
  147917. static static_codebook _44u9_p8_0 = {
  147918. 2, 225,
  147919. _vq_lengthlist__44u9_p8_0,
  147920. 1, -520986624, 1620377600, 4, 0,
  147921. _vq_quantlist__44u9_p8_0,
  147922. NULL,
  147923. &_vq_auxt__44u9_p8_0,
  147924. NULL,
  147925. 0
  147926. };
  147927. static long _vq_quantlist__44u9_p8_1[] = {
  147928. 10,
  147929. 9,
  147930. 11,
  147931. 8,
  147932. 12,
  147933. 7,
  147934. 13,
  147935. 6,
  147936. 14,
  147937. 5,
  147938. 15,
  147939. 4,
  147940. 16,
  147941. 3,
  147942. 17,
  147943. 2,
  147944. 18,
  147945. 1,
  147946. 19,
  147947. 0,
  147948. 20,
  147949. };
  147950. static long _vq_lengthlist__44u9_p8_1[] = {
  147951. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  147952. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  147953. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  147954. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  147955. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  147956. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  147957. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  147958. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  147959. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147960. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147961. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  147962. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  147963. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147964. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  147965. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147966. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  147967. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147968. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  147969. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  147970. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  147971. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147972. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  147973. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  147974. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  147975. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  147976. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  147977. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  147978. 10,10,10,10,10,10,10,10,10,
  147979. };
  147980. static float _vq_quantthresh__44u9_p8_1[] = {
  147981. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  147982. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  147983. 6.5, 7.5, 8.5, 9.5,
  147984. };
  147985. static long _vq_quantmap__44u9_p8_1[] = {
  147986. 19, 17, 15, 13, 11, 9, 7, 5,
  147987. 3, 1, 0, 2, 4, 6, 8, 10,
  147988. 12, 14, 16, 18, 20,
  147989. };
  147990. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  147991. _vq_quantthresh__44u9_p8_1,
  147992. _vq_quantmap__44u9_p8_1,
  147993. 21,
  147994. 21
  147995. };
  147996. static static_codebook _44u9_p8_1 = {
  147997. 2, 441,
  147998. _vq_lengthlist__44u9_p8_1,
  147999. 1, -529268736, 1611661312, 5, 0,
  148000. _vq_quantlist__44u9_p8_1,
  148001. NULL,
  148002. &_vq_auxt__44u9_p8_1,
  148003. NULL,
  148004. 0
  148005. };
  148006. static long _vq_quantlist__44u9_p9_0[] = {
  148007. 7,
  148008. 6,
  148009. 8,
  148010. 5,
  148011. 9,
  148012. 4,
  148013. 10,
  148014. 3,
  148015. 11,
  148016. 2,
  148017. 12,
  148018. 1,
  148019. 13,
  148020. 0,
  148021. 14,
  148022. };
  148023. static long _vq_lengthlist__44u9_p9_0[] = {
  148024. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  148025. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  148026. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148027. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148028. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148030. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148037. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148038. 10,
  148039. };
  148040. static float _vq_quantthresh__44u9_p9_0[] = {
  148041. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  148042. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  148043. };
  148044. static long _vq_quantmap__44u9_p9_0[] = {
  148045. 13, 11, 9, 7, 5, 3, 1, 0,
  148046. 2, 4, 6, 8, 10, 12, 14,
  148047. };
  148048. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  148049. _vq_quantthresh__44u9_p9_0,
  148050. _vq_quantmap__44u9_p9_0,
  148051. 15,
  148052. 15
  148053. };
  148054. static static_codebook _44u9_p9_0 = {
  148055. 2, 225,
  148056. _vq_lengthlist__44u9_p9_0,
  148057. 1, -510036736, 1631393792, 4, 0,
  148058. _vq_quantlist__44u9_p9_0,
  148059. NULL,
  148060. &_vq_auxt__44u9_p9_0,
  148061. NULL,
  148062. 0
  148063. };
  148064. static long _vq_quantlist__44u9_p9_1[] = {
  148065. 9,
  148066. 8,
  148067. 10,
  148068. 7,
  148069. 11,
  148070. 6,
  148071. 12,
  148072. 5,
  148073. 13,
  148074. 4,
  148075. 14,
  148076. 3,
  148077. 15,
  148078. 2,
  148079. 16,
  148080. 1,
  148081. 17,
  148082. 0,
  148083. 18,
  148084. };
  148085. static long _vq_lengthlist__44u9_p9_1[] = {
  148086. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  148087. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  148088. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  148089. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  148090. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  148091. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  148092. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  148093. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  148094. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  148095. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  148096. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  148097. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  148098. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  148099. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  148100. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  148101. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  148102. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  148103. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  148104. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  148105. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  148106. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  148107. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  148108. 17,17,15,17,15,17,16,16,17,
  148109. };
  148110. static float _vq_quantthresh__44u9_p9_1[] = {
  148111. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  148112. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  148113. 367.5, 416.5,
  148114. };
  148115. static long _vq_quantmap__44u9_p9_1[] = {
  148116. 17, 15, 13, 11, 9, 7, 5, 3,
  148117. 1, 0, 2, 4, 6, 8, 10, 12,
  148118. 14, 16, 18,
  148119. };
  148120. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  148121. _vq_quantthresh__44u9_p9_1,
  148122. _vq_quantmap__44u9_p9_1,
  148123. 19,
  148124. 19
  148125. };
  148126. static static_codebook _44u9_p9_1 = {
  148127. 2, 361,
  148128. _vq_lengthlist__44u9_p9_1,
  148129. 1, -518287360, 1622704128, 5, 0,
  148130. _vq_quantlist__44u9_p9_1,
  148131. NULL,
  148132. &_vq_auxt__44u9_p9_1,
  148133. NULL,
  148134. 0
  148135. };
  148136. static long _vq_quantlist__44u9_p9_2[] = {
  148137. 24,
  148138. 23,
  148139. 25,
  148140. 22,
  148141. 26,
  148142. 21,
  148143. 27,
  148144. 20,
  148145. 28,
  148146. 19,
  148147. 29,
  148148. 18,
  148149. 30,
  148150. 17,
  148151. 31,
  148152. 16,
  148153. 32,
  148154. 15,
  148155. 33,
  148156. 14,
  148157. 34,
  148158. 13,
  148159. 35,
  148160. 12,
  148161. 36,
  148162. 11,
  148163. 37,
  148164. 10,
  148165. 38,
  148166. 9,
  148167. 39,
  148168. 8,
  148169. 40,
  148170. 7,
  148171. 41,
  148172. 6,
  148173. 42,
  148174. 5,
  148175. 43,
  148176. 4,
  148177. 44,
  148178. 3,
  148179. 45,
  148180. 2,
  148181. 46,
  148182. 1,
  148183. 47,
  148184. 0,
  148185. 48,
  148186. };
  148187. static long _vq_lengthlist__44u9_p9_2[] = {
  148188. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  148189. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148190. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148191. 7,
  148192. };
  148193. static float _vq_quantthresh__44u9_p9_2[] = {
  148194. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  148195. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  148196. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148197. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148198. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  148199. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  148200. };
  148201. static long _vq_quantmap__44u9_p9_2[] = {
  148202. 47, 45, 43, 41, 39, 37, 35, 33,
  148203. 31, 29, 27, 25, 23, 21, 19, 17,
  148204. 15, 13, 11, 9, 7, 5, 3, 1,
  148205. 0, 2, 4, 6, 8, 10, 12, 14,
  148206. 16, 18, 20, 22, 24, 26, 28, 30,
  148207. 32, 34, 36, 38, 40, 42, 44, 46,
  148208. 48,
  148209. };
  148210. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  148211. _vq_quantthresh__44u9_p9_2,
  148212. _vq_quantmap__44u9_p9_2,
  148213. 49,
  148214. 49
  148215. };
  148216. static static_codebook _44u9_p9_2 = {
  148217. 1, 49,
  148218. _vq_lengthlist__44u9_p9_2,
  148219. 1, -526909440, 1611661312, 6, 0,
  148220. _vq_quantlist__44u9_p9_2,
  148221. NULL,
  148222. &_vq_auxt__44u9_p9_2,
  148223. NULL,
  148224. 0
  148225. };
  148226. static long _huff_lengthlist__44un1__long[] = {
  148227. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  148228. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  148229. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  148230. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  148231. };
  148232. static static_codebook _huff_book__44un1__long = {
  148233. 2, 64,
  148234. _huff_lengthlist__44un1__long,
  148235. 0, 0, 0, 0, 0,
  148236. NULL,
  148237. NULL,
  148238. NULL,
  148239. NULL,
  148240. 0
  148241. };
  148242. static long _vq_quantlist__44un1__p1_0[] = {
  148243. 1,
  148244. 0,
  148245. 2,
  148246. };
  148247. static long _vq_lengthlist__44un1__p1_0[] = {
  148248. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148249. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  148250. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  148251. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  148252. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  148253. 12,
  148254. };
  148255. static float _vq_quantthresh__44un1__p1_0[] = {
  148256. -0.5, 0.5,
  148257. };
  148258. static long _vq_quantmap__44un1__p1_0[] = {
  148259. 1, 0, 2,
  148260. };
  148261. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  148262. _vq_quantthresh__44un1__p1_0,
  148263. _vq_quantmap__44un1__p1_0,
  148264. 3,
  148265. 3
  148266. };
  148267. static static_codebook _44un1__p1_0 = {
  148268. 4, 81,
  148269. _vq_lengthlist__44un1__p1_0,
  148270. 1, -535822336, 1611661312, 2, 0,
  148271. _vq_quantlist__44un1__p1_0,
  148272. NULL,
  148273. &_vq_auxt__44un1__p1_0,
  148274. NULL,
  148275. 0
  148276. };
  148277. static long _vq_quantlist__44un1__p2_0[] = {
  148278. 1,
  148279. 0,
  148280. 2,
  148281. };
  148282. static long _vq_lengthlist__44un1__p2_0[] = {
  148283. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  148284. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  148285. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  148286. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  148287. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  148288. 8,
  148289. };
  148290. static float _vq_quantthresh__44un1__p2_0[] = {
  148291. -0.5, 0.5,
  148292. };
  148293. static long _vq_quantmap__44un1__p2_0[] = {
  148294. 1, 0, 2,
  148295. };
  148296. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  148297. _vq_quantthresh__44un1__p2_0,
  148298. _vq_quantmap__44un1__p2_0,
  148299. 3,
  148300. 3
  148301. };
  148302. static static_codebook _44un1__p2_0 = {
  148303. 4, 81,
  148304. _vq_lengthlist__44un1__p2_0,
  148305. 1, -535822336, 1611661312, 2, 0,
  148306. _vq_quantlist__44un1__p2_0,
  148307. NULL,
  148308. &_vq_auxt__44un1__p2_0,
  148309. NULL,
  148310. 0
  148311. };
  148312. static long _vq_quantlist__44un1__p3_0[] = {
  148313. 2,
  148314. 1,
  148315. 3,
  148316. 0,
  148317. 4,
  148318. };
  148319. static long _vq_lengthlist__44un1__p3_0[] = {
  148320. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  148321. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  148322. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  148323. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  148324. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  148325. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  148326. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  148327. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  148328. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  148329. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  148330. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  148331. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  148332. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  148333. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  148334. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  148335. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  148336. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  148337. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  148338. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  148339. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  148340. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  148341. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  148342. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  148343. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  148344. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  148345. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  148346. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  148347. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  148348. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  148349. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  148350. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  148351. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  148352. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  148353. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  148354. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  148355. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  148356. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  148357. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  148358. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  148359. 17,
  148360. };
  148361. static float _vq_quantthresh__44un1__p3_0[] = {
  148362. -1.5, -0.5, 0.5, 1.5,
  148363. };
  148364. static long _vq_quantmap__44un1__p3_0[] = {
  148365. 3, 1, 0, 2, 4,
  148366. };
  148367. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  148368. _vq_quantthresh__44un1__p3_0,
  148369. _vq_quantmap__44un1__p3_0,
  148370. 5,
  148371. 5
  148372. };
  148373. static static_codebook _44un1__p3_0 = {
  148374. 4, 625,
  148375. _vq_lengthlist__44un1__p3_0,
  148376. 1, -533725184, 1611661312, 3, 0,
  148377. _vq_quantlist__44un1__p3_0,
  148378. NULL,
  148379. &_vq_auxt__44un1__p3_0,
  148380. NULL,
  148381. 0
  148382. };
  148383. static long _vq_quantlist__44un1__p4_0[] = {
  148384. 2,
  148385. 1,
  148386. 3,
  148387. 0,
  148388. 4,
  148389. };
  148390. static long _vq_lengthlist__44un1__p4_0[] = {
  148391. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  148392. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  148393. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  148394. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  148395. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  148396. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  148397. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  148398. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  148399. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  148400. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  148401. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  148402. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  148403. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  148404. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  148405. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  148406. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  148407. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  148408. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  148409. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  148410. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  148411. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  148412. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  148413. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  148414. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  148415. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  148416. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  148417. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  148418. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  148419. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  148420. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  148421. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  148422. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  148423. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  148424. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  148425. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  148426. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  148427. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  148428. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  148429. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  148430. 12,
  148431. };
  148432. static float _vq_quantthresh__44un1__p4_0[] = {
  148433. -1.5, -0.5, 0.5, 1.5,
  148434. };
  148435. static long _vq_quantmap__44un1__p4_0[] = {
  148436. 3, 1, 0, 2, 4,
  148437. };
  148438. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  148439. _vq_quantthresh__44un1__p4_0,
  148440. _vq_quantmap__44un1__p4_0,
  148441. 5,
  148442. 5
  148443. };
  148444. static static_codebook _44un1__p4_0 = {
  148445. 4, 625,
  148446. _vq_lengthlist__44un1__p4_0,
  148447. 1, -533725184, 1611661312, 3, 0,
  148448. _vq_quantlist__44un1__p4_0,
  148449. NULL,
  148450. &_vq_auxt__44un1__p4_0,
  148451. NULL,
  148452. 0
  148453. };
  148454. static long _vq_quantlist__44un1__p5_0[] = {
  148455. 4,
  148456. 3,
  148457. 5,
  148458. 2,
  148459. 6,
  148460. 1,
  148461. 7,
  148462. 0,
  148463. 8,
  148464. };
  148465. static long _vq_lengthlist__44un1__p5_0[] = {
  148466. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  148467. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  148468. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  148469. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  148470. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148471. 12,
  148472. };
  148473. static float _vq_quantthresh__44un1__p5_0[] = {
  148474. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148475. };
  148476. static long _vq_quantmap__44un1__p5_0[] = {
  148477. 7, 5, 3, 1, 0, 2, 4, 6,
  148478. 8,
  148479. };
  148480. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  148481. _vq_quantthresh__44un1__p5_0,
  148482. _vq_quantmap__44un1__p5_0,
  148483. 9,
  148484. 9
  148485. };
  148486. static static_codebook _44un1__p5_0 = {
  148487. 2, 81,
  148488. _vq_lengthlist__44un1__p5_0,
  148489. 1, -531628032, 1611661312, 4, 0,
  148490. _vq_quantlist__44un1__p5_0,
  148491. NULL,
  148492. &_vq_auxt__44un1__p5_0,
  148493. NULL,
  148494. 0
  148495. };
  148496. static long _vq_quantlist__44un1__p6_0[] = {
  148497. 6,
  148498. 5,
  148499. 7,
  148500. 4,
  148501. 8,
  148502. 3,
  148503. 9,
  148504. 2,
  148505. 10,
  148506. 1,
  148507. 11,
  148508. 0,
  148509. 12,
  148510. };
  148511. static long _vq_lengthlist__44un1__p6_0[] = {
  148512. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  148513. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  148514. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  148515. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  148516. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  148517. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  148518. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  148519. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  148520. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  148521. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  148522. 16, 0,15,18,18, 0,16, 0, 0,
  148523. };
  148524. static float _vq_quantthresh__44un1__p6_0[] = {
  148525. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148526. 12.5, 17.5, 22.5, 27.5,
  148527. };
  148528. static long _vq_quantmap__44un1__p6_0[] = {
  148529. 11, 9, 7, 5, 3, 1, 0, 2,
  148530. 4, 6, 8, 10, 12,
  148531. };
  148532. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  148533. _vq_quantthresh__44un1__p6_0,
  148534. _vq_quantmap__44un1__p6_0,
  148535. 13,
  148536. 13
  148537. };
  148538. static static_codebook _44un1__p6_0 = {
  148539. 2, 169,
  148540. _vq_lengthlist__44un1__p6_0,
  148541. 1, -526516224, 1616117760, 4, 0,
  148542. _vq_quantlist__44un1__p6_0,
  148543. NULL,
  148544. &_vq_auxt__44un1__p6_0,
  148545. NULL,
  148546. 0
  148547. };
  148548. static long _vq_quantlist__44un1__p6_1[] = {
  148549. 2,
  148550. 1,
  148551. 3,
  148552. 0,
  148553. 4,
  148554. };
  148555. static long _vq_lengthlist__44un1__p6_1[] = {
  148556. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  148557. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  148558. };
  148559. static float _vq_quantthresh__44un1__p6_1[] = {
  148560. -1.5, -0.5, 0.5, 1.5,
  148561. };
  148562. static long _vq_quantmap__44un1__p6_1[] = {
  148563. 3, 1, 0, 2, 4,
  148564. };
  148565. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  148566. _vq_quantthresh__44un1__p6_1,
  148567. _vq_quantmap__44un1__p6_1,
  148568. 5,
  148569. 5
  148570. };
  148571. static static_codebook _44un1__p6_1 = {
  148572. 2, 25,
  148573. _vq_lengthlist__44un1__p6_1,
  148574. 1, -533725184, 1611661312, 3, 0,
  148575. _vq_quantlist__44un1__p6_1,
  148576. NULL,
  148577. &_vq_auxt__44un1__p6_1,
  148578. NULL,
  148579. 0
  148580. };
  148581. static long _vq_quantlist__44un1__p7_0[] = {
  148582. 2,
  148583. 1,
  148584. 3,
  148585. 0,
  148586. 4,
  148587. };
  148588. static long _vq_lengthlist__44un1__p7_0[] = {
  148589. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  148590. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  148591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148592. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148594. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148596. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  148597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  148600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148604. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  148605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148606. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  148607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148612. 11,11,11,11,11,11,11,11,11,11,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,11,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,11,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,11,
  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. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148626. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148627. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148628. 10,
  148629. };
  148630. static float _vq_quantthresh__44un1__p7_0[] = {
  148631. -253.5, -84.5, 84.5, 253.5,
  148632. };
  148633. static long _vq_quantmap__44un1__p7_0[] = {
  148634. 3, 1, 0, 2, 4,
  148635. };
  148636. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  148637. _vq_quantthresh__44un1__p7_0,
  148638. _vq_quantmap__44un1__p7_0,
  148639. 5,
  148640. 5
  148641. };
  148642. static static_codebook _44un1__p7_0 = {
  148643. 4, 625,
  148644. _vq_lengthlist__44un1__p7_0,
  148645. 1, -518709248, 1626677248, 3, 0,
  148646. _vq_quantlist__44un1__p7_0,
  148647. NULL,
  148648. &_vq_auxt__44un1__p7_0,
  148649. NULL,
  148650. 0
  148651. };
  148652. static long _vq_quantlist__44un1__p7_1[] = {
  148653. 6,
  148654. 5,
  148655. 7,
  148656. 4,
  148657. 8,
  148658. 3,
  148659. 9,
  148660. 2,
  148661. 10,
  148662. 1,
  148663. 11,
  148664. 0,
  148665. 12,
  148666. };
  148667. static long _vq_lengthlist__44un1__p7_1[] = {
  148668. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  148669. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  148670. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  148671. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  148672. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  148673. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  148674. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  148675. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  148676. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  148677. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  148678. 12,13,13,12,13,13,14,14,14,
  148679. };
  148680. static float _vq_quantthresh__44un1__p7_1[] = {
  148681. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148682. 32.5, 45.5, 58.5, 71.5,
  148683. };
  148684. static long _vq_quantmap__44un1__p7_1[] = {
  148685. 11, 9, 7, 5, 3, 1, 0, 2,
  148686. 4, 6, 8, 10, 12,
  148687. };
  148688. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  148689. _vq_quantthresh__44un1__p7_1,
  148690. _vq_quantmap__44un1__p7_1,
  148691. 13,
  148692. 13
  148693. };
  148694. static static_codebook _44un1__p7_1 = {
  148695. 2, 169,
  148696. _vq_lengthlist__44un1__p7_1,
  148697. 1, -523010048, 1618608128, 4, 0,
  148698. _vq_quantlist__44un1__p7_1,
  148699. NULL,
  148700. &_vq_auxt__44un1__p7_1,
  148701. NULL,
  148702. 0
  148703. };
  148704. static long _vq_quantlist__44un1__p7_2[] = {
  148705. 6,
  148706. 5,
  148707. 7,
  148708. 4,
  148709. 8,
  148710. 3,
  148711. 9,
  148712. 2,
  148713. 10,
  148714. 1,
  148715. 11,
  148716. 0,
  148717. 12,
  148718. };
  148719. static long _vq_lengthlist__44un1__p7_2[] = {
  148720. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  148721. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  148722. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  148723. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  148724. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  148725. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  148726. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  148727. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  148728. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  148729. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  148730. 9, 9, 9,10,10,10,10,10,10,
  148731. };
  148732. static float _vq_quantthresh__44un1__p7_2[] = {
  148733. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148734. 2.5, 3.5, 4.5, 5.5,
  148735. };
  148736. static long _vq_quantmap__44un1__p7_2[] = {
  148737. 11, 9, 7, 5, 3, 1, 0, 2,
  148738. 4, 6, 8, 10, 12,
  148739. };
  148740. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  148741. _vq_quantthresh__44un1__p7_2,
  148742. _vq_quantmap__44un1__p7_2,
  148743. 13,
  148744. 13
  148745. };
  148746. static static_codebook _44un1__p7_2 = {
  148747. 2, 169,
  148748. _vq_lengthlist__44un1__p7_2,
  148749. 1, -531103744, 1611661312, 4, 0,
  148750. _vq_quantlist__44un1__p7_2,
  148751. NULL,
  148752. &_vq_auxt__44un1__p7_2,
  148753. NULL,
  148754. 0
  148755. };
  148756. static long _huff_lengthlist__44un1__short[] = {
  148757. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  148758. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  148759. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  148760. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  148761. };
  148762. static static_codebook _huff_book__44un1__short = {
  148763. 2, 64,
  148764. _huff_lengthlist__44un1__short,
  148765. 0, 0, 0, 0, 0,
  148766. NULL,
  148767. NULL,
  148768. NULL,
  148769. NULL,
  148770. 0
  148771. };
  148772. /********* End of inlined file: res_books_uncoupled.h *********/
  148773. /***** residue backends *********************************************/
  148774. static vorbis_info_residue0 _residue_44_low_un={
  148775. 0,-1, -1, 8,-1,
  148776. {0},
  148777. {-1},
  148778. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  148779. { -1, 25, -1, 45, -1, -1, -1}
  148780. };
  148781. static vorbis_info_residue0 _residue_44_mid_un={
  148782. 0,-1, -1, 10,-1,
  148783. /* 0 1 2 3 4 5 6 7 8 9 */
  148784. {0},
  148785. {-1},
  148786. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  148787. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  148788. };
  148789. static vorbis_info_residue0 _residue_44_hi_un={
  148790. 0,-1, -1, 10,-1,
  148791. /* 0 1 2 3 4 5 6 7 8 9 */
  148792. {0},
  148793. {-1},
  148794. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  148795. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  148796. };
  148797. /* mapping conventions:
  148798. only one submap (this would change for efficient 5.1 support for example)*/
  148799. /* Four psychoacoustic profiles are used, one for each blocktype */
  148800. static vorbis_info_mapping0 _map_nominal_u[2]={
  148801. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  148802. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  148803. };
  148804. static static_bookblock _resbook_44u_n1={
  148805. {
  148806. {0},
  148807. {0,0,&_44un1__p1_0},
  148808. {0,0,&_44un1__p2_0},
  148809. {0,0,&_44un1__p3_0},
  148810. {0,0,&_44un1__p4_0},
  148811. {0,0,&_44un1__p5_0},
  148812. {&_44un1__p6_0,&_44un1__p6_1},
  148813. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  148814. }
  148815. };
  148816. static static_bookblock _resbook_44u_0={
  148817. {
  148818. {0},
  148819. {0,0,&_44u0__p1_0},
  148820. {0,0,&_44u0__p2_0},
  148821. {0,0,&_44u0__p3_0},
  148822. {0,0,&_44u0__p4_0},
  148823. {0,0,&_44u0__p5_0},
  148824. {&_44u0__p6_0,&_44u0__p6_1},
  148825. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  148826. }
  148827. };
  148828. static static_bookblock _resbook_44u_1={
  148829. {
  148830. {0},
  148831. {0,0,&_44u1__p1_0},
  148832. {0,0,&_44u1__p2_0},
  148833. {0,0,&_44u1__p3_0},
  148834. {0,0,&_44u1__p4_0},
  148835. {0,0,&_44u1__p5_0},
  148836. {&_44u1__p6_0,&_44u1__p6_1},
  148837. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  148838. }
  148839. };
  148840. static static_bookblock _resbook_44u_2={
  148841. {
  148842. {0},
  148843. {0,0,&_44u2__p1_0},
  148844. {0,0,&_44u2__p2_0},
  148845. {0,0,&_44u2__p3_0},
  148846. {0,0,&_44u2__p4_0},
  148847. {0,0,&_44u2__p5_0},
  148848. {&_44u2__p6_0,&_44u2__p6_1},
  148849. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  148850. }
  148851. };
  148852. static static_bookblock _resbook_44u_3={
  148853. {
  148854. {0},
  148855. {0,0,&_44u3__p1_0},
  148856. {0,0,&_44u3__p2_0},
  148857. {0,0,&_44u3__p3_0},
  148858. {0,0,&_44u3__p4_0},
  148859. {0,0,&_44u3__p5_0},
  148860. {&_44u3__p6_0,&_44u3__p6_1},
  148861. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  148862. }
  148863. };
  148864. static static_bookblock _resbook_44u_4={
  148865. {
  148866. {0},
  148867. {0,0,&_44u4__p1_0},
  148868. {0,0,&_44u4__p2_0},
  148869. {0,0,&_44u4__p3_0},
  148870. {0,0,&_44u4__p4_0},
  148871. {0,0,&_44u4__p5_0},
  148872. {&_44u4__p6_0,&_44u4__p6_1},
  148873. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  148874. }
  148875. };
  148876. static static_bookblock _resbook_44u_5={
  148877. {
  148878. {0},
  148879. {0,0,&_44u5__p1_0},
  148880. {0,0,&_44u5__p2_0},
  148881. {0,0,&_44u5__p3_0},
  148882. {0,0,&_44u5__p4_0},
  148883. {0,0,&_44u5__p5_0},
  148884. {0,0,&_44u5__p6_0},
  148885. {&_44u5__p7_0,&_44u5__p7_1},
  148886. {&_44u5__p8_0,&_44u5__p8_1},
  148887. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  148888. }
  148889. };
  148890. static static_bookblock _resbook_44u_6={
  148891. {
  148892. {0},
  148893. {0,0,&_44u6__p1_0},
  148894. {0,0,&_44u6__p2_0},
  148895. {0,0,&_44u6__p3_0},
  148896. {0,0,&_44u6__p4_0},
  148897. {0,0,&_44u6__p5_0},
  148898. {0,0,&_44u6__p6_0},
  148899. {&_44u6__p7_0,&_44u6__p7_1},
  148900. {&_44u6__p8_0,&_44u6__p8_1},
  148901. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  148902. }
  148903. };
  148904. static static_bookblock _resbook_44u_7={
  148905. {
  148906. {0},
  148907. {0,0,&_44u7__p1_0},
  148908. {0,0,&_44u7__p2_0},
  148909. {0,0,&_44u7__p3_0},
  148910. {0,0,&_44u7__p4_0},
  148911. {0,0,&_44u7__p5_0},
  148912. {0,0,&_44u7__p6_0},
  148913. {&_44u7__p7_0,&_44u7__p7_1},
  148914. {&_44u7__p8_0,&_44u7__p8_1},
  148915. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  148916. }
  148917. };
  148918. static static_bookblock _resbook_44u_8={
  148919. {
  148920. {0},
  148921. {0,0,&_44u8_p1_0},
  148922. {0,0,&_44u8_p2_0},
  148923. {0,0,&_44u8_p3_0},
  148924. {0,0,&_44u8_p4_0},
  148925. {&_44u8_p5_0,&_44u8_p5_1},
  148926. {&_44u8_p6_0,&_44u8_p6_1},
  148927. {&_44u8_p7_0,&_44u8_p7_1},
  148928. {&_44u8_p8_0,&_44u8_p8_1},
  148929. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  148930. }
  148931. };
  148932. static static_bookblock _resbook_44u_9={
  148933. {
  148934. {0},
  148935. {0,0,&_44u9_p1_0},
  148936. {0,0,&_44u9_p2_0},
  148937. {0,0,&_44u9_p3_0},
  148938. {0,0,&_44u9_p4_0},
  148939. {&_44u9_p5_0,&_44u9_p5_1},
  148940. {&_44u9_p6_0,&_44u9_p6_1},
  148941. {&_44u9_p7_0,&_44u9_p7_1},
  148942. {&_44u9_p8_0,&_44u9_p8_1},
  148943. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  148944. }
  148945. };
  148946. static vorbis_residue_template _res_44u_n1[]={
  148947. {1,0, &_residue_44_low_un,
  148948. &_huff_book__44un1__short,&_huff_book__44un1__short,
  148949. &_resbook_44u_n1,&_resbook_44u_n1},
  148950. {1,0, &_residue_44_low_un,
  148951. &_huff_book__44un1__long,&_huff_book__44un1__long,
  148952. &_resbook_44u_n1,&_resbook_44u_n1}
  148953. };
  148954. static vorbis_residue_template _res_44u_0[]={
  148955. {1,0, &_residue_44_low_un,
  148956. &_huff_book__44u0__short,&_huff_book__44u0__short,
  148957. &_resbook_44u_0,&_resbook_44u_0},
  148958. {1,0, &_residue_44_low_un,
  148959. &_huff_book__44u0__long,&_huff_book__44u0__long,
  148960. &_resbook_44u_0,&_resbook_44u_0}
  148961. };
  148962. static vorbis_residue_template _res_44u_1[]={
  148963. {1,0, &_residue_44_low_un,
  148964. &_huff_book__44u1__short,&_huff_book__44u1__short,
  148965. &_resbook_44u_1,&_resbook_44u_1},
  148966. {1,0, &_residue_44_low_un,
  148967. &_huff_book__44u1__long,&_huff_book__44u1__long,
  148968. &_resbook_44u_1,&_resbook_44u_1}
  148969. };
  148970. static vorbis_residue_template _res_44u_2[]={
  148971. {1,0, &_residue_44_low_un,
  148972. &_huff_book__44u2__short,&_huff_book__44u2__short,
  148973. &_resbook_44u_2,&_resbook_44u_2},
  148974. {1,0, &_residue_44_low_un,
  148975. &_huff_book__44u2__long,&_huff_book__44u2__long,
  148976. &_resbook_44u_2,&_resbook_44u_2}
  148977. };
  148978. static vorbis_residue_template _res_44u_3[]={
  148979. {1,0, &_residue_44_low_un,
  148980. &_huff_book__44u3__short,&_huff_book__44u3__short,
  148981. &_resbook_44u_3,&_resbook_44u_3},
  148982. {1,0, &_residue_44_low_un,
  148983. &_huff_book__44u3__long,&_huff_book__44u3__long,
  148984. &_resbook_44u_3,&_resbook_44u_3}
  148985. };
  148986. static vorbis_residue_template _res_44u_4[]={
  148987. {1,0, &_residue_44_low_un,
  148988. &_huff_book__44u4__short,&_huff_book__44u4__short,
  148989. &_resbook_44u_4,&_resbook_44u_4},
  148990. {1,0, &_residue_44_low_un,
  148991. &_huff_book__44u4__long,&_huff_book__44u4__long,
  148992. &_resbook_44u_4,&_resbook_44u_4}
  148993. };
  148994. static vorbis_residue_template _res_44u_5[]={
  148995. {1,0, &_residue_44_mid_un,
  148996. &_huff_book__44u5__short,&_huff_book__44u5__short,
  148997. &_resbook_44u_5,&_resbook_44u_5},
  148998. {1,0, &_residue_44_mid_un,
  148999. &_huff_book__44u5__long,&_huff_book__44u5__long,
  149000. &_resbook_44u_5,&_resbook_44u_5}
  149001. };
  149002. static vorbis_residue_template _res_44u_6[]={
  149003. {1,0, &_residue_44_mid_un,
  149004. &_huff_book__44u6__short,&_huff_book__44u6__short,
  149005. &_resbook_44u_6,&_resbook_44u_6},
  149006. {1,0, &_residue_44_mid_un,
  149007. &_huff_book__44u6__long,&_huff_book__44u6__long,
  149008. &_resbook_44u_6,&_resbook_44u_6}
  149009. };
  149010. static vorbis_residue_template _res_44u_7[]={
  149011. {1,0, &_residue_44_mid_un,
  149012. &_huff_book__44u7__short,&_huff_book__44u7__short,
  149013. &_resbook_44u_7,&_resbook_44u_7},
  149014. {1,0, &_residue_44_mid_un,
  149015. &_huff_book__44u7__long,&_huff_book__44u7__long,
  149016. &_resbook_44u_7,&_resbook_44u_7}
  149017. };
  149018. static vorbis_residue_template _res_44u_8[]={
  149019. {1,0, &_residue_44_hi_un,
  149020. &_huff_book__44u8__short,&_huff_book__44u8__short,
  149021. &_resbook_44u_8,&_resbook_44u_8},
  149022. {1,0, &_residue_44_hi_un,
  149023. &_huff_book__44u8__long,&_huff_book__44u8__long,
  149024. &_resbook_44u_8,&_resbook_44u_8}
  149025. };
  149026. static vorbis_residue_template _res_44u_9[]={
  149027. {1,0, &_residue_44_hi_un,
  149028. &_huff_book__44u9__short,&_huff_book__44u9__short,
  149029. &_resbook_44u_9,&_resbook_44u_9},
  149030. {1,0, &_residue_44_hi_un,
  149031. &_huff_book__44u9__long,&_huff_book__44u9__long,
  149032. &_resbook_44u_9,&_resbook_44u_9}
  149033. };
  149034. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  149035. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  149036. { _map_nominal_u, _res_44u_0 }, /* 0 */
  149037. { _map_nominal_u, _res_44u_1 }, /* 1 */
  149038. { _map_nominal_u, _res_44u_2 }, /* 2 */
  149039. { _map_nominal_u, _res_44u_3 }, /* 3 */
  149040. { _map_nominal_u, _res_44u_4 }, /* 4 */
  149041. { _map_nominal_u, _res_44u_5 }, /* 5 */
  149042. { _map_nominal_u, _res_44u_6 }, /* 6 */
  149043. { _map_nominal_u, _res_44u_7 }, /* 7 */
  149044. { _map_nominal_u, _res_44u_8 }, /* 8 */
  149045. { _map_nominal_u, _res_44u_9 }, /* 9 */
  149046. };
  149047. /********* End of inlined file: residue_44u.h *********/
  149048. static double rate_mapping_44_un[12]={
  149049. 32000.,48000.,60000.,70000.,80000.,86000.,
  149050. 96000.,110000.,120000.,140000.,160000.,240001.
  149051. };
  149052. ve_setup_data_template ve_setup_44_uncoupled={
  149053. 11,
  149054. rate_mapping_44_un,
  149055. quality_mapping_44,
  149056. -1,
  149057. 40000,
  149058. 50000,
  149059. blocksize_short_44,
  149060. blocksize_long_44,
  149061. _psy_tone_masteratt_44,
  149062. _psy_tone_0dB,
  149063. _psy_tone_suppress,
  149064. _vp_tonemask_adj_otherblock,
  149065. _vp_tonemask_adj_longblock,
  149066. _vp_tonemask_adj_otherblock,
  149067. _psy_noiseguards_44,
  149068. _psy_noisebias_impulse,
  149069. _psy_noisebias_padding,
  149070. _psy_noisebias_trans,
  149071. _psy_noisebias_long,
  149072. _psy_noise_suppress,
  149073. _psy_compand_44,
  149074. _psy_compand_short_mapping,
  149075. _psy_compand_long_mapping,
  149076. {_noise_start_short_44,_noise_start_long_44},
  149077. {_noise_part_short_44,_noise_part_long_44},
  149078. _noise_thresh_44,
  149079. _psy_ath_floater,
  149080. _psy_ath_abs,
  149081. _psy_lowpass_44,
  149082. _psy_global_44,
  149083. _global_mapping_44,
  149084. NULL,
  149085. _floor_books,
  149086. _floor,
  149087. _floor_short_mapping_44,
  149088. _floor_long_mapping_44,
  149089. _mapres_template_44_uncoupled
  149090. };
  149091. /********* End of inlined file: setup_44u.h *********/
  149092. /********* Start of inlined file: setup_32.h *********/
  149093. static double rate_mapping_32[12]={
  149094. 18000.,28000.,35000.,45000.,56000.,60000.,
  149095. 75000.,90000.,100000.,115000.,150000.,190000.,
  149096. };
  149097. static double rate_mapping_32_un[12]={
  149098. 30000.,42000.,52000.,64000.,72000.,78000.,
  149099. 86000.,92000.,110000.,120000.,140000.,190000.,
  149100. };
  149101. static double _psy_lowpass_32[12]={
  149102. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  149103. };
  149104. ve_setup_data_template ve_setup_32_stereo={
  149105. 11,
  149106. rate_mapping_32,
  149107. quality_mapping_44,
  149108. 2,
  149109. 26000,
  149110. 40000,
  149111. blocksize_short_44,
  149112. blocksize_long_44,
  149113. _psy_tone_masteratt_44,
  149114. _psy_tone_0dB,
  149115. _psy_tone_suppress,
  149116. _vp_tonemask_adj_otherblock,
  149117. _vp_tonemask_adj_longblock,
  149118. _vp_tonemask_adj_otherblock,
  149119. _psy_noiseguards_44,
  149120. _psy_noisebias_impulse,
  149121. _psy_noisebias_padding,
  149122. _psy_noisebias_trans,
  149123. _psy_noisebias_long,
  149124. _psy_noise_suppress,
  149125. _psy_compand_44,
  149126. _psy_compand_short_mapping,
  149127. _psy_compand_long_mapping,
  149128. {_noise_start_short_44,_noise_start_long_44},
  149129. {_noise_part_short_44,_noise_part_long_44},
  149130. _noise_thresh_44,
  149131. _psy_ath_floater,
  149132. _psy_ath_abs,
  149133. _psy_lowpass_32,
  149134. _psy_global_44,
  149135. _global_mapping_44,
  149136. _psy_stereo_modes_44,
  149137. _floor_books,
  149138. _floor,
  149139. _floor_short_mapping_44,
  149140. _floor_long_mapping_44,
  149141. _mapres_template_44_stereo
  149142. };
  149143. ve_setup_data_template ve_setup_32_uncoupled={
  149144. 11,
  149145. rate_mapping_32_un,
  149146. quality_mapping_44,
  149147. -1,
  149148. 26000,
  149149. 40000,
  149150. blocksize_short_44,
  149151. blocksize_long_44,
  149152. _psy_tone_masteratt_44,
  149153. _psy_tone_0dB,
  149154. _psy_tone_suppress,
  149155. _vp_tonemask_adj_otherblock,
  149156. _vp_tonemask_adj_longblock,
  149157. _vp_tonemask_adj_otherblock,
  149158. _psy_noiseguards_44,
  149159. _psy_noisebias_impulse,
  149160. _psy_noisebias_padding,
  149161. _psy_noisebias_trans,
  149162. _psy_noisebias_long,
  149163. _psy_noise_suppress,
  149164. _psy_compand_44,
  149165. _psy_compand_short_mapping,
  149166. _psy_compand_long_mapping,
  149167. {_noise_start_short_44,_noise_start_long_44},
  149168. {_noise_part_short_44,_noise_part_long_44},
  149169. _noise_thresh_44,
  149170. _psy_ath_floater,
  149171. _psy_ath_abs,
  149172. _psy_lowpass_32,
  149173. _psy_global_44,
  149174. _global_mapping_44,
  149175. NULL,
  149176. _floor_books,
  149177. _floor,
  149178. _floor_short_mapping_44,
  149179. _floor_long_mapping_44,
  149180. _mapres_template_44_uncoupled
  149181. };
  149182. /********* End of inlined file: setup_32.h *********/
  149183. /********* Start of inlined file: setup_8.h *********/
  149184. /********* Start of inlined file: psych_8.h *********/
  149185. static att3 _psy_tone_masteratt_8[3]={
  149186. {{ 32, 25, 12}, 0, 0}, /* 0 */
  149187. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149188. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149189. };
  149190. static vp_adjblock _vp_tonemask_adj_8[3]={
  149191. /* adjust for mode zero */
  149192. /* 63 125 250 500 1 2 4 8 16 */
  149193. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149194. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  149195. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  149196. };
  149197. static noise3 _psy_noisebias_8[3]={
  149198. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149199. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149200. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  149201. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149202. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  149203. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149204. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149205. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149206. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149207. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149208. };
  149209. /* stereo mode by base quality level */
  149210. static adj_stereo _psy_stereo_modes_8[3]={
  149211. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149212. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149213. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149214. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149215. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149216. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149217. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149218. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149219. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149220. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149221. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149222. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  149223. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149224. };
  149225. static noiseguard _psy_noiseguards_8[2]={
  149226. {10,10,-1},
  149227. {10,10,-1},
  149228. };
  149229. static compandblock _psy_compand_8[2]={
  149230. {{
  149231. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  149232. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  149233. 12,12,13,13,14,14,15, 15, /* 23dB */
  149234. 16,16,17,17,17,18,18, 19, /* 31dB */
  149235. 19,19,20,21,22,23,24, 25, /* 39dB */
  149236. }},
  149237. {{
  149238. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  149239. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  149240. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  149241. 9,10,11,12,13,14,15, 16, /* 31dB */
  149242. 17,18,19,20,21,22,23, 24, /* 39dB */
  149243. }},
  149244. };
  149245. static double _psy_lowpass_8[3]={3.,4.,4.};
  149246. static int _noise_start_8[2]={
  149247. 64,64,
  149248. };
  149249. static int _noise_part_8[2]={
  149250. 8,8,
  149251. };
  149252. static int _psy_ath_floater_8[3]={
  149253. -100,-100,-105,
  149254. };
  149255. static int _psy_ath_abs_8[3]={
  149256. -130,-130,-140,
  149257. };
  149258. /********* End of inlined file: psych_8.h *********/
  149259. /********* Start of inlined file: residue_8.h *********/
  149260. /***** residue backends *********************************************/
  149261. static static_bookblock _resbook_8s_0={
  149262. {
  149263. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  149264. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  149265. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  149266. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  149267. }
  149268. };
  149269. static static_bookblock _resbook_8s_1={
  149270. {
  149271. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  149272. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  149273. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  149274. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  149275. }
  149276. };
  149277. static vorbis_residue_template _res_8s_0[]={
  149278. {2,0, &_residue_44_mid,
  149279. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  149280. &_resbook_8s_0,&_resbook_8s_0},
  149281. };
  149282. static vorbis_residue_template _res_8s_1[]={
  149283. {2,0, &_residue_44_mid,
  149284. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  149285. &_resbook_8s_1,&_resbook_8s_1},
  149286. };
  149287. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  149288. { _map_nominal, _res_8s_0 }, /* 0 */
  149289. { _map_nominal, _res_8s_1 }, /* 1 */
  149290. };
  149291. static static_bookblock _resbook_8u_0={
  149292. {
  149293. {0},
  149294. {0,0,&_8u0__p1_0},
  149295. {0,0,&_8u0__p2_0},
  149296. {0,0,&_8u0__p3_0},
  149297. {0,0,&_8u0__p4_0},
  149298. {0,0,&_8u0__p5_0},
  149299. {&_8u0__p6_0,&_8u0__p6_1},
  149300. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  149301. }
  149302. };
  149303. static static_bookblock _resbook_8u_1={
  149304. {
  149305. {0},
  149306. {0,0,&_8u1__p1_0},
  149307. {0,0,&_8u1__p2_0},
  149308. {0,0,&_8u1__p3_0},
  149309. {0,0,&_8u1__p4_0},
  149310. {0,0,&_8u1__p5_0},
  149311. {0,0,&_8u1__p6_0},
  149312. {&_8u1__p7_0,&_8u1__p7_1},
  149313. {&_8u1__p8_0,&_8u1__p8_1},
  149314. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  149315. }
  149316. };
  149317. static vorbis_residue_template _res_8u_0[]={
  149318. {1,0, &_residue_44_low_un,
  149319. &_huff_book__8u0__single,&_huff_book__8u0__single,
  149320. &_resbook_8u_0,&_resbook_8u_0},
  149321. };
  149322. static vorbis_residue_template _res_8u_1[]={
  149323. {1,0, &_residue_44_mid_un,
  149324. &_huff_book__8u1__single,&_huff_book__8u1__single,
  149325. &_resbook_8u_1,&_resbook_8u_1},
  149326. };
  149327. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  149328. { _map_nominal_u, _res_8u_0 }, /* 0 */
  149329. { _map_nominal_u, _res_8u_1 }, /* 1 */
  149330. };
  149331. /********* End of inlined file: residue_8.h *********/
  149332. static int blocksize_8[2]={
  149333. 512,512
  149334. };
  149335. static int _floor_mapping_8[2]={
  149336. 6,6,
  149337. };
  149338. static double rate_mapping_8[3]={
  149339. 6000.,9000.,32000.,
  149340. };
  149341. static double rate_mapping_8_uncoupled[3]={
  149342. 8000.,14000.,42000.,
  149343. };
  149344. static double quality_mapping_8[3]={
  149345. -.1,.0,1.
  149346. };
  149347. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  149348. static double _global_mapping_8[3]={ 1., 2., 3. };
  149349. ve_setup_data_template ve_setup_8_stereo={
  149350. 2,
  149351. rate_mapping_8,
  149352. quality_mapping_8,
  149353. 2,
  149354. 8000,
  149355. 9000,
  149356. blocksize_8,
  149357. blocksize_8,
  149358. _psy_tone_masteratt_8,
  149359. _psy_tone_0dB,
  149360. _psy_tone_suppress,
  149361. _vp_tonemask_adj_8,
  149362. NULL,
  149363. _vp_tonemask_adj_8,
  149364. _psy_noiseguards_8,
  149365. _psy_noisebias_8,
  149366. _psy_noisebias_8,
  149367. NULL,
  149368. NULL,
  149369. _psy_noise_suppress,
  149370. _psy_compand_8,
  149371. _psy_compand_8_mapping,
  149372. NULL,
  149373. {_noise_start_8,_noise_start_8},
  149374. {_noise_part_8,_noise_part_8},
  149375. _noise_thresh_5only,
  149376. _psy_ath_floater_8,
  149377. _psy_ath_abs_8,
  149378. _psy_lowpass_8,
  149379. _psy_global_44,
  149380. _global_mapping_8,
  149381. _psy_stereo_modes_8,
  149382. _floor_books,
  149383. _floor,
  149384. _floor_mapping_8,
  149385. NULL,
  149386. _mapres_template_8_stereo
  149387. };
  149388. ve_setup_data_template ve_setup_8_uncoupled={
  149389. 2,
  149390. rate_mapping_8_uncoupled,
  149391. quality_mapping_8,
  149392. -1,
  149393. 8000,
  149394. 9000,
  149395. blocksize_8,
  149396. blocksize_8,
  149397. _psy_tone_masteratt_8,
  149398. _psy_tone_0dB,
  149399. _psy_tone_suppress,
  149400. _vp_tonemask_adj_8,
  149401. NULL,
  149402. _vp_tonemask_adj_8,
  149403. _psy_noiseguards_8,
  149404. _psy_noisebias_8,
  149405. _psy_noisebias_8,
  149406. NULL,
  149407. NULL,
  149408. _psy_noise_suppress,
  149409. _psy_compand_8,
  149410. _psy_compand_8_mapping,
  149411. NULL,
  149412. {_noise_start_8,_noise_start_8},
  149413. {_noise_part_8,_noise_part_8},
  149414. _noise_thresh_5only,
  149415. _psy_ath_floater_8,
  149416. _psy_ath_abs_8,
  149417. _psy_lowpass_8,
  149418. _psy_global_44,
  149419. _global_mapping_8,
  149420. _psy_stereo_modes_8,
  149421. _floor_books,
  149422. _floor,
  149423. _floor_mapping_8,
  149424. NULL,
  149425. _mapres_template_8_uncoupled
  149426. };
  149427. /********* End of inlined file: setup_8.h *********/
  149428. /********* Start of inlined file: setup_11.h *********/
  149429. /********* Start of inlined file: psych_11.h *********/
  149430. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  149431. static att3 _psy_tone_masteratt_11[3]={
  149432. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149433. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149434. {{ 20, 0, -14}, 0, 0}, /* 0 */
  149435. };
  149436. static vp_adjblock _vp_tonemask_adj_11[3]={
  149437. /* adjust for mode zero */
  149438. /* 63 125 250 500 1 2 4 8 16 */
  149439. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  149440. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  149441. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  149442. };
  149443. static noise3 _psy_noisebias_11[3]={
  149444. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149445. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149446. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  149447. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149448. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  149449. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  149450. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  149451. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  149452. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  149453. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  149454. };
  149455. static double _noise_thresh_11[3]={ .3,.5,.5 };
  149456. /********* End of inlined file: psych_11.h *********/
  149457. static int blocksize_11[2]={
  149458. 512,512
  149459. };
  149460. static int _floor_mapping_11[2]={
  149461. 6,6,
  149462. };
  149463. static double rate_mapping_11[3]={
  149464. 8000.,13000.,44000.,
  149465. };
  149466. static double rate_mapping_11_uncoupled[3]={
  149467. 12000.,20000.,50000.,
  149468. };
  149469. static double quality_mapping_11[3]={
  149470. -.1,.0,1.
  149471. };
  149472. ve_setup_data_template ve_setup_11_stereo={
  149473. 2,
  149474. rate_mapping_11,
  149475. quality_mapping_11,
  149476. 2,
  149477. 9000,
  149478. 15000,
  149479. blocksize_11,
  149480. blocksize_11,
  149481. _psy_tone_masteratt_11,
  149482. _psy_tone_0dB,
  149483. _psy_tone_suppress,
  149484. _vp_tonemask_adj_11,
  149485. NULL,
  149486. _vp_tonemask_adj_11,
  149487. _psy_noiseguards_8,
  149488. _psy_noisebias_11,
  149489. _psy_noisebias_11,
  149490. NULL,
  149491. NULL,
  149492. _psy_noise_suppress,
  149493. _psy_compand_8,
  149494. _psy_compand_8_mapping,
  149495. NULL,
  149496. {_noise_start_8,_noise_start_8},
  149497. {_noise_part_8,_noise_part_8},
  149498. _noise_thresh_11,
  149499. _psy_ath_floater_8,
  149500. _psy_ath_abs_8,
  149501. _psy_lowpass_11,
  149502. _psy_global_44,
  149503. _global_mapping_8,
  149504. _psy_stereo_modes_8,
  149505. _floor_books,
  149506. _floor,
  149507. _floor_mapping_11,
  149508. NULL,
  149509. _mapres_template_8_stereo
  149510. };
  149511. ve_setup_data_template ve_setup_11_uncoupled={
  149512. 2,
  149513. rate_mapping_11_uncoupled,
  149514. quality_mapping_11,
  149515. -1,
  149516. 9000,
  149517. 15000,
  149518. blocksize_11,
  149519. blocksize_11,
  149520. _psy_tone_masteratt_11,
  149521. _psy_tone_0dB,
  149522. _psy_tone_suppress,
  149523. _vp_tonemask_adj_11,
  149524. NULL,
  149525. _vp_tonemask_adj_11,
  149526. _psy_noiseguards_8,
  149527. _psy_noisebias_11,
  149528. _psy_noisebias_11,
  149529. NULL,
  149530. NULL,
  149531. _psy_noise_suppress,
  149532. _psy_compand_8,
  149533. _psy_compand_8_mapping,
  149534. NULL,
  149535. {_noise_start_8,_noise_start_8},
  149536. {_noise_part_8,_noise_part_8},
  149537. _noise_thresh_11,
  149538. _psy_ath_floater_8,
  149539. _psy_ath_abs_8,
  149540. _psy_lowpass_11,
  149541. _psy_global_44,
  149542. _global_mapping_8,
  149543. _psy_stereo_modes_8,
  149544. _floor_books,
  149545. _floor,
  149546. _floor_mapping_11,
  149547. NULL,
  149548. _mapres_template_8_uncoupled
  149549. };
  149550. /********* End of inlined file: setup_11.h *********/
  149551. /********* Start of inlined file: setup_16.h *********/
  149552. /********* Start of inlined file: psych_16.h *********/
  149553. /* stereo mode by base quality level */
  149554. static adj_stereo _psy_stereo_modes_16[4]={
  149555. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  149556. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149557. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149558. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  149559. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149560. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149561. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149562. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  149563. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149564. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149565. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  149566. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  149567. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149568. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149569. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  149570. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  149571. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  149572. };
  149573. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  149574. static att3 _psy_tone_masteratt_16[4]={
  149575. {{ 30, 25, 12}, 0, 0}, /* 0 */
  149576. {{ 25, 22, 12}, 0, 0}, /* 0 */
  149577. {{ 20, 12, 0}, 0, 0}, /* 0 */
  149578. {{ 15, 0, -14}, 0, 0}, /* 0 */
  149579. };
  149580. static vp_adjblock _vp_tonemask_adj_16[4]={
  149581. /* adjust for mode zero */
  149582. /* 63 125 250 500 1 2 4 8 16 */
  149583. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  149584. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  149585. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149586. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  149587. };
  149588. static noise3 _psy_noisebias_16_short[4]={
  149589. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149590. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149591. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149592. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149593. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149594. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  149595. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149596. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149597. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  149598. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149599. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149600. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149601. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149602. };
  149603. static noise3 _psy_noisebias_16_impulse[4]={
  149604. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149605. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  149606. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  149607. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149608. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  149609. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  149610. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  149611. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  149612. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  149613. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149614. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149615. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  149616. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149617. };
  149618. static noise3 _psy_noisebias_16[4]={
  149619. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  149620. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  149621. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149622. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149623. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  149624. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  149625. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  149626. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  149627. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  149628. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149629. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  149630. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  149631. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  149632. };
  149633. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  149634. static int _noise_start_16[3]={ 256,256,9999 };
  149635. static int _noise_part_16[4]={ 8,8,8,8 };
  149636. static int _psy_ath_floater_16[4]={
  149637. -100,-100,-100,-105,
  149638. };
  149639. static int _psy_ath_abs_16[4]={
  149640. -130,-130,-130,-140,
  149641. };
  149642. /********* End of inlined file: psych_16.h *********/
  149643. /********* Start of inlined file: residue_16.h *********/
  149644. /***** residue backends *********************************************/
  149645. static static_bookblock _resbook_16s_0={
  149646. {
  149647. {0},
  149648. {0,0,&_16c0_s_p1_0},
  149649. {0,0,&_16c0_s_p2_0},
  149650. {0,0,&_16c0_s_p3_0},
  149651. {0,0,&_16c0_s_p4_0},
  149652. {0,0,&_16c0_s_p5_0},
  149653. {0,0,&_16c0_s_p6_0},
  149654. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  149655. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  149656. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  149657. }
  149658. };
  149659. static static_bookblock _resbook_16s_1={
  149660. {
  149661. {0},
  149662. {0,0,&_16c1_s_p1_0},
  149663. {0,0,&_16c1_s_p2_0},
  149664. {0,0,&_16c1_s_p3_0},
  149665. {0,0,&_16c1_s_p4_0},
  149666. {0,0,&_16c1_s_p5_0},
  149667. {0,0,&_16c1_s_p6_0},
  149668. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  149669. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  149670. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  149671. }
  149672. };
  149673. static static_bookblock _resbook_16s_2={
  149674. {
  149675. {0},
  149676. {0,0,&_16c2_s_p1_0},
  149677. {0,0,&_16c2_s_p2_0},
  149678. {0,0,&_16c2_s_p3_0},
  149679. {0,0,&_16c2_s_p4_0},
  149680. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  149681. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  149682. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  149683. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  149684. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  149685. }
  149686. };
  149687. static vorbis_residue_template _res_16s_0[]={
  149688. {2,0, &_residue_44_mid,
  149689. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  149690. &_resbook_16s_0,&_resbook_16s_0},
  149691. };
  149692. static vorbis_residue_template _res_16s_1[]={
  149693. {2,0, &_residue_44_mid,
  149694. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  149695. &_resbook_16s_1,&_resbook_16s_1},
  149696. {2,0, &_residue_44_mid,
  149697. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  149698. &_resbook_16s_1,&_resbook_16s_1}
  149699. };
  149700. static vorbis_residue_template _res_16s_2[]={
  149701. {2,0, &_residue_44_high,
  149702. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  149703. &_resbook_16s_2,&_resbook_16s_2},
  149704. {2,0, &_residue_44_high,
  149705. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  149706. &_resbook_16s_2,&_resbook_16s_2}
  149707. };
  149708. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  149709. { _map_nominal, _res_16s_0 }, /* 0 */
  149710. { _map_nominal, _res_16s_1 }, /* 1 */
  149711. { _map_nominal, _res_16s_2 }, /* 2 */
  149712. };
  149713. static static_bookblock _resbook_16u_0={
  149714. {
  149715. {0},
  149716. {0,0,&_16u0__p1_0},
  149717. {0,0,&_16u0__p2_0},
  149718. {0,0,&_16u0__p3_0},
  149719. {0,0,&_16u0__p4_0},
  149720. {0,0,&_16u0__p5_0},
  149721. {&_16u0__p6_0,&_16u0__p6_1},
  149722. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  149723. }
  149724. };
  149725. static static_bookblock _resbook_16u_1={
  149726. {
  149727. {0},
  149728. {0,0,&_16u1__p1_0},
  149729. {0,0,&_16u1__p2_0},
  149730. {0,0,&_16u1__p3_0},
  149731. {0,0,&_16u1__p4_0},
  149732. {0,0,&_16u1__p5_0},
  149733. {0,0,&_16u1__p6_0},
  149734. {&_16u1__p7_0,&_16u1__p7_1},
  149735. {&_16u1__p8_0,&_16u1__p8_1},
  149736. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  149737. }
  149738. };
  149739. static static_bookblock _resbook_16u_2={
  149740. {
  149741. {0},
  149742. {0,0,&_16u2_p1_0},
  149743. {0,0,&_16u2_p2_0},
  149744. {0,0,&_16u2_p3_0},
  149745. {0,0,&_16u2_p4_0},
  149746. {&_16u2_p5_0,&_16u2_p5_1},
  149747. {&_16u2_p6_0,&_16u2_p6_1},
  149748. {&_16u2_p7_0,&_16u2_p7_1},
  149749. {&_16u2_p8_0,&_16u2_p8_1},
  149750. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  149751. }
  149752. };
  149753. static vorbis_residue_template _res_16u_0[]={
  149754. {1,0, &_residue_44_low_un,
  149755. &_huff_book__16u0__single,&_huff_book__16u0__single,
  149756. &_resbook_16u_0,&_resbook_16u_0},
  149757. };
  149758. static vorbis_residue_template _res_16u_1[]={
  149759. {1,0, &_residue_44_mid_un,
  149760. &_huff_book__16u1__short,&_huff_book__16u1__short,
  149761. &_resbook_16u_1,&_resbook_16u_1},
  149762. {1,0, &_residue_44_mid_un,
  149763. &_huff_book__16u1__long,&_huff_book__16u1__long,
  149764. &_resbook_16u_1,&_resbook_16u_1}
  149765. };
  149766. static vorbis_residue_template _res_16u_2[]={
  149767. {1,0, &_residue_44_hi_un,
  149768. &_huff_book__16u2__short,&_huff_book__16u2__short,
  149769. &_resbook_16u_2,&_resbook_16u_2},
  149770. {1,0, &_residue_44_hi_un,
  149771. &_huff_book__16u2__long,&_huff_book__16u2__long,
  149772. &_resbook_16u_2,&_resbook_16u_2}
  149773. };
  149774. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  149775. { _map_nominal_u, _res_16u_0 }, /* 0 */
  149776. { _map_nominal_u, _res_16u_1 }, /* 1 */
  149777. { _map_nominal_u, _res_16u_2 }, /* 2 */
  149778. };
  149779. /********* End of inlined file: residue_16.h *********/
  149780. static int blocksize_16_short[3]={
  149781. 1024,512,512
  149782. };
  149783. static int blocksize_16_long[3]={
  149784. 1024,1024,1024
  149785. };
  149786. static int _floor_mapping_16_short[3]={
  149787. 9,3,3
  149788. };
  149789. static int _floor_mapping_16[3]={
  149790. 9,9,9
  149791. };
  149792. static double rate_mapping_16[4]={
  149793. 12000.,20000.,44000.,86000.
  149794. };
  149795. static double rate_mapping_16_uncoupled[4]={
  149796. 16000.,28000.,64000.,100000.
  149797. };
  149798. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  149799. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  149800. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  149801. ve_setup_data_template ve_setup_16_stereo={
  149802. 3,
  149803. rate_mapping_16,
  149804. quality_mapping_16,
  149805. 2,
  149806. 15000,
  149807. 19000,
  149808. blocksize_16_short,
  149809. blocksize_16_long,
  149810. _psy_tone_masteratt_16,
  149811. _psy_tone_0dB,
  149812. _psy_tone_suppress,
  149813. _vp_tonemask_adj_16,
  149814. _vp_tonemask_adj_16,
  149815. _vp_tonemask_adj_16,
  149816. _psy_noiseguards_8,
  149817. _psy_noisebias_16_impulse,
  149818. _psy_noisebias_16_short,
  149819. _psy_noisebias_16_short,
  149820. _psy_noisebias_16,
  149821. _psy_noise_suppress,
  149822. _psy_compand_8,
  149823. _psy_compand_16_mapping,
  149824. _psy_compand_16_mapping,
  149825. {_noise_start_16,_noise_start_16},
  149826. { _noise_part_16, _noise_part_16},
  149827. _noise_thresh_16,
  149828. _psy_ath_floater_16,
  149829. _psy_ath_abs_16,
  149830. _psy_lowpass_16,
  149831. _psy_global_44,
  149832. _global_mapping_16,
  149833. _psy_stereo_modes_16,
  149834. _floor_books,
  149835. _floor,
  149836. _floor_mapping_16_short,
  149837. _floor_mapping_16,
  149838. _mapres_template_16_stereo
  149839. };
  149840. ve_setup_data_template ve_setup_16_uncoupled={
  149841. 3,
  149842. rate_mapping_16_uncoupled,
  149843. quality_mapping_16,
  149844. -1,
  149845. 15000,
  149846. 19000,
  149847. blocksize_16_short,
  149848. blocksize_16_long,
  149849. _psy_tone_masteratt_16,
  149850. _psy_tone_0dB,
  149851. _psy_tone_suppress,
  149852. _vp_tonemask_adj_16,
  149853. _vp_tonemask_adj_16,
  149854. _vp_tonemask_adj_16,
  149855. _psy_noiseguards_8,
  149856. _psy_noisebias_16_impulse,
  149857. _psy_noisebias_16_short,
  149858. _psy_noisebias_16_short,
  149859. _psy_noisebias_16,
  149860. _psy_noise_suppress,
  149861. _psy_compand_8,
  149862. _psy_compand_16_mapping,
  149863. _psy_compand_16_mapping,
  149864. {_noise_start_16,_noise_start_16},
  149865. { _noise_part_16, _noise_part_16},
  149866. _noise_thresh_16,
  149867. _psy_ath_floater_16,
  149868. _psy_ath_abs_16,
  149869. _psy_lowpass_16,
  149870. _psy_global_44,
  149871. _global_mapping_16,
  149872. _psy_stereo_modes_16,
  149873. _floor_books,
  149874. _floor,
  149875. _floor_mapping_16_short,
  149876. _floor_mapping_16,
  149877. _mapres_template_16_uncoupled
  149878. };
  149879. /********* End of inlined file: setup_16.h *********/
  149880. /********* Start of inlined file: setup_22.h *********/
  149881. static double rate_mapping_22[4]={
  149882. 15000.,20000.,44000.,86000.
  149883. };
  149884. static double rate_mapping_22_uncoupled[4]={
  149885. 16000.,28000.,50000.,90000.
  149886. };
  149887. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  149888. ve_setup_data_template ve_setup_22_stereo={
  149889. 3,
  149890. rate_mapping_22,
  149891. quality_mapping_16,
  149892. 2,
  149893. 19000,
  149894. 26000,
  149895. blocksize_16_short,
  149896. blocksize_16_long,
  149897. _psy_tone_masteratt_16,
  149898. _psy_tone_0dB,
  149899. _psy_tone_suppress,
  149900. _vp_tonemask_adj_16,
  149901. _vp_tonemask_adj_16,
  149902. _vp_tonemask_adj_16,
  149903. _psy_noiseguards_8,
  149904. _psy_noisebias_16_impulse,
  149905. _psy_noisebias_16_short,
  149906. _psy_noisebias_16_short,
  149907. _psy_noisebias_16,
  149908. _psy_noise_suppress,
  149909. _psy_compand_8,
  149910. _psy_compand_8_mapping,
  149911. _psy_compand_8_mapping,
  149912. {_noise_start_16,_noise_start_16},
  149913. { _noise_part_16, _noise_part_16},
  149914. _noise_thresh_16,
  149915. _psy_ath_floater_16,
  149916. _psy_ath_abs_16,
  149917. _psy_lowpass_22,
  149918. _psy_global_44,
  149919. _global_mapping_16,
  149920. _psy_stereo_modes_16,
  149921. _floor_books,
  149922. _floor,
  149923. _floor_mapping_16_short,
  149924. _floor_mapping_16,
  149925. _mapres_template_16_stereo
  149926. };
  149927. ve_setup_data_template ve_setup_22_uncoupled={
  149928. 3,
  149929. rate_mapping_22_uncoupled,
  149930. quality_mapping_16,
  149931. -1,
  149932. 19000,
  149933. 26000,
  149934. blocksize_16_short,
  149935. blocksize_16_long,
  149936. _psy_tone_masteratt_16,
  149937. _psy_tone_0dB,
  149938. _psy_tone_suppress,
  149939. _vp_tonemask_adj_16,
  149940. _vp_tonemask_adj_16,
  149941. _vp_tonemask_adj_16,
  149942. _psy_noiseguards_8,
  149943. _psy_noisebias_16_impulse,
  149944. _psy_noisebias_16_short,
  149945. _psy_noisebias_16_short,
  149946. _psy_noisebias_16,
  149947. _psy_noise_suppress,
  149948. _psy_compand_8,
  149949. _psy_compand_8_mapping,
  149950. _psy_compand_8_mapping,
  149951. {_noise_start_16,_noise_start_16},
  149952. { _noise_part_16, _noise_part_16},
  149953. _noise_thresh_16,
  149954. _psy_ath_floater_16,
  149955. _psy_ath_abs_16,
  149956. _psy_lowpass_22,
  149957. _psy_global_44,
  149958. _global_mapping_16,
  149959. _psy_stereo_modes_16,
  149960. _floor_books,
  149961. _floor,
  149962. _floor_mapping_16_short,
  149963. _floor_mapping_16,
  149964. _mapres_template_16_uncoupled
  149965. };
  149966. /********* End of inlined file: setup_22.h *********/
  149967. /********* Start of inlined file: setup_X.h *********/
  149968. static double rate_mapping_X[12]={
  149969. -1.,-1.,-1.,-1.,-1.,-1.,
  149970. -1.,-1.,-1.,-1.,-1.,-1.
  149971. };
  149972. ve_setup_data_template ve_setup_X_stereo={
  149973. 11,
  149974. rate_mapping_X,
  149975. quality_mapping_44,
  149976. 2,
  149977. 50000,
  149978. 200000,
  149979. blocksize_short_44,
  149980. blocksize_long_44,
  149981. _psy_tone_masteratt_44,
  149982. _psy_tone_0dB,
  149983. _psy_tone_suppress,
  149984. _vp_tonemask_adj_otherblock,
  149985. _vp_tonemask_adj_longblock,
  149986. _vp_tonemask_adj_otherblock,
  149987. _psy_noiseguards_44,
  149988. _psy_noisebias_impulse,
  149989. _psy_noisebias_padding,
  149990. _psy_noisebias_trans,
  149991. _psy_noisebias_long,
  149992. _psy_noise_suppress,
  149993. _psy_compand_44,
  149994. _psy_compand_short_mapping,
  149995. _psy_compand_long_mapping,
  149996. {_noise_start_short_44,_noise_start_long_44},
  149997. {_noise_part_short_44,_noise_part_long_44},
  149998. _noise_thresh_44,
  149999. _psy_ath_floater,
  150000. _psy_ath_abs,
  150001. _psy_lowpass_44,
  150002. _psy_global_44,
  150003. _global_mapping_44,
  150004. _psy_stereo_modes_44,
  150005. _floor_books,
  150006. _floor,
  150007. _floor_short_mapping_44,
  150008. _floor_long_mapping_44,
  150009. _mapres_template_44_stereo
  150010. };
  150011. ve_setup_data_template ve_setup_X_uncoupled={
  150012. 11,
  150013. rate_mapping_X,
  150014. quality_mapping_44,
  150015. -1,
  150016. 50000,
  150017. 200000,
  150018. blocksize_short_44,
  150019. blocksize_long_44,
  150020. _psy_tone_masteratt_44,
  150021. _psy_tone_0dB,
  150022. _psy_tone_suppress,
  150023. _vp_tonemask_adj_otherblock,
  150024. _vp_tonemask_adj_longblock,
  150025. _vp_tonemask_adj_otherblock,
  150026. _psy_noiseguards_44,
  150027. _psy_noisebias_impulse,
  150028. _psy_noisebias_padding,
  150029. _psy_noisebias_trans,
  150030. _psy_noisebias_long,
  150031. _psy_noise_suppress,
  150032. _psy_compand_44,
  150033. _psy_compand_short_mapping,
  150034. _psy_compand_long_mapping,
  150035. {_noise_start_short_44,_noise_start_long_44},
  150036. {_noise_part_short_44,_noise_part_long_44},
  150037. _noise_thresh_44,
  150038. _psy_ath_floater,
  150039. _psy_ath_abs,
  150040. _psy_lowpass_44,
  150041. _psy_global_44,
  150042. _global_mapping_44,
  150043. NULL,
  150044. _floor_books,
  150045. _floor,
  150046. _floor_short_mapping_44,
  150047. _floor_long_mapping_44,
  150048. _mapres_template_44_uncoupled
  150049. };
  150050. ve_setup_data_template ve_setup_XX_stereo={
  150051. 2,
  150052. rate_mapping_X,
  150053. quality_mapping_8,
  150054. 2,
  150055. 0,
  150056. 8000,
  150057. blocksize_8,
  150058. blocksize_8,
  150059. _psy_tone_masteratt_8,
  150060. _psy_tone_0dB,
  150061. _psy_tone_suppress,
  150062. _vp_tonemask_adj_8,
  150063. NULL,
  150064. _vp_tonemask_adj_8,
  150065. _psy_noiseguards_8,
  150066. _psy_noisebias_8,
  150067. _psy_noisebias_8,
  150068. NULL,
  150069. NULL,
  150070. _psy_noise_suppress,
  150071. _psy_compand_8,
  150072. _psy_compand_8_mapping,
  150073. NULL,
  150074. {_noise_start_8,_noise_start_8},
  150075. {_noise_part_8,_noise_part_8},
  150076. _noise_thresh_5only,
  150077. _psy_ath_floater_8,
  150078. _psy_ath_abs_8,
  150079. _psy_lowpass_8,
  150080. _psy_global_44,
  150081. _global_mapping_8,
  150082. _psy_stereo_modes_8,
  150083. _floor_books,
  150084. _floor,
  150085. _floor_mapping_8,
  150086. NULL,
  150087. _mapres_template_8_stereo
  150088. };
  150089. ve_setup_data_template ve_setup_XX_uncoupled={
  150090. 2,
  150091. rate_mapping_X,
  150092. quality_mapping_8,
  150093. -1,
  150094. 0,
  150095. 8000,
  150096. blocksize_8,
  150097. blocksize_8,
  150098. _psy_tone_masteratt_8,
  150099. _psy_tone_0dB,
  150100. _psy_tone_suppress,
  150101. _vp_tonemask_adj_8,
  150102. NULL,
  150103. _vp_tonemask_adj_8,
  150104. _psy_noiseguards_8,
  150105. _psy_noisebias_8,
  150106. _psy_noisebias_8,
  150107. NULL,
  150108. NULL,
  150109. _psy_noise_suppress,
  150110. _psy_compand_8,
  150111. _psy_compand_8_mapping,
  150112. NULL,
  150113. {_noise_start_8,_noise_start_8},
  150114. {_noise_part_8,_noise_part_8},
  150115. _noise_thresh_5only,
  150116. _psy_ath_floater_8,
  150117. _psy_ath_abs_8,
  150118. _psy_lowpass_8,
  150119. _psy_global_44,
  150120. _global_mapping_8,
  150121. _psy_stereo_modes_8,
  150122. _floor_books,
  150123. _floor,
  150124. _floor_mapping_8,
  150125. NULL,
  150126. _mapres_template_8_uncoupled
  150127. };
  150128. /********* End of inlined file: setup_X.h *********/
  150129. static ve_setup_data_template *setup_list[]={
  150130. &ve_setup_44_stereo,
  150131. &ve_setup_44_uncoupled,
  150132. &ve_setup_32_stereo,
  150133. &ve_setup_32_uncoupled,
  150134. &ve_setup_22_stereo,
  150135. &ve_setup_22_uncoupled,
  150136. &ve_setup_16_stereo,
  150137. &ve_setup_16_uncoupled,
  150138. &ve_setup_11_stereo,
  150139. &ve_setup_11_uncoupled,
  150140. &ve_setup_8_stereo,
  150141. &ve_setup_8_uncoupled,
  150142. &ve_setup_X_stereo,
  150143. &ve_setup_X_uncoupled,
  150144. &ve_setup_XX_stereo,
  150145. &ve_setup_XX_uncoupled,
  150146. 0
  150147. };
  150148. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  150149. if(vi && vi->codec_setup){
  150150. vi->version=0;
  150151. vi->channels=ch;
  150152. vi->rate=rate;
  150153. return(0);
  150154. }
  150155. return(OV_EINVAL);
  150156. }
  150157. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  150158. static_codebook ***books,
  150159. vorbis_info_floor1 *in,
  150160. int *x){
  150161. int i,k,is=s;
  150162. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  150163. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150164. memcpy(f,in+x[is],sizeof(*f));
  150165. /* fill in the lowpass field, even if it's temporary */
  150166. f->n=ci->blocksizes[block]>>1;
  150167. /* books */
  150168. {
  150169. int partitions=f->partitions;
  150170. int maxclass=-1;
  150171. int maxbook=-1;
  150172. for(i=0;i<partitions;i++)
  150173. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  150174. for(i=0;i<=maxclass;i++){
  150175. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  150176. f->class_book[i]+=ci->books;
  150177. for(k=0;k<(1<<f->class_subs[i]);k++){
  150178. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  150179. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  150180. }
  150181. }
  150182. for(i=0;i<=maxbook;i++)
  150183. ci->book_param[ci->books++]=books[x[is]][i];
  150184. }
  150185. /* for now, we're only using floor 1 */
  150186. ci->floor_type[ci->floors]=1;
  150187. ci->floor_param[ci->floors]=f;
  150188. ci->floors++;
  150189. return;
  150190. }
  150191. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  150192. vorbis_info_psy_global *in,
  150193. double *x){
  150194. int i,is=s;
  150195. double ds=s-is;
  150196. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150197. vorbis_info_psy_global *g=&ci->psy_g_param;
  150198. memcpy(g,in+(int)x[is],sizeof(*g));
  150199. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150200. is=(int)ds;
  150201. ds-=is;
  150202. if(ds==0 && is>0){
  150203. is--;
  150204. ds=1.;
  150205. }
  150206. /* interpolate the trigger threshholds */
  150207. for(i=0;i<4;i++){
  150208. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  150209. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  150210. }
  150211. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  150212. return;
  150213. }
  150214. static void vorbis_encode_global_stereo(vorbis_info *vi,
  150215. highlevel_encode_setup *hi,
  150216. adj_stereo *p){
  150217. float s=hi->stereo_point_setting;
  150218. int i,is=s;
  150219. double ds=s-is;
  150220. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150221. vorbis_info_psy_global *g=&ci->psy_g_param;
  150222. if(p){
  150223. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  150224. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  150225. if(hi->managed){
  150226. /* interpolate the kHz threshholds */
  150227. for(i=0;i<PACKETBLOBS;i++){
  150228. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  150229. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150230. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150231. g->coupling_pkHz[i]=kHz;
  150232. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  150233. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150234. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150235. }
  150236. }else{
  150237. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  150238. for(i=0;i<PACKETBLOBS;i++){
  150239. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150240. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150241. g->coupling_pkHz[i]=kHz;
  150242. }
  150243. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  150244. for(i=0;i<PACKETBLOBS;i++){
  150245. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  150246. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  150247. }
  150248. }
  150249. }else{
  150250. for(i=0;i<PACKETBLOBS;i++){
  150251. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  150252. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  150253. }
  150254. }
  150255. return;
  150256. }
  150257. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  150258. int *nn_start,
  150259. int *nn_partition,
  150260. double *nn_thresh,
  150261. int block){
  150262. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150263. vorbis_info_psy *p=ci->psy_param[block];
  150264. highlevel_encode_setup *hi=&ci->hi;
  150265. int is=s;
  150266. if(block>=ci->psys)
  150267. ci->psys=block+1;
  150268. if(!p){
  150269. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  150270. ci->psy_param[block]=p;
  150271. }
  150272. memcpy(p,&_psy_info_template,sizeof(*p));
  150273. p->blockflag=block>>1;
  150274. if(hi->noise_normalize_p){
  150275. p->normal_channel_p=1;
  150276. p->normal_point_p=1;
  150277. p->normal_start=nn_start[is];
  150278. p->normal_partition=nn_partition[is];
  150279. p->normal_thresh=nn_thresh[is];
  150280. }
  150281. return;
  150282. }
  150283. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  150284. att3 *att,
  150285. int *max,
  150286. vp_adjblock *in){
  150287. int i,is=s;
  150288. double ds=s-is;
  150289. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150290. vorbis_info_psy *p=ci->psy_param[block];
  150291. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  150292. filling the values in here */
  150293. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  150294. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  150295. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  150296. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  150297. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  150298. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  150299. for(i=0;i<P_BANDS;i++)
  150300. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  150301. return;
  150302. }
  150303. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  150304. compandblock *in, double *x){
  150305. int i,is=s;
  150306. double ds=s-is;
  150307. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150308. vorbis_info_psy *p=ci->psy_param[block];
  150309. ds=x[is]*(1.-ds)+x[is+1]*ds;
  150310. is=(int)ds;
  150311. ds-=is;
  150312. if(ds==0 && is>0){
  150313. is--;
  150314. ds=1.;
  150315. }
  150316. /* interpolate the compander settings */
  150317. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  150318. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  150319. return;
  150320. }
  150321. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  150322. int *suppress){
  150323. int is=s;
  150324. double ds=s-is;
  150325. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150326. vorbis_info_psy *p=ci->psy_param[block];
  150327. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150328. return;
  150329. }
  150330. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  150331. int *suppress,
  150332. noise3 *in,
  150333. noiseguard *guard,
  150334. double userbias){
  150335. int i,is=s,j;
  150336. double ds=s-is;
  150337. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150338. vorbis_info_psy *p=ci->psy_param[block];
  150339. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  150340. p->noisewindowlomin=guard[block].lo;
  150341. p->noisewindowhimin=guard[block].hi;
  150342. p->noisewindowfixed=guard[block].fixed;
  150343. for(j=0;j<P_NOISECURVES;j++)
  150344. for(i=0;i<P_BANDS;i++)
  150345. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  150346. /* impulse blocks may take a user specified bias to boost the
  150347. nominal/high noise encoding depth */
  150348. for(j=0;j<P_NOISECURVES;j++){
  150349. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  150350. for(i=0;i<P_BANDS;i++){
  150351. p->noiseoff[j][i]+=userbias;
  150352. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  150353. }
  150354. }
  150355. return;
  150356. }
  150357. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  150358. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150359. vorbis_info_psy *p=ci->psy_param[block];
  150360. p->ath_adjatt=ci->hi.ath_floating_dB;
  150361. p->ath_maxatt=ci->hi.ath_absolute_dB;
  150362. return;
  150363. }
  150364. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  150365. int i;
  150366. for(i=0;i<ci->books;i++)
  150367. if(ci->book_param[i]==book)return(i);
  150368. return(ci->books++);
  150369. }
  150370. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  150371. int *shortb,int *longb){
  150372. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150373. int is=s;
  150374. int blockshort=shortb[is];
  150375. int blocklong=longb[is];
  150376. ci->blocksizes[0]=blockshort;
  150377. ci->blocksizes[1]=blocklong;
  150378. }
  150379. static void vorbis_encode_residue_setup(vorbis_info *vi,
  150380. int number, int block,
  150381. vorbis_residue_template *res){
  150382. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150383. int i,n;
  150384. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  150385. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  150386. memcpy(r,res->res,sizeof(*r));
  150387. if(ci->residues<=number)ci->residues=number+1;
  150388. switch(ci->blocksizes[block]){
  150389. case 64:case 128:case 256:
  150390. r->grouping=16;
  150391. break;
  150392. default:
  150393. r->grouping=32;
  150394. break;
  150395. }
  150396. ci->residue_type[number]=res->res_type;
  150397. /* to be adjusted by lowpass/pointlimit later */
  150398. n=r->end=ci->blocksizes[block]>>1;
  150399. if(res->res_type==2)
  150400. n=r->end*=vi->channels;
  150401. /* fill in all the books */
  150402. {
  150403. int booklist=0,k;
  150404. if(ci->hi.managed){
  150405. for(i=0;i<r->partitions;i++)
  150406. for(k=0;k<3;k++)
  150407. if(res->books_base_managed->books[i][k])
  150408. r->secondstages[i]|=(1<<k);
  150409. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  150410. ci->book_param[r->groupbook]=res->book_aux_managed;
  150411. for(i=0;i<r->partitions;i++){
  150412. for(k=0;k<3;k++){
  150413. if(res->books_base_managed->books[i][k]){
  150414. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  150415. r->booklist[booklist++]=bookid;
  150416. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  150417. }
  150418. }
  150419. }
  150420. }else{
  150421. for(i=0;i<r->partitions;i++)
  150422. for(k=0;k<3;k++)
  150423. if(res->books_base->books[i][k])
  150424. r->secondstages[i]|=(1<<k);
  150425. r->groupbook=book_dup_or_new(ci,res->book_aux);
  150426. ci->book_param[r->groupbook]=res->book_aux;
  150427. for(i=0;i<r->partitions;i++){
  150428. for(k=0;k<3;k++){
  150429. if(res->books_base->books[i][k]){
  150430. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  150431. r->booklist[booklist++]=bookid;
  150432. ci->book_param[bookid]=res->books_base->books[i][k];
  150433. }
  150434. }
  150435. }
  150436. }
  150437. }
  150438. /* lowpass setup/pointlimit */
  150439. {
  150440. double freq=ci->hi.lowpass_kHz*1000.;
  150441. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  150442. double nyq=vi->rate/2.;
  150443. long blocksize=ci->blocksizes[block]>>1;
  150444. /* lowpass needs to be set in the floor and the residue. */
  150445. if(freq>nyq)freq=nyq;
  150446. /* in the floor, the granularity can be very fine; it doesn't alter
  150447. the encoding structure, only the samples used to fit the floor
  150448. approximation */
  150449. f->n=freq/nyq*blocksize;
  150450. /* this res may by limited by the maximum pointlimit of the mode,
  150451. not the lowpass. the floor is always lowpass limited. */
  150452. if(res->limit_type){
  150453. if(ci->hi.managed)
  150454. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  150455. else
  150456. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  150457. if(freq>nyq)freq=nyq;
  150458. }
  150459. /* in the residue, we're constrained, physically, by partition
  150460. boundaries. We still lowpass 'wherever', but we have to round up
  150461. here to next boundary, or the vorbis spec will round it *down* to
  150462. previous boundary in encode/decode */
  150463. if(ci->residue_type[block]==2)
  150464. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  150465. r->grouping;
  150466. else
  150467. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  150468. r->grouping;
  150469. }
  150470. }
  150471. /* we assume two maps in this encoder */
  150472. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  150473. vorbis_mapping_template *maps){
  150474. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150475. int i,j,is=s,modes=2;
  150476. vorbis_info_mapping0 *map=maps[is].map;
  150477. vorbis_info_mode *mode=_mode_template;
  150478. vorbis_residue_template *res=maps[is].res;
  150479. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  150480. for(i=0;i<modes;i++){
  150481. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  150482. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  150483. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  150484. if(i>=ci->modes)ci->modes=i+1;
  150485. ci->map_type[i]=0;
  150486. memcpy(ci->map_param[i],map+i,sizeof(*map));
  150487. if(i>=ci->maps)ci->maps=i+1;
  150488. for(j=0;j<map[i].submaps;j++)
  150489. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  150490. ,res+map[i].residuesubmap[j]);
  150491. }
  150492. }
  150493. static double setting_to_approx_bitrate(vorbis_info *vi){
  150494. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150495. highlevel_encode_setup *hi=&ci->hi;
  150496. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  150497. int is=hi->base_setting;
  150498. double ds=hi->base_setting-is;
  150499. int ch=vi->channels;
  150500. double *r=setup->rate_mapping;
  150501. if(r==NULL)
  150502. return(-1);
  150503. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  150504. }
  150505. static void get_setup_template(vorbis_info *vi,
  150506. long ch,long srate,
  150507. double req,int q_or_bitrate){
  150508. int i=0,j;
  150509. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150510. highlevel_encode_setup *hi=&ci->hi;
  150511. if(q_or_bitrate)req/=ch;
  150512. while(setup_list[i]){
  150513. if(setup_list[i]->coupling_restriction==-1 ||
  150514. setup_list[i]->coupling_restriction==ch){
  150515. if(srate>=setup_list[i]->samplerate_min_restriction &&
  150516. srate<=setup_list[i]->samplerate_max_restriction){
  150517. int mappings=setup_list[i]->mappings;
  150518. double *map=(q_or_bitrate?
  150519. setup_list[i]->rate_mapping:
  150520. setup_list[i]->quality_mapping);
  150521. /* the template matches. Does the requested quality mode
  150522. fall within this template's modes? */
  150523. if(req<map[0]){++i;continue;}
  150524. if(req>map[setup_list[i]->mappings]){++i;continue;}
  150525. for(j=0;j<mappings;j++)
  150526. if(req>=map[j] && req<map[j+1])break;
  150527. /* an all-points match */
  150528. hi->setup=setup_list[i];
  150529. if(j==mappings)
  150530. hi->base_setting=j-.001;
  150531. else{
  150532. float low=map[j];
  150533. float high=map[j+1];
  150534. float del=(req-low)/(high-low);
  150535. hi->base_setting=j+del;
  150536. }
  150537. return;
  150538. }
  150539. }
  150540. i++;
  150541. }
  150542. hi->setup=NULL;
  150543. }
  150544. /* encoders will need to use vorbis_info_init beforehand and call
  150545. vorbis_info clear when all done */
  150546. /* two interfaces; this, more detailed one, and later a convenience
  150547. layer on top */
  150548. /* the final setup call */
  150549. int vorbis_encode_setup_init(vorbis_info *vi){
  150550. int i0=0,singleblock=0;
  150551. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150552. ve_setup_data_template *setup=NULL;
  150553. highlevel_encode_setup *hi=&ci->hi;
  150554. if(ci==NULL)return(OV_EINVAL);
  150555. if(!hi->impulse_block_p)i0=1;
  150556. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  150557. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  150558. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  150559. /* again, bound this to avoid the app shooting itself int he foot
  150560. too badly */
  150561. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  150562. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  150563. /* get the appropriate setup template; matches the fetch in previous
  150564. stages */
  150565. setup=(ve_setup_data_template *)hi->setup;
  150566. if(setup==NULL)return(OV_EINVAL);
  150567. hi->set_in_stone=1;
  150568. /* choose block sizes from configured sizes as well as paying
  150569. attention to long_block_p and short_block_p. If the configured
  150570. short and long blocks are the same length, we set long_block_p
  150571. and unset short_block_p */
  150572. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  150573. setup->blocksize_short,
  150574. setup->blocksize_long);
  150575. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  150576. /* floor setup; choose proper floor params. Allocated on the floor
  150577. stack in order; if we alloc only long floor, it's 0 */
  150578. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  150579. setup->floor_books,
  150580. setup->floor_params,
  150581. setup->floor_short_mapping);
  150582. if(!singleblock)
  150583. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  150584. setup->floor_books,
  150585. setup->floor_params,
  150586. setup->floor_long_mapping);
  150587. /* setup of [mostly] short block detection and stereo*/
  150588. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  150589. setup->global_params,
  150590. setup->global_mapping);
  150591. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  150592. /* basic psych setup and noise normalization */
  150593. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150594. setup->psy_noise_normal_start[0],
  150595. setup->psy_noise_normal_partition[0],
  150596. setup->psy_noise_normal_thresh,
  150597. 0);
  150598. vorbis_encode_psyset_setup(vi,hi->short_setting,
  150599. setup->psy_noise_normal_start[0],
  150600. setup->psy_noise_normal_partition[0],
  150601. setup->psy_noise_normal_thresh,
  150602. 1);
  150603. if(!singleblock){
  150604. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150605. setup->psy_noise_normal_start[1],
  150606. setup->psy_noise_normal_partition[1],
  150607. setup->psy_noise_normal_thresh,
  150608. 2);
  150609. vorbis_encode_psyset_setup(vi,hi->long_setting,
  150610. setup->psy_noise_normal_start[1],
  150611. setup->psy_noise_normal_partition[1],
  150612. setup->psy_noise_normal_thresh,
  150613. 3);
  150614. }
  150615. /* tone masking setup */
  150616. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  150617. setup->psy_tone_masteratt,
  150618. setup->psy_tone_0dB,
  150619. setup->psy_tone_adj_impulse);
  150620. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  150621. setup->psy_tone_masteratt,
  150622. setup->psy_tone_0dB,
  150623. setup->psy_tone_adj_other);
  150624. if(!singleblock){
  150625. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  150626. setup->psy_tone_masteratt,
  150627. setup->psy_tone_0dB,
  150628. setup->psy_tone_adj_other);
  150629. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  150630. setup->psy_tone_masteratt,
  150631. setup->psy_tone_0dB,
  150632. setup->psy_tone_adj_long);
  150633. }
  150634. /* noise companding setup */
  150635. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  150636. setup->psy_noise_compand,
  150637. setup->psy_noise_compand_short_mapping);
  150638. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  150639. setup->psy_noise_compand,
  150640. setup->psy_noise_compand_short_mapping);
  150641. if(!singleblock){
  150642. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  150643. setup->psy_noise_compand,
  150644. setup->psy_noise_compand_long_mapping);
  150645. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  150646. setup->psy_noise_compand,
  150647. setup->psy_noise_compand_long_mapping);
  150648. }
  150649. /* peak guarding setup */
  150650. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  150651. setup->psy_tone_dBsuppress);
  150652. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  150653. setup->psy_tone_dBsuppress);
  150654. if(!singleblock){
  150655. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  150656. setup->psy_tone_dBsuppress);
  150657. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  150658. setup->psy_tone_dBsuppress);
  150659. }
  150660. /* noise bias setup */
  150661. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  150662. setup->psy_noise_dBsuppress,
  150663. setup->psy_noise_bias_impulse,
  150664. setup->psy_noiseguards,
  150665. (i0==0?hi->impulse_noisetune:0.));
  150666. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  150667. setup->psy_noise_dBsuppress,
  150668. setup->psy_noise_bias_padding,
  150669. setup->psy_noiseguards,0.);
  150670. if(!singleblock){
  150671. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  150672. setup->psy_noise_dBsuppress,
  150673. setup->psy_noise_bias_trans,
  150674. setup->psy_noiseguards,0.);
  150675. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  150676. setup->psy_noise_dBsuppress,
  150677. setup->psy_noise_bias_long,
  150678. setup->psy_noiseguards,0.);
  150679. }
  150680. vorbis_encode_ath_setup(vi,0);
  150681. vorbis_encode_ath_setup(vi,1);
  150682. if(!singleblock){
  150683. vorbis_encode_ath_setup(vi,2);
  150684. vorbis_encode_ath_setup(vi,3);
  150685. }
  150686. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  150687. /* set bitrate readonlies and management */
  150688. if(hi->bitrate_av>0)
  150689. vi->bitrate_nominal=hi->bitrate_av;
  150690. else{
  150691. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  150692. }
  150693. vi->bitrate_lower=hi->bitrate_min;
  150694. vi->bitrate_upper=hi->bitrate_max;
  150695. if(hi->bitrate_av)
  150696. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  150697. else
  150698. vi->bitrate_window=0.;
  150699. if(hi->managed){
  150700. ci->bi.avg_rate=hi->bitrate_av;
  150701. ci->bi.min_rate=hi->bitrate_min;
  150702. ci->bi.max_rate=hi->bitrate_max;
  150703. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  150704. ci->bi.reservoir_bias=
  150705. hi->bitrate_reservoir_bias;
  150706. ci->bi.slew_damp=hi->bitrate_av_damp;
  150707. }
  150708. return(0);
  150709. }
  150710. static int vorbis_encode_setup_setting(vorbis_info *vi,
  150711. long channels,
  150712. long rate){
  150713. int ret=0,i,is;
  150714. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150715. highlevel_encode_setup *hi=&ci->hi;
  150716. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  150717. double ds;
  150718. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  150719. if(ret)return(ret);
  150720. is=hi->base_setting;
  150721. ds=hi->base_setting-is;
  150722. hi->short_setting=hi->base_setting;
  150723. hi->long_setting=hi->base_setting;
  150724. hi->managed=0;
  150725. hi->impulse_block_p=1;
  150726. hi->noise_normalize_p=1;
  150727. hi->stereo_point_setting=hi->base_setting;
  150728. hi->lowpass_kHz=
  150729. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  150730. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  150731. setup->psy_ath_float[is+1]*ds;
  150732. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  150733. setup->psy_ath_abs[is+1]*ds;
  150734. hi->amplitude_track_dBpersec=-6.;
  150735. hi->trigger_setting=hi->base_setting;
  150736. for(i=0;i<4;i++){
  150737. hi->block[i].tone_mask_setting=hi->base_setting;
  150738. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  150739. hi->block[i].noise_bias_setting=hi->base_setting;
  150740. hi->block[i].noise_compand_setting=hi->base_setting;
  150741. }
  150742. return(ret);
  150743. }
  150744. int vorbis_encode_setup_vbr(vorbis_info *vi,
  150745. long channels,
  150746. long rate,
  150747. float quality){
  150748. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  150749. highlevel_encode_setup *hi=&ci->hi;
  150750. quality+=.0000001;
  150751. if(quality>=1.)quality=.9999;
  150752. get_setup_template(vi,channels,rate,quality,0);
  150753. if(!hi->setup)return OV_EIMPL;
  150754. return vorbis_encode_setup_setting(vi,channels,rate);
  150755. }
  150756. int vorbis_encode_init_vbr(vorbis_info *vi,
  150757. long channels,
  150758. long rate,
  150759. float base_quality /* 0. to 1. */
  150760. ){
  150761. int ret=0;
  150762. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  150763. if(ret){
  150764. vorbis_info_clear(vi);
  150765. return ret;
  150766. }
  150767. ret=vorbis_encode_setup_init(vi);
  150768. if(ret)
  150769. vorbis_info_clear(vi);
  150770. return(ret);
  150771. }
  150772. int vorbis_encode_setup_managed(vorbis_info *vi,
  150773. long channels,
  150774. long rate,
  150775. long max_bitrate,
  150776. long nominal_bitrate,
  150777. long min_bitrate){
  150778. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150779. highlevel_encode_setup *hi=&ci->hi;
  150780. double tnominal=nominal_bitrate;
  150781. int ret=0;
  150782. if(nominal_bitrate<=0.){
  150783. if(max_bitrate>0.){
  150784. if(min_bitrate>0.)
  150785. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  150786. else
  150787. nominal_bitrate=max_bitrate*.875;
  150788. }else{
  150789. if(min_bitrate>0.){
  150790. nominal_bitrate=min_bitrate;
  150791. }else{
  150792. return(OV_EINVAL);
  150793. }
  150794. }
  150795. }
  150796. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  150797. if(!hi->setup)return OV_EIMPL;
  150798. ret=vorbis_encode_setup_setting(vi,channels,rate);
  150799. if(ret){
  150800. vorbis_info_clear(vi);
  150801. return ret;
  150802. }
  150803. /* initialize management with sane defaults */
  150804. hi->managed=1;
  150805. hi->bitrate_min=min_bitrate;
  150806. hi->bitrate_max=max_bitrate;
  150807. hi->bitrate_av=tnominal;
  150808. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  150809. hi->bitrate_reservoir=nominal_bitrate*2;
  150810. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  150811. return(ret);
  150812. }
  150813. int vorbis_encode_init(vorbis_info *vi,
  150814. long channels,
  150815. long rate,
  150816. long max_bitrate,
  150817. long nominal_bitrate,
  150818. long min_bitrate){
  150819. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  150820. max_bitrate,
  150821. nominal_bitrate,
  150822. min_bitrate);
  150823. if(ret){
  150824. vorbis_info_clear(vi);
  150825. return(ret);
  150826. }
  150827. ret=vorbis_encode_setup_init(vi);
  150828. if(ret)
  150829. vorbis_info_clear(vi);
  150830. return(ret);
  150831. }
  150832. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  150833. if(vi){
  150834. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  150835. highlevel_encode_setup *hi=&ci->hi;
  150836. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  150837. if(setp && hi->set_in_stone)return(OV_EINVAL);
  150838. switch(number){
  150839. /* now deprecated *****************/
  150840. case OV_ECTL_RATEMANAGE_GET:
  150841. {
  150842. struct ovectl_ratemanage_arg *ai=
  150843. (struct ovectl_ratemanage_arg *)arg;
  150844. ai->management_active=hi->managed;
  150845. ai->bitrate_hard_window=ai->bitrate_av_window=
  150846. (double)hi->bitrate_reservoir/vi->rate;
  150847. ai->bitrate_av_window_center=1.;
  150848. ai->bitrate_hard_min=hi->bitrate_min;
  150849. ai->bitrate_hard_max=hi->bitrate_max;
  150850. ai->bitrate_av_lo=hi->bitrate_av;
  150851. ai->bitrate_av_hi=hi->bitrate_av;
  150852. }
  150853. return(0);
  150854. /* now deprecated *****************/
  150855. case OV_ECTL_RATEMANAGE_SET:
  150856. {
  150857. struct ovectl_ratemanage_arg *ai=
  150858. (struct ovectl_ratemanage_arg *)arg;
  150859. if(ai==NULL){
  150860. hi->managed=0;
  150861. }else{
  150862. hi->managed=ai->management_active;
  150863. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  150864. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  150865. }
  150866. }
  150867. return 0;
  150868. /* now deprecated *****************/
  150869. case OV_ECTL_RATEMANAGE_AVG:
  150870. {
  150871. struct ovectl_ratemanage_arg *ai=
  150872. (struct ovectl_ratemanage_arg *)arg;
  150873. if(ai==NULL){
  150874. hi->bitrate_av=0;
  150875. }else{
  150876. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  150877. }
  150878. }
  150879. return(0);
  150880. /* now deprecated *****************/
  150881. case OV_ECTL_RATEMANAGE_HARD:
  150882. {
  150883. struct ovectl_ratemanage_arg *ai=
  150884. (struct ovectl_ratemanage_arg *)arg;
  150885. if(ai==NULL){
  150886. hi->bitrate_min=0;
  150887. hi->bitrate_max=0;
  150888. }else{
  150889. hi->bitrate_min=ai->bitrate_hard_min;
  150890. hi->bitrate_max=ai->bitrate_hard_max;
  150891. hi->bitrate_reservoir=ai->bitrate_hard_window*
  150892. (hi->bitrate_max+hi->bitrate_min)*.5;
  150893. }
  150894. if(hi->bitrate_reservoir<128.)
  150895. hi->bitrate_reservoir=128.;
  150896. }
  150897. return(0);
  150898. /* replacement ratemanage interface */
  150899. case OV_ECTL_RATEMANAGE2_GET:
  150900. {
  150901. struct ovectl_ratemanage2_arg *ai=
  150902. (struct ovectl_ratemanage2_arg *)arg;
  150903. if(ai==NULL)return OV_EINVAL;
  150904. ai->management_active=hi->managed;
  150905. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  150906. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  150907. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  150908. ai->bitrate_average_damping=hi->bitrate_av_damp;
  150909. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  150910. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  150911. }
  150912. return (0);
  150913. case OV_ECTL_RATEMANAGE2_SET:
  150914. {
  150915. struct ovectl_ratemanage2_arg *ai=
  150916. (struct ovectl_ratemanage2_arg *)arg;
  150917. if(ai==NULL){
  150918. hi->managed=0;
  150919. }else{
  150920. /* sanity check; only catch invariant violations */
  150921. if(ai->bitrate_limit_min_kbps>0 &&
  150922. ai->bitrate_average_kbps>0 &&
  150923. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  150924. return OV_EINVAL;
  150925. if(ai->bitrate_limit_max_kbps>0 &&
  150926. ai->bitrate_average_kbps>0 &&
  150927. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  150928. return OV_EINVAL;
  150929. if(ai->bitrate_limit_min_kbps>0 &&
  150930. ai->bitrate_limit_max_kbps>0 &&
  150931. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  150932. return OV_EINVAL;
  150933. if(ai->bitrate_average_damping <= 0.)
  150934. return OV_EINVAL;
  150935. if(ai->bitrate_limit_reservoir_bits < 0)
  150936. return OV_EINVAL;
  150937. if(ai->bitrate_limit_reservoir_bias < 0.)
  150938. return OV_EINVAL;
  150939. if(ai->bitrate_limit_reservoir_bias > 1.)
  150940. return OV_EINVAL;
  150941. hi->managed=ai->management_active;
  150942. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  150943. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  150944. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  150945. hi->bitrate_av_damp=ai->bitrate_average_damping;
  150946. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  150947. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  150948. }
  150949. }
  150950. return 0;
  150951. case OV_ECTL_LOWPASS_GET:
  150952. {
  150953. double *farg=(double *)arg;
  150954. *farg=hi->lowpass_kHz;
  150955. }
  150956. return(0);
  150957. case OV_ECTL_LOWPASS_SET:
  150958. {
  150959. double *farg=(double *)arg;
  150960. hi->lowpass_kHz=*farg;
  150961. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  150962. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  150963. }
  150964. return(0);
  150965. case OV_ECTL_IBLOCK_GET:
  150966. {
  150967. double *farg=(double *)arg;
  150968. *farg=hi->impulse_noisetune;
  150969. }
  150970. return(0);
  150971. case OV_ECTL_IBLOCK_SET:
  150972. {
  150973. double *farg=(double *)arg;
  150974. hi->impulse_noisetune=*farg;
  150975. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  150976. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  150977. }
  150978. return(0);
  150979. }
  150980. return(OV_EIMPL);
  150981. }
  150982. return(OV_EINVAL);
  150983. }
  150984. #endif
  150985. /********* End of inlined file: vorbisenc.c *********/
  150986. /********* Start of inlined file: vorbisfile.c *********/
  150987. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  150988. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  150989. // tasks..
  150990. #ifdef _MSC_VER
  150991. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  150992. #endif
  150993. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  150994. #if JUCE_USE_OGGVORBIS
  150995. #include <stdlib.h>
  150996. #include <stdio.h>
  150997. #include <errno.h>
  150998. #include <string.h>
  150999. #include <math.h>
  151000. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  151001. one logical bitstream arranged end to end (the only form of Ogg
  151002. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  151003. multiplexing] is not allowed in Vorbis) */
  151004. /* A Vorbis file can be played beginning to end (streamed) without
  151005. worrying ahead of time about chaining (see decoder_example.c). If
  151006. we have the whole file, however, and want random access
  151007. (seeking/scrubbing) or desire to know the total length/time of a
  151008. file, we need to account for the possibility of chaining. */
  151009. /* We can handle things a number of ways; we can determine the entire
  151010. bitstream structure right off the bat, or find pieces on demand.
  151011. This example determines and caches structure for the entire
  151012. bitstream, but builds a virtual decoder on the fly when moving
  151013. between links in the chain. */
  151014. /* There are also different ways to implement seeking. Enough
  151015. information exists in an Ogg bitstream to seek to
  151016. sample-granularity positions in the output. Or, one can seek by
  151017. picking some portion of the stream roughly in the desired area if
  151018. we only want coarse navigation through the stream. */
  151019. /*************************************************************************
  151020. * Many, many internal helpers. The intention is not to be confusing;
  151021. * rampant duplication and monolithic function implementation would be
  151022. * harder to understand anyway. The high level functions are last. Begin
  151023. * grokking near the end of the file */
  151024. /* read a little more data from the file/pipe into the ogg_sync framer
  151025. */
  151026. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  151027. over 8k gets what they deserve */
  151028. static long _get_data(OggVorbis_File *vf){
  151029. errno=0;
  151030. if(vf->datasource){
  151031. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  151032. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  151033. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  151034. if(bytes==0 && errno)return(-1);
  151035. return(bytes);
  151036. }else
  151037. return(0);
  151038. }
  151039. /* save a tiny smidge of verbosity to make the code more readable */
  151040. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  151041. if(vf->datasource){
  151042. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  151043. vf->offset=offset;
  151044. ogg_sync_reset(&vf->oy);
  151045. }else{
  151046. /* shouldn't happen unless someone writes a broken callback */
  151047. return;
  151048. }
  151049. }
  151050. /* The read/seek functions track absolute position within the stream */
  151051. /* from the head of the stream, get the next page. boundary specifies
  151052. if the function is allowed to fetch more data from the stream (and
  151053. how much) or only use internally buffered data.
  151054. boundary: -1) unbounded search
  151055. 0) read no additional data; use cached only
  151056. n) search for a new page beginning for n bytes
  151057. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  151058. n) found a page at absolute offset n */
  151059. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  151060. ogg_int64_t boundary){
  151061. if(boundary>0)boundary+=vf->offset;
  151062. while(1){
  151063. long more;
  151064. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  151065. more=ogg_sync_pageseek(&vf->oy,og);
  151066. if(more<0){
  151067. /* skipped n bytes */
  151068. vf->offset-=more;
  151069. }else{
  151070. if(more==0){
  151071. /* send more paramedics */
  151072. if(!boundary)return(OV_FALSE);
  151073. {
  151074. long ret=_get_data(vf);
  151075. if(ret==0)return(OV_EOF);
  151076. if(ret<0)return(OV_EREAD);
  151077. }
  151078. }else{
  151079. /* got a page. Return the offset at the page beginning,
  151080. advance the internal offset past the page end */
  151081. ogg_int64_t ret=vf->offset;
  151082. vf->offset+=more;
  151083. return(ret);
  151084. }
  151085. }
  151086. }
  151087. }
  151088. /* find the latest page beginning before the current stream cursor
  151089. position. Much dirtier than the above as Ogg doesn't have any
  151090. backward search linkage. no 'readp' as it will certainly have to
  151091. read. */
  151092. /* returns offset or OV_EREAD, OV_FAULT */
  151093. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  151094. ogg_int64_t begin=vf->offset;
  151095. ogg_int64_t end=begin;
  151096. ogg_int64_t ret;
  151097. ogg_int64_t offset=-1;
  151098. while(offset==-1){
  151099. begin-=CHUNKSIZE;
  151100. if(begin<0)
  151101. begin=0;
  151102. _seek_helper(vf,begin);
  151103. while(vf->offset<end){
  151104. ret=_get_next_page(vf,og,end-vf->offset);
  151105. if(ret==OV_EREAD)return(OV_EREAD);
  151106. if(ret<0){
  151107. break;
  151108. }else{
  151109. offset=ret;
  151110. }
  151111. }
  151112. }
  151113. /* we have the offset. Actually snork and hold the page now */
  151114. _seek_helper(vf,offset);
  151115. ret=_get_next_page(vf,og,CHUNKSIZE);
  151116. if(ret<0)
  151117. /* this shouldn't be possible */
  151118. return(OV_EFAULT);
  151119. return(offset);
  151120. }
  151121. /* finds each bitstream link one at a time using a bisection search
  151122. (has to begin by knowing the offset of the lb's initial page).
  151123. Recurses for each link so it can alloc the link storage after
  151124. finding them all, then unroll and fill the cache at the same time */
  151125. static int _bisect_forward_serialno(OggVorbis_File *vf,
  151126. ogg_int64_t begin,
  151127. ogg_int64_t searched,
  151128. ogg_int64_t end,
  151129. long currentno,
  151130. long m){
  151131. ogg_int64_t endsearched=end;
  151132. ogg_int64_t next=end;
  151133. ogg_page og;
  151134. ogg_int64_t ret;
  151135. /* the below guards against garbage seperating the last and
  151136. first pages of two links. */
  151137. while(searched<endsearched){
  151138. ogg_int64_t bisect;
  151139. if(endsearched-searched<CHUNKSIZE){
  151140. bisect=searched;
  151141. }else{
  151142. bisect=(searched+endsearched)/2;
  151143. }
  151144. _seek_helper(vf,bisect);
  151145. ret=_get_next_page(vf,&og,-1);
  151146. if(ret==OV_EREAD)return(OV_EREAD);
  151147. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  151148. endsearched=bisect;
  151149. if(ret>=0)next=ret;
  151150. }else{
  151151. searched=ret+og.header_len+og.body_len;
  151152. }
  151153. }
  151154. _seek_helper(vf,next);
  151155. ret=_get_next_page(vf,&og,-1);
  151156. if(ret==OV_EREAD)return(OV_EREAD);
  151157. if(searched>=end || ret<0){
  151158. vf->links=m+1;
  151159. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  151160. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  151161. vf->offsets[m+1]=searched;
  151162. }else{
  151163. ret=_bisect_forward_serialno(vf,next,vf->offset,
  151164. end,ogg_page_serialno(&og),m+1);
  151165. if(ret==OV_EREAD)return(OV_EREAD);
  151166. }
  151167. vf->offsets[m]=begin;
  151168. vf->serialnos[m]=currentno;
  151169. return(0);
  151170. }
  151171. /* uses the local ogg_stream storage in vf; this is important for
  151172. non-streaming input sources */
  151173. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  151174. long *serialno,ogg_page *og_ptr){
  151175. ogg_page og;
  151176. ogg_packet op;
  151177. int i,ret;
  151178. if(!og_ptr){
  151179. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  151180. if(llret==OV_EREAD)return(OV_EREAD);
  151181. if(llret<0)return OV_ENOTVORBIS;
  151182. og_ptr=&og;
  151183. }
  151184. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  151185. if(serialno)*serialno=vf->os.serialno;
  151186. vf->ready_state=STREAMSET;
  151187. /* extract the initial header from the first page and verify that the
  151188. Ogg bitstream is in fact Vorbis data */
  151189. vorbis_info_init(vi);
  151190. vorbis_comment_init(vc);
  151191. i=0;
  151192. while(i<3){
  151193. ogg_stream_pagein(&vf->os,og_ptr);
  151194. while(i<3){
  151195. int result=ogg_stream_packetout(&vf->os,&op);
  151196. if(result==0)break;
  151197. if(result==-1){
  151198. ret=OV_EBADHEADER;
  151199. goto bail_header;
  151200. }
  151201. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  151202. goto bail_header;
  151203. }
  151204. i++;
  151205. }
  151206. if(i<3)
  151207. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  151208. ret=OV_EBADHEADER;
  151209. goto bail_header;
  151210. }
  151211. }
  151212. return 0;
  151213. bail_header:
  151214. vorbis_info_clear(vi);
  151215. vorbis_comment_clear(vc);
  151216. vf->ready_state=OPENED;
  151217. return ret;
  151218. }
  151219. /* last step of the OggVorbis_File initialization; get all the
  151220. vorbis_info structs and PCM positions. Only called by the seekable
  151221. initialization (local stream storage is hacked slightly; pay
  151222. attention to how that's done) */
  151223. /* this is void and does not propogate errors up because we want to be
  151224. able to open and use damaged bitstreams as well as we can. Just
  151225. watch out for missing information for links in the OggVorbis_File
  151226. struct */
  151227. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  151228. ogg_page og;
  151229. int i;
  151230. ogg_int64_t ret;
  151231. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  151232. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  151233. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  151234. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  151235. for(i=0;i<vf->links;i++){
  151236. if(i==0){
  151237. /* we already grabbed the initial header earlier. Just set the offset */
  151238. vf->dataoffsets[i]=dataoffset;
  151239. _seek_helper(vf,dataoffset);
  151240. }else{
  151241. /* seek to the location of the initial header */
  151242. _seek_helper(vf,vf->offsets[i]);
  151243. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  151244. vf->dataoffsets[i]=-1;
  151245. }else{
  151246. vf->dataoffsets[i]=vf->offset;
  151247. }
  151248. }
  151249. /* fetch beginning PCM offset */
  151250. if(vf->dataoffsets[i]!=-1){
  151251. ogg_int64_t accumulated=0;
  151252. long lastblock=-1;
  151253. int result;
  151254. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  151255. while(1){
  151256. ogg_packet op;
  151257. ret=_get_next_page(vf,&og,-1);
  151258. if(ret<0)
  151259. /* this should not be possible unless the file is
  151260. truncated/mangled */
  151261. break;
  151262. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  151263. break;
  151264. /* count blocksizes of all frames in the page */
  151265. ogg_stream_pagein(&vf->os,&og);
  151266. while((result=ogg_stream_packetout(&vf->os,&op))){
  151267. if(result>0){ /* ignore holes */
  151268. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  151269. if(lastblock!=-1)
  151270. accumulated+=(lastblock+thisblock)>>2;
  151271. lastblock=thisblock;
  151272. }
  151273. }
  151274. if(ogg_page_granulepos(&og)!=-1){
  151275. /* pcm offset of last packet on the first audio page */
  151276. accumulated= ogg_page_granulepos(&og)-accumulated;
  151277. break;
  151278. }
  151279. }
  151280. /* less than zero? This is a stream with samples trimmed off
  151281. the beginning, a normal occurrence; set the offset to zero */
  151282. if(accumulated<0)accumulated=0;
  151283. vf->pcmlengths[i*2]=accumulated;
  151284. }
  151285. /* get the PCM length of this link. To do this,
  151286. get the last page of the stream */
  151287. {
  151288. ogg_int64_t end=vf->offsets[i+1];
  151289. _seek_helper(vf,end);
  151290. while(1){
  151291. ret=_get_prev_page(vf,&og);
  151292. if(ret<0){
  151293. /* this should not be possible */
  151294. vorbis_info_clear(vf->vi+i);
  151295. vorbis_comment_clear(vf->vc+i);
  151296. break;
  151297. }
  151298. if(ogg_page_granulepos(&og)!=-1){
  151299. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  151300. break;
  151301. }
  151302. vf->offset=ret;
  151303. }
  151304. }
  151305. }
  151306. }
  151307. static int _make_decode_ready(OggVorbis_File *vf){
  151308. if(vf->ready_state>STREAMSET)return 0;
  151309. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  151310. if(vf->seekable){
  151311. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  151312. return OV_EBADLINK;
  151313. }else{
  151314. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  151315. return OV_EBADLINK;
  151316. }
  151317. vorbis_block_init(&vf->vd,&vf->vb);
  151318. vf->ready_state=INITSET;
  151319. vf->bittrack=0.f;
  151320. vf->samptrack=0.f;
  151321. return 0;
  151322. }
  151323. static int _open_seekable2(OggVorbis_File *vf){
  151324. long serialno=vf->current_serialno;
  151325. ogg_int64_t dataoffset=vf->offset, end;
  151326. ogg_page og;
  151327. /* we're partially open and have a first link header state in
  151328. storage in vf */
  151329. /* we can seek, so set out learning all about this file */
  151330. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  151331. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  151332. /* We get the offset for the last page of the physical bitstream.
  151333. Most OggVorbis files will contain a single logical bitstream */
  151334. end=_get_prev_page(vf,&og);
  151335. if(end<0)return(end);
  151336. /* more than one logical bitstream? */
  151337. if(ogg_page_serialno(&og)!=serialno){
  151338. /* Chained bitstream. Bisect-search each logical bitstream
  151339. section. Do so based on serial number only */
  151340. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  151341. }else{
  151342. /* Only one logical bitstream */
  151343. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  151344. }
  151345. /* the initial header memory is referenced by vf after; don't free it */
  151346. _prefetch_all_headers(vf,dataoffset);
  151347. return(ov_raw_seek(vf,0));
  151348. }
  151349. /* clear out the current logical bitstream decoder */
  151350. static void _decode_clear(OggVorbis_File *vf){
  151351. vorbis_dsp_clear(&vf->vd);
  151352. vorbis_block_clear(&vf->vb);
  151353. vf->ready_state=OPENED;
  151354. }
  151355. /* fetch and process a packet. Handles the case where we're at a
  151356. bitstream boundary and dumps the decoding machine. If the decoding
  151357. machine is unloaded, it loads it. It also keeps pcm_offset up to
  151358. date (seek and read both use this. seek uses a special hack with
  151359. readp).
  151360. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  151361. 0) need more data (only if readp==0)
  151362. 1) got a packet
  151363. */
  151364. static int _fetch_and_process_packet(OggVorbis_File *vf,
  151365. ogg_packet *op_in,
  151366. int readp,
  151367. int spanp){
  151368. ogg_page og;
  151369. /* handle one packet. Try to fetch it from current stream state */
  151370. /* extract packets from page */
  151371. while(1){
  151372. /* process a packet if we can. If the machine isn't loaded,
  151373. neither is a page */
  151374. if(vf->ready_state==INITSET){
  151375. while(1) {
  151376. ogg_packet op;
  151377. ogg_packet *op_ptr=(op_in?op_in:&op);
  151378. int result=ogg_stream_packetout(&vf->os,op_ptr);
  151379. ogg_int64_t granulepos;
  151380. op_in=NULL;
  151381. if(result==-1)return(OV_HOLE); /* hole in the data. */
  151382. if(result>0){
  151383. /* got a packet. process it */
  151384. granulepos=op_ptr->granulepos;
  151385. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  151386. header handling. The
  151387. header packets aren't
  151388. audio, so if/when we
  151389. submit them,
  151390. vorbis_synthesis will
  151391. reject them */
  151392. /* suck in the synthesis data and track bitrate */
  151393. {
  151394. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151395. /* for proper use of libvorbis within libvorbisfile,
  151396. oldsamples will always be zero. */
  151397. if(oldsamples)return(OV_EFAULT);
  151398. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  151399. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  151400. vf->bittrack+=op_ptr->bytes*8;
  151401. }
  151402. /* update the pcm offset. */
  151403. if(granulepos!=-1 && !op_ptr->e_o_s){
  151404. int link=(vf->seekable?vf->current_link:0);
  151405. int i,samples;
  151406. /* this packet has a pcm_offset on it (the last packet
  151407. completed on a page carries the offset) After processing
  151408. (above), we know the pcm position of the *last* sample
  151409. ready to be returned. Find the offset of the *first*
  151410. As an aside, this trick is inaccurate if we begin
  151411. reading anew right at the last page; the end-of-stream
  151412. granulepos declares the last frame in the stream, and the
  151413. last packet of the last page may be a partial frame.
  151414. So, we need a previous granulepos from an in-sequence page
  151415. to have a reference point. Thus the !op_ptr->e_o_s clause
  151416. above */
  151417. if(vf->seekable && link>0)
  151418. granulepos-=vf->pcmlengths[link*2];
  151419. if(granulepos<0)granulepos=0; /* actually, this
  151420. shouldn't be possible
  151421. here unless the stream
  151422. is very broken */
  151423. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  151424. granulepos-=samples;
  151425. for(i=0;i<link;i++)
  151426. granulepos+=vf->pcmlengths[i*2+1];
  151427. vf->pcm_offset=granulepos;
  151428. }
  151429. return(1);
  151430. }
  151431. }
  151432. else
  151433. break;
  151434. }
  151435. }
  151436. if(vf->ready_state>=OPENED){
  151437. ogg_int64_t ret;
  151438. if(!readp)return(0);
  151439. if((ret=_get_next_page(vf,&og,-1))<0){
  151440. return(OV_EOF); /* eof.
  151441. leave unitialized */
  151442. }
  151443. /* bitrate tracking; add the header's bytes here, the body bytes
  151444. are done by packet above */
  151445. vf->bittrack+=og.header_len*8;
  151446. /* has our decoding just traversed a bitstream boundary? */
  151447. if(vf->ready_state==INITSET){
  151448. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151449. if(!spanp)
  151450. return(OV_EOF);
  151451. _decode_clear(vf);
  151452. if(!vf->seekable){
  151453. vorbis_info_clear(vf->vi);
  151454. vorbis_comment_clear(vf->vc);
  151455. }
  151456. }
  151457. }
  151458. }
  151459. /* Do we need to load a new machine before submitting the page? */
  151460. /* This is different in the seekable and non-seekable cases.
  151461. In the seekable case, we already have all the header
  151462. information loaded and cached; we just initialize the machine
  151463. with it and continue on our merry way.
  151464. In the non-seekable (streaming) case, we'll only be at a
  151465. boundary if we just left the previous logical bitstream and
  151466. we're now nominally at the header of the next bitstream
  151467. */
  151468. if(vf->ready_state!=INITSET){
  151469. int link;
  151470. if(vf->ready_state<STREAMSET){
  151471. if(vf->seekable){
  151472. vf->current_serialno=ogg_page_serialno(&og);
  151473. /* match the serialno to bitstream section. We use this rather than
  151474. offset positions to avoid problems near logical bitstream
  151475. boundaries */
  151476. for(link=0;link<vf->links;link++)
  151477. if(vf->serialnos[link]==vf->current_serialno)break;
  151478. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  151479. stream. error out,
  151480. leave machine
  151481. uninitialized */
  151482. vf->current_link=link;
  151483. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151484. vf->ready_state=STREAMSET;
  151485. }else{
  151486. /* we're streaming */
  151487. /* fetch the three header packets, build the info struct */
  151488. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  151489. if(ret)return(ret);
  151490. vf->current_link++;
  151491. link=0;
  151492. }
  151493. }
  151494. {
  151495. int ret=_make_decode_ready(vf);
  151496. if(ret<0)return ret;
  151497. }
  151498. }
  151499. ogg_stream_pagein(&vf->os,&og);
  151500. }
  151501. }
  151502. /* if, eg, 64 bit stdio is configured by default, this will build with
  151503. fseek64 */
  151504. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  151505. if(f==NULL)return(-1);
  151506. return fseek(f,off,whence);
  151507. }
  151508. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  151509. long ibytes, ov_callbacks callbacks){
  151510. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  151511. int ret;
  151512. memset(vf,0,sizeof(*vf));
  151513. vf->datasource=f;
  151514. vf->callbacks = callbacks;
  151515. /* init the framing state */
  151516. ogg_sync_init(&vf->oy);
  151517. /* perhaps some data was previously read into a buffer for testing
  151518. against other stream types. Allow initialization from this
  151519. previously read data (as we may be reading from a non-seekable
  151520. stream) */
  151521. if(initial){
  151522. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  151523. memcpy(buffer,initial,ibytes);
  151524. ogg_sync_wrote(&vf->oy,ibytes);
  151525. }
  151526. /* can we seek? Stevens suggests the seek test was portable */
  151527. if(offsettest!=-1)vf->seekable=1;
  151528. /* No seeking yet; Set up a 'single' (current) logical bitstream
  151529. entry for partial open */
  151530. vf->links=1;
  151531. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  151532. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  151533. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  151534. /* Try to fetch the headers, maintaining all the storage */
  151535. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  151536. vf->datasource=NULL;
  151537. ov_clear(vf);
  151538. }else
  151539. vf->ready_state=PARTOPEN;
  151540. return(ret);
  151541. }
  151542. static int _ov_open2(OggVorbis_File *vf){
  151543. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  151544. vf->ready_state=OPENED;
  151545. if(vf->seekable){
  151546. int ret=_open_seekable2(vf);
  151547. if(ret){
  151548. vf->datasource=NULL;
  151549. ov_clear(vf);
  151550. }
  151551. return(ret);
  151552. }else
  151553. vf->ready_state=STREAMSET;
  151554. return 0;
  151555. }
  151556. /* clear out the OggVorbis_File struct */
  151557. int ov_clear(OggVorbis_File *vf){
  151558. if(vf){
  151559. vorbis_block_clear(&vf->vb);
  151560. vorbis_dsp_clear(&vf->vd);
  151561. ogg_stream_clear(&vf->os);
  151562. if(vf->vi && vf->links){
  151563. int i;
  151564. for(i=0;i<vf->links;i++){
  151565. vorbis_info_clear(vf->vi+i);
  151566. vorbis_comment_clear(vf->vc+i);
  151567. }
  151568. _ogg_free(vf->vi);
  151569. _ogg_free(vf->vc);
  151570. }
  151571. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  151572. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  151573. if(vf->serialnos)_ogg_free(vf->serialnos);
  151574. if(vf->offsets)_ogg_free(vf->offsets);
  151575. ogg_sync_clear(&vf->oy);
  151576. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  151577. memset(vf,0,sizeof(*vf));
  151578. }
  151579. #ifdef DEBUG_LEAKS
  151580. _VDBG_dump();
  151581. #endif
  151582. return(0);
  151583. }
  151584. /* inspects the OggVorbis file and finds/documents all the logical
  151585. bitstreams contained in it. Tries to be tolerant of logical
  151586. bitstream sections that are truncated/woogie.
  151587. return: -1) error
  151588. 0) OK
  151589. */
  151590. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151591. ov_callbacks callbacks){
  151592. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  151593. if(ret)return ret;
  151594. return _ov_open2(vf);
  151595. }
  151596. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151597. ov_callbacks callbacks = {
  151598. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151599. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151600. (int (*)(void *)) fclose,
  151601. (long (*)(void *)) ftell
  151602. };
  151603. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151604. }
  151605. /* cheap hack for game usage where downsampling is desirable; there's
  151606. no need for SRC as we can just do it cheaply in libvorbis. */
  151607. int ov_halfrate(OggVorbis_File *vf,int flag){
  151608. int i;
  151609. if(vf->vi==NULL)return OV_EINVAL;
  151610. if(!vf->seekable)return OV_EINVAL;
  151611. if(vf->ready_state>=STREAMSET)
  151612. _decode_clear(vf); /* clear out stream state; later on libvorbis
  151613. will be able to swap this on the fly, but
  151614. for now dumping the decode machine is needed
  151615. to reinit the MDCT lookups. 1.1 libvorbis
  151616. is planned to be able to switch on the fly */
  151617. for(i=0;i<vf->links;i++){
  151618. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  151619. ov_halfrate(vf,0);
  151620. return OV_EINVAL;
  151621. }
  151622. }
  151623. return 0;
  151624. }
  151625. int ov_halfrate_p(OggVorbis_File *vf){
  151626. if(vf->vi==NULL)return OV_EINVAL;
  151627. return vorbis_synthesis_halfrate_p(vf->vi);
  151628. }
  151629. /* Only partially open the vorbis file; test for Vorbisness, and load
  151630. the headers for the first chain. Do not seek (although test for
  151631. seekability). Use ov_test_open to finish opening the file, else
  151632. ov_clear to close/free it. Same return codes as open. */
  151633. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  151634. ov_callbacks callbacks)
  151635. {
  151636. return _ov_open1(f,vf,initial,ibytes,callbacks);
  151637. }
  151638. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  151639. ov_callbacks callbacks = {
  151640. (size_t (*)(void *, size_t, size_t, void *)) fread,
  151641. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  151642. (int (*)(void *)) fclose,
  151643. (long (*)(void *)) ftell
  151644. };
  151645. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  151646. }
  151647. int ov_test_open(OggVorbis_File *vf){
  151648. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  151649. return _ov_open2(vf);
  151650. }
  151651. /* How many logical bitstreams in this physical bitstream? */
  151652. long ov_streams(OggVorbis_File *vf){
  151653. return vf->links;
  151654. }
  151655. /* Is the FILE * associated with vf seekable? */
  151656. long ov_seekable(OggVorbis_File *vf){
  151657. return vf->seekable;
  151658. }
  151659. /* returns the bitrate for a given logical bitstream or the entire
  151660. physical bitstream. If the file is open for random access, it will
  151661. find the *actual* average bitrate. If the file is streaming, it
  151662. returns the nominal bitrate (if set) else the average of the
  151663. upper/lower bounds (if set) else -1 (unset).
  151664. If you want the actual bitrate field settings, get them from the
  151665. vorbis_info structs */
  151666. long ov_bitrate(OggVorbis_File *vf,int i){
  151667. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151668. if(i>=vf->links)return(OV_EINVAL);
  151669. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  151670. if(i<0){
  151671. ogg_int64_t bits=0;
  151672. int i;
  151673. float br;
  151674. for(i=0;i<vf->links;i++)
  151675. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  151676. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  151677. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  151678. * so this is slightly transformed to make it work.
  151679. */
  151680. br = bits/ov_time_total(vf,-1);
  151681. return(rint(br));
  151682. }else{
  151683. if(vf->seekable){
  151684. /* return the actual bitrate */
  151685. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  151686. }else{
  151687. /* return nominal if set */
  151688. if(vf->vi[i].bitrate_nominal>0){
  151689. return vf->vi[i].bitrate_nominal;
  151690. }else{
  151691. if(vf->vi[i].bitrate_upper>0){
  151692. if(vf->vi[i].bitrate_lower>0){
  151693. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  151694. }else{
  151695. return vf->vi[i].bitrate_upper;
  151696. }
  151697. }
  151698. return(OV_FALSE);
  151699. }
  151700. }
  151701. }
  151702. }
  151703. /* returns the actual bitrate since last call. returns -1 if no
  151704. additional data to offer since last call (or at beginning of stream),
  151705. EINVAL if stream is only partially open
  151706. */
  151707. long ov_bitrate_instant(OggVorbis_File *vf){
  151708. int link=(vf->seekable?vf->current_link:0);
  151709. long ret;
  151710. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151711. if(vf->samptrack==0)return(OV_FALSE);
  151712. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  151713. vf->bittrack=0.f;
  151714. vf->samptrack=0.f;
  151715. return(ret);
  151716. }
  151717. /* Guess */
  151718. long ov_serialnumber(OggVorbis_File *vf,int i){
  151719. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  151720. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  151721. if(i<0){
  151722. return(vf->current_serialno);
  151723. }else{
  151724. return(vf->serialnos[i]);
  151725. }
  151726. }
  151727. /* returns: total raw (compressed) length of content if i==-1
  151728. raw (compressed) length of that logical bitstream for i==0 to n
  151729. OV_EINVAL if the stream is not seekable (we can't know the length)
  151730. or if stream is only partially open
  151731. */
  151732. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  151733. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151734. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151735. if(i<0){
  151736. ogg_int64_t acc=0;
  151737. int i;
  151738. for(i=0;i<vf->links;i++)
  151739. acc+=ov_raw_total(vf,i);
  151740. return(acc);
  151741. }else{
  151742. return(vf->offsets[i+1]-vf->offsets[i]);
  151743. }
  151744. }
  151745. /* returns: total PCM length (samples) of content if i==-1 PCM length
  151746. (samples) of that logical bitstream for i==0 to n
  151747. OV_EINVAL if the stream is not seekable (we can't know the
  151748. length) or only partially open
  151749. */
  151750. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  151751. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151752. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151753. if(i<0){
  151754. ogg_int64_t acc=0;
  151755. int i;
  151756. for(i=0;i<vf->links;i++)
  151757. acc+=ov_pcm_total(vf,i);
  151758. return(acc);
  151759. }else{
  151760. return(vf->pcmlengths[i*2+1]);
  151761. }
  151762. }
  151763. /* returns: total seconds of content if i==-1
  151764. seconds in that logical bitstream for i==0 to n
  151765. OV_EINVAL if the stream is not seekable (we can't know the
  151766. length) or only partially open
  151767. */
  151768. double ov_time_total(OggVorbis_File *vf,int i){
  151769. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151770. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  151771. if(i<0){
  151772. double acc=0;
  151773. int i;
  151774. for(i=0;i<vf->links;i++)
  151775. acc+=ov_time_total(vf,i);
  151776. return(acc);
  151777. }else{
  151778. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  151779. }
  151780. }
  151781. /* seek to an offset relative to the *compressed* data. This also
  151782. scans packets to update the PCM cursor. It will cross a logical
  151783. bitstream boundary, but only if it can't get any packets out of the
  151784. tail of the bitstream we seek to (so no surprises).
  151785. returns zero on success, nonzero on failure */
  151786. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  151787. ogg_stream_state work_os;
  151788. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151789. if(!vf->seekable)
  151790. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  151791. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  151792. /* don't yet clear out decoding machine (if it's initialized), in
  151793. the case we're in the same link. Restart the decode lapping, and
  151794. let _fetch_and_process_packet deal with a potential bitstream
  151795. boundary */
  151796. vf->pcm_offset=-1;
  151797. ogg_stream_reset_serialno(&vf->os,
  151798. vf->current_serialno); /* must set serialno */
  151799. vorbis_synthesis_restart(&vf->vd);
  151800. _seek_helper(vf,pos);
  151801. /* we need to make sure the pcm_offset is set, but we don't want to
  151802. advance the raw cursor past good packets just to get to the first
  151803. with a granulepos. That's not equivalent behavior to beginning
  151804. decoding as immediately after the seek position as possible.
  151805. So, a hack. We use two stream states; a local scratch state and
  151806. the shared vf->os stream state. We use the local state to
  151807. scan, and the shared state as a buffer for later decode.
  151808. Unfortuantely, on the last page we still advance to last packet
  151809. because the granulepos on the last page is not necessarily on a
  151810. packet boundary, and we need to make sure the granpos is
  151811. correct.
  151812. */
  151813. {
  151814. ogg_page og;
  151815. ogg_packet op;
  151816. int lastblock=0;
  151817. int accblock=0;
  151818. int thisblock;
  151819. int eosflag;
  151820. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  151821. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  151822. return from not necessarily
  151823. starting from the beginning */
  151824. while(1){
  151825. if(vf->ready_state>=STREAMSET){
  151826. /* snarf/scan a packet if we can */
  151827. int result=ogg_stream_packetout(&work_os,&op);
  151828. if(result>0){
  151829. if(vf->vi[vf->current_link].codec_setup){
  151830. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  151831. if(thisblock<0){
  151832. ogg_stream_packetout(&vf->os,NULL);
  151833. thisblock=0;
  151834. }else{
  151835. if(eosflag)
  151836. ogg_stream_packetout(&vf->os,NULL);
  151837. else
  151838. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  151839. }
  151840. if(op.granulepos!=-1){
  151841. int i,link=vf->current_link;
  151842. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  151843. if(granulepos<0)granulepos=0;
  151844. for(i=0;i<link;i++)
  151845. granulepos+=vf->pcmlengths[i*2+1];
  151846. vf->pcm_offset=granulepos-accblock;
  151847. break;
  151848. }
  151849. lastblock=thisblock;
  151850. continue;
  151851. }else
  151852. ogg_stream_packetout(&vf->os,NULL);
  151853. }
  151854. }
  151855. if(!lastblock){
  151856. if(_get_next_page(vf,&og,-1)<0){
  151857. vf->pcm_offset=ov_pcm_total(vf,-1);
  151858. break;
  151859. }
  151860. }else{
  151861. /* huh? Bogus stream with packets but no granulepos */
  151862. vf->pcm_offset=-1;
  151863. break;
  151864. }
  151865. /* has our decoding just traversed a bitstream boundary? */
  151866. if(vf->ready_state>=STREAMSET)
  151867. if(vf->current_serialno!=ogg_page_serialno(&og)){
  151868. _decode_clear(vf); /* clear out stream state */
  151869. ogg_stream_clear(&work_os);
  151870. }
  151871. if(vf->ready_state<STREAMSET){
  151872. int link;
  151873. vf->current_serialno=ogg_page_serialno(&og);
  151874. for(link=0;link<vf->links;link++)
  151875. if(vf->serialnos[link]==vf->current_serialno)break;
  151876. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  151877. error out, leave
  151878. machine uninitialized */
  151879. vf->current_link=link;
  151880. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  151881. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  151882. vf->ready_state=STREAMSET;
  151883. }
  151884. ogg_stream_pagein(&vf->os,&og);
  151885. ogg_stream_pagein(&work_os,&og);
  151886. eosflag=ogg_page_eos(&og);
  151887. }
  151888. }
  151889. ogg_stream_clear(&work_os);
  151890. vf->bittrack=0.f;
  151891. vf->samptrack=0.f;
  151892. return(0);
  151893. seek_error:
  151894. /* dump the machine so we're in a known state */
  151895. vf->pcm_offset=-1;
  151896. ogg_stream_clear(&work_os);
  151897. _decode_clear(vf);
  151898. return OV_EBADLINK;
  151899. }
  151900. /* Page granularity seek (faster than sample granularity because we
  151901. don't do the last bit of decode to find a specific sample).
  151902. Seek to the last [granule marked] page preceeding the specified pos
  151903. location, such that decoding past the returned point will quickly
  151904. arrive at the requested position. */
  151905. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  151906. int link=-1;
  151907. ogg_int64_t result=0;
  151908. ogg_int64_t total=ov_pcm_total(vf,-1);
  151909. if(vf->ready_state<OPENED)return(OV_EINVAL);
  151910. if(!vf->seekable)return(OV_ENOSEEK);
  151911. if(pos<0 || pos>total)return(OV_EINVAL);
  151912. /* which bitstream section does this pcm offset occur in? */
  151913. for(link=vf->links-1;link>=0;link--){
  151914. total-=vf->pcmlengths[link*2+1];
  151915. if(pos>=total)break;
  151916. }
  151917. /* search within the logical bitstream for the page with the highest
  151918. pcm_pos preceeding (or equal to) pos. There is a danger here;
  151919. missing pages or incorrect frame number information in the
  151920. bitstream could make our task impossible. Account for that (it
  151921. would be an error condition) */
  151922. /* new search algorithm by HB (Nicholas Vinen) */
  151923. {
  151924. ogg_int64_t end=vf->offsets[link+1];
  151925. ogg_int64_t begin=vf->offsets[link];
  151926. ogg_int64_t begintime = vf->pcmlengths[link*2];
  151927. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  151928. ogg_int64_t target=pos-total+begintime;
  151929. ogg_int64_t best=begin;
  151930. ogg_page og;
  151931. while(begin<end){
  151932. ogg_int64_t bisect;
  151933. if(end-begin<CHUNKSIZE){
  151934. bisect=begin;
  151935. }else{
  151936. /* take a (pretty decent) guess. */
  151937. bisect=begin +
  151938. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  151939. if(bisect<=begin)
  151940. bisect=begin+1;
  151941. }
  151942. _seek_helper(vf,bisect);
  151943. while(begin<end){
  151944. result=_get_next_page(vf,&og,end-vf->offset);
  151945. if(result==OV_EREAD) goto seek_error;
  151946. if(result<0){
  151947. if(bisect<=begin+1)
  151948. end=begin; /* found it */
  151949. else{
  151950. if(bisect==0) goto seek_error;
  151951. bisect-=CHUNKSIZE;
  151952. if(bisect<=begin)bisect=begin+1;
  151953. _seek_helper(vf,bisect);
  151954. }
  151955. }else{
  151956. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  151957. if(granulepos==-1)continue;
  151958. if(granulepos<target){
  151959. best=result; /* raw offset of packet with granulepos */
  151960. begin=vf->offset; /* raw offset of next page */
  151961. begintime=granulepos;
  151962. if(target-begintime>44100)break;
  151963. bisect=begin; /* *not* begin + 1 */
  151964. }else{
  151965. if(bisect<=begin+1)
  151966. end=begin; /* found it */
  151967. else{
  151968. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  151969. end=result;
  151970. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  151971. if(bisect<=begin)bisect=begin+1;
  151972. _seek_helper(vf,bisect);
  151973. }else{
  151974. end=result;
  151975. endtime=granulepos;
  151976. break;
  151977. }
  151978. }
  151979. }
  151980. }
  151981. }
  151982. }
  151983. /* found our page. seek to it, update pcm offset. Easier case than
  151984. raw_seek, don't keep packets preceeding granulepos. */
  151985. {
  151986. ogg_page og;
  151987. ogg_packet op;
  151988. /* seek */
  151989. _seek_helper(vf,best);
  151990. vf->pcm_offset=-1;
  151991. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  151992. if(link!=vf->current_link){
  151993. /* Different link; dump entire decode machine */
  151994. _decode_clear(vf);
  151995. vf->current_link=link;
  151996. vf->current_serialno=ogg_page_serialno(&og);
  151997. vf->ready_state=STREAMSET;
  151998. }else{
  151999. vorbis_synthesis_restart(&vf->vd);
  152000. }
  152001. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152002. ogg_stream_pagein(&vf->os,&og);
  152003. /* pull out all but last packet; the one with granulepos */
  152004. while(1){
  152005. result=ogg_stream_packetpeek(&vf->os,&op);
  152006. if(result==0){
  152007. /* !!! the packet finishing this page originated on a
  152008. preceeding page. Keep fetching previous pages until we
  152009. get one with a granulepos or without the 'continued' flag
  152010. set. Then just use raw_seek for simplicity. */
  152011. _seek_helper(vf,best);
  152012. while(1){
  152013. result=_get_prev_page(vf,&og);
  152014. if(result<0) goto seek_error;
  152015. if(ogg_page_granulepos(&og)>-1 ||
  152016. !ogg_page_continued(&og)){
  152017. return ov_raw_seek(vf,result);
  152018. }
  152019. vf->offset=result;
  152020. }
  152021. }
  152022. if(result<0){
  152023. result = OV_EBADPACKET;
  152024. goto seek_error;
  152025. }
  152026. if(op.granulepos!=-1){
  152027. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152028. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152029. vf->pcm_offset+=total;
  152030. break;
  152031. }else
  152032. result=ogg_stream_packetout(&vf->os,NULL);
  152033. }
  152034. }
  152035. }
  152036. /* verify result */
  152037. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  152038. result=OV_EFAULT;
  152039. goto seek_error;
  152040. }
  152041. vf->bittrack=0.f;
  152042. vf->samptrack=0.f;
  152043. return(0);
  152044. seek_error:
  152045. /* dump machine so we're in a known state */
  152046. vf->pcm_offset=-1;
  152047. _decode_clear(vf);
  152048. return (int)result;
  152049. }
  152050. /* seek to a sample offset relative to the decompressed pcm stream
  152051. returns zero on success, nonzero on failure */
  152052. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  152053. int thisblock,lastblock=0;
  152054. int ret=ov_pcm_seek_page(vf,pos);
  152055. if(ret<0)return(ret);
  152056. if((ret=_make_decode_ready(vf)))return ret;
  152057. /* discard leading packets we don't need for the lapping of the
  152058. position we want; don't decode them */
  152059. while(1){
  152060. ogg_packet op;
  152061. ogg_page og;
  152062. int ret=ogg_stream_packetpeek(&vf->os,&op);
  152063. if(ret>0){
  152064. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  152065. if(thisblock<0){
  152066. ogg_stream_packetout(&vf->os,NULL);
  152067. continue; /* non audio packet */
  152068. }
  152069. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  152070. if(vf->pcm_offset+((thisblock+
  152071. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  152072. /* remove the packet from packet queue and track its granulepos */
  152073. ogg_stream_packetout(&vf->os,NULL);
  152074. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  152075. only tracking, no
  152076. pcm_decode */
  152077. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  152078. /* end of logical stream case is hard, especially with exact
  152079. length positioning. */
  152080. if(op.granulepos>-1){
  152081. int i;
  152082. /* always believe the stream markers */
  152083. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  152084. if(vf->pcm_offset<0)vf->pcm_offset=0;
  152085. for(i=0;i<vf->current_link;i++)
  152086. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  152087. }
  152088. lastblock=thisblock;
  152089. }else{
  152090. if(ret<0 && ret!=OV_HOLE)break;
  152091. /* suck in a new page */
  152092. if(_get_next_page(vf,&og,-1)<0)break;
  152093. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  152094. if(vf->ready_state<STREAMSET){
  152095. int link;
  152096. vf->current_serialno=ogg_page_serialno(&og);
  152097. for(link=0;link<vf->links;link++)
  152098. if(vf->serialnos[link]==vf->current_serialno)break;
  152099. if(link==vf->links)return(OV_EBADLINK);
  152100. vf->current_link=link;
  152101. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  152102. vf->ready_state=STREAMSET;
  152103. ret=_make_decode_ready(vf);
  152104. if(ret)return ret;
  152105. lastblock=0;
  152106. }
  152107. ogg_stream_pagein(&vf->os,&og);
  152108. }
  152109. }
  152110. vf->bittrack=0.f;
  152111. vf->samptrack=0.f;
  152112. /* discard samples until we reach the desired position. Crossing a
  152113. logical bitstream boundary with abandon is OK. */
  152114. while(vf->pcm_offset<pos){
  152115. ogg_int64_t target=pos-vf->pcm_offset;
  152116. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  152117. if(samples>target)samples=target;
  152118. vorbis_synthesis_read(&vf->vd,samples);
  152119. vf->pcm_offset+=samples;
  152120. if(samples<target)
  152121. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  152122. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  152123. }
  152124. return 0;
  152125. }
  152126. /* seek to a playback time relative to the decompressed pcm stream
  152127. returns zero on success, nonzero on failure */
  152128. int ov_time_seek(OggVorbis_File *vf,double seconds){
  152129. /* translate time to PCM position and call ov_pcm_seek */
  152130. int link=-1;
  152131. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  152132. double time_total=ov_time_total(vf,-1);
  152133. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152134. if(!vf->seekable)return(OV_ENOSEEK);
  152135. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  152136. /* which bitstream section does this time offset occur in? */
  152137. for(link=vf->links-1;link>=0;link--){
  152138. pcm_total-=vf->pcmlengths[link*2+1];
  152139. time_total-=ov_time_total(vf,link);
  152140. if(seconds>=time_total)break;
  152141. }
  152142. /* enough information to convert time offset to pcm offset */
  152143. {
  152144. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  152145. return(ov_pcm_seek(vf,target));
  152146. }
  152147. }
  152148. /* page-granularity version of ov_time_seek
  152149. returns zero on success, nonzero on failure */
  152150. int ov_time_seek_page(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_page(vf,target));
  152168. }
  152169. }
  152170. /* tell the current stream offset cursor. Note that seek followed by
  152171. tell will likely not give the set offset due to caching */
  152172. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  152173. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152174. return(vf->offset);
  152175. }
  152176. /* return PCM offset (sample) of next PCM sample to be read */
  152177. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  152178. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152179. return(vf->pcm_offset);
  152180. }
  152181. /* return time offset (seconds) of next PCM sample to be read */
  152182. double ov_time_tell(OggVorbis_File *vf){
  152183. int link=0;
  152184. ogg_int64_t pcm_total=0;
  152185. double time_total=0.f;
  152186. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152187. if(vf->seekable){
  152188. pcm_total=ov_pcm_total(vf,-1);
  152189. time_total=ov_time_total(vf,-1);
  152190. /* which bitstream section does this time offset occur in? */
  152191. for(link=vf->links-1;link>=0;link--){
  152192. pcm_total-=vf->pcmlengths[link*2+1];
  152193. time_total-=ov_time_total(vf,link);
  152194. if(vf->pcm_offset>=pcm_total)break;
  152195. }
  152196. }
  152197. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  152198. }
  152199. /* link: -1) return the vorbis_info struct for the bitstream section
  152200. currently being decoded
  152201. 0-n) to request information for a specific bitstream section
  152202. In the case of a non-seekable bitstream, any call returns the
  152203. current bitstream. NULL in the case that the machine is not
  152204. initialized */
  152205. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  152206. if(vf->seekable){
  152207. if(link<0)
  152208. if(vf->ready_state>=STREAMSET)
  152209. return vf->vi+vf->current_link;
  152210. else
  152211. return vf->vi;
  152212. else
  152213. if(link>=vf->links)
  152214. return NULL;
  152215. else
  152216. return vf->vi+link;
  152217. }else{
  152218. return vf->vi;
  152219. }
  152220. }
  152221. /* grr, strong typing, grr, no templates/inheritence, grr */
  152222. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  152223. if(vf->seekable){
  152224. if(link<0)
  152225. if(vf->ready_state>=STREAMSET)
  152226. return vf->vc+vf->current_link;
  152227. else
  152228. return vf->vc;
  152229. else
  152230. if(link>=vf->links)
  152231. return NULL;
  152232. else
  152233. return vf->vc+link;
  152234. }else{
  152235. return vf->vc;
  152236. }
  152237. }
  152238. static int host_is_big_endian() {
  152239. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  152240. unsigned char *bytewise = (unsigned char *)&pattern;
  152241. if (bytewise[0] == 0xfe) return 1;
  152242. return 0;
  152243. }
  152244. /* up to this point, everything could more or less hide the multiple
  152245. logical bitstream nature of chaining from the toplevel application
  152246. if the toplevel application didn't particularly care. However, at
  152247. the point that we actually read audio back, the multiple-section
  152248. nature must surface: Multiple bitstream sections do not necessarily
  152249. have to have the same number of channels or sampling rate.
  152250. ov_read returns the sequential logical bitstream number currently
  152251. being decoded along with the PCM data in order that the toplevel
  152252. application can take action on channel/sample rate changes. This
  152253. number will be incremented even for streamed (non-seekable) streams
  152254. (for seekable streams, it represents the actual logical bitstream
  152255. index within the physical bitstream. Note that the accessor
  152256. functions above are aware of this dichotomy).
  152257. input values: buffer) a buffer to hold packed PCM data for return
  152258. length) the byte length requested to be placed into buffer
  152259. bigendianp) should the data be packed LSB first (0) or
  152260. MSB first (1)
  152261. word) word size for output. currently 1 (byte) or
  152262. 2 (16 bit short)
  152263. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152264. 0) EOF
  152265. n) number of bytes of PCM actually returned. The
  152266. below works on a packet-by-packet basis, so the
  152267. return length is not related to the 'length' passed
  152268. in, just guaranteed to fit.
  152269. *section) set to the logical bitstream number */
  152270. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  152271. int bigendianp,int word,int sgned,int *bitstream){
  152272. int i,j;
  152273. int host_endian = host_is_big_endian();
  152274. float **pcm;
  152275. long samples;
  152276. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152277. while(1){
  152278. if(vf->ready_state==INITSET){
  152279. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152280. if(samples)break;
  152281. }
  152282. /* suck in another packet */
  152283. {
  152284. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152285. if(ret==OV_EOF)
  152286. return(0);
  152287. if(ret<=0)
  152288. return(ret);
  152289. }
  152290. }
  152291. if(samples>0){
  152292. /* yay! proceed to pack data into the byte buffer */
  152293. long channels=ov_info(vf,-1)->channels;
  152294. long bytespersample=word * channels;
  152295. vorbis_fpu_control fpu;
  152296. (void) fpu; // (to avoid a warning about it being unused)
  152297. if(samples>length/bytespersample)samples=length/bytespersample;
  152298. if(samples <= 0)
  152299. return OV_EINVAL;
  152300. /* a tight loop to pack each size */
  152301. {
  152302. int val;
  152303. if(word==1){
  152304. int off=(sgned?0:128);
  152305. vorbis_fpu_setround(&fpu);
  152306. for(j=0;j<samples;j++)
  152307. for(i=0;i<channels;i++){
  152308. val=vorbis_ftoi(pcm[i][j]*128.f);
  152309. if(val>127)val=127;
  152310. else if(val<-128)val=-128;
  152311. *buffer++=val+off;
  152312. }
  152313. vorbis_fpu_restore(fpu);
  152314. }else{
  152315. int off=(sgned?0:32768);
  152316. if(host_endian==bigendianp){
  152317. if(sgned){
  152318. vorbis_fpu_setround(&fpu);
  152319. for(i=0;i<channels;i++) { /* It's faster in this order */
  152320. float *src=pcm[i];
  152321. short *dest=((short *)buffer)+i;
  152322. for(j=0;j<samples;j++) {
  152323. val=vorbis_ftoi(src[j]*32768.f);
  152324. if(val>32767)val=32767;
  152325. else if(val<-32768)val=-32768;
  152326. *dest=val;
  152327. dest+=channels;
  152328. }
  152329. }
  152330. vorbis_fpu_restore(fpu);
  152331. }else{
  152332. vorbis_fpu_setround(&fpu);
  152333. for(i=0;i<channels;i++) {
  152334. float *src=pcm[i];
  152335. short *dest=((short *)buffer)+i;
  152336. for(j=0;j<samples;j++) {
  152337. val=vorbis_ftoi(src[j]*32768.f);
  152338. if(val>32767)val=32767;
  152339. else if(val<-32768)val=-32768;
  152340. *dest=val+off;
  152341. dest+=channels;
  152342. }
  152343. }
  152344. vorbis_fpu_restore(fpu);
  152345. }
  152346. }else if(bigendianp){
  152347. vorbis_fpu_setround(&fpu);
  152348. for(j=0;j<samples;j++)
  152349. for(i=0;i<channels;i++){
  152350. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152351. if(val>32767)val=32767;
  152352. else if(val<-32768)val=-32768;
  152353. val+=off;
  152354. *buffer++=(val>>8);
  152355. *buffer++=(val&0xff);
  152356. }
  152357. vorbis_fpu_restore(fpu);
  152358. }else{
  152359. int val;
  152360. vorbis_fpu_setround(&fpu);
  152361. for(j=0;j<samples;j++)
  152362. for(i=0;i<channels;i++){
  152363. val=vorbis_ftoi(pcm[i][j]*32768.f);
  152364. if(val>32767)val=32767;
  152365. else if(val<-32768)val=-32768;
  152366. val+=off;
  152367. *buffer++=(val&0xff);
  152368. *buffer++=(val>>8);
  152369. }
  152370. vorbis_fpu_restore(fpu);
  152371. }
  152372. }
  152373. }
  152374. vorbis_synthesis_read(&vf->vd,samples);
  152375. vf->pcm_offset+=samples;
  152376. if(bitstream)*bitstream=vf->current_link;
  152377. return(samples*bytespersample);
  152378. }else{
  152379. return(samples);
  152380. }
  152381. }
  152382. /* input values: pcm_channels) a float vector per channel of output
  152383. length) the sample length being read by the app
  152384. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  152385. 0) EOF
  152386. n) number of samples of PCM actually returned. The
  152387. below works on a packet-by-packet basis, so the
  152388. return length is not related to the 'length' passed
  152389. in, just guaranteed to fit.
  152390. *section) set to the logical bitstream number */
  152391. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  152392. int *bitstream){
  152393. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152394. while(1){
  152395. if(vf->ready_state==INITSET){
  152396. float **pcm;
  152397. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  152398. if(samples){
  152399. if(pcm_channels)*pcm_channels=pcm;
  152400. if(samples>length)samples=length;
  152401. vorbis_synthesis_read(&vf->vd,samples);
  152402. vf->pcm_offset+=samples;
  152403. if(bitstream)*bitstream=vf->current_link;
  152404. return samples;
  152405. }
  152406. }
  152407. /* suck in another packet */
  152408. {
  152409. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  152410. if(ret==OV_EOF)return(0);
  152411. if(ret<=0)return(ret);
  152412. }
  152413. }
  152414. }
  152415. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  152416. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  152417. ogg_int64_t off);
  152418. static void _ov_splice(float **pcm,float **lappcm,
  152419. int n1, int n2,
  152420. int ch1, int ch2,
  152421. float *w1, float *w2){
  152422. int i,j;
  152423. float *w=w1;
  152424. int n=n1;
  152425. if(n1>n2){
  152426. n=n2;
  152427. w=w2;
  152428. }
  152429. /* splice */
  152430. for(j=0;j<ch1 && j<ch2;j++){
  152431. float *s=lappcm[j];
  152432. float *d=pcm[j];
  152433. for(i=0;i<n;i++){
  152434. float wd=w[i]*w[i];
  152435. float ws=1.-wd;
  152436. d[i]=d[i]*wd + s[i]*ws;
  152437. }
  152438. }
  152439. /* window from zero */
  152440. for(;j<ch2;j++){
  152441. float *d=pcm[j];
  152442. for(i=0;i<n;i++){
  152443. float wd=w[i]*w[i];
  152444. d[i]=d[i]*wd;
  152445. }
  152446. }
  152447. }
  152448. /* make sure vf is INITSET */
  152449. static int _ov_initset(OggVorbis_File *vf){
  152450. while(1){
  152451. if(vf->ready_state==INITSET)break;
  152452. /* suck in another packet */
  152453. {
  152454. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152455. if(ret<0 && ret!=OV_HOLE)return(ret);
  152456. }
  152457. }
  152458. return 0;
  152459. }
  152460. /* make sure vf is INITSET and that we have a primed buffer; if
  152461. we're crosslapping at a stream section boundary, this also makes
  152462. sure we're sanity checking against the right stream information */
  152463. static int _ov_initprime(OggVorbis_File *vf){
  152464. vorbis_dsp_state *vd=&vf->vd;
  152465. while(1){
  152466. if(vf->ready_state==INITSET)
  152467. if(vorbis_synthesis_pcmout(vd,NULL))break;
  152468. /* suck in another packet */
  152469. {
  152470. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  152471. if(ret<0 && ret!=OV_HOLE)return(ret);
  152472. }
  152473. }
  152474. return 0;
  152475. }
  152476. /* grab enough data for lapping from vf; this may be in the form of
  152477. unreturned, already-decoded pcm, remaining PCM we will need to
  152478. decode, or synthetic postextrapolation from last packets. */
  152479. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  152480. float **lappcm,int lapsize){
  152481. int lapcount=0,i;
  152482. float **pcm;
  152483. /* try first to decode the lapping data */
  152484. while(lapcount<lapsize){
  152485. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  152486. if(samples){
  152487. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152488. for(i=0;i<vi->channels;i++)
  152489. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152490. lapcount+=samples;
  152491. vorbis_synthesis_read(vd,samples);
  152492. }else{
  152493. /* suck in another packet */
  152494. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  152495. if(ret==OV_EOF)break;
  152496. }
  152497. }
  152498. if(lapcount<lapsize){
  152499. /* failed to get lapping data from normal decode; pry it from the
  152500. postextrapolation buffering, or the second half of the MDCT
  152501. from the last packet */
  152502. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  152503. if(samples==0){
  152504. for(i=0;i<vi->channels;i++)
  152505. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  152506. lapcount=lapsize;
  152507. }else{
  152508. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  152509. for(i=0;i<vi->channels;i++)
  152510. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  152511. lapcount+=samples;
  152512. }
  152513. }
  152514. }
  152515. /* this sets up crosslapping of a sample by using trailing data from
  152516. sample 1 and lapping it into the windowing buffer of sample 2 */
  152517. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  152518. vorbis_info *vi1,*vi2;
  152519. float **lappcm;
  152520. float **pcm;
  152521. float *w1,*w2;
  152522. int n1,n2,i,ret,hs1,hs2;
  152523. if(vf1==vf2)return(0); /* degenerate case */
  152524. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  152525. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  152526. /* the relevant overlap buffers must be pre-checked and pre-primed
  152527. before looking at settings in the event that priming would cross
  152528. a bitstream boundary. So, do it now */
  152529. ret=_ov_initset(vf1);
  152530. if(ret)return(ret);
  152531. ret=_ov_initprime(vf2);
  152532. if(ret)return(ret);
  152533. vi1=ov_info(vf1,-1);
  152534. vi2=ov_info(vf2,-1);
  152535. hs1=ov_halfrate_p(vf1);
  152536. hs2=ov_halfrate_p(vf2);
  152537. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  152538. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  152539. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  152540. w1=vorbis_window(&vf1->vd,0);
  152541. w2=vorbis_window(&vf2->vd,0);
  152542. for(i=0;i<vi1->channels;i++)
  152543. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152544. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  152545. /* have a lapping buffer from vf1; now to splice it into the lapping
  152546. buffer of vf2 */
  152547. /* consolidate and expose the buffer. */
  152548. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  152549. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  152550. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  152551. /* splice */
  152552. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  152553. /* done */
  152554. return(0);
  152555. }
  152556. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  152557. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  152558. vorbis_info *vi;
  152559. float **lappcm;
  152560. float **pcm;
  152561. float *w1,*w2;
  152562. int n1,n2,ch1,ch2,hs;
  152563. int i,ret;
  152564. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152565. ret=_ov_initset(vf);
  152566. if(ret)return(ret);
  152567. vi=ov_info(vf,-1);
  152568. hs=ov_halfrate_p(vf);
  152569. ch1=vi->channels;
  152570. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152571. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152572. persistent; even if the decode state
  152573. from this link gets dumped, this
  152574. window array continues to exist */
  152575. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152576. for(i=0;i<ch1;i++)
  152577. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152578. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152579. /* have lapping data; seek and prime the buffer */
  152580. ret=localseek(vf,pos);
  152581. if(ret)return ret;
  152582. ret=_ov_initprime(vf);
  152583. if(ret)return(ret);
  152584. /* Guard against cross-link changes; they're perfectly legal */
  152585. vi=ov_info(vf,-1);
  152586. ch2=vi->channels;
  152587. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152588. w2=vorbis_window(&vf->vd,0);
  152589. /* consolidate and expose the buffer. */
  152590. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152591. /* splice */
  152592. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152593. /* done */
  152594. return(0);
  152595. }
  152596. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152597. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  152598. }
  152599. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152600. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  152601. }
  152602. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  152603. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  152604. }
  152605. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  152606. int (*localseek)(OggVorbis_File *,double)){
  152607. vorbis_info *vi;
  152608. float **lappcm;
  152609. float **pcm;
  152610. float *w1,*w2;
  152611. int n1,n2,ch1,ch2,hs;
  152612. int i,ret;
  152613. if(vf->ready_state<OPENED)return(OV_EINVAL);
  152614. ret=_ov_initset(vf);
  152615. if(ret)return(ret);
  152616. vi=ov_info(vf,-1);
  152617. hs=ov_halfrate_p(vf);
  152618. ch1=vi->channels;
  152619. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  152620. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  152621. persistent; even if the decode state
  152622. from this link gets dumped, this
  152623. window array continues to exist */
  152624. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  152625. for(i=0;i<ch1;i++)
  152626. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  152627. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  152628. /* have lapping data; seek and prime the buffer */
  152629. ret=localseek(vf,pos);
  152630. if(ret)return ret;
  152631. ret=_ov_initprime(vf);
  152632. if(ret)return(ret);
  152633. /* Guard against cross-link changes; they're perfectly legal */
  152634. vi=ov_info(vf,-1);
  152635. ch2=vi->channels;
  152636. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  152637. w2=vorbis_window(&vf->vd,0);
  152638. /* consolidate and expose the buffer. */
  152639. vorbis_synthesis_lapout(&vf->vd,&pcm);
  152640. /* splice */
  152641. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  152642. /* done */
  152643. return(0);
  152644. }
  152645. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  152646. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  152647. }
  152648. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  152649. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  152650. }
  152651. #endif
  152652. /********* End of inlined file: vorbisfile.c *********/
  152653. /********* Start of inlined file: window.c *********/
  152654. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  152655. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  152656. // tasks..
  152657. #ifdef _MSC_VER
  152658. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  152659. #endif
  152660. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  152661. #if JUCE_USE_OGGVORBIS
  152662. #include <stdlib.h>
  152663. #include <math.h>
  152664. static float vwin64[32] = {
  152665. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  152666. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  152667. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  152668. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  152669. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  152670. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  152671. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  152672. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  152673. };
  152674. static float vwin128[64] = {
  152675. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  152676. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  152677. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  152678. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  152679. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  152680. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  152681. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  152682. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  152683. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  152684. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  152685. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  152686. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  152687. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  152688. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  152689. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  152690. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  152691. };
  152692. static float vwin256[128] = {
  152693. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  152694. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  152695. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  152696. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  152697. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  152698. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  152699. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  152700. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  152701. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  152702. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  152703. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  152704. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  152705. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  152706. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  152707. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  152708. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  152709. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  152710. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  152711. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  152712. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  152713. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  152714. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  152715. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  152716. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  152717. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  152718. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  152719. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  152720. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  152721. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  152722. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  152723. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  152724. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  152725. };
  152726. static float vwin512[256] = {
  152727. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  152728. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  152729. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  152730. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  152731. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  152732. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  152733. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  152734. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  152735. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  152736. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  152737. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  152738. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  152739. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  152740. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  152741. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  152742. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  152743. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  152744. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  152745. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  152746. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  152747. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  152748. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  152749. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  152750. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  152751. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  152752. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  152753. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  152754. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  152755. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  152756. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  152757. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  152758. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  152759. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  152760. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  152761. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  152762. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  152763. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  152764. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  152765. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  152766. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  152767. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  152768. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  152769. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  152770. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  152771. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  152772. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  152773. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  152774. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  152775. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  152776. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  152777. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  152778. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  152779. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  152780. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  152781. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  152782. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  152783. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  152784. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  152785. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  152786. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  152787. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  152788. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  152789. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  152790. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  152791. };
  152792. static float vwin1024[512] = {
  152793. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  152794. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  152795. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  152796. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  152797. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  152798. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  152799. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  152800. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  152801. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  152802. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  152803. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  152804. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  152805. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  152806. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  152807. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  152808. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  152809. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  152810. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  152811. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  152812. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  152813. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  152814. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  152815. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  152816. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  152817. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  152818. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  152819. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  152820. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  152821. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  152822. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  152823. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  152824. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  152825. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  152826. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  152827. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  152828. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  152829. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  152830. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  152831. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  152832. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  152833. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  152834. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  152835. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  152836. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  152837. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  152838. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  152839. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  152840. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  152841. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  152842. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  152843. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  152844. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  152845. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  152846. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  152847. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  152848. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  152849. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  152850. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  152851. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  152852. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  152853. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  152854. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  152855. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  152856. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  152857. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  152858. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  152859. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  152860. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  152861. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  152862. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  152863. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  152864. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  152865. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  152866. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  152867. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  152868. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  152869. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  152870. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  152871. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  152872. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  152873. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  152874. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  152875. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  152876. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  152877. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  152878. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  152879. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  152880. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  152881. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  152882. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  152883. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  152884. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  152885. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  152886. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  152887. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  152888. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  152889. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  152890. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  152891. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  152892. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  152893. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  152894. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  152895. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  152896. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  152897. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  152898. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  152899. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  152900. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  152901. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  152902. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  152903. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  152904. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  152905. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  152906. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  152907. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  152908. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  152909. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  152910. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  152911. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  152912. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  152913. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  152914. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  152915. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  152916. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  152917. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  152918. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  152919. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  152920. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  152921. };
  152922. static float vwin2048[1024] = {
  152923. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  152924. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  152925. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  152926. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  152927. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  152928. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  152929. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  152930. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  152931. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  152932. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  152933. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  152934. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  152935. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  152936. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  152937. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  152938. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  152939. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  152940. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  152941. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  152942. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  152943. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  152944. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  152945. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  152946. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  152947. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  152948. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  152949. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  152950. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  152951. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  152952. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  152953. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  152954. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  152955. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  152956. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  152957. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  152958. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  152959. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  152960. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  152961. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  152962. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  152963. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  152964. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  152965. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  152966. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  152967. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  152968. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  152969. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  152970. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  152971. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  152972. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  152973. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  152974. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  152975. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  152976. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  152977. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  152978. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  152979. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  152980. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  152981. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  152982. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  152983. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  152984. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  152985. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  152986. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  152987. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  152988. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  152989. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  152990. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  152991. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  152992. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  152993. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  152994. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  152995. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  152996. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  152997. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  152998. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  152999. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  153000. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  153001. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  153002. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  153003. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  153004. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  153005. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  153006. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  153007. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  153008. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  153009. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  153010. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  153011. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  153012. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  153013. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  153014. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  153015. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  153016. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  153017. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  153018. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  153019. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  153020. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  153021. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  153022. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  153023. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  153024. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  153025. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  153026. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  153027. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  153028. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  153029. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  153030. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  153031. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  153032. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  153033. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  153034. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  153035. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  153036. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  153037. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  153038. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  153039. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  153040. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  153041. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  153042. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  153043. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  153044. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  153045. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  153046. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  153047. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  153048. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  153049. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  153050. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  153051. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  153052. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  153053. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  153054. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  153055. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  153056. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  153057. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  153058. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  153059. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  153060. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  153061. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  153062. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  153063. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  153064. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  153065. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  153066. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  153067. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  153068. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  153069. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  153070. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  153071. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  153072. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  153073. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  153074. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  153075. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  153076. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  153077. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  153078. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  153079. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  153080. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  153081. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  153082. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  153083. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  153084. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  153085. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  153086. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  153087. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  153088. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  153089. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  153090. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  153091. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  153092. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  153093. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  153094. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  153095. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  153096. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  153097. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  153098. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  153099. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  153100. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  153101. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  153102. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  153103. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  153104. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  153105. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  153106. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  153107. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  153108. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  153109. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  153110. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  153111. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  153112. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  153113. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  153114. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  153115. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  153116. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  153117. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  153118. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  153119. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  153120. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  153121. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  153122. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  153123. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  153124. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  153125. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  153126. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  153127. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  153128. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  153129. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  153130. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  153131. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  153132. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  153133. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  153134. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  153135. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  153136. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  153137. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  153138. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  153139. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  153140. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  153141. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  153142. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  153143. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  153144. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  153145. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  153146. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  153147. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  153148. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  153149. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  153150. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  153151. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  153152. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  153153. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  153154. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  153155. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  153156. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  153157. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  153158. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  153159. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  153160. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  153161. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  153162. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  153163. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  153164. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  153165. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  153166. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  153167. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  153168. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  153169. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  153170. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  153171. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  153172. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  153173. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  153174. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  153175. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  153176. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  153177. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  153178. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  153179. };
  153180. static float vwin4096[2048] = {
  153181. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  153182. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  153183. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  153184. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  153185. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  153186. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  153187. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  153188. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  153189. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  153190. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  153191. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  153192. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  153193. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  153194. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  153195. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  153196. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  153197. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  153198. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  153199. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  153200. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  153201. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  153202. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  153203. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  153204. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  153205. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  153206. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  153207. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  153208. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  153209. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  153210. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  153211. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  153212. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  153213. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  153214. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  153215. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  153216. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  153217. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  153218. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  153219. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  153220. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  153221. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  153222. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  153223. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  153224. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  153225. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  153226. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  153227. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  153228. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  153229. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  153230. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  153231. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  153232. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  153233. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  153234. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  153235. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  153236. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  153237. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  153238. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  153239. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  153240. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  153241. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  153242. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  153243. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  153244. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  153245. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  153246. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  153247. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  153248. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  153249. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  153250. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  153251. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  153252. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  153253. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  153254. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  153255. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  153256. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  153257. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  153258. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  153259. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  153260. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  153261. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  153262. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  153263. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  153264. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  153265. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  153266. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  153267. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  153268. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  153269. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  153270. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  153271. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  153272. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  153273. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  153274. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  153275. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  153276. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  153277. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  153278. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  153279. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  153280. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  153281. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  153282. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  153283. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  153284. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  153285. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  153286. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  153287. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  153288. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  153289. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  153290. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  153291. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  153292. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  153293. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  153294. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  153295. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  153296. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  153297. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  153298. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  153299. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  153300. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  153301. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  153302. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  153303. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  153304. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  153305. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  153306. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  153307. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  153308. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  153309. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  153310. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  153311. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  153312. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  153313. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  153314. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  153315. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  153316. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  153317. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  153318. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  153319. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  153320. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  153321. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  153322. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  153323. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  153324. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  153325. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  153326. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  153327. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  153328. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  153329. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  153330. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  153331. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  153332. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  153333. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  153334. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  153335. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  153336. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  153337. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  153338. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  153339. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  153340. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  153341. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  153342. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  153343. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  153344. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  153345. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  153346. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  153347. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  153348. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  153349. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  153350. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  153351. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  153352. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  153353. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  153354. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  153355. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  153356. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  153357. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  153358. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  153359. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  153360. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  153361. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  153362. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  153363. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  153364. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  153365. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  153366. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  153367. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  153368. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  153369. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  153370. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  153371. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  153372. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  153373. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  153374. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  153375. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  153376. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  153377. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  153378. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  153379. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  153380. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  153381. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  153382. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  153383. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  153384. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  153385. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  153386. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  153387. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  153388. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  153389. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  153390. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  153391. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  153392. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  153393. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  153394. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  153395. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  153396. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  153397. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  153398. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  153399. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  153400. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  153401. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  153402. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  153403. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  153404. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  153405. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  153406. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  153407. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  153408. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  153409. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  153410. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  153411. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  153412. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  153413. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  153414. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  153415. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  153416. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  153417. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  153418. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  153419. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  153420. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  153421. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  153422. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  153423. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  153424. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  153425. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  153426. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  153427. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  153428. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  153429. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  153430. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  153431. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  153432. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  153433. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  153434. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  153435. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  153436. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  153437. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  153438. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  153439. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  153440. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  153441. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  153442. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  153443. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  153444. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  153445. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  153446. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  153447. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  153448. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  153449. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  153450. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  153451. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  153452. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  153453. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  153454. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  153455. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  153456. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  153457. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  153458. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  153459. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  153460. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  153461. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  153462. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  153463. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  153464. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  153465. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  153466. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  153467. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  153468. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  153469. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  153470. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  153471. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  153472. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  153473. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  153474. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  153475. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  153476. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  153477. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  153478. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  153479. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  153480. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  153481. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  153482. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  153483. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  153484. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  153485. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  153486. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  153487. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  153488. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  153489. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  153490. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  153491. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  153492. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  153493. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  153494. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  153495. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  153496. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  153497. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  153498. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  153499. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  153500. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  153501. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  153502. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  153503. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  153504. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  153505. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  153506. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  153507. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  153508. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  153509. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  153510. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  153511. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  153512. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  153513. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  153514. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  153515. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  153516. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  153517. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  153518. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  153519. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  153520. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  153521. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  153522. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  153523. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  153524. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  153525. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  153526. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  153527. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  153528. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  153529. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  153530. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  153531. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  153532. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  153533. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  153534. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  153535. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  153536. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  153537. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  153538. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  153539. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  153540. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  153541. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  153542. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  153543. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  153544. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  153545. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  153546. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  153547. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  153548. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  153549. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  153550. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  153551. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  153552. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  153553. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  153554. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  153555. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  153556. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  153557. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  153558. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  153559. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  153560. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  153561. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  153562. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  153563. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  153564. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  153565. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  153566. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  153567. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  153568. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  153569. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  153570. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  153571. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  153572. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  153573. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  153574. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  153575. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  153576. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  153577. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  153578. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  153579. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  153580. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  153581. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  153582. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  153583. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  153584. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  153585. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  153586. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  153587. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  153588. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  153589. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  153590. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  153591. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  153592. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  153593. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  153594. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  153595. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  153596. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  153597. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  153598. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  153599. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  153600. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  153601. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  153602. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  153603. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  153604. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  153605. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  153606. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  153607. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  153608. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  153609. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  153610. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  153611. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  153612. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  153613. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  153614. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  153615. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  153616. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  153617. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  153618. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  153619. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  153620. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  153621. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  153622. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  153623. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  153624. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  153625. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  153626. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  153627. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  153628. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  153629. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  153630. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  153631. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  153632. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  153633. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  153634. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  153635. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  153636. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  153637. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  153638. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  153639. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  153640. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  153641. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  153642. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  153643. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  153644. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  153645. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  153646. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  153647. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  153648. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  153649. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  153650. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  153651. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  153652. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  153653. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  153654. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  153655. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  153656. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  153657. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  153658. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  153659. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  153660. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  153661. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  153662. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  153663. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  153664. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  153665. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  153666. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  153667. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  153668. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  153669. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  153670. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  153671. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  153672. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  153673. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  153674. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  153675. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  153676. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  153677. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  153678. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  153679. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  153680. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  153681. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  153682. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  153683. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  153684. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  153685. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  153686. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  153687. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  153688. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  153689. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  153690. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  153691. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  153692. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  153693. };
  153694. static float vwin8192[4096] = {
  153695. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  153696. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  153697. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  153698. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  153699. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  153700. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  153701. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  153702. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  153703. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  153704. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  153705. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  153706. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  153707. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  153708. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  153709. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  153710. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  153711. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  153712. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  153713. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  153714. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  153715. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  153716. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  153717. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  153718. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  153719. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  153720. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  153721. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  153722. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  153723. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  153724. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  153725. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  153726. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  153727. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  153728. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  153729. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  153730. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  153731. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  153732. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  153733. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  153734. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  153735. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  153736. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  153737. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  153738. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  153739. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  153740. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  153741. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  153742. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  153743. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  153744. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  153745. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  153746. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  153747. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  153748. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  153749. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  153750. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  153751. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  153752. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  153753. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  153754. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  153755. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  153756. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  153757. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  153758. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  153759. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  153760. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  153761. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  153762. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  153763. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  153764. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  153765. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  153766. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  153767. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  153768. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  153769. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  153770. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  153771. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  153772. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  153773. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  153774. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  153775. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  153776. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  153777. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  153778. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  153779. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  153780. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  153781. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  153782. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  153783. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  153784. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  153785. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  153786. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  153787. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  153788. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  153789. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  153790. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  153791. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  153792. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  153793. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  153794. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  153795. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  153796. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  153797. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  153798. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  153799. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  153800. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  153801. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  153802. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  153803. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  153804. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  153805. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  153806. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  153807. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  153808. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  153809. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  153810. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  153811. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  153812. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  153813. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  153814. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  153815. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  153816. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  153817. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  153818. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  153819. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  153820. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  153821. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  153822. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  153823. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  153824. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  153825. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  153826. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  153827. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  153828. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  153829. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  153830. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  153831. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  153832. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  153833. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  153834. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  153835. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  153836. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  153837. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  153838. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  153839. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  153840. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  153841. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  153842. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  153843. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  153844. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  153845. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  153846. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  153847. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  153848. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  153849. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  153850. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  153851. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  153852. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  153853. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  153854. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  153855. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  153856. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  153857. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  153858. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  153859. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  153860. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  153861. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  153862. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  153863. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  153864. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  153865. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  153866. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  153867. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  153868. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  153869. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  153870. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  153871. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  153872. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  153873. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  153874. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  153875. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  153876. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  153877. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  153878. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  153879. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  153880. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  153881. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  153882. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  153883. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  153884. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  153885. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  153886. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  153887. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  153888. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  153889. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  153890. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  153891. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  153892. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  153893. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  153894. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  153895. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  153896. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  153897. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  153898. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  153899. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  153900. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  153901. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  153902. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  153903. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  153904. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  153905. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  153906. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  153907. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  153908. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  153909. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  153910. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  153911. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  153912. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  153913. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  153914. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  153915. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  153916. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  153917. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  153918. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  153919. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  153920. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  153921. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  153922. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  153923. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  153924. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  153925. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  153926. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  153927. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  153928. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  153929. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  153930. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  153931. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  153932. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  153933. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  153934. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  153935. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  153936. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  153937. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  153938. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  153939. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  153940. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  153941. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  153942. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  153943. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  153944. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  153945. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  153946. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  153947. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  153948. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  153949. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  153950. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  153951. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  153952. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  153953. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  153954. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  153955. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  153956. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  153957. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  153958. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  153959. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  153960. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  153961. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  153962. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  153963. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  153964. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  153965. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  153966. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  153967. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  153968. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  153969. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  153970. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  153971. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  153972. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  153973. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  153974. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  153975. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  153976. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  153977. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  153978. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  153979. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  153980. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  153981. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  153982. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  153983. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  153984. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  153985. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  153986. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  153987. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  153988. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  153989. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  153990. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  153991. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  153992. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  153993. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  153994. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  153995. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  153996. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  153997. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  153998. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  153999. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  154000. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  154001. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  154002. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  154003. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  154004. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  154005. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  154006. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  154007. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  154008. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  154009. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  154010. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  154011. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  154012. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  154013. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  154014. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  154015. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  154016. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  154017. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  154018. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  154019. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  154020. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  154021. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  154022. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  154023. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  154024. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  154025. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  154026. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  154027. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  154028. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  154029. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  154030. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  154031. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  154032. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  154033. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  154034. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  154035. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  154036. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  154037. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  154038. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  154039. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  154040. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  154041. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  154042. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  154043. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  154044. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  154045. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  154046. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  154047. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  154048. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  154049. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  154050. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  154051. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  154052. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  154053. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  154054. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  154055. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  154056. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  154057. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  154058. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  154059. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  154060. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  154061. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  154062. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  154063. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  154064. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  154065. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  154066. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  154067. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  154068. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  154069. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  154070. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  154071. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  154072. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  154073. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  154074. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  154075. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  154076. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  154077. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  154078. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  154079. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  154080. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  154081. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  154082. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  154083. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  154084. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  154085. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  154086. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  154087. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  154088. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  154089. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  154090. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  154091. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  154092. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  154093. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  154094. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  154095. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  154096. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  154097. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  154098. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  154099. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  154100. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  154101. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  154102. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  154103. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  154104. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  154105. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  154106. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  154107. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  154108. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  154109. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  154110. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  154111. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  154112. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  154113. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  154114. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  154115. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  154116. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  154117. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  154118. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  154119. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  154120. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  154121. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  154122. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  154123. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  154124. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  154125. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  154126. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  154127. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  154128. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  154129. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  154130. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  154131. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  154132. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  154133. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  154134. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  154135. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  154136. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  154137. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  154138. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  154139. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  154140. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  154141. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  154142. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  154143. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  154144. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  154145. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  154146. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  154147. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  154148. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  154149. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  154150. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  154151. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  154152. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  154153. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  154154. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  154155. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  154156. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  154157. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  154158. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  154159. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  154160. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  154161. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  154162. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  154163. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  154164. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  154165. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  154166. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  154167. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  154168. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  154169. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  154170. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  154171. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  154172. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  154173. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  154174. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  154175. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  154176. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  154177. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  154178. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  154179. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  154180. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  154181. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  154182. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  154183. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  154184. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  154185. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  154186. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  154187. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  154188. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  154189. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  154190. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  154191. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  154192. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  154193. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  154194. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  154195. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  154196. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  154197. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  154198. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  154199. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  154200. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  154201. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  154202. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  154203. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  154204. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  154205. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  154206. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  154207. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  154208. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  154209. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  154210. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  154211. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  154212. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  154213. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  154214. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  154215. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  154216. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  154217. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  154218. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  154219. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  154220. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  154221. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  154222. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  154223. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  154224. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  154225. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  154226. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  154227. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  154228. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  154229. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  154230. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  154231. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  154232. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  154233. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  154234. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  154235. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  154236. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  154237. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  154238. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  154239. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  154240. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  154241. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  154242. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  154243. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  154244. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  154245. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  154246. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  154247. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  154248. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  154249. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  154250. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  154251. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  154252. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  154253. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  154254. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  154255. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  154256. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  154257. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  154258. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  154259. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  154260. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  154261. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  154262. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  154263. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  154264. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  154265. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  154266. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  154267. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  154268. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  154269. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  154270. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  154271. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  154272. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  154273. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  154274. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  154275. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  154276. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  154277. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  154278. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  154279. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  154280. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  154281. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  154282. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  154283. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  154284. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  154285. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  154286. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  154287. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  154288. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  154289. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  154290. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  154291. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  154292. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  154293. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  154294. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  154295. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  154296. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  154297. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  154298. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  154299. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  154300. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  154301. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  154302. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  154303. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  154304. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  154305. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  154306. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  154307. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  154308. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  154309. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  154310. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  154311. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  154312. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  154313. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  154314. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  154315. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  154316. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  154317. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  154318. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  154319. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  154320. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  154321. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  154322. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  154323. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  154324. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  154325. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  154326. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  154327. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  154328. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  154329. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  154330. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  154331. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  154332. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  154333. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  154334. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  154335. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  154336. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  154337. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  154338. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  154339. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  154340. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  154341. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  154342. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  154343. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  154344. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  154345. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  154346. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  154347. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  154348. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  154349. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  154350. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  154351. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  154352. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  154353. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  154354. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  154355. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  154356. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  154357. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  154358. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  154359. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  154360. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  154361. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  154362. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  154363. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  154364. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  154365. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  154366. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  154367. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  154368. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  154369. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  154370. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  154371. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  154372. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  154373. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  154374. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  154375. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  154376. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  154377. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  154378. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  154379. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  154380. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  154381. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  154382. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  154383. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  154384. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  154385. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  154386. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  154387. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  154388. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  154389. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  154390. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  154391. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  154392. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  154393. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  154394. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  154395. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  154396. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  154397. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  154398. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  154399. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  154400. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  154401. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  154402. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  154403. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  154404. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  154405. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  154406. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  154407. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  154408. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  154409. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  154410. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  154411. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  154412. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  154413. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  154414. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  154415. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  154416. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  154417. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  154418. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  154419. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  154420. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  154421. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  154422. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  154423. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  154424. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  154425. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  154426. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  154427. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  154428. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  154429. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  154430. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  154431. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  154432. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  154433. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  154434. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  154435. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  154436. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  154437. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  154438. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  154439. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  154440. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  154441. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  154442. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  154443. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  154444. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  154445. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  154446. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  154447. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  154448. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  154449. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  154450. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  154451. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  154452. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  154453. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  154454. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  154455. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  154456. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  154457. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  154458. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  154459. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  154460. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  154461. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  154462. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  154463. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  154464. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  154465. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  154466. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  154467. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  154468. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  154469. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  154470. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  154471. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  154472. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  154473. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  154474. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  154475. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  154476. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  154477. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  154478. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  154479. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  154480. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  154481. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  154482. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  154483. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  154484. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  154485. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  154486. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  154487. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  154488. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  154489. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  154490. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  154491. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  154492. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  154493. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  154494. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  154495. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  154496. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  154497. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  154498. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  154499. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  154500. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  154501. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  154502. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  154503. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  154504. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  154505. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  154506. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  154507. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  154508. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  154509. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  154510. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  154511. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  154512. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  154513. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  154514. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  154515. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  154516. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  154517. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  154518. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  154519. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  154520. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  154521. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  154522. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  154523. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  154524. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  154525. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  154526. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  154527. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  154528. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  154529. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  154530. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  154531. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  154532. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  154533. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  154534. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  154535. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  154536. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  154537. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  154538. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  154539. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  154540. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  154541. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  154542. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  154543. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  154544. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  154545. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  154546. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  154547. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  154548. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  154549. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  154550. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  154551. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  154552. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  154553. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  154554. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  154555. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  154556. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  154557. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  154558. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  154559. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  154560. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  154561. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  154562. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  154563. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  154564. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  154565. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  154566. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  154567. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  154568. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  154569. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  154570. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  154571. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  154572. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  154573. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  154574. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  154575. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  154576. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  154577. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  154578. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  154579. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  154580. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  154581. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  154582. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  154583. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  154584. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  154585. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  154586. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  154587. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  154588. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  154589. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  154590. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  154591. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  154592. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  154593. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  154594. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  154595. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  154596. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  154597. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  154598. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  154599. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  154600. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  154601. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  154602. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  154603. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  154604. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  154605. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  154606. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  154607. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  154608. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  154609. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  154610. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  154611. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  154612. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  154613. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  154614. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  154615. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  154616. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  154617. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  154618. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  154619. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  154620. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  154621. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  154622. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  154623. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  154624. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  154625. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  154626. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  154627. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  154628. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  154629. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  154630. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  154631. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  154632. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  154633. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  154634. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  154635. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  154636. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  154637. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  154638. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  154639. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  154640. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  154641. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  154642. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  154643. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  154644. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  154645. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  154646. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  154647. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  154648. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  154649. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  154650. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  154651. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  154652. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  154653. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  154654. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  154655. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  154656. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  154657. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  154658. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  154659. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  154660. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  154661. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  154662. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  154663. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  154664. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  154665. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  154666. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  154667. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  154668. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  154669. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  154670. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  154671. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  154672. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  154673. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  154674. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  154675. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  154676. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  154677. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  154678. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  154679. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  154680. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  154681. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  154682. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  154683. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  154684. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  154685. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  154686. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  154687. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  154688. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  154689. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  154690. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  154691. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  154692. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  154693. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  154694. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  154695. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  154696. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  154697. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  154698. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  154699. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  154700. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  154701. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  154702. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  154703. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  154704. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  154705. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  154706. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  154707. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  154708. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  154709. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  154710. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  154711. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  154712. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  154713. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  154714. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  154715. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  154716. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  154717. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154718. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  154719. };
  154720. static float *vwin[8] = {
  154721. vwin64,
  154722. vwin128,
  154723. vwin256,
  154724. vwin512,
  154725. vwin1024,
  154726. vwin2048,
  154727. vwin4096,
  154728. vwin8192,
  154729. };
  154730. float *_vorbis_window_get(int n){
  154731. return vwin[n];
  154732. }
  154733. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  154734. int lW,int W,int nW){
  154735. lW=(W?lW:0);
  154736. nW=(W?nW:0);
  154737. {
  154738. float *windowLW=vwin[winno[lW]];
  154739. float *windowNW=vwin[winno[nW]];
  154740. long n=blocksizes[W];
  154741. long ln=blocksizes[lW];
  154742. long rn=blocksizes[nW];
  154743. long leftbegin=n/4-ln/4;
  154744. long leftend=leftbegin+ln/2;
  154745. long rightbegin=n/2+n/4-rn/4;
  154746. long rightend=rightbegin+rn/2;
  154747. int i,p;
  154748. for(i=0;i<leftbegin;i++)
  154749. d[i]=0.f;
  154750. for(p=0;i<leftend;i++,p++)
  154751. d[i]*=windowLW[p];
  154752. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  154753. d[i]*=windowNW[p];
  154754. for(;i<n;i++)
  154755. d[i]=0.f;
  154756. }
  154757. }
  154758. #endif
  154759. /********* End of inlined file: window.c *********/
  154760. #else
  154761. #include <vorbis/vorbisenc.h>
  154762. #include <vorbis/codec.h>
  154763. #include <vorbis/vorbisfile.h>
  154764. #endif
  154765. }
  154766. BEGIN_JUCE_NAMESPACE
  154767. using namespace OggVorbisNamespace;
  154768. #define oggFormatName TRANS("Ogg-Vorbis file")
  154769. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  154770. class OggReader : public AudioFormatReader
  154771. {
  154772. OggVorbis_File ovFile;
  154773. ov_callbacks callbacks;
  154774. AudioSampleBuffer reservoir;
  154775. int reservoirStart, samplesInReservoir;
  154776. public:
  154777. OggReader (InputStream* const inp)
  154778. : AudioFormatReader (inp, oggFormatName),
  154779. reservoir (2, 4096),
  154780. reservoirStart (0),
  154781. samplesInReservoir (0)
  154782. {
  154783. sampleRate = 0;
  154784. usesFloatingPointData = true;
  154785. callbacks.read_func = &oggReadCallback;
  154786. callbacks.seek_func = &oggSeekCallback;
  154787. callbacks.close_func = &oggCloseCallback;
  154788. callbacks.tell_func = &oggTellCallback;
  154789. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  154790. if (err == 0)
  154791. {
  154792. vorbis_info* info = ov_info (&ovFile, -1);
  154793. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  154794. numChannels = info->channels;
  154795. bitsPerSample = 16;
  154796. sampleRate = info->rate;
  154797. reservoir.setSize (numChannels,
  154798. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  154799. }
  154800. }
  154801. ~OggReader()
  154802. {
  154803. ov_clear (&ovFile);
  154804. }
  154805. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  154806. int64 startSampleInFile, int numSamples)
  154807. {
  154808. while (numSamples > 0)
  154809. {
  154810. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  154811. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  154812. {
  154813. // got a few samples overlapping, so use them before seeking..
  154814. const int numToUse = jmin (numSamples, numAvailable);
  154815. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  154816. if (destSamples[i] != 0)
  154817. memcpy (destSamples[i] + startOffsetInDestBuffer,
  154818. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  154819. sizeof (float) * numToUse);
  154820. startSampleInFile += numToUse;
  154821. numSamples -= numToUse;
  154822. startOffsetInDestBuffer += numToUse;
  154823. if (numSamples == 0)
  154824. break;
  154825. }
  154826. if (startSampleInFile < reservoirStart
  154827. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  154828. {
  154829. // buffer miss, so refill the reservoir
  154830. int bitStream = 0;
  154831. reservoirStart = jmax (0, (int) startSampleInFile);
  154832. samplesInReservoir = reservoir.getNumSamples();
  154833. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  154834. ov_pcm_seek (&ovFile, reservoirStart);
  154835. int offset = 0;
  154836. int numToRead = samplesInReservoir;
  154837. while (numToRead > 0)
  154838. {
  154839. float** dataIn = 0;
  154840. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  154841. if (samps == 0)
  154842. break;
  154843. jassert (samps <= numToRead);
  154844. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  154845. {
  154846. memcpy (reservoir.getSampleData (i, offset),
  154847. dataIn[i],
  154848. sizeof (float) * samps);
  154849. }
  154850. numToRead -= samps;
  154851. offset += samps;
  154852. }
  154853. if (numToRead > 0)
  154854. reservoir.clear (offset, numToRead);
  154855. }
  154856. }
  154857. if (numSamples > 0)
  154858. {
  154859. for (int i = numDestChannels; --i >= 0;)
  154860. if (destSamples[i] != 0)
  154861. zeromem (destSamples[i] + startOffsetInDestBuffer,
  154862. sizeof (int) * numSamples);
  154863. }
  154864. return true;
  154865. }
  154866. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  154867. {
  154868. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  154869. }
  154870. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  154871. {
  154872. InputStream* const in = (InputStream*) datasource;
  154873. if (whence == SEEK_CUR)
  154874. offset += in->getPosition();
  154875. else if (whence == SEEK_END)
  154876. offset += in->getTotalLength();
  154877. in->setPosition (offset);
  154878. return 0;
  154879. }
  154880. static int oggCloseCallback (void*)
  154881. {
  154882. return 0;
  154883. }
  154884. static long oggTellCallback (void* datasource)
  154885. {
  154886. return (long) ((InputStream*) datasource)->getPosition();
  154887. }
  154888. juce_UseDebuggingNewOperator
  154889. };
  154890. class OggWriter : public AudioFormatWriter
  154891. {
  154892. ogg_stream_state os;
  154893. ogg_page og;
  154894. ogg_packet op;
  154895. vorbis_info vi;
  154896. vorbis_comment vc;
  154897. vorbis_dsp_state vd;
  154898. vorbis_block vb;
  154899. public:
  154900. bool ok;
  154901. OggWriter (OutputStream* const out,
  154902. const double sampleRate,
  154903. const int numChannels,
  154904. const int bitsPerSample,
  154905. const int qualityIndex)
  154906. : AudioFormatWriter (out, oggFormatName,
  154907. sampleRate,
  154908. numChannels,
  154909. bitsPerSample)
  154910. {
  154911. ok = false;
  154912. vorbis_info_init (&vi);
  154913. if (vorbis_encode_init_vbr (&vi,
  154914. numChannels,
  154915. (int) sampleRate,
  154916. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  154917. {
  154918. vorbis_comment_init (&vc);
  154919. if (JUCEApplication::getInstance() != 0)
  154920. vorbis_comment_add_tag (&vc, "ENCODER",
  154921. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  154922. vorbis_analysis_init (&vd, &vi);
  154923. vorbis_block_init (&vd, &vb);
  154924. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  154925. ogg_packet header;
  154926. ogg_packet header_comm;
  154927. ogg_packet header_code;
  154928. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  154929. ogg_stream_packetin (&os, &header);
  154930. ogg_stream_packetin (&os, &header_comm);
  154931. ogg_stream_packetin (&os, &header_code);
  154932. for (;;)
  154933. {
  154934. if (ogg_stream_flush (&os, &og) == 0)
  154935. break;
  154936. output->write (og.header, og.header_len);
  154937. output->write (og.body, og.body_len);
  154938. }
  154939. ok = true;
  154940. }
  154941. }
  154942. ~OggWriter()
  154943. {
  154944. if (ok)
  154945. {
  154946. // write a zero-length packet to show ogg that we're finished..
  154947. write (0, 0);
  154948. ogg_stream_clear (&os);
  154949. vorbis_block_clear (&vb);
  154950. vorbis_dsp_clear (&vd);
  154951. vorbis_comment_clear (&vc);
  154952. vorbis_info_clear (&vi);
  154953. output->flush();
  154954. }
  154955. else
  154956. {
  154957. vorbis_info_clear (&vi);
  154958. output = 0; // to stop the base class deleting this, as it needs to be returned
  154959. // to the caller of createWriter()
  154960. }
  154961. }
  154962. bool write (const int** samplesToWrite, int numSamples)
  154963. {
  154964. if (! ok)
  154965. return false;
  154966. if (numSamples > 0)
  154967. {
  154968. const double gain = 1.0 / 0x80000000u;
  154969. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  154970. for (int i = numChannels; --i >= 0;)
  154971. {
  154972. float* const dst = vorbisBuffer[i];
  154973. const int* const src = samplesToWrite [i];
  154974. if (src != 0 && dst != 0)
  154975. {
  154976. for (int j = 0; j < numSamples; ++j)
  154977. dst[j] = (float) (src[j] * gain);
  154978. }
  154979. }
  154980. }
  154981. vorbis_analysis_wrote (&vd, numSamples);
  154982. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  154983. {
  154984. vorbis_analysis (&vb, 0);
  154985. vorbis_bitrate_addblock (&vb);
  154986. while (vorbis_bitrate_flushpacket (&vd, &op))
  154987. {
  154988. ogg_stream_packetin (&os, &op);
  154989. for (;;)
  154990. {
  154991. if (ogg_stream_pageout (&os, &og) == 0)
  154992. break;
  154993. output->write (og.header, og.header_len);
  154994. output->write (og.body, og.body_len);
  154995. if (ogg_page_eos (&og))
  154996. break;
  154997. }
  154998. }
  154999. }
  155000. return true;
  155001. }
  155002. juce_UseDebuggingNewOperator
  155003. };
  155004. OggVorbisAudioFormat::OggVorbisAudioFormat()
  155005. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  155006. {
  155007. }
  155008. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  155009. {
  155010. }
  155011. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  155012. {
  155013. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  155014. return Array <int> (rates);
  155015. }
  155016. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  155017. {
  155018. Array <int> depths;
  155019. depths.add (32);
  155020. return depths;
  155021. }
  155022. bool OggVorbisAudioFormat::canDoStereo()
  155023. {
  155024. return true;
  155025. }
  155026. bool OggVorbisAudioFormat::canDoMono()
  155027. {
  155028. return true;
  155029. }
  155030. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  155031. const bool deleteStreamIfOpeningFails)
  155032. {
  155033. OggReader* r = new OggReader (in);
  155034. if (r->sampleRate == 0)
  155035. {
  155036. if (! deleteStreamIfOpeningFails)
  155037. r->input = 0;
  155038. deleteAndZero (r);
  155039. }
  155040. return r;
  155041. }
  155042. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  155043. double sampleRate,
  155044. unsigned int numChannels,
  155045. int bitsPerSample,
  155046. const StringPairArray& /*metadataValues*/,
  155047. int qualityOptionIndex)
  155048. {
  155049. OggWriter* w = new OggWriter (out,
  155050. sampleRate,
  155051. numChannels,
  155052. bitsPerSample,
  155053. qualityOptionIndex);
  155054. if (! w->ok)
  155055. deleteAndZero (w);
  155056. return w;
  155057. }
  155058. bool OggVorbisAudioFormat::isCompressed()
  155059. {
  155060. return true;
  155061. }
  155062. const StringArray OggVorbisAudioFormat::getQualityOptions()
  155063. {
  155064. StringArray s;
  155065. s.add ("Low Quality");
  155066. s.add ("Medium Quality");
  155067. s.add ("High Quality");
  155068. return s;
  155069. }
  155070. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  155071. {
  155072. FileInputStream* const in = source.createInputStream();
  155073. if (in != 0)
  155074. {
  155075. AudioFormatReader* const r = createReaderFor (in, true);
  155076. if (r != 0)
  155077. {
  155078. const int64 numSamps = r->lengthInSamples;
  155079. delete r;
  155080. const int64 fileNumSamps = source.getSize() / 4;
  155081. const double ratio = numSamps / (double) fileNumSamps;
  155082. if (ratio > 12.0)
  155083. return 0;
  155084. else if (ratio > 6.0)
  155085. return 1;
  155086. else
  155087. return 2;
  155088. }
  155089. }
  155090. return 1;
  155091. }
  155092. END_JUCE_NAMESPACE
  155093. #endif
  155094. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  155095. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  155096. #if JUCE_MSVC
  155097. #pragma warning (push)
  155098. #endif
  155099. namespace jpeglibNamespace
  155100. {
  155101. #if JUCE_INCLUDE_JPEGLIB_CODE
  155102. extern "C"
  155103. {
  155104. #define JPEG_INTERNALS
  155105. #undef FAR
  155106. /********* Start of inlined file: jpeglib.h *********/
  155107. #ifndef JPEGLIB_H
  155108. #define JPEGLIB_H
  155109. /*
  155110. * First we include the configuration files that record how this
  155111. * installation of the JPEG library is set up. jconfig.h can be
  155112. * generated automatically for many systems. jmorecfg.h contains
  155113. * manual configuration options that most people need not worry about.
  155114. */
  155115. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  155116. /********* Start of inlined file: jconfig.h *********/
  155117. /* see jconfig.doc for explanations */
  155118. // disable all the warnings under MSVC
  155119. #ifdef _MSC_VER
  155120. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  155121. #endif
  155122. #ifdef __BORLANDC__
  155123. #pragma warn -8057
  155124. #pragma warn -8019
  155125. #pragma warn -8004
  155126. #pragma warn -8008
  155127. #endif
  155128. #define HAVE_PROTOTYPES
  155129. #define HAVE_UNSIGNED_CHAR
  155130. #define HAVE_UNSIGNED_SHORT
  155131. /* #define void char */
  155132. /* #define const */
  155133. #undef CHAR_IS_UNSIGNED
  155134. #define HAVE_STDDEF_H
  155135. #define HAVE_STDLIB_H
  155136. #undef NEED_BSD_STRINGS
  155137. #undef NEED_SYS_TYPES_H
  155138. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  155139. #undef NEED_SHORT_EXTERNAL_NAMES
  155140. #undef INCOMPLETE_TYPES_BROKEN
  155141. /* Define "boolean" as unsigned char, not int, per Windows custom */
  155142. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  155143. typedef unsigned char boolean;
  155144. #endif
  155145. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  155146. #ifdef JPEG_INTERNALS
  155147. #undef RIGHT_SHIFT_IS_UNSIGNED
  155148. #endif /* JPEG_INTERNALS */
  155149. #ifdef JPEG_CJPEG_DJPEG
  155150. #define BMP_SUPPORTED /* BMP image file format */
  155151. #define GIF_SUPPORTED /* GIF image file format */
  155152. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  155153. #undef RLE_SUPPORTED /* Utah RLE image file format */
  155154. #define TARGA_SUPPORTED /* Targa image file format */
  155155. #define TWO_FILE_COMMANDLINE /* optional */
  155156. #define USE_SETMODE /* Microsoft has setmode() */
  155157. #undef NEED_SIGNAL_CATCHER
  155158. #undef DONT_USE_B_MODE
  155159. #undef PROGRESS_REPORT /* optional */
  155160. #endif /* JPEG_CJPEG_DJPEG */
  155161. /********* End of inlined file: jconfig.h *********/
  155162. /* widely used configuration options */
  155163. #endif
  155164. /********* Start of inlined file: jmorecfg.h *********/
  155165. /*
  155166. * Define BITS_IN_JSAMPLE as either
  155167. * 8 for 8-bit sample values (the usual setting)
  155168. * 12 for 12-bit sample values
  155169. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  155170. * JPEG standard, and the IJG code does not support anything else!
  155171. * We do not support run-time selection of data precision, sorry.
  155172. */
  155173. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  155174. /*
  155175. * Maximum number of components (color channels) allowed in JPEG image.
  155176. * To meet the letter of the JPEG spec, set this to 255. However, darn
  155177. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  155178. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  155179. * really short on memory. (Each allowed component costs a hundred or so
  155180. * bytes of storage, whether actually used in an image or not.)
  155181. */
  155182. #define MAX_COMPONENTS 10 /* maximum number of image components */
  155183. /*
  155184. * Basic data types.
  155185. * You may need to change these if you have a machine with unusual data
  155186. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  155187. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  155188. * but it had better be at least 16.
  155189. */
  155190. /* Representation of a single sample (pixel element value).
  155191. * We frequently allocate large arrays of these, so it's important to keep
  155192. * them small. But if you have memory to burn and access to char or short
  155193. * arrays is very slow on your hardware, you might want to change these.
  155194. */
  155195. #if BITS_IN_JSAMPLE == 8
  155196. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  155197. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  155198. */
  155199. #ifdef HAVE_UNSIGNED_CHAR
  155200. typedef unsigned char JSAMPLE;
  155201. #define GETJSAMPLE(value) ((int) (value))
  155202. #else /* not HAVE_UNSIGNED_CHAR */
  155203. typedef char JSAMPLE;
  155204. #ifdef CHAR_IS_UNSIGNED
  155205. #define GETJSAMPLE(value) ((int) (value))
  155206. #else
  155207. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  155208. #endif /* CHAR_IS_UNSIGNED */
  155209. #endif /* HAVE_UNSIGNED_CHAR */
  155210. #define MAXJSAMPLE 255
  155211. #define CENTERJSAMPLE 128
  155212. #endif /* BITS_IN_JSAMPLE == 8 */
  155213. #if BITS_IN_JSAMPLE == 12
  155214. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  155215. * On nearly all machines "short" will do nicely.
  155216. */
  155217. typedef short JSAMPLE;
  155218. #define GETJSAMPLE(value) ((int) (value))
  155219. #define MAXJSAMPLE 4095
  155220. #define CENTERJSAMPLE 2048
  155221. #endif /* BITS_IN_JSAMPLE == 12 */
  155222. /* Representation of a DCT frequency coefficient.
  155223. * This should be a signed value of at least 16 bits; "short" is usually OK.
  155224. * Again, we allocate large arrays of these, but you can change to int
  155225. * if you have memory to burn and "short" is really slow.
  155226. */
  155227. typedef short JCOEF;
  155228. /* Compressed datastreams are represented as arrays of JOCTET.
  155229. * These must be EXACTLY 8 bits wide, at least once they are written to
  155230. * external storage. Note that when using the stdio data source/destination
  155231. * managers, this is also the data type passed to fread/fwrite.
  155232. */
  155233. #ifdef HAVE_UNSIGNED_CHAR
  155234. typedef unsigned char JOCTET;
  155235. #define GETJOCTET(value) (value)
  155236. #else /* not HAVE_UNSIGNED_CHAR */
  155237. typedef char JOCTET;
  155238. #ifdef CHAR_IS_UNSIGNED
  155239. #define GETJOCTET(value) (value)
  155240. #else
  155241. #define GETJOCTET(value) ((value) & 0xFF)
  155242. #endif /* CHAR_IS_UNSIGNED */
  155243. #endif /* HAVE_UNSIGNED_CHAR */
  155244. /* These typedefs are used for various table entries and so forth.
  155245. * They must be at least as wide as specified; but making them too big
  155246. * won't cost a huge amount of memory, so we don't provide special
  155247. * extraction code like we did for JSAMPLE. (In other words, these
  155248. * typedefs live at a different point on the speed/space tradeoff curve.)
  155249. */
  155250. /* UINT8 must hold at least the values 0..255. */
  155251. #ifdef HAVE_UNSIGNED_CHAR
  155252. typedef unsigned char UINT8;
  155253. #else /* not HAVE_UNSIGNED_CHAR */
  155254. #ifdef CHAR_IS_UNSIGNED
  155255. typedef char UINT8;
  155256. #else /* not CHAR_IS_UNSIGNED */
  155257. typedef short UINT8;
  155258. #endif /* CHAR_IS_UNSIGNED */
  155259. #endif /* HAVE_UNSIGNED_CHAR */
  155260. /* UINT16 must hold at least the values 0..65535. */
  155261. #ifdef HAVE_UNSIGNED_SHORT
  155262. typedef unsigned short UINT16;
  155263. #else /* not HAVE_UNSIGNED_SHORT */
  155264. typedef unsigned int UINT16;
  155265. #endif /* HAVE_UNSIGNED_SHORT */
  155266. /* INT16 must hold at least the values -32768..32767. */
  155267. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  155268. typedef short INT16;
  155269. #endif
  155270. /* INT32 must hold at least signed 32-bit values. */
  155271. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  155272. typedef long INT32;
  155273. #endif
  155274. /* Datatype used for image dimensions. The JPEG standard only supports
  155275. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  155276. * "unsigned int" is sufficient on all machines. However, if you need to
  155277. * handle larger images and you don't mind deviating from the spec, you
  155278. * can change this datatype.
  155279. */
  155280. typedef unsigned int JDIMENSION;
  155281. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  155282. /* These macros are used in all function definitions and extern declarations.
  155283. * You could modify them if you need to change function linkage conventions;
  155284. * in particular, you'll need to do that to make the library a Windows DLL.
  155285. * Another application is to make all functions global for use with debuggers
  155286. * or code profilers that require it.
  155287. */
  155288. /* a function called through method pointers: */
  155289. #define METHODDEF(type) static type
  155290. /* a function used only in its module: */
  155291. #define LOCAL(type) static type
  155292. /* a function referenced thru EXTERNs: */
  155293. #define GLOBAL(type) type
  155294. /* a reference to a GLOBAL function: */
  155295. #define EXTERN(type) extern type
  155296. /* This macro is used to declare a "method", that is, a function pointer.
  155297. * We want to supply prototype parameters if the compiler can cope.
  155298. * Note that the arglist parameter must be parenthesized!
  155299. * Again, you can customize this if you need special linkage keywords.
  155300. */
  155301. #ifdef HAVE_PROTOTYPES
  155302. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  155303. #else
  155304. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  155305. #endif
  155306. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  155307. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  155308. * by just saying "FAR *" where such a pointer is needed. In a few places
  155309. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  155310. */
  155311. #ifdef NEED_FAR_POINTERS
  155312. #define FAR far
  155313. #else
  155314. #define FAR
  155315. #endif
  155316. /*
  155317. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  155318. * in standard header files. Or you may have conflicts with application-
  155319. * specific header files that you want to include together with these files.
  155320. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  155321. */
  155322. #ifndef HAVE_BOOLEAN
  155323. typedef int boolean;
  155324. #endif
  155325. #ifndef FALSE /* in case these macros already exist */
  155326. #define FALSE 0 /* values of boolean */
  155327. #endif
  155328. #ifndef TRUE
  155329. #define TRUE 1
  155330. #endif
  155331. /*
  155332. * The remaining options affect code selection within the JPEG library,
  155333. * but they don't need to be visible to most applications using the library.
  155334. * To minimize application namespace pollution, the symbols won't be
  155335. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  155336. */
  155337. #ifdef JPEG_INTERNALS
  155338. #define JPEG_INTERNAL_OPTIONS
  155339. #endif
  155340. #ifdef JPEG_INTERNAL_OPTIONS
  155341. /*
  155342. * These defines indicate whether to include various optional functions.
  155343. * Undefining some of these symbols will produce a smaller but less capable
  155344. * library. Note that you can leave certain source files out of the
  155345. * compilation/linking process if you've #undef'd the corresponding symbols.
  155346. * (You may HAVE to do that if your compiler doesn't like null source files.)
  155347. */
  155348. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  155349. /* Capability options common to encoder and decoder: */
  155350. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  155351. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  155352. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  155353. /* Encoder capability options: */
  155354. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155355. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155356. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155357. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  155358. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  155359. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  155360. * precision, so jchuff.c normally uses entropy optimization to compute
  155361. * usable tables for higher precision. If you don't want to do optimization,
  155362. * you'll have to supply different default Huffman tables.
  155363. * The exact same statements apply for progressive JPEG: the default tables
  155364. * don't work for progressive mode. (This may get fixed, however.)
  155365. */
  155366. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  155367. /* Decoder capability options: */
  155368. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  155369. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  155370. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  155371. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  155372. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  155373. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  155374. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  155375. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  155376. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  155377. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  155378. /* more capability options later, no doubt */
  155379. /*
  155380. * Ordering of RGB data in scanlines passed to or from the application.
  155381. * If your application wants to deal with data in the order B,G,R, just
  155382. * change these macros. You can also deal with formats such as R,G,B,X
  155383. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  155384. * the offsets will also change the order in which colormap data is organized.
  155385. * RESTRICTIONS:
  155386. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  155387. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  155388. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  155389. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  155390. * is not 3 (they don't understand about dummy color components!). So you
  155391. * can't use color quantization if you change that value.
  155392. */
  155393. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  155394. #define RGB_GREEN 1 /* Offset of Green */
  155395. #define RGB_BLUE 2 /* Offset of Blue */
  155396. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  155397. /* Definitions for speed-related optimizations. */
  155398. /* If your compiler supports inline functions, define INLINE
  155399. * as the inline keyword; otherwise define it as empty.
  155400. */
  155401. #ifndef INLINE
  155402. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  155403. #define INLINE __inline__
  155404. #endif
  155405. #ifndef INLINE
  155406. #define INLINE /* default is to define it as empty */
  155407. #endif
  155408. #endif
  155409. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  155410. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  155411. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  155412. */
  155413. #ifndef MULTIPLIER
  155414. #define MULTIPLIER int /* type for fastest integer multiply */
  155415. #endif
  155416. /* FAST_FLOAT should be either float or double, whichever is done faster
  155417. * by your compiler. (Note that this type is only used in the floating point
  155418. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  155419. * Typically, float is faster in ANSI C compilers, while double is faster in
  155420. * pre-ANSI compilers (because they insist on converting to double anyway).
  155421. * The code below therefore chooses float if we have ANSI-style prototypes.
  155422. */
  155423. #ifndef FAST_FLOAT
  155424. #ifdef HAVE_PROTOTYPES
  155425. #define FAST_FLOAT float
  155426. #else
  155427. #define FAST_FLOAT double
  155428. #endif
  155429. #endif
  155430. #endif /* JPEG_INTERNAL_OPTIONS */
  155431. /********* End of inlined file: jmorecfg.h *********/
  155432. /* seldom changed options */
  155433. /* Version ID for the JPEG library.
  155434. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  155435. */
  155436. #define JPEG_LIB_VERSION 62 /* Version 6b */
  155437. /* Various constants determining the sizes of things.
  155438. * All of these are specified by the JPEG standard, so don't change them
  155439. * if you want to be compatible.
  155440. */
  155441. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  155442. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  155443. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  155444. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  155445. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  155446. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  155447. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  155448. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  155449. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  155450. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  155451. * to handle it. We even let you do this from the jconfig.h file. However,
  155452. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  155453. * sometimes emits noncompliant files doesn't mean you should too.
  155454. */
  155455. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  155456. #ifndef D_MAX_BLOCKS_IN_MCU
  155457. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  155458. #endif
  155459. /* Data structures for images (arrays of samples and of DCT coefficients).
  155460. * On 80x86 machines, the image arrays are too big for near pointers,
  155461. * but the pointer arrays can fit in near memory.
  155462. */
  155463. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  155464. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  155465. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  155466. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  155467. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  155468. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  155469. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  155470. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  155471. /* Types for JPEG compression parameters and working tables. */
  155472. /* DCT coefficient quantization tables. */
  155473. typedef struct {
  155474. /* This array gives the coefficient quantizers in natural array order
  155475. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  155476. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  155477. */
  155478. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  155479. /* This field is used only during compression. It's initialized FALSE when
  155480. * the table is created, and set TRUE when it's been output to the file.
  155481. * You could suppress output of a table by setting this to TRUE.
  155482. * (See jpeg_suppress_tables for an example.)
  155483. */
  155484. boolean sent_table; /* TRUE when table has been output */
  155485. } JQUANT_TBL;
  155486. /* Huffman coding tables. */
  155487. typedef struct {
  155488. /* These two fields directly represent the contents of a JPEG DHT marker */
  155489. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  155490. /* length k bits; bits[0] is unused */
  155491. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  155492. /* This field is used only during compression. It's initialized FALSE when
  155493. * the table is created, and set TRUE when it's been output to the file.
  155494. * You could suppress output of a table by setting this to TRUE.
  155495. * (See jpeg_suppress_tables for an example.)
  155496. */
  155497. boolean sent_table; /* TRUE when table has been output */
  155498. } JHUFF_TBL;
  155499. /* Basic info about one component (color channel). */
  155500. typedef struct {
  155501. /* These values are fixed over the whole image. */
  155502. /* For compression, they must be supplied by parameter setup; */
  155503. /* for decompression, they are read from the SOF marker. */
  155504. int component_id; /* identifier for this component (0..255) */
  155505. int component_index; /* its index in SOF or cinfo->comp_info[] */
  155506. int h_samp_factor; /* horizontal sampling factor (1..4) */
  155507. int v_samp_factor; /* vertical sampling factor (1..4) */
  155508. int quant_tbl_no; /* quantization table selector (0..3) */
  155509. /* These values may vary between scans. */
  155510. /* For compression, they must be supplied by parameter setup; */
  155511. /* for decompression, they are read from the SOS marker. */
  155512. /* The decompressor output side may not use these variables. */
  155513. int dc_tbl_no; /* DC entropy table selector (0..3) */
  155514. int ac_tbl_no; /* AC entropy table selector (0..3) */
  155515. /* Remaining fields should be treated as private by applications. */
  155516. /* These values are computed during compression or decompression startup: */
  155517. /* Component's size in DCT blocks.
  155518. * Any dummy blocks added to complete an MCU are not counted; therefore
  155519. * these values do not depend on whether a scan is interleaved or not.
  155520. */
  155521. JDIMENSION width_in_blocks;
  155522. JDIMENSION height_in_blocks;
  155523. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  155524. * For decompression this is the size of the output from one DCT block,
  155525. * reflecting any scaling we choose to apply during the IDCT step.
  155526. * Values of 1,2,4,8 are likely to be supported. Note that different
  155527. * components may receive different IDCT scalings.
  155528. */
  155529. int DCT_scaled_size;
  155530. /* The downsampled dimensions are the component's actual, unpadded number
  155531. * of samples at the main buffer (preprocessing/compression interface), thus
  155532. * downsampled_width = ceil(image_width * Hi/Hmax)
  155533. * and similarly for height. For decompression, IDCT scaling is included, so
  155534. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  155535. */
  155536. JDIMENSION downsampled_width; /* actual width in samples */
  155537. JDIMENSION downsampled_height; /* actual height in samples */
  155538. /* This flag is used only for decompression. In cases where some of the
  155539. * components will be ignored (eg grayscale output from YCbCr image),
  155540. * we can skip most computations for the unused components.
  155541. */
  155542. boolean component_needed; /* do we need the value of this component? */
  155543. /* These values are computed before starting a scan of the component. */
  155544. /* The decompressor output side may not use these variables. */
  155545. int MCU_width; /* number of blocks per MCU, horizontally */
  155546. int MCU_height; /* number of blocks per MCU, vertically */
  155547. int MCU_blocks; /* MCU_width * MCU_height */
  155548. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  155549. int last_col_width; /* # of non-dummy blocks across in last MCU */
  155550. int last_row_height; /* # of non-dummy blocks down in last MCU */
  155551. /* Saved quantization table for component; NULL if none yet saved.
  155552. * See jdinput.c comments about the need for this information.
  155553. * This field is currently used only for decompression.
  155554. */
  155555. JQUANT_TBL * quant_table;
  155556. /* Private per-component storage for DCT or IDCT subsystem. */
  155557. void * dct_table;
  155558. } jpeg_component_info;
  155559. /* The script for encoding a multiple-scan file is an array of these: */
  155560. typedef struct {
  155561. int comps_in_scan; /* number of components encoded in this scan */
  155562. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  155563. int Ss, Se; /* progressive JPEG spectral selection parms */
  155564. int Ah, Al; /* progressive JPEG successive approx. parms */
  155565. } jpeg_scan_info;
  155566. /* The decompressor can save APPn and COM markers in a list of these: */
  155567. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  155568. struct jpeg_marker_struct {
  155569. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  155570. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  155571. unsigned int original_length; /* # bytes of data in the file */
  155572. unsigned int data_length; /* # bytes of data saved at data[] */
  155573. JOCTET FAR * data; /* the data contained in the marker */
  155574. /* the marker length word is not counted in data_length or original_length */
  155575. };
  155576. /* Known color spaces. */
  155577. typedef enum {
  155578. JCS_UNKNOWN, /* error/unspecified */
  155579. JCS_GRAYSCALE, /* monochrome */
  155580. JCS_RGB, /* red/green/blue */
  155581. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  155582. JCS_CMYK, /* C/M/Y/K */
  155583. JCS_YCCK /* Y/Cb/Cr/K */
  155584. } J_COLOR_SPACE;
  155585. /* DCT/IDCT algorithm options. */
  155586. typedef enum {
  155587. JDCT_ISLOW, /* slow but accurate integer algorithm */
  155588. JDCT_IFAST, /* faster, less accurate integer method */
  155589. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  155590. } J_DCT_METHOD;
  155591. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  155592. #define JDCT_DEFAULT JDCT_ISLOW
  155593. #endif
  155594. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  155595. #define JDCT_FASTEST JDCT_IFAST
  155596. #endif
  155597. /* Dithering options for decompression. */
  155598. typedef enum {
  155599. JDITHER_NONE, /* no dithering */
  155600. JDITHER_ORDERED, /* simple ordered dither */
  155601. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  155602. } J_DITHER_MODE;
  155603. /* Common fields between JPEG compression and decompression master structs. */
  155604. #define jpeg_common_fields \
  155605. struct jpeg_error_mgr * err; /* Error handler module */\
  155606. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  155607. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  155608. void * client_data; /* Available for use by application */\
  155609. boolean is_decompressor; /* So common code can tell which is which */\
  155610. int global_state /* For checking call sequence validity */
  155611. /* Routines that are to be used by both halves of the library are declared
  155612. * to receive a pointer to this structure. There are no actual instances of
  155613. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  155614. */
  155615. struct jpeg_common_struct {
  155616. jpeg_common_fields; /* Fields common to both master struct types */
  155617. /* Additional fields follow in an actual jpeg_compress_struct or
  155618. * jpeg_decompress_struct. All three structs must agree on these
  155619. * initial fields! (This would be a lot cleaner in C++.)
  155620. */
  155621. };
  155622. typedef struct jpeg_common_struct * j_common_ptr;
  155623. typedef struct jpeg_compress_struct * j_compress_ptr;
  155624. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  155625. /* Master record for a compression instance */
  155626. struct jpeg_compress_struct {
  155627. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  155628. /* Destination for compressed data */
  155629. struct jpeg_destination_mgr * dest;
  155630. /* Description of source image --- these fields must be filled in by
  155631. * outer application before starting compression. in_color_space must
  155632. * be correct before you can even call jpeg_set_defaults().
  155633. */
  155634. JDIMENSION image_width; /* input image width */
  155635. JDIMENSION image_height; /* input image height */
  155636. int input_components; /* # of color components in input image */
  155637. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  155638. double input_gamma; /* image gamma of input image */
  155639. /* Compression parameters --- these fields must be set before calling
  155640. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  155641. * initialize everything to reasonable defaults, then changing anything
  155642. * the application specifically wants to change. That way you won't get
  155643. * burnt when new parameters are added. Also note that there are several
  155644. * helper routines to simplify changing parameters.
  155645. */
  155646. int data_precision; /* bits of precision in image data */
  155647. int num_components; /* # of color components in JPEG image */
  155648. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155649. jpeg_component_info * comp_info;
  155650. /* comp_info[i] describes component that appears i'th in SOF */
  155651. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155652. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155653. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155654. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155655. /* ptrs to Huffman coding tables, or NULL if not defined */
  155656. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155657. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155658. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155659. int num_scans; /* # of entries in scan_info array */
  155660. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  155661. /* The default value of scan_info is NULL, which causes a single-scan
  155662. * sequential JPEG file to be emitted. To create a multi-scan file,
  155663. * set num_scans and scan_info to point to an array of scan definitions.
  155664. */
  155665. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  155666. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155667. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  155668. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155669. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  155670. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  155671. /* The restart interval can be specified in absolute MCUs by setting
  155672. * restart_interval, or in MCU rows by setting restart_in_rows
  155673. * (in which case the correct restart_interval will be figured
  155674. * for each scan).
  155675. */
  155676. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  155677. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  155678. /* Parameters controlling emission of special markers. */
  155679. boolean write_JFIF_header; /* should a JFIF marker be written? */
  155680. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  155681. UINT8 JFIF_minor_version;
  155682. /* These three values are not used by the JPEG code, merely copied */
  155683. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  155684. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  155685. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  155686. UINT8 density_unit; /* JFIF code for pixel size units */
  155687. UINT16 X_density; /* Horizontal pixel density */
  155688. UINT16 Y_density; /* Vertical pixel density */
  155689. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  155690. /* State variable: index of next scanline to be written to
  155691. * jpeg_write_scanlines(). Application may use this to control its
  155692. * processing loop, e.g., "while (next_scanline < image_height)".
  155693. */
  155694. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  155695. /* Remaining fields are known throughout compressor, but generally
  155696. * should not be touched by a surrounding application.
  155697. */
  155698. /*
  155699. * These fields are computed during compression startup
  155700. */
  155701. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  155702. int max_h_samp_factor; /* largest h_samp_factor */
  155703. int max_v_samp_factor; /* largest v_samp_factor */
  155704. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  155705. /* The coefficient controller receives data in units of MCU rows as defined
  155706. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  155707. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  155708. * "iMCU" (interleaved MCU) row.
  155709. */
  155710. /*
  155711. * These fields are valid during any one scan.
  155712. * They describe the components and MCUs actually appearing in the scan.
  155713. */
  155714. int comps_in_scan; /* # of JPEG components in this scan */
  155715. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155716. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155717. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155718. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155719. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155720. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  155721. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155722. /* i'th block in an MCU */
  155723. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155724. /*
  155725. * Links to compression subobjects (methods and private variables of modules)
  155726. */
  155727. struct jpeg_comp_master * master;
  155728. struct jpeg_c_main_controller * main;
  155729. struct jpeg_c_prep_controller * prep;
  155730. struct jpeg_c_coef_controller * coef;
  155731. struct jpeg_marker_writer * marker;
  155732. struct jpeg_color_converter * cconvert;
  155733. struct jpeg_downsampler * downsample;
  155734. struct jpeg_forward_dct * fdct;
  155735. struct jpeg_entropy_encoder * entropy;
  155736. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  155737. int script_space_size;
  155738. };
  155739. /* Master record for a decompression instance */
  155740. struct jpeg_decompress_struct {
  155741. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  155742. /* Source of compressed data */
  155743. struct jpeg_source_mgr * src;
  155744. /* Basic description of image --- filled in by jpeg_read_header(). */
  155745. /* Application may inspect these values to decide how to process image. */
  155746. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  155747. JDIMENSION image_height; /* nominal image height */
  155748. int num_components; /* # of color components in JPEG image */
  155749. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  155750. /* Decompression processing parameters --- these fields must be set before
  155751. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  155752. * them to default values.
  155753. */
  155754. J_COLOR_SPACE out_color_space; /* colorspace for output */
  155755. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  155756. double output_gamma; /* image gamma wanted in output */
  155757. boolean buffered_image; /* TRUE=multiple output passes */
  155758. boolean raw_data_out; /* TRUE=downsampled data wanted */
  155759. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  155760. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  155761. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  155762. boolean quantize_colors; /* TRUE=colormapped output wanted */
  155763. /* the following are ignored if not quantize_colors: */
  155764. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  155765. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  155766. int desired_number_of_colors; /* max # colors to use in created colormap */
  155767. /* these are significant only in buffered-image mode: */
  155768. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  155769. boolean enable_external_quant;/* enable future use of external colormap */
  155770. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  155771. /* Description of actual output image that will be returned to application.
  155772. * These fields are computed by jpeg_start_decompress().
  155773. * You can also use jpeg_calc_output_dimensions() to determine these values
  155774. * in advance of calling jpeg_start_decompress().
  155775. */
  155776. JDIMENSION output_width; /* scaled image width */
  155777. JDIMENSION output_height; /* scaled image height */
  155778. int out_color_components; /* # of color components in out_color_space */
  155779. int output_components; /* # of color components returned */
  155780. /* output_components is 1 (a colormap index) when quantizing colors;
  155781. * otherwise it equals out_color_components.
  155782. */
  155783. int rec_outbuf_height; /* min recommended height of scanline buffer */
  155784. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  155785. * high, space and time will be wasted due to unnecessary data copying.
  155786. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  155787. */
  155788. /* When quantizing colors, the output colormap is described by these fields.
  155789. * The application can supply a colormap by setting colormap non-NULL before
  155790. * calling jpeg_start_decompress; otherwise a colormap is created during
  155791. * jpeg_start_decompress or jpeg_start_output.
  155792. * The map has out_color_components rows and actual_number_of_colors columns.
  155793. */
  155794. int actual_number_of_colors; /* number of entries in use */
  155795. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  155796. /* State variables: these variables indicate the progress of decompression.
  155797. * The application may examine these but must not modify them.
  155798. */
  155799. /* Row index of next scanline to be read from jpeg_read_scanlines().
  155800. * Application may use this to control its processing loop, e.g.,
  155801. * "while (output_scanline < output_height)".
  155802. */
  155803. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  155804. /* Current input scan number and number of iMCU rows completed in scan.
  155805. * These indicate the progress of the decompressor input side.
  155806. */
  155807. int input_scan_number; /* Number of SOS markers seen so far */
  155808. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  155809. /* The "output scan number" is the notional scan being displayed by the
  155810. * output side. The decompressor will not allow output scan/row number
  155811. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  155812. */
  155813. int output_scan_number; /* Nominal scan number being displayed */
  155814. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  155815. /* Current progression status. coef_bits[c][i] indicates the precision
  155816. * with which component c's DCT coefficient i (in zigzag order) is known.
  155817. * It is -1 when no data has yet been received, otherwise it is the point
  155818. * transform (shift) value for the most recent scan of the coefficient
  155819. * (thus, 0 at completion of the progression).
  155820. * This pointer is NULL when reading a non-progressive file.
  155821. */
  155822. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  155823. /* Internal JPEG parameters --- the application usually need not look at
  155824. * these fields. Note that the decompressor output side may not use
  155825. * any parameters that can change between scans.
  155826. */
  155827. /* Quantization and Huffman tables are carried forward across input
  155828. * datastreams when processing abbreviated JPEG datastreams.
  155829. */
  155830. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  155831. /* ptrs to coefficient quantization tables, or NULL if not defined */
  155832. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155833. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  155834. /* ptrs to Huffman coding tables, or NULL if not defined */
  155835. /* These parameters are never carried across datastreams, since they
  155836. * are given in SOF/SOS markers or defined to be reset by SOI.
  155837. */
  155838. int data_precision; /* bits of precision in image data */
  155839. jpeg_component_info * comp_info;
  155840. /* comp_info[i] describes component that appears i'th in SOF */
  155841. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  155842. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  155843. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  155844. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  155845. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  155846. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  155847. /* These fields record data obtained from optional markers recognized by
  155848. * the JPEG library.
  155849. */
  155850. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  155851. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  155852. UINT8 JFIF_major_version; /* JFIF version number */
  155853. UINT8 JFIF_minor_version;
  155854. UINT8 density_unit; /* JFIF code for pixel size units */
  155855. UINT16 X_density; /* Horizontal pixel density */
  155856. UINT16 Y_density; /* Vertical pixel density */
  155857. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  155858. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  155859. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  155860. /* Aside from the specific data retained from APPn markers known to the
  155861. * library, the uninterpreted contents of any or all APPn and COM markers
  155862. * can be saved in a list for examination by the application.
  155863. */
  155864. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  155865. /* Remaining fields are known throughout decompressor, but generally
  155866. * should not be touched by a surrounding application.
  155867. */
  155868. /*
  155869. * These fields are computed during decompression startup
  155870. */
  155871. int max_h_samp_factor; /* largest h_samp_factor */
  155872. int max_v_samp_factor; /* largest v_samp_factor */
  155873. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  155874. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  155875. /* The coefficient controller's input and output progress is measured in
  155876. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  155877. * in fully interleaved JPEG scans, but are used whether the scan is
  155878. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  155879. * rows of each component. Therefore, the IDCT output contains
  155880. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  155881. */
  155882. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  155883. /*
  155884. * These fields are valid during any one scan.
  155885. * They describe the components and MCUs actually appearing in the scan.
  155886. * Note that the decompressor output side must not use these fields.
  155887. */
  155888. int comps_in_scan; /* # of JPEG components in this scan */
  155889. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  155890. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  155891. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  155892. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  155893. int blocks_in_MCU; /* # of DCT blocks per MCU */
  155894. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  155895. /* MCU_membership[i] is index in cur_comp_info of component owning */
  155896. /* i'th block in an MCU */
  155897. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  155898. /* This field is shared between entropy decoder and marker parser.
  155899. * It is either zero or the code of a JPEG marker that has been
  155900. * read from the data source, but has not yet been processed.
  155901. */
  155902. int unread_marker;
  155903. /*
  155904. * Links to decompression subobjects (methods, private variables of modules)
  155905. */
  155906. struct jpeg_decomp_master * master;
  155907. struct jpeg_d_main_controller * main;
  155908. struct jpeg_d_coef_controller * coef;
  155909. struct jpeg_d_post_controller * post;
  155910. struct jpeg_input_controller * inputctl;
  155911. struct jpeg_marker_reader * marker;
  155912. struct jpeg_entropy_decoder * entropy;
  155913. struct jpeg_inverse_dct * idct;
  155914. struct jpeg_upsampler * upsample;
  155915. struct jpeg_color_deconverter * cconvert;
  155916. struct jpeg_color_quantizer * cquantize;
  155917. };
  155918. /* "Object" declarations for JPEG modules that may be supplied or called
  155919. * directly by the surrounding application.
  155920. * As with all objects in the JPEG library, these structs only define the
  155921. * publicly visible methods and state variables of a module. Additional
  155922. * private fields may exist after the public ones.
  155923. */
  155924. /* Error handler object */
  155925. struct jpeg_error_mgr {
  155926. /* Error exit handler: does not return to caller */
  155927. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  155928. /* Conditionally emit a trace or warning message */
  155929. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  155930. /* Routine that actually outputs a trace or error message */
  155931. JMETHOD(void, output_message, (j_common_ptr cinfo));
  155932. /* Format a message string for the most recent JPEG error or message */
  155933. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  155934. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  155935. /* Reset error state variables at start of a new image */
  155936. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  155937. /* The message ID code and any parameters are saved here.
  155938. * A message can have one string parameter or up to 8 int parameters.
  155939. */
  155940. int msg_code;
  155941. #define JMSG_STR_PARM_MAX 80
  155942. union {
  155943. int i[8];
  155944. char s[JMSG_STR_PARM_MAX];
  155945. } msg_parm;
  155946. /* Standard state variables for error facility */
  155947. int trace_level; /* max msg_level that will be displayed */
  155948. /* For recoverable corrupt-data errors, we emit a warning message,
  155949. * but keep going unless emit_message chooses to abort. emit_message
  155950. * should count warnings in num_warnings. The surrounding application
  155951. * can check for bad data by seeing if num_warnings is nonzero at the
  155952. * end of processing.
  155953. */
  155954. long num_warnings; /* number of corrupt-data warnings */
  155955. /* These fields point to the table(s) of error message strings.
  155956. * An application can change the table pointer to switch to a different
  155957. * message list (typically, to change the language in which errors are
  155958. * reported). Some applications may wish to add additional error codes
  155959. * that will be handled by the JPEG library error mechanism; the second
  155960. * table pointer is used for this purpose.
  155961. *
  155962. * First table includes all errors generated by JPEG library itself.
  155963. * Error code 0 is reserved for a "no such error string" message.
  155964. */
  155965. const char * const * jpeg_message_table; /* Library errors */
  155966. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  155967. /* Second table can be added by application (see cjpeg/djpeg for example).
  155968. * It contains strings numbered first_addon_message..last_addon_message.
  155969. */
  155970. const char * const * addon_message_table; /* Non-library errors */
  155971. int first_addon_message; /* code for first string in addon table */
  155972. int last_addon_message; /* code for last string in addon table */
  155973. };
  155974. /* Progress monitor object */
  155975. struct jpeg_progress_mgr {
  155976. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  155977. long pass_counter; /* work units completed in this pass */
  155978. long pass_limit; /* total number of work units in this pass */
  155979. int completed_passes; /* passes completed so far */
  155980. int total_passes; /* total number of passes expected */
  155981. };
  155982. /* Data destination object for compression */
  155983. struct jpeg_destination_mgr {
  155984. JOCTET * next_output_byte; /* => next byte to write in buffer */
  155985. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  155986. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  155987. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  155988. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  155989. };
  155990. /* Data source object for decompression */
  155991. struct jpeg_source_mgr {
  155992. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  155993. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  155994. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  155995. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  155996. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  155997. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  155998. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  155999. };
  156000. /* Memory manager object.
  156001. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  156002. * and "really big" objects (virtual arrays with backing store if needed).
  156003. * The memory manager does not allow individual objects to be freed; rather,
  156004. * each created object is assigned to a pool, and whole pools can be freed
  156005. * at once. This is faster and more convenient than remembering exactly what
  156006. * to free, especially where malloc()/free() are not too speedy.
  156007. * NB: alloc routines never return NULL. They exit to error_exit if not
  156008. * successful.
  156009. */
  156010. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  156011. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  156012. #define JPOOL_NUMPOOLS 2
  156013. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  156014. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  156015. struct jpeg_memory_mgr {
  156016. /* Method pointers */
  156017. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  156018. size_t sizeofobject));
  156019. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  156020. size_t sizeofobject));
  156021. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  156022. JDIMENSION samplesperrow,
  156023. JDIMENSION numrows));
  156024. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  156025. JDIMENSION blocksperrow,
  156026. JDIMENSION numrows));
  156027. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  156028. int pool_id,
  156029. boolean pre_zero,
  156030. JDIMENSION samplesperrow,
  156031. JDIMENSION numrows,
  156032. JDIMENSION maxaccess));
  156033. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  156034. int pool_id,
  156035. boolean pre_zero,
  156036. JDIMENSION blocksperrow,
  156037. JDIMENSION numrows,
  156038. JDIMENSION maxaccess));
  156039. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  156040. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  156041. jvirt_sarray_ptr ptr,
  156042. JDIMENSION start_row,
  156043. JDIMENSION num_rows,
  156044. boolean writable));
  156045. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  156046. jvirt_barray_ptr ptr,
  156047. JDIMENSION start_row,
  156048. JDIMENSION num_rows,
  156049. boolean writable));
  156050. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  156051. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  156052. /* Limit on memory allocation for this JPEG object. (Note that this is
  156053. * merely advisory, not a guaranteed maximum; it only affects the space
  156054. * used for virtual-array buffers.) May be changed by outer application
  156055. * after creating the JPEG object.
  156056. */
  156057. long max_memory_to_use;
  156058. /* Maximum allocation request accepted by alloc_large. */
  156059. long max_alloc_chunk;
  156060. };
  156061. /* Routine signature for application-supplied marker processing methods.
  156062. * Need not pass marker code since it is stored in cinfo->unread_marker.
  156063. */
  156064. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  156065. /* Declarations for routines called by application.
  156066. * The JPP macro hides prototype parameters from compilers that can't cope.
  156067. * Note JPP requires double parentheses.
  156068. */
  156069. #ifdef HAVE_PROTOTYPES
  156070. #define JPP(arglist) arglist
  156071. #else
  156072. #define JPP(arglist) ()
  156073. #endif
  156074. /* Short forms of external names for systems with brain-damaged linkers.
  156075. * We shorten external names to be unique in the first six letters, which
  156076. * is good enough for all known systems.
  156077. * (If your compiler itself needs names to be unique in less than 15
  156078. * characters, you are out of luck. Get a better compiler.)
  156079. */
  156080. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156081. #define jpeg_std_error jStdError
  156082. #define jpeg_CreateCompress jCreaCompress
  156083. #define jpeg_CreateDecompress jCreaDecompress
  156084. #define jpeg_destroy_compress jDestCompress
  156085. #define jpeg_destroy_decompress jDestDecompress
  156086. #define jpeg_stdio_dest jStdDest
  156087. #define jpeg_stdio_src jStdSrc
  156088. #define jpeg_set_defaults jSetDefaults
  156089. #define jpeg_set_colorspace jSetColorspace
  156090. #define jpeg_default_colorspace jDefColorspace
  156091. #define jpeg_set_quality jSetQuality
  156092. #define jpeg_set_linear_quality jSetLQuality
  156093. #define jpeg_add_quant_table jAddQuantTable
  156094. #define jpeg_quality_scaling jQualityScaling
  156095. #define jpeg_simple_progression jSimProgress
  156096. #define jpeg_suppress_tables jSuppressTables
  156097. #define jpeg_alloc_quant_table jAlcQTable
  156098. #define jpeg_alloc_huff_table jAlcHTable
  156099. #define jpeg_start_compress jStrtCompress
  156100. #define jpeg_write_scanlines jWrtScanlines
  156101. #define jpeg_finish_compress jFinCompress
  156102. #define jpeg_write_raw_data jWrtRawData
  156103. #define jpeg_write_marker jWrtMarker
  156104. #define jpeg_write_m_header jWrtMHeader
  156105. #define jpeg_write_m_byte jWrtMByte
  156106. #define jpeg_write_tables jWrtTables
  156107. #define jpeg_read_header jReadHeader
  156108. #define jpeg_start_decompress jStrtDecompress
  156109. #define jpeg_read_scanlines jReadScanlines
  156110. #define jpeg_finish_decompress jFinDecompress
  156111. #define jpeg_read_raw_data jReadRawData
  156112. #define jpeg_has_multiple_scans jHasMultScn
  156113. #define jpeg_start_output jStrtOutput
  156114. #define jpeg_finish_output jFinOutput
  156115. #define jpeg_input_complete jInComplete
  156116. #define jpeg_new_colormap jNewCMap
  156117. #define jpeg_consume_input jConsumeInput
  156118. #define jpeg_calc_output_dimensions jCalcDimensions
  156119. #define jpeg_save_markers jSaveMarkers
  156120. #define jpeg_set_marker_processor jSetMarker
  156121. #define jpeg_read_coefficients jReadCoefs
  156122. #define jpeg_write_coefficients jWrtCoefs
  156123. #define jpeg_copy_critical_parameters jCopyCrit
  156124. #define jpeg_abort_compress jAbrtCompress
  156125. #define jpeg_abort_decompress jAbrtDecompress
  156126. #define jpeg_abort jAbort
  156127. #define jpeg_destroy jDestroy
  156128. #define jpeg_resync_to_restart jResyncRestart
  156129. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156130. /* Default error-management setup */
  156131. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  156132. JPP((struct jpeg_error_mgr * err));
  156133. /* Initialization of JPEG compression objects.
  156134. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  156135. * names that applications should call. These expand to calls on
  156136. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  156137. * passed for version mismatch checking.
  156138. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  156139. */
  156140. #define jpeg_create_compress(cinfo) \
  156141. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  156142. (size_t) sizeof(struct jpeg_compress_struct))
  156143. #define jpeg_create_decompress(cinfo) \
  156144. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  156145. (size_t) sizeof(struct jpeg_decompress_struct))
  156146. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  156147. int version, size_t structsize));
  156148. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  156149. int version, size_t structsize));
  156150. /* Destruction of JPEG compression objects */
  156151. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  156152. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  156153. /* Standard data source and destination managers: stdio streams. */
  156154. /* Caller is responsible for opening the file before and closing after. */
  156155. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  156156. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  156157. /* Default parameter setup for compression */
  156158. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  156159. /* Compression parameter setup aids */
  156160. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  156161. J_COLOR_SPACE colorspace));
  156162. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  156163. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  156164. boolean force_baseline));
  156165. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  156166. int scale_factor,
  156167. boolean force_baseline));
  156168. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  156169. const unsigned int *basic_table,
  156170. int scale_factor,
  156171. boolean force_baseline));
  156172. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  156173. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  156174. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  156175. boolean suppress));
  156176. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  156177. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  156178. /* Main entry points for compression */
  156179. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  156180. boolean write_all_tables));
  156181. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  156182. JSAMPARRAY scanlines,
  156183. JDIMENSION num_lines));
  156184. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  156185. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  156186. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  156187. JSAMPIMAGE data,
  156188. JDIMENSION num_lines));
  156189. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  156190. EXTERN(void) jpeg_write_marker
  156191. JPP((j_compress_ptr cinfo, int marker,
  156192. const JOCTET * dataptr, unsigned int datalen));
  156193. /* Same, but piecemeal. */
  156194. EXTERN(void) jpeg_write_m_header
  156195. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  156196. EXTERN(void) jpeg_write_m_byte
  156197. JPP((j_compress_ptr cinfo, int val));
  156198. /* Alternate compression function: just write an abbreviated table file */
  156199. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  156200. /* Decompression startup: read start of JPEG datastream to see what's there */
  156201. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  156202. boolean require_image));
  156203. /* Return value is one of: */
  156204. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  156205. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  156206. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  156207. /* If you pass require_image = TRUE (normal case), you need not check for
  156208. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  156209. * JPEG_SUSPENDED is only possible if you use a data source module that can
  156210. * give a suspension return (the stdio source module doesn't).
  156211. */
  156212. /* Main entry points for decompression */
  156213. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  156214. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  156215. JSAMPARRAY scanlines,
  156216. JDIMENSION max_lines));
  156217. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  156218. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  156219. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  156220. JSAMPIMAGE data,
  156221. JDIMENSION max_lines));
  156222. /* Additional entry points for buffered-image mode. */
  156223. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  156224. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  156225. int scan_number));
  156226. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  156227. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  156228. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  156229. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  156230. /* Return value is one of: */
  156231. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  156232. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  156233. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  156234. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  156235. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  156236. /* Precalculate output dimensions for current decompression parameters. */
  156237. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  156238. /* Control saving of COM and APPn markers into marker_list. */
  156239. EXTERN(void) jpeg_save_markers
  156240. JPP((j_decompress_ptr cinfo, int marker_code,
  156241. unsigned int length_limit));
  156242. /* Install a special processing method for COM or APPn markers. */
  156243. EXTERN(void) jpeg_set_marker_processor
  156244. JPP((j_decompress_ptr cinfo, int marker_code,
  156245. jpeg_marker_parser_method routine));
  156246. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  156247. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  156248. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  156249. jvirt_barray_ptr * coef_arrays));
  156250. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  156251. j_compress_ptr dstinfo));
  156252. /* If you choose to abort compression or decompression before completing
  156253. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  156254. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  156255. * if you're done with the JPEG object, but if you want to clean it up and
  156256. * reuse it, call this:
  156257. */
  156258. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  156259. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  156260. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  156261. * flavor of JPEG object. These may be more convenient in some places.
  156262. */
  156263. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  156264. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  156265. /* Default restart-marker-resync procedure for use by data source modules */
  156266. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  156267. int desired));
  156268. /* These marker codes are exported since applications and data source modules
  156269. * are likely to want to use them.
  156270. */
  156271. #define JPEG_RST0 0xD0 /* RST0 marker code */
  156272. #define JPEG_EOI 0xD9 /* EOI marker code */
  156273. #define JPEG_APP0 0xE0 /* APP0 marker code */
  156274. #define JPEG_COM 0xFE /* COM marker code */
  156275. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  156276. * for structure definitions that are never filled in, keep it quiet by
  156277. * supplying dummy definitions for the various substructures.
  156278. */
  156279. #ifdef INCOMPLETE_TYPES_BROKEN
  156280. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  156281. struct jvirt_sarray_control { long dummy; };
  156282. struct jvirt_barray_control { long dummy; };
  156283. struct jpeg_comp_master { long dummy; };
  156284. struct jpeg_c_main_controller { long dummy; };
  156285. struct jpeg_c_prep_controller { long dummy; };
  156286. struct jpeg_c_coef_controller { long dummy; };
  156287. struct jpeg_marker_writer { long dummy; };
  156288. struct jpeg_color_converter { long dummy; };
  156289. struct jpeg_downsampler { long dummy; };
  156290. struct jpeg_forward_dct { long dummy; };
  156291. struct jpeg_entropy_encoder { long dummy; };
  156292. struct jpeg_decomp_master { long dummy; };
  156293. struct jpeg_d_main_controller { long dummy; };
  156294. struct jpeg_d_coef_controller { long dummy; };
  156295. struct jpeg_d_post_controller { long dummy; };
  156296. struct jpeg_input_controller { long dummy; };
  156297. struct jpeg_marker_reader { long dummy; };
  156298. struct jpeg_entropy_decoder { long dummy; };
  156299. struct jpeg_inverse_dct { long dummy; };
  156300. struct jpeg_upsampler { long dummy; };
  156301. struct jpeg_color_deconverter { long dummy; };
  156302. struct jpeg_color_quantizer { long dummy; };
  156303. #endif /* JPEG_INTERNALS */
  156304. #endif /* INCOMPLETE_TYPES_BROKEN */
  156305. /*
  156306. * The JPEG library modules define JPEG_INTERNALS before including this file.
  156307. * The internal structure declarations are read only when that is true.
  156308. * Applications using the library should not include jpegint.h, but may wish
  156309. * to include jerror.h.
  156310. */
  156311. #ifdef JPEG_INTERNALS
  156312. /********* Start of inlined file: jpegint.h *********/
  156313. /* Declarations for both compression & decompression */
  156314. typedef enum { /* Operating modes for buffer controllers */
  156315. JBUF_PASS_THRU, /* Plain stripwise operation */
  156316. /* Remaining modes require a full-image buffer to have been created */
  156317. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  156318. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  156319. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  156320. } J_BUF_MODE;
  156321. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  156322. #define CSTATE_START 100 /* after create_compress */
  156323. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  156324. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  156325. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  156326. #define DSTATE_START 200 /* after create_decompress */
  156327. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  156328. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  156329. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  156330. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  156331. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  156332. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  156333. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  156334. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  156335. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  156336. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  156337. /* Declarations for compression modules */
  156338. /* Master control module */
  156339. struct jpeg_comp_master {
  156340. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  156341. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  156342. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156343. /* State variables made visible to other modules */
  156344. boolean call_pass_startup; /* True if pass_startup must be called */
  156345. boolean is_last_pass; /* True during last pass */
  156346. };
  156347. /* Main buffer control (downsampled-data buffer) */
  156348. struct jpeg_c_main_controller {
  156349. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156350. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  156351. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  156352. JDIMENSION in_rows_avail));
  156353. };
  156354. /* Compression preprocessing (downsampling input buffer control) */
  156355. struct jpeg_c_prep_controller {
  156356. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156357. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  156358. JSAMPARRAY input_buf,
  156359. JDIMENSION *in_row_ctr,
  156360. JDIMENSION in_rows_avail,
  156361. JSAMPIMAGE output_buf,
  156362. JDIMENSION *out_row_group_ctr,
  156363. JDIMENSION out_row_groups_avail));
  156364. };
  156365. /* Coefficient buffer control */
  156366. struct jpeg_c_coef_controller {
  156367. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  156368. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  156369. JSAMPIMAGE input_buf));
  156370. };
  156371. /* Colorspace conversion */
  156372. struct jpeg_color_converter {
  156373. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156374. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  156375. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  156376. JDIMENSION output_row, int num_rows));
  156377. };
  156378. /* Downsampling */
  156379. struct jpeg_downsampler {
  156380. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156381. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  156382. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  156383. JSAMPIMAGE output_buf,
  156384. JDIMENSION out_row_group_index));
  156385. boolean need_context_rows; /* TRUE if need rows above & below */
  156386. };
  156387. /* Forward DCT (also controls coefficient quantization) */
  156388. struct jpeg_forward_dct {
  156389. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  156390. /* perhaps this should be an array??? */
  156391. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  156392. jpeg_component_info * compptr,
  156393. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156394. JDIMENSION start_row, JDIMENSION start_col,
  156395. JDIMENSION num_blocks));
  156396. };
  156397. /* Entropy encoding */
  156398. struct jpeg_entropy_encoder {
  156399. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  156400. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  156401. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  156402. };
  156403. /* Marker writing */
  156404. struct jpeg_marker_writer {
  156405. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  156406. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  156407. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  156408. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  156409. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  156410. /* These routines are exported to allow insertion of extra markers */
  156411. /* Probably only COM and APPn markers should be written this way */
  156412. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  156413. unsigned int datalen));
  156414. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  156415. };
  156416. /* Declarations for decompression modules */
  156417. /* Master control module */
  156418. struct jpeg_decomp_master {
  156419. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  156420. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  156421. /* State variables made visible to other modules */
  156422. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  156423. };
  156424. /* Input control module */
  156425. struct jpeg_input_controller {
  156426. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  156427. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  156428. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156429. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  156430. /* State variables made visible to other modules */
  156431. boolean has_multiple_scans; /* True if file has multiple scans */
  156432. boolean eoi_reached; /* True when EOI has been consumed */
  156433. };
  156434. /* Main buffer control (downsampled-data buffer) */
  156435. struct jpeg_d_main_controller {
  156436. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156437. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  156438. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  156439. JDIMENSION out_rows_avail));
  156440. };
  156441. /* Coefficient buffer control */
  156442. struct jpeg_d_coef_controller {
  156443. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  156444. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  156445. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  156446. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  156447. JSAMPIMAGE output_buf));
  156448. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  156449. jvirt_barray_ptr *coef_arrays;
  156450. };
  156451. /* Decompression postprocessing (color quantization buffer control) */
  156452. struct jpeg_d_post_controller {
  156453. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  156454. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  156455. JSAMPIMAGE input_buf,
  156456. JDIMENSION *in_row_group_ctr,
  156457. JDIMENSION in_row_groups_avail,
  156458. JSAMPARRAY output_buf,
  156459. JDIMENSION *out_row_ctr,
  156460. JDIMENSION out_rows_avail));
  156461. };
  156462. /* Marker reading & parsing */
  156463. struct jpeg_marker_reader {
  156464. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  156465. /* Read markers until SOS or EOI.
  156466. * Returns same codes as are defined for jpeg_consume_input:
  156467. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  156468. */
  156469. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  156470. /* Read a restart marker --- exported for use by entropy decoder only */
  156471. jpeg_marker_parser_method read_restart_marker;
  156472. /* State of marker reader --- nominally internal, but applications
  156473. * supplying COM or APPn handlers might like to know the state.
  156474. */
  156475. boolean saw_SOI; /* found SOI? */
  156476. boolean saw_SOF; /* found SOF? */
  156477. int next_restart_num; /* next restart number expected (0-7) */
  156478. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  156479. };
  156480. /* Entropy decoding */
  156481. struct jpeg_entropy_decoder {
  156482. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156483. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  156484. JBLOCKROW *MCU_data));
  156485. /* This is here to share code between baseline and progressive decoders; */
  156486. /* other modules probably should not use it */
  156487. boolean insufficient_data; /* set TRUE after emitting warning */
  156488. };
  156489. /* Inverse DCT (also performs dequantization) */
  156490. typedef JMETHOD(void, inverse_DCT_method_ptr,
  156491. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156492. JCOEFPTR coef_block,
  156493. JSAMPARRAY output_buf, JDIMENSION output_col));
  156494. struct jpeg_inverse_dct {
  156495. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156496. /* It is useful to allow each component to have a separate IDCT method. */
  156497. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  156498. };
  156499. /* Upsampling (note that upsampler must also call color converter) */
  156500. struct jpeg_upsampler {
  156501. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156502. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  156503. JSAMPIMAGE input_buf,
  156504. JDIMENSION *in_row_group_ctr,
  156505. JDIMENSION in_row_groups_avail,
  156506. JSAMPARRAY output_buf,
  156507. JDIMENSION *out_row_ctr,
  156508. JDIMENSION out_rows_avail));
  156509. boolean need_context_rows; /* TRUE if need rows above & below */
  156510. };
  156511. /* Colorspace conversion */
  156512. struct jpeg_color_deconverter {
  156513. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  156514. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  156515. JSAMPIMAGE input_buf, JDIMENSION input_row,
  156516. JSAMPARRAY output_buf, int num_rows));
  156517. };
  156518. /* Color quantization or color precision reduction */
  156519. struct jpeg_color_quantizer {
  156520. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  156521. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  156522. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  156523. int num_rows));
  156524. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  156525. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  156526. };
  156527. /* Miscellaneous useful macros */
  156528. #undef MAX
  156529. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  156530. #undef MIN
  156531. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  156532. /* We assume that right shift corresponds to signed division by 2 with
  156533. * rounding towards minus infinity. This is correct for typical "arithmetic
  156534. * shift" instructions that shift in copies of the sign bit. But some
  156535. * C compilers implement >> with an unsigned shift. For these machines you
  156536. * must define RIGHT_SHIFT_IS_UNSIGNED.
  156537. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  156538. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  156539. * included in the variables of any routine using RIGHT_SHIFT.
  156540. */
  156541. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  156542. #define SHIFT_TEMPS INT32 shift_temp;
  156543. #define RIGHT_SHIFT(x,shft) \
  156544. ((shift_temp = (x)) < 0 ? \
  156545. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  156546. (shift_temp >> (shft)))
  156547. #else
  156548. #define SHIFT_TEMPS
  156549. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  156550. #endif
  156551. /* Short forms of external names for systems with brain-damaged linkers. */
  156552. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156553. #define jinit_compress_master jICompress
  156554. #define jinit_c_master_control jICMaster
  156555. #define jinit_c_main_controller jICMainC
  156556. #define jinit_c_prep_controller jICPrepC
  156557. #define jinit_c_coef_controller jICCoefC
  156558. #define jinit_color_converter jICColor
  156559. #define jinit_downsampler jIDownsampler
  156560. #define jinit_forward_dct jIFDCT
  156561. #define jinit_huff_encoder jIHEncoder
  156562. #define jinit_phuff_encoder jIPHEncoder
  156563. #define jinit_marker_writer jIMWriter
  156564. #define jinit_master_decompress jIDMaster
  156565. #define jinit_d_main_controller jIDMainC
  156566. #define jinit_d_coef_controller jIDCoefC
  156567. #define jinit_d_post_controller jIDPostC
  156568. #define jinit_input_controller jIInCtlr
  156569. #define jinit_marker_reader jIMReader
  156570. #define jinit_huff_decoder jIHDecoder
  156571. #define jinit_phuff_decoder jIPHDecoder
  156572. #define jinit_inverse_dct jIIDCT
  156573. #define jinit_upsampler jIUpsampler
  156574. #define jinit_color_deconverter jIDColor
  156575. #define jinit_1pass_quantizer jI1Quant
  156576. #define jinit_2pass_quantizer jI2Quant
  156577. #define jinit_merged_upsampler jIMUpsampler
  156578. #define jinit_memory_mgr jIMemMgr
  156579. #define jdiv_round_up jDivRound
  156580. #define jround_up jRound
  156581. #define jcopy_sample_rows jCopySamples
  156582. #define jcopy_block_row jCopyBlocks
  156583. #define jzero_far jZeroFar
  156584. #define jpeg_zigzag_order jZIGTable
  156585. #define jpeg_natural_order jZAGTable
  156586. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156587. /* Compression module initialization routines */
  156588. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  156589. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  156590. boolean transcode_only));
  156591. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  156592. boolean need_full_buffer));
  156593. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  156594. boolean need_full_buffer));
  156595. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  156596. boolean need_full_buffer));
  156597. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  156598. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  156599. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  156600. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  156601. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  156602. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  156603. /* Decompression module initialization routines */
  156604. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  156605. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  156606. boolean need_full_buffer));
  156607. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  156608. boolean need_full_buffer));
  156609. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  156610. boolean need_full_buffer));
  156611. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  156612. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  156613. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  156614. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  156615. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  156616. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  156617. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  156618. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  156619. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  156620. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  156621. /* Memory manager initialization */
  156622. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  156623. /* Utility routines in jutils.c */
  156624. EXTERN(long) jdiv_round_up JPP((long a, long b));
  156625. EXTERN(long) jround_up JPP((long a, long b));
  156626. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  156627. JSAMPARRAY output_array, int dest_row,
  156628. int num_rows, JDIMENSION num_cols));
  156629. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  156630. JDIMENSION num_blocks));
  156631. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  156632. /* Constant tables in jutils.c */
  156633. #if 0 /* This table is not actually needed in v6a */
  156634. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  156635. #endif
  156636. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  156637. /* Suppress undefined-structure complaints if necessary. */
  156638. #ifdef INCOMPLETE_TYPES_BROKEN
  156639. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  156640. struct jvirt_sarray_control { long dummy; };
  156641. struct jvirt_barray_control { long dummy; };
  156642. #endif
  156643. #endif /* INCOMPLETE_TYPES_BROKEN */
  156644. /********* End of inlined file: jpegint.h *********/
  156645. /* fetch private declarations */
  156646. /********* Start of inlined file: jerror.h *********/
  156647. /*
  156648. * To define the enum list of message codes, include this file without
  156649. * defining macro JMESSAGE. To create a message string table, include it
  156650. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  156651. */
  156652. #ifndef JMESSAGE
  156653. #ifndef JERROR_H
  156654. /* First time through, define the enum list */
  156655. #define JMAKE_ENUM_LIST
  156656. #else
  156657. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  156658. #define JMESSAGE(code,string)
  156659. #endif /* JERROR_H */
  156660. #endif /* JMESSAGE */
  156661. #ifdef JMAKE_ENUM_LIST
  156662. typedef enum {
  156663. #define JMESSAGE(code,string) code ,
  156664. #endif /* JMAKE_ENUM_LIST */
  156665. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  156666. /* For maintenance convenience, list is alphabetical by message code name */
  156667. JMESSAGE(JERR_ARITH_NOTIMPL,
  156668. "Sorry, there are legal restrictions on arithmetic coding")
  156669. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  156670. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  156671. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  156672. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  156673. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  156674. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  156675. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  156676. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  156677. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  156678. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  156679. JMESSAGE(JERR_BAD_LIB_VERSION,
  156680. "Wrong JPEG library version: library is %d, caller expects %d")
  156681. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  156682. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  156683. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  156684. JMESSAGE(JERR_BAD_PROGRESSION,
  156685. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  156686. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  156687. "Invalid progressive parameters at scan script entry %d")
  156688. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  156689. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  156690. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  156691. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  156692. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  156693. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  156694. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  156695. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  156696. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  156697. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  156698. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  156699. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  156700. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  156701. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  156702. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  156703. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  156704. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  156705. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  156706. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  156707. JMESSAGE(JERR_FILE_READ, "Input file read error")
  156708. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  156709. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  156710. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  156711. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  156712. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  156713. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  156714. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  156715. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  156716. "Cannot transcode due to multiple use of quantization table %d")
  156717. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  156718. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  156719. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  156720. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  156721. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  156722. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  156723. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  156724. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  156725. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  156726. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  156727. JMESSAGE(JERR_QUANT_COMPONENTS,
  156728. "Cannot quantize more than %d color components")
  156729. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  156730. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  156731. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  156732. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  156733. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  156734. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  156735. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  156736. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  156737. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  156738. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  156739. JMESSAGE(JERR_TFILE_WRITE,
  156740. "Write failed on temporary file --- out of disk space?")
  156741. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  156742. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  156743. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  156744. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  156745. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  156746. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  156747. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  156748. JMESSAGE(JMSG_VERSION, JVERSION)
  156749. JMESSAGE(JTRC_16BIT_TABLES,
  156750. "Caution: quantization tables are too coarse for baseline JPEG")
  156751. JMESSAGE(JTRC_ADOBE,
  156752. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  156753. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  156754. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  156755. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  156756. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  156757. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  156758. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  156759. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  156760. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  156761. JMESSAGE(JTRC_EOI, "End Of Image")
  156762. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  156763. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  156764. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  156765. "Warning: thumbnail image size does not match data length %u")
  156766. JMESSAGE(JTRC_JFIF_EXTENSION,
  156767. "JFIF extension marker: type 0x%02x, length %u")
  156768. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  156769. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  156770. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  156771. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  156772. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  156773. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  156774. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  156775. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  156776. JMESSAGE(JTRC_RST, "RST%d")
  156777. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  156778. "Smoothing not supported with nonstandard sampling ratios")
  156779. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  156780. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  156781. JMESSAGE(JTRC_SOI, "Start of Image")
  156782. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  156783. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  156784. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  156785. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  156786. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  156787. JMESSAGE(JTRC_THUMB_JPEG,
  156788. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  156789. JMESSAGE(JTRC_THUMB_PALETTE,
  156790. "JFIF extension marker: palette thumbnail image, length %u")
  156791. JMESSAGE(JTRC_THUMB_RGB,
  156792. "JFIF extension marker: RGB thumbnail image, length %u")
  156793. JMESSAGE(JTRC_UNKNOWN_IDS,
  156794. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  156795. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  156796. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  156797. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  156798. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  156799. "Inconsistent progression sequence for component %d coefficient %d")
  156800. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  156801. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  156802. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  156803. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  156804. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  156805. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  156806. JMESSAGE(JWRN_MUST_RESYNC,
  156807. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  156808. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  156809. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  156810. #ifdef JMAKE_ENUM_LIST
  156811. JMSG_LASTMSGCODE
  156812. } J_MESSAGE_CODE;
  156813. #undef JMAKE_ENUM_LIST
  156814. #endif /* JMAKE_ENUM_LIST */
  156815. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  156816. #undef JMESSAGE
  156817. #ifndef JERROR_H
  156818. #define JERROR_H
  156819. /* Macros to simplify using the error and trace message stuff */
  156820. /* The first parameter is either type of cinfo pointer */
  156821. /* Fatal errors (print message and exit) */
  156822. #define ERREXIT(cinfo,code) \
  156823. ((cinfo)->err->msg_code = (code), \
  156824. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156825. #define ERREXIT1(cinfo,code,p1) \
  156826. ((cinfo)->err->msg_code = (code), \
  156827. (cinfo)->err->msg_parm.i[0] = (p1), \
  156828. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156829. #define ERREXIT2(cinfo,code,p1,p2) \
  156830. ((cinfo)->err->msg_code = (code), \
  156831. (cinfo)->err->msg_parm.i[0] = (p1), \
  156832. (cinfo)->err->msg_parm.i[1] = (p2), \
  156833. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156834. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  156835. ((cinfo)->err->msg_code = (code), \
  156836. (cinfo)->err->msg_parm.i[0] = (p1), \
  156837. (cinfo)->err->msg_parm.i[1] = (p2), \
  156838. (cinfo)->err->msg_parm.i[2] = (p3), \
  156839. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156840. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  156841. ((cinfo)->err->msg_code = (code), \
  156842. (cinfo)->err->msg_parm.i[0] = (p1), \
  156843. (cinfo)->err->msg_parm.i[1] = (p2), \
  156844. (cinfo)->err->msg_parm.i[2] = (p3), \
  156845. (cinfo)->err->msg_parm.i[3] = (p4), \
  156846. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156847. #define ERREXITS(cinfo,code,str) \
  156848. ((cinfo)->err->msg_code = (code), \
  156849. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156850. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  156851. #define MAKESTMT(stuff) do { stuff } while (0)
  156852. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  156853. #define WARNMS(cinfo,code) \
  156854. ((cinfo)->err->msg_code = (code), \
  156855. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156856. #define WARNMS1(cinfo,code,p1) \
  156857. ((cinfo)->err->msg_code = (code), \
  156858. (cinfo)->err->msg_parm.i[0] = (p1), \
  156859. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156860. #define WARNMS2(cinfo,code,p1,p2) \
  156861. ((cinfo)->err->msg_code = (code), \
  156862. (cinfo)->err->msg_parm.i[0] = (p1), \
  156863. (cinfo)->err->msg_parm.i[1] = (p2), \
  156864. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  156865. /* Informational/debugging messages */
  156866. #define TRACEMS(cinfo,lvl,code) \
  156867. ((cinfo)->err->msg_code = (code), \
  156868. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156869. #define TRACEMS1(cinfo,lvl,code,p1) \
  156870. ((cinfo)->err->msg_code = (code), \
  156871. (cinfo)->err->msg_parm.i[0] = (p1), \
  156872. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156873. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  156874. ((cinfo)->err->msg_code = (code), \
  156875. (cinfo)->err->msg_parm.i[0] = (p1), \
  156876. (cinfo)->err->msg_parm.i[1] = (p2), \
  156877. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156878. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  156879. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156880. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  156881. (cinfo)->err->msg_code = (code); \
  156882. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156883. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  156884. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156885. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156886. (cinfo)->err->msg_code = (code); \
  156887. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156888. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  156889. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156890. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156891. _mp[4] = (p5); \
  156892. (cinfo)->err->msg_code = (code); \
  156893. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156894. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  156895. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  156896. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  156897. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  156898. (cinfo)->err->msg_code = (code); \
  156899. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  156900. #define TRACEMSS(cinfo,lvl,code,str) \
  156901. ((cinfo)->err->msg_code = (code), \
  156902. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  156903. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  156904. #endif /* JERROR_H */
  156905. /********* End of inlined file: jerror.h *********/
  156906. /* fetch error codes too */
  156907. #endif
  156908. #endif /* JPEGLIB_H */
  156909. /********* End of inlined file: jpeglib.h *********/
  156910. /********* Start of inlined file: jcapimin.c *********/
  156911. #define JPEG_INTERNALS
  156912. /********* Start of inlined file: jinclude.h *********/
  156913. /* Include auto-config file to find out which system include files we need. */
  156914. #ifndef __jinclude_h__
  156915. #define __jinclude_h__
  156916. /********* Start of inlined file: jconfig.h *********/
  156917. /* see jconfig.doc for explanations */
  156918. // disable all the warnings under MSVC
  156919. #ifdef _MSC_VER
  156920. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  156921. #endif
  156922. #ifdef __BORLANDC__
  156923. #pragma warn -8057
  156924. #pragma warn -8019
  156925. #pragma warn -8004
  156926. #pragma warn -8008
  156927. #endif
  156928. #define HAVE_PROTOTYPES
  156929. #define HAVE_UNSIGNED_CHAR
  156930. #define HAVE_UNSIGNED_SHORT
  156931. /* #define void char */
  156932. /* #define const */
  156933. #undef CHAR_IS_UNSIGNED
  156934. #define HAVE_STDDEF_H
  156935. #define HAVE_STDLIB_H
  156936. #undef NEED_BSD_STRINGS
  156937. #undef NEED_SYS_TYPES_H
  156938. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  156939. #undef NEED_SHORT_EXTERNAL_NAMES
  156940. #undef INCOMPLETE_TYPES_BROKEN
  156941. /* Define "boolean" as unsigned char, not int, per Windows custom */
  156942. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  156943. typedef unsigned char boolean;
  156944. #endif
  156945. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  156946. #ifdef JPEG_INTERNALS
  156947. #undef RIGHT_SHIFT_IS_UNSIGNED
  156948. #endif /* JPEG_INTERNALS */
  156949. #ifdef JPEG_CJPEG_DJPEG
  156950. #define BMP_SUPPORTED /* BMP image file format */
  156951. #define GIF_SUPPORTED /* GIF image file format */
  156952. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  156953. #undef RLE_SUPPORTED /* Utah RLE image file format */
  156954. #define TARGA_SUPPORTED /* Targa image file format */
  156955. #define TWO_FILE_COMMANDLINE /* optional */
  156956. #define USE_SETMODE /* Microsoft has setmode() */
  156957. #undef NEED_SIGNAL_CATCHER
  156958. #undef DONT_USE_B_MODE
  156959. #undef PROGRESS_REPORT /* optional */
  156960. #endif /* JPEG_CJPEG_DJPEG */
  156961. /********* End of inlined file: jconfig.h *********/
  156962. /* auto configuration options */
  156963. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  156964. /*
  156965. * We need the NULL macro and size_t typedef.
  156966. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  156967. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  156968. * pull in <sys/types.h> as well.
  156969. * Note that the core JPEG library does not require <stdio.h>;
  156970. * only the default error handler and data source/destination modules do.
  156971. * But we must pull it in because of the references to FILE in jpeglib.h.
  156972. * You can remove those references if you want to compile without <stdio.h>.
  156973. */
  156974. #ifdef HAVE_STDDEF_H
  156975. #include <stddef.h>
  156976. #endif
  156977. #ifdef HAVE_STDLIB_H
  156978. #include <stdlib.h>
  156979. #endif
  156980. #ifdef NEED_SYS_TYPES_H
  156981. #include <sys/types.h>
  156982. #endif
  156983. #include <stdio.h>
  156984. /*
  156985. * We need memory copying and zeroing functions, plus strncpy().
  156986. * ANSI and System V implementations declare these in <string.h>.
  156987. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  156988. * Some systems may declare memset and memcpy in <memory.h>.
  156989. *
  156990. * NOTE: we assume the size parameters to these functions are of type size_t.
  156991. * Change the casts in these macros if not!
  156992. */
  156993. #ifdef NEED_BSD_STRINGS
  156994. #include <strings.h>
  156995. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  156996. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  156997. #else /* not BSD, assume ANSI/SysV string lib */
  156998. #include <string.h>
  156999. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  157000. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  157001. #endif
  157002. /*
  157003. * In ANSI C, and indeed any rational implementation, size_t is also the
  157004. * type returned by sizeof(). However, it seems there are some irrational
  157005. * implementations out there, in which sizeof() returns an int even though
  157006. * size_t is defined as long or unsigned long. To ensure consistent results
  157007. * we always use this SIZEOF() macro in place of using sizeof() directly.
  157008. */
  157009. #define SIZEOF(object) ((size_t) sizeof(object))
  157010. /*
  157011. * The modules that use fread() and fwrite() always invoke them through
  157012. * these macros. On some systems you may need to twiddle the argument casts.
  157013. * CAUTION: argument order is different from underlying functions!
  157014. */
  157015. #define JFREAD(file,buf,sizeofbuf) \
  157016. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157017. #define JFWRITE(file,buf,sizeofbuf) \
  157018. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  157019. typedef enum { /* JPEG marker codes */
  157020. M_SOF0 = 0xc0,
  157021. M_SOF1 = 0xc1,
  157022. M_SOF2 = 0xc2,
  157023. M_SOF3 = 0xc3,
  157024. M_SOF5 = 0xc5,
  157025. M_SOF6 = 0xc6,
  157026. M_SOF7 = 0xc7,
  157027. M_JPG = 0xc8,
  157028. M_SOF9 = 0xc9,
  157029. M_SOF10 = 0xca,
  157030. M_SOF11 = 0xcb,
  157031. M_SOF13 = 0xcd,
  157032. M_SOF14 = 0xce,
  157033. M_SOF15 = 0xcf,
  157034. M_DHT = 0xc4,
  157035. M_DAC = 0xcc,
  157036. M_RST0 = 0xd0,
  157037. M_RST1 = 0xd1,
  157038. M_RST2 = 0xd2,
  157039. M_RST3 = 0xd3,
  157040. M_RST4 = 0xd4,
  157041. M_RST5 = 0xd5,
  157042. M_RST6 = 0xd6,
  157043. M_RST7 = 0xd7,
  157044. M_SOI = 0xd8,
  157045. M_EOI = 0xd9,
  157046. M_SOS = 0xda,
  157047. M_DQT = 0xdb,
  157048. M_DNL = 0xdc,
  157049. M_DRI = 0xdd,
  157050. M_DHP = 0xde,
  157051. M_EXP = 0xdf,
  157052. M_APP0 = 0xe0,
  157053. M_APP1 = 0xe1,
  157054. M_APP2 = 0xe2,
  157055. M_APP3 = 0xe3,
  157056. M_APP4 = 0xe4,
  157057. M_APP5 = 0xe5,
  157058. M_APP6 = 0xe6,
  157059. M_APP7 = 0xe7,
  157060. M_APP8 = 0xe8,
  157061. M_APP9 = 0xe9,
  157062. M_APP10 = 0xea,
  157063. M_APP11 = 0xeb,
  157064. M_APP12 = 0xec,
  157065. M_APP13 = 0xed,
  157066. M_APP14 = 0xee,
  157067. M_APP15 = 0xef,
  157068. M_JPG0 = 0xf0,
  157069. M_JPG13 = 0xfd,
  157070. M_COM = 0xfe,
  157071. M_TEM = 0x01,
  157072. M_ERROR = 0x100
  157073. } JPEG_MARKER;
  157074. /*
  157075. * Figure F.12: extend sign bit.
  157076. * On some machines, a shift and add will be faster than a table lookup.
  157077. */
  157078. #ifdef AVOID_TABLES
  157079. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  157080. #else
  157081. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  157082. static const int extend_test[16] = /* entry n is 2**(n-1) */
  157083. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  157084. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  157085. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  157086. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  157087. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  157088. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  157089. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  157090. #endif /* AVOID_TABLES */
  157091. #endif
  157092. /********* End of inlined file: jinclude.h *********/
  157093. /*
  157094. * Initialization of a JPEG compression object.
  157095. * The error manager must already be set up (in case memory manager fails).
  157096. */
  157097. GLOBAL(void)
  157098. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  157099. {
  157100. int i;
  157101. /* Guard against version mismatches between library and caller. */
  157102. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  157103. if (version != JPEG_LIB_VERSION)
  157104. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  157105. if (structsize != SIZEOF(struct jpeg_compress_struct))
  157106. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  157107. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  157108. /* For debugging purposes, we zero the whole master structure.
  157109. * But the application has already set the err pointer, and may have set
  157110. * client_data, so we have to save and restore those fields.
  157111. * Note: if application hasn't set client_data, tools like Purify may
  157112. * complain here.
  157113. */
  157114. {
  157115. struct jpeg_error_mgr * err = cinfo->err;
  157116. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  157117. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  157118. cinfo->err = err;
  157119. cinfo->client_data = client_data;
  157120. }
  157121. cinfo->is_decompressor = FALSE;
  157122. /* Initialize a memory manager instance for this object */
  157123. jinit_memory_mgr((j_common_ptr) cinfo);
  157124. /* Zero out pointers to permanent structures. */
  157125. cinfo->progress = NULL;
  157126. cinfo->dest = NULL;
  157127. cinfo->comp_info = NULL;
  157128. for (i = 0; i < NUM_QUANT_TBLS; i++)
  157129. cinfo->quant_tbl_ptrs[i] = NULL;
  157130. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157131. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  157132. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  157133. }
  157134. cinfo->script_space = NULL;
  157135. cinfo->input_gamma = 1.0; /* in case application forgets */
  157136. /* OK, I'm ready */
  157137. cinfo->global_state = CSTATE_START;
  157138. }
  157139. /*
  157140. * Destruction of a JPEG compression object
  157141. */
  157142. GLOBAL(void)
  157143. jpeg_destroy_compress (j_compress_ptr cinfo)
  157144. {
  157145. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  157146. }
  157147. /*
  157148. * Abort processing of a JPEG compression operation,
  157149. * but don't destroy the object itself.
  157150. */
  157151. GLOBAL(void)
  157152. jpeg_abort_compress (j_compress_ptr cinfo)
  157153. {
  157154. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  157155. }
  157156. /*
  157157. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  157158. * Marks all currently defined tables as already written (if suppress)
  157159. * or not written (if !suppress). This will control whether they get emitted
  157160. * by a subsequent jpeg_start_compress call.
  157161. *
  157162. * This routine is exported for use by applications that want to produce
  157163. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  157164. * since it is called by jpeg_start_compress, we put it here --- otherwise
  157165. * jcparam.o would be linked whether the application used it or not.
  157166. */
  157167. GLOBAL(void)
  157168. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  157169. {
  157170. int i;
  157171. JQUANT_TBL * qtbl;
  157172. JHUFF_TBL * htbl;
  157173. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157174. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  157175. qtbl->sent_table = suppress;
  157176. }
  157177. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157178. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  157179. htbl->sent_table = suppress;
  157180. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  157181. htbl->sent_table = suppress;
  157182. }
  157183. }
  157184. /*
  157185. * Finish JPEG compression.
  157186. *
  157187. * If a multipass operating mode was selected, this may do a great deal of
  157188. * work including most of the actual output.
  157189. */
  157190. GLOBAL(void)
  157191. jpeg_finish_compress (j_compress_ptr cinfo)
  157192. {
  157193. JDIMENSION iMCU_row;
  157194. if (cinfo->global_state == CSTATE_SCANNING ||
  157195. cinfo->global_state == CSTATE_RAW_OK) {
  157196. /* Terminate first pass */
  157197. if (cinfo->next_scanline < cinfo->image_height)
  157198. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  157199. (*cinfo->master->finish_pass) (cinfo);
  157200. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  157201. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157202. /* Perform any remaining passes */
  157203. while (! cinfo->master->is_last_pass) {
  157204. (*cinfo->master->prepare_for_pass) (cinfo);
  157205. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  157206. if (cinfo->progress != NULL) {
  157207. cinfo->progress->pass_counter = (long) iMCU_row;
  157208. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  157209. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157210. }
  157211. /* We bypass the main controller and invoke coef controller directly;
  157212. * all work is being done from the coefficient buffer.
  157213. */
  157214. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  157215. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157216. }
  157217. (*cinfo->master->finish_pass) (cinfo);
  157218. }
  157219. /* Write EOI, do final cleanup */
  157220. (*cinfo->marker->write_file_trailer) (cinfo);
  157221. (*cinfo->dest->term_destination) (cinfo);
  157222. /* We can use jpeg_abort to release memory and reset global_state */
  157223. jpeg_abort((j_common_ptr) cinfo);
  157224. }
  157225. /*
  157226. * Write a special marker.
  157227. * This is only recommended for writing COM or APPn markers.
  157228. * Must be called after jpeg_start_compress() and before
  157229. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  157230. */
  157231. GLOBAL(void)
  157232. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  157233. const JOCTET *dataptr, unsigned int datalen)
  157234. {
  157235. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  157236. if (cinfo->next_scanline != 0 ||
  157237. (cinfo->global_state != CSTATE_SCANNING &&
  157238. cinfo->global_state != CSTATE_RAW_OK &&
  157239. cinfo->global_state != CSTATE_WRCOEFS))
  157240. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157241. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157242. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  157243. while (datalen--) {
  157244. (*write_marker_byte) (cinfo, *dataptr);
  157245. dataptr++;
  157246. }
  157247. }
  157248. /* Same, but piecemeal. */
  157249. GLOBAL(void)
  157250. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157251. {
  157252. if (cinfo->next_scanline != 0 ||
  157253. (cinfo->global_state != CSTATE_SCANNING &&
  157254. cinfo->global_state != CSTATE_RAW_OK &&
  157255. cinfo->global_state != CSTATE_WRCOEFS))
  157256. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157257. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  157258. }
  157259. GLOBAL(void)
  157260. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  157261. {
  157262. (*cinfo->marker->write_marker_byte) (cinfo, val);
  157263. }
  157264. /*
  157265. * Alternate compression function: just write an abbreviated table file.
  157266. * Before calling this, all parameters and a data destination must be set up.
  157267. *
  157268. * To produce a pair of files containing abbreviated tables and abbreviated
  157269. * image data, one would proceed as follows:
  157270. *
  157271. * initialize JPEG object
  157272. * set JPEG parameters
  157273. * set destination to table file
  157274. * jpeg_write_tables(cinfo);
  157275. * set destination to image file
  157276. * jpeg_start_compress(cinfo, FALSE);
  157277. * write data...
  157278. * jpeg_finish_compress(cinfo);
  157279. *
  157280. * jpeg_write_tables has the side effect of marking all tables written
  157281. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  157282. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  157283. */
  157284. GLOBAL(void)
  157285. jpeg_write_tables (j_compress_ptr cinfo)
  157286. {
  157287. if (cinfo->global_state != CSTATE_START)
  157288. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157289. /* (Re)initialize error mgr and destination modules */
  157290. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157291. (*cinfo->dest->init_destination) (cinfo);
  157292. /* Initialize the marker writer ... bit of a crock to do it here. */
  157293. jinit_marker_writer(cinfo);
  157294. /* Write them tables! */
  157295. (*cinfo->marker->write_tables_only) (cinfo);
  157296. /* And clean up. */
  157297. (*cinfo->dest->term_destination) (cinfo);
  157298. /*
  157299. * In library releases up through v6a, we called jpeg_abort() here to free
  157300. * any working memory allocated by the destination manager and marker
  157301. * writer. Some applications had a problem with that: they allocated space
  157302. * of their own from the library memory manager, and didn't want it to go
  157303. * away during write_tables. So now we do nothing. This will cause a
  157304. * memory leak if an app calls write_tables repeatedly without doing a full
  157305. * compression cycle or otherwise resetting the JPEG object. However, that
  157306. * seems less bad than unexpectedly freeing memory in the normal case.
  157307. * An app that prefers the old behavior can call jpeg_abort for itself after
  157308. * each call to jpeg_write_tables().
  157309. */
  157310. }
  157311. /********* End of inlined file: jcapimin.c *********/
  157312. /********* Start of inlined file: jcapistd.c *********/
  157313. #define JPEG_INTERNALS
  157314. /*
  157315. * Compression initialization.
  157316. * Before calling this, all parameters and a data destination must be set up.
  157317. *
  157318. * We require a write_all_tables parameter as a failsafe check when writing
  157319. * multiple datastreams from the same compression object. Since prior runs
  157320. * will have left all the tables marked sent_table=TRUE, a subsequent run
  157321. * would emit an abbreviated stream (no tables) by default. This may be what
  157322. * is wanted, but for safety's sake it should not be the default behavior:
  157323. * programmers should have to make a deliberate choice to emit abbreviated
  157324. * images. Therefore the documentation and examples should encourage people
  157325. * to pass write_all_tables=TRUE; then it will take active thought to do the
  157326. * wrong thing.
  157327. */
  157328. GLOBAL(void)
  157329. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  157330. {
  157331. if (cinfo->global_state != CSTATE_START)
  157332. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157333. if (write_all_tables)
  157334. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  157335. /* (Re)initialize error mgr and destination modules */
  157336. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  157337. (*cinfo->dest->init_destination) (cinfo);
  157338. /* Perform master selection of active modules */
  157339. jinit_compress_master(cinfo);
  157340. /* Set up for the first pass */
  157341. (*cinfo->master->prepare_for_pass) (cinfo);
  157342. /* Ready for application to drive first pass through jpeg_write_scanlines
  157343. * or jpeg_write_raw_data.
  157344. */
  157345. cinfo->next_scanline = 0;
  157346. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  157347. }
  157348. /*
  157349. * Write some scanlines of data to the JPEG compressor.
  157350. *
  157351. * The return value will be the number of lines actually written.
  157352. * This should be less than the supplied num_lines only in case that
  157353. * the data destination module has requested suspension of the compressor,
  157354. * or if more than image_height scanlines are passed in.
  157355. *
  157356. * Note: we warn about excess calls to jpeg_write_scanlines() since
  157357. * this likely signals an application programmer error. However,
  157358. * excess scanlines passed in the last valid call are *silently* ignored,
  157359. * so that the application need not adjust num_lines for end-of-image
  157360. * when using a multiple-scanline buffer.
  157361. */
  157362. GLOBAL(JDIMENSION)
  157363. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  157364. JDIMENSION num_lines)
  157365. {
  157366. JDIMENSION row_ctr, rows_left;
  157367. if (cinfo->global_state != CSTATE_SCANNING)
  157368. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157369. if (cinfo->next_scanline >= cinfo->image_height)
  157370. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157371. /* Call progress monitor hook if present */
  157372. if (cinfo->progress != NULL) {
  157373. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157374. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157375. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157376. }
  157377. /* Give master control module another chance if this is first call to
  157378. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  157379. * delayed so that application can write COM, etc, markers between
  157380. * jpeg_start_compress and jpeg_write_scanlines.
  157381. */
  157382. if (cinfo->master->call_pass_startup)
  157383. (*cinfo->master->pass_startup) (cinfo);
  157384. /* Ignore any extra scanlines at bottom of image. */
  157385. rows_left = cinfo->image_height - cinfo->next_scanline;
  157386. if (num_lines > rows_left)
  157387. num_lines = rows_left;
  157388. row_ctr = 0;
  157389. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  157390. cinfo->next_scanline += row_ctr;
  157391. return row_ctr;
  157392. }
  157393. /*
  157394. * Alternate entry point to write raw data.
  157395. * Processes exactly one iMCU row per call, unless suspended.
  157396. */
  157397. GLOBAL(JDIMENSION)
  157398. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  157399. JDIMENSION num_lines)
  157400. {
  157401. JDIMENSION lines_per_iMCU_row;
  157402. if (cinfo->global_state != CSTATE_RAW_OK)
  157403. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  157404. if (cinfo->next_scanline >= cinfo->image_height) {
  157405. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  157406. return 0;
  157407. }
  157408. /* Call progress monitor hook if present */
  157409. if (cinfo->progress != NULL) {
  157410. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  157411. cinfo->progress->pass_limit = (long) cinfo->image_height;
  157412. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  157413. }
  157414. /* Give master control module another chance if this is first call to
  157415. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  157416. * delayed so that application can write COM, etc, markers between
  157417. * jpeg_start_compress and jpeg_write_raw_data.
  157418. */
  157419. if (cinfo->master->call_pass_startup)
  157420. (*cinfo->master->pass_startup) (cinfo);
  157421. /* Verify that at least one iMCU row has been passed. */
  157422. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  157423. if (num_lines < lines_per_iMCU_row)
  157424. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  157425. /* Directly compress the row. */
  157426. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  157427. /* If compressor did not consume the whole row, suspend processing. */
  157428. return 0;
  157429. }
  157430. /* OK, we processed one iMCU row. */
  157431. cinfo->next_scanline += lines_per_iMCU_row;
  157432. return lines_per_iMCU_row;
  157433. }
  157434. /********* End of inlined file: jcapistd.c *********/
  157435. /********* Start of inlined file: jccoefct.c *********/
  157436. #define JPEG_INTERNALS
  157437. /* We use a full-image coefficient buffer when doing Huffman optimization,
  157438. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  157439. * step is run during the first pass, and subsequent passes need only read
  157440. * the buffered coefficients.
  157441. */
  157442. #ifdef ENTROPY_OPT_SUPPORTED
  157443. #define FULL_COEF_BUFFER_SUPPORTED
  157444. #else
  157445. #ifdef C_MULTISCAN_FILES_SUPPORTED
  157446. #define FULL_COEF_BUFFER_SUPPORTED
  157447. #endif
  157448. #endif
  157449. /* Private buffer controller object */
  157450. typedef struct {
  157451. struct jpeg_c_coef_controller pub; /* public fields */
  157452. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  157453. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  157454. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  157455. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  157456. /* For single-pass compression, it's sufficient to buffer just one MCU
  157457. * (although this may prove a bit slow in practice). We allocate a
  157458. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  157459. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  157460. * it's not really very big; this is to keep the module interfaces unchanged
  157461. * when a large coefficient buffer is necessary.)
  157462. * In multi-pass modes, this array points to the current MCU's blocks
  157463. * within the virtual arrays.
  157464. */
  157465. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  157466. /* In multi-pass modes, we need a virtual block array for each component. */
  157467. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  157468. } my_coef_controller;
  157469. typedef my_coef_controller * my_coef_ptr;
  157470. /* Forward declarations */
  157471. METHODDEF(boolean) compress_data
  157472. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157473. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157474. METHODDEF(boolean) compress_first_pass
  157475. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157476. METHODDEF(boolean) compress_output
  157477. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  157478. #endif
  157479. LOCAL(void)
  157480. start_iMCU_row (j_compress_ptr cinfo)
  157481. /* Reset within-iMCU-row counters for a new row */
  157482. {
  157483. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157484. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  157485. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  157486. * But at the bottom of the image, process only what's left.
  157487. */
  157488. if (cinfo->comps_in_scan > 1) {
  157489. coef->MCU_rows_per_iMCU_row = 1;
  157490. } else {
  157491. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  157492. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  157493. else
  157494. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  157495. }
  157496. coef->mcu_ctr = 0;
  157497. coef->MCU_vert_offset = 0;
  157498. }
  157499. /*
  157500. * Initialize for a processing pass.
  157501. */
  157502. METHODDEF(void)
  157503. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157504. {
  157505. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157506. coef->iMCU_row_num = 0;
  157507. start_iMCU_row(cinfo);
  157508. switch (pass_mode) {
  157509. case JBUF_PASS_THRU:
  157510. if (coef->whole_image[0] != NULL)
  157511. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157512. coef->pub.compress_data = compress_data;
  157513. break;
  157514. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157515. case JBUF_SAVE_AND_PASS:
  157516. if (coef->whole_image[0] == NULL)
  157517. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157518. coef->pub.compress_data = compress_first_pass;
  157519. break;
  157520. case JBUF_CRANK_DEST:
  157521. if (coef->whole_image[0] == NULL)
  157522. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157523. coef->pub.compress_data = compress_output;
  157524. break;
  157525. #endif
  157526. default:
  157527. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157528. break;
  157529. }
  157530. }
  157531. /*
  157532. * Process some data in the single-pass case.
  157533. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157534. * per call, ie, v_samp_factor block rows for each component in the image.
  157535. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157536. *
  157537. * NB: input_buf contains a plane for each component in image,
  157538. * which we index according to the component's SOF position.
  157539. */
  157540. METHODDEF(boolean)
  157541. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157542. {
  157543. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157544. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157545. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  157546. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157547. int blkn, bi, ci, yindex, yoffset, blockcnt;
  157548. JDIMENSION ypos, xpos;
  157549. jpeg_component_info *compptr;
  157550. /* Loop to write as much as one whole iMCU row */
  157551. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157552. yoffset++) {
  157553. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  157554. MCU_col_num++) {
  157555. /* Determine where data comes from in input_buf and do the DCT thing.
  157556. * Each call on forward_DCT processes a horizontal row of DCT blocks
  157557. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  157558. * sequentially. Dummy blocks at the right or bottom edge are filled in
  157559. * specially. The data in them does not matter for image reconstruction,
  157560. * so we fill them with values that will encode to the smallest amount of
  157561. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  157562. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  157563. */
  157564. blkn = 0;
  157565. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157566. compptr = cinfo->cur_comp_info[ci];
  157567. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  157568. : compptr->last_col_width;
  157569. xpos = MCU_col_num * compptr->MCU_sample_width;
  157570. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  157571. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157572. if (coef->iMCU_row_num < last_iMCU_row ||
  157573. yoffset+yindex < compptr->last_row_height) {
  157574. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157575. input_buf[compptr->component_index],
  157576. coef->MCU_buffer[blkn],
  157577. ypos, xpos, (JDIMENSION) blockcnt);
  157578. if (blockcnt < compptr->MCU_width) {
  157579. /* Create some dummy blocks at the right edge of the image. */
  157580. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  157581. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  157582. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  157583. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  157584. }
  157585. }
  157586. } else {
  157587. /* Create a row of dummy blocks at the bottom of the image. */
  157588. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  157589. compptr->MCU_width * SIZEOF(JBLOCK));
  157590. for (bi = 0; bi < compptr->MCU_width; bi++) {
  157591. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  157592. }
  157593. }
  157594. blkn += compptr->MCU_width;
  157595. ypos += DCTSIZE;
  157596. }
  157597. }
  157598. /* Try to write the MCU. In event of a suspension failure, we will
  157599. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  157600. */
  157601. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157602. /* Suspension forced; update state counters and exit */
  157603. coef->MCU_vert_offset = yoffset;
  157604. coef->mcu_ctr = MCU_col_num;
  157605. return FALSE;
  157606. }
  157607. }
  157608. /* Completed an MCU row, but perhaps not an iMCU row */
  157609. coef->mcu_ctr = 0;
  157610. }
  157611. /* Completed the iMCU row, advance counters for next one */
  157612. coef->iMCU_row_num++;
  157613. start_iMCU_row(cinfo);
  157614. return TRUE;
  157615. }
  157616. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157617. /*
  157618. * Process some data in the first pass of a multi-pass case.
  157619. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157620. * per call, ie, v_samp_factor block rows for each component in the image.
  157621. * This amount of data is read from the source buffer, DCT'd and quantized,
  157622. * and saved into the virtual arrays. We also generate suitable dummy blocks
  157623. * as needed at the right and lower edges. (The dummy blocks are constructed
  157624. * in the virtual arrays, which have been padded appropriately.) This makes
  157625. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  157626. *
  157627. * We must also emit the data to the entropy encoder. This is conveniently
  157628. * done by calling compress_output() after we've loaded the current strip
  157629. * of the virtual arrays.
  157630. *
  157631. * NB: input_buf contains a plane for each component in image. All
  157632. * components are DCT'd and loaded into the virtual arrays in this pass.
  157633. * However, it may be that only a subset of the components are emitted to
  157634. * the entropy encoder during this first pass; be careful about looking
  157635. * at the scan-dependent variables (MCU dimensions, etc).
  157636. */
  157637. METHODDEF(boolean)
  157638. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157639. {
  157640. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157641. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  157642. JDIMENSION blocks_across, MCUs_across, MCUindex;
  157643. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  157644. JCOEF lastDC;
  157645. jpeg_component_info *compptr;
  157646. JBLOCKARRAY buffer;
  157647. JBLOCKROW thisblockrow, lastblockrow;
  157648. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157649. ci++, compptr++) {
  157650. /* Align the virtual buffer for this component. */
  157651. buffer = (*cinfo->mem->access_virt_barray)
  157652. ((j_common_ptr) cinfo, coef->whole_image[ci],
  157653. coef->iMCU_row_num * compptr->v_samp_factor,
  157654. (JDIMENSION) compptr->v_samp_factor, TRUE);
  157655. /* Count non-dummy DCT block rows in this iMCU row. */
  157656. if (coef->iMCU_row_num < last_iMCU_row)
  157657. block_rows = compptr->v_samp_factor;
  157658. else {
  157659. /* NB: can't use last_row_height here, since may not be set! */
  157660. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  157661. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  157662. }
  157663. blocks_across = compptr->width_in_blocks;
  157664. h_samp_factor = compptr->h_samp_factor;
  157665. /* Count number of dummy blocks to be added at the right margin. */
  157666. ndummy = (int) (blocks_across % h_samp_factor);
  157667. if (ndummy > 0)
  157668. ndummy = h_samp_factor - ndummy;
  157669. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  157670. * on forward_DCT processes a complete horizontal row of DCT blocks.
  157671. */
  157672. for (block_row = 0; block_row < block_rows; block_row++) {
  157673. thisblockrow = buffer[block_row];
  157674. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  157675. input_buf[ci], thisblockrow,
  157676. (JDIMENSION) (block_row * DCTSIZE),
  157677. (JDIMENSION) 0, blocks_across);
  157678. if (ndummy > 0) {
  157679. /* Create dummy blocks at the right edge of the image. */
  157680. thisblockrow += blocks_across; /* => first dummy block */
  157681. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  157682. lastDC = thisblockrow[-1][0];
  157683. for (bi = 0; bi < ndummy; bi++) {
  157684. thisblockrow[bi][0] = lastDC;
  157685. }
  157686. }
  157687. }
  157688. /* If at end of image, create dummy block rows as needed.
  157689. * The tricky part here is that within each MCU, we want the DC values
  157690. * of the dummy blocks to match the last real block's DC value.
  157691. * This squeezes a few more bytes out of the resulting file...
  157692. */
  157693. if (coef->iMCU_row_num == last_iMCU_row) {
  157694. blocks_across += ndummy; /* include lower right corner */
  157695. MCUs_across = blocks_across / h_samp_factor;
  157696. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  157697. block_row++) {
  157698. thisblockrow = buffer[block_row];
  157699. lastblockrow = buffer[block_row-1];
  157700. jzero_far((void FAR *) thisblockrow,
  157701. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  157702. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  157703. lastDC = lastblockrow[h_samp_factor-1][0];
  157704. for (bi = 0; bi < h_samp_factor; bi++) {
  157705. thisblockrow[bi][0] = lastDC;
  157706. }
  157707. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  157708. lastblockrow += h_samp_factor;
  157709. }
  157710. }
  157711. }
  157712. }
  157713. /* NB: compress_output will increment iMCU_row_num if successful.
  157714. * A suspension return will result in redoing all the work above next time.
  157715. */
  157716. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  157717. return compress_output(cinfo, input_buf);
  157718. }
  157719. /*
  157720. * Process some data in subsequent passes of a multi-pass case.
  157721. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  157722. * per call, ie, v_samp_factor block rows for each component in the scan.
  157723. * The data is obtained from the virtual arrays and fed to the entropy coder.
  157724. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  157725. *
  157726. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  157727. */
  157728. METHODDEF(boolean)
  157729. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  157730. {
  157731. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  157732. JDIMENSION MCU_col_num; /* index of current MCU within row */
  157733. int blkn, ci, xindex, yindex, yoffset;
  157734. JDIMENSION start_col;
  157735. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  157736. JBLOCKROW buffer_ptr;
  157737. jpeg_component_info *compptr;
  157738. /* Align the virtual buffers for the components used in this scan.
  157739. * NB: during first pass, this is safe only because the buffers will
  157740. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  157741. */
  157742. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157743. compptr = cinfo->cur_comp_info[ci];
  157744. buffer[ci] = (*cinfo->mem->access_virt_barray)
  157745. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  157746. coef->iMCU_row_num * compptr->v_samp_factor,
  157747. (JDIMENSION) compptr->v_samp_factor, FALSE);
  157748. }
  157749. /* Loop to process one whole iMCU row */
  157750. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  157751. yoffset++) {
  157752. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  157753. MCU_col_num++) {
  157754. /* Construct list of pointers to DCT blocks belonging to this MCU */
  157755. blkn = 0; /* index of current DCT block within MCU */
  157756. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157757. compptr = cinfo->cur_comp_info[ci];
  157758. start_col = MCU_col_num * compptr->MCU_width;
  157759. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  157760. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  157761. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  157762. coef->MCU_buffer[blkn++] = buffer_ptr++;
  157763. }
  157764. }
  157765. }
  157766. /* Try to write the MCU. */
  157767. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  157768. /* Suspension forced; update state counters and exit */
  157769. coef->MCU_vert_offset = yoffset;
  157770. coef->mcu_ctr = MCU_col_num;
  157771. return FALSE;
  157772. }
  157773. }
  157774. /* Completed an MCU row, but perhaps not an iMCU row */
  157775. coef->mcu_ctr = 0;
  157776. }
  157777. /* Completed the iMCU row, advance counters for next one */
  157778. coef->iMCU_row_num++;
  157779. start_iMCU_row(cinfo);
  157780. return TRUE;
  157781. }
  157782. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  157783. /*
  157784. * Initialize coefficient buffer controller.
  157785. */
  157786. GLOBAL(void)
  157787. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157788. {
  157789. my_coef_ptr coef;
  157790. coef = (my_coef_ptr)
  157791. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157792. SIZEOF(my_coef_controller));
  157793. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  157794. coef->pub.start_pass = start_pass_coef;
  157795. /* Create the coefficient buffer. */
  157796. if (need_full_buffer) {
  157797. #ifdef FULL_COEF_BUFFER_SUPPORTED
  157798. /* Allocate a full-image virtual array for each component, */
  157799. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  157800. int ci;
  157801. jpeg_component_info *compptr;
  157802. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157803. ci++, compptr++) {
  157804. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  157805. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157806. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  157807. (long) compptr->h_samp_factor),
  157808. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157809. (long) compptr->v_samp_factor),
  157810. (JDIMENSION) compptr->v_samp_factor);
  157811. }
  157812. #else
  157813. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157814. #endif
  157815. } else {
  157816. /* We only need a single-MCU buffer. */
  157817. JBLOCKROW buffer;
  157818. int i;
  157819. buffer = (JBLOCKROW)
  157820. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157821. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  157822. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  157823. coef->MCU_buffer[i] = buffer + i;
  157824. }
  157825. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  157826. }
  157827. }
  157828. /********* End of inlined file: jccoefct.c *********/
  157829. /********* Start of inlined file: jccolor.c *********/
  157830. #define JPEG_INTERNALS
  157831. /* Private subobject */
  157832. typedef struct {
  157833. struct jpeg_color_converter pub; /* public fields */
  157834. /* Private state for RGB->YCC conversion */
  157835. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  157836. } my_color_converter;
  157837. typedef my_color_converter * my_cconvert_ptr;
  157838. /**************** RGB -> YCbCr conversion: most common case **************/
  157839. /*
  157840. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  157841. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  157842. * The conversion equations to be implemented are therefore
  157843. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  157844. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  157845. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  157846. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  157847. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  157848. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  157849. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  157850. * were not represented exactly. Now we sacrifice exact representation of
  157851. * maximum red and maximum blue in order to get exact grayscales.
  157852. *
  157853. * To avoid floating-point arithmetic, we represent the fractional constants
  157854. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  157855. * the products by 2^16, with appropriate rounding, to get the correct answer.
  157856. *
  157857. * For even more speed, we avoid doing any multiplications in the inner loop
  157858. * by precalculating the constants times R,G,B for all possible values.
  157859. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  157860. * for 12-bit samples it is still acceptable. It's not very reasonable for
  157861. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  157862. * colorspace anyway.
  157863. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  157864. * in the tables to save adding them separately in the inner loop.
  157865. */
  157866. #define SCALEBITS 16 /* speediest right-shift on some machines */
  157867. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  157868. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  157869. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  157870. /* We allocate one big table and divide it up into eight parts, instead of
  157871. * doing eight alloc_small requests. This lets us use a single table base
  157872. * address, which can be held in a register in the inner loops on many
  157873. * machines (more than can hold all eight addresses, anyway).
  157874. */
  157875. #define R_Y_OFF 0 /* offset to R => Y section */
  157876. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  157877. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  157878. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  157879. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  157880. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  157881. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  157882. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  157883. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  157884. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  157885. /*
  157886. * Initialize for RGB->YCC colorspace conversion.
  157887. */
  157888. METHODDEF(void)
  157889. rgb_ycc_start (j_compress_ptr cinfo)
  157890. {
  157891. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157892. INT32 * rgb_ycc_tab;
  157893. INT32 i;
  157894. /* Allocate and fill in the conversion tables. */
  157895. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  157896. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157897. (TABLE_SIZE * SIZEOF(INT32)));
  157898. for (i = 0; i <= MAXJSAMPLE; i++) {
  157899. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  157900. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  157901. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  157902. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  157903. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  157904. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  157905. * This ensures that the maximum output will round to MAXJSAMPLE
  157906. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  157907. */
  157908. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157909. /* B=>Cb and R=>Cr tables are the same
  157910. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  157911. */
  157912. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  157913. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  157914. }
  157915. }
  157916. /*
  157917. * Convert some rows of samples to the JPEG colorspace.
  157918. *
  157919. * Note that we change from the application's interleaved-pixel format
  157920. * to our internal noninterleaved, one-plane-per-component format.
  157921. * The input buffer is therefore three times as wide as the output buffer.
  157922. *
  157923. * A starting row offset is provided only for the output buffer. The caller
  157924. * can easily adjust the passed input_buf value to accommodate any row
  157925. * offset required on that side.
  157926. */
  157927. METHODDEF(void)
  157928. rgb_ycc_convert (j_compress_ptr cinfo,
  157929. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157930. JDIMENSION output_row, int num_rows)
  157931. {
  157932. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157933. register int r, g, b;
  157934. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157935. register JSAMPROW inptr;
  157936. register JSAMPROW outptr0, outptr1, outptr2;
  157937. register JDIMENSION col;
  157938. JDIMENSION num_cols = cinfo->image_width;
  157939. while (--num_rows >= 0) {
  157940. inptr = *input_buf++;
  157941. outptr0 = output_buf[0][output_row];
  157942. outptr1 = output_buf[1][output_row];
  157943. outptr2 = output_buf[2][output_row];
  157944. output_row++;
  157945. for (col = 0; col < num_cols; col++) {
  157946. r = GETJSAMPLE(inptr[RGB_RED]);
  157947. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157948. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157949. inptr += RGB_PIXELSIZE;
  157950. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  157951. * must be too; we do not need an explicit range-limiting operation.
  157952. * Hence the value being shifted is never negative, and we don't
  157953. * need the general RIGHT_SHIFT macro.
  157954. */
  157955. /* Y */
  157956. outptr0[col] = (JSAMPLE)
  157957. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  157958. >> SCALEBITS);
  157959. /* Cb */
  157960. outptr1[col] = (JSAMPLE)
  157961. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  157962. >> SCALEBITS);
  157963. /* Cr */
  157964. outptr2[col] = (JSAMPLE)
  157965. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  157966. >> SCALEBITS);
  157967. }
  157968. }
  157969. }
  157970. /**************** Cases other than RGB -> YCbCr **************/
  157971. /*
  157972. * Convert some rows of samples to the JPEG colorspace.
  157973. * This version handles RGB->grayscale conversion, which is the same
  157974. * as the RGB->Y portion of RGB->YCbCr.
  157975. * We assume rgb_ycc_start has been called (we only use the Y tables).
  157976. */
  157977. METHODDEF(void)
  157978. rgb_gray_convert (j_compress_ptr cinfo,
  157979. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  157980. JDIMENSION output_row, int num_rows)
  157981. {
  157982. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  157983. register int r, g, b;
  157984. register INT32 * ctab = cconvert->rgb_ycc_tab;
  157985. register JSAMPROW inptr;
  157986. register JSAMPROW outptr;
  157987. register JDIMENSION col;
  157988. JDIMENSION num_cols = cinfo->image_width;
  157989. while (--num_rows >= 0) {
  157990. inptr = *input_buf++;
  157991. outptr = output_buf[0][output_row];
  157992. output_row++;
  157993. for (col = 0; col < num_cols; col++) {
  157994. r = GETJSAMPLE(inptr[RGB_RED]);
  157995. g = GETJSAMPLE(inptr[RGB_GREEN]);
  157996. b = GETJSAMPLE(inptr[RGB_BLUE]);
  157997. inptr += RGB_PIXELSIZE;
  157998. /* Y */
  157999. outptr[col] = (JSAMPLE)
  158000. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158001. >> SCALEBITS);
  158002. }
  158003. }
  158004. }
  158005. /*
  158006. * Convert some rows of samples to the JPEG colorspace.
  158007. * This version handles Adobe-style CMYK->YCCK conversion,
  158008. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  158009. * conversion as above, while passing K (black) unchanged.
  158010. * We assume rgb_ycc_start has been called.
  158011. */
  158012. METHODDEF(void)
  158013. cmyk_ycck_convert (j_compress_ptr cinfo,
  158014. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158015. JDIMENSION output_row, int num_rows)
  158016. {
  158017. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  158018. register int r, g, b;
  158019. register INT32 * ctab = cconvert->rgb_ycc_tab;
  158020. register JSAMPROW inptr;
  158021. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  158022. register JDIMENSION col;
  158023. JDIMENSION num_cols = cinfo->image_width;
  158024. while (--num_rows >= 0) {
  158025. inptr = *input_buf++;
  158026. outptr0 = output_buf[0][output_row];
  158027. outptr1 = output_buf[1][output_row];
  158028. outptr2 = output_buf[2][output_row];
  158029. outptr3 = output_buf[3][output_row];
  158030. output_row++;
  158031. for (col = 0; col < num_cols; col++) {
  158032. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  158033. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  158034. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  158035. /* K passes through as-is */
  158036. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  158037. inptr += 4;
  158038. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  158039. * must be too; we do not need an explicit range-limiting operation.
  158040. * Hence the value being shifted is never negative, and we don't
  158041. * need the general RIGHT_SHIFT macro.
  158042. */
  158043. /* Y */
  158044. outptr0[col] = (JSAMPLE)
  158045. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  158046. >> SCALEBITS);
  158047. /* Cb */
  158048. outptr1[col] = (JSAMPLE)
  158049. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  158050. >> SCALEBITS);
  158051. /* Cr */
  158052. outptr2[col] = (JSAMPLE)
  158053. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  158054. >> SCALEBITS);
  158055. }
  158056. }
  158057. }
  158058. /*
  158059. * Convert some rows of samples to the JPEG colorspace.
  158060. * This version handles grayscale output with no conversion.
  158061. * The source can be either plain grayscale or YCbCr (since Y == gray).
  158062. */
  158063. METHODDEF(void)
  158064. grayscale_convert (j_compress_ptr cinfo,
  158065. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158066. JDIMENSION output_row, int num_rows)
  158067. {
  158068. register JSAMPROW inptr;
  158069. register JSAMPROW outptr;
  158070. register JDIMENSION col;
  158071. JDIMENSION num_cols = cinfo->image_width;
  158072. int instride = cinfo->input_components;
  158073. while (--num_rows >= 0) {
  158074. inptr = *input_buf++;
  158075. outptr = output_buf[0][output_row];
  158076. output_row++;
  158077. for (col = 0; col < num_cols; col++) {
  158078. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  158079. inptr += instride;
  158080. }
  158081. }
  158082. }
  158083. /*
  158084. * Convert some rows of samples to the JPEG colorspace.
  158085. * This version handles multi-component colorspaces without conversion.
  158086. * We assume input_components == num_components.
  158087. */
  158088. METHODDEF(void)
  158089. null_convert (j_compress_ptr cinfo,
  158090. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  158091. JDIMENSION output_row, int num_rows)
  158092. {
  158093. register JSAMPROW inptr;
  158094. register JSAMPROW outptr;
  158095. register JDIMENSION col;
  158096. register int ci;
  158097. int nc = cinfo->num_components;
  158098. JDIMENSION num_cols = cinfo->image_width;
  158099. while (--num_rows >= 0) {
  158100. /* It seems fastest to make a separate pass for each component. */
  158101. for (ci = 0; ci < nc; ci++) {
  158102. inptr = *input_buf;
  158103. outptr = output_buf[ci][output_row];
  158104. for (col = 0; col < num_cols; col++) {
  158105. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  158106. inptr += nc;
  158107. }
  158108. }
  158109. input_buf++;
  158110. output_row++;
  158111. }
  158112. }
  158113. /*
  158114. * Empty method for start_pass.
  158115. */
  158116. METHODDEF(void)
  158117. null_method (j_compress_ptr cinfo)
  158118. {
  158119. /* no work needed */
  158120. }
  158121. /*
  158122. * Module initialization routine for input colorspace conversion.
  158123. */
  158124. GLOBAL(void)
  158125. jinit_color_converter (j_compress_ptr cinfo)
  158126. {
  158127. my_cconvert_ptr cconvert;
  158128. cconvert = (my_cconvert_ptr)
  158129. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158130. SIZEOF(my_color_converter));
  158131. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  158132. /* set start_pass to null method until we find out differently */
  158133. cconvert->pub.start_pass = null_method;
  158134. /* Make sure input_components agrees with in_color_space */
  158135. switch (cinfo->in_color_space) {
  158136. case JCS_GRAYSCALE:
  158137. if (cinfo->input_components != 1)
  158138. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158139. break;
  158140. case JCS_RGB:
  158141. #if RGB_PIXELSIZE != 3
  158142. if (cinfo->input_components != RGB_PIXELSIZE)
  158143. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158144. break;
  158145. #endif /* else share code with YCbCr */
  158146. case JCS_YCbCr:
  158147. if (cinfo->input_components != 3)
  158148. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158149. break;
  158150. case JCS_CMYK:
  158151. case JCS_YCCK:
  158152. if (cinfo->input_components != 4)
  158153. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158154. break;
  158155. default: /* JCS_UNKNOWN can be anything */
  158156. if (cinfo->input_components < 1)
  158157. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158158. break;
  158159. }
  158160. /* Check num_components, set conversion method based on requested space */
  158161. switch (cinfo->jpeg_color_space) {
  158162. case JCS_GRAYSCALE:
  158163. if (cinfo->num_components != 1)
  158164. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158165. if (cinfo->in_color_space == JCS_GRAYSCALE)
  158166. cconvert->pub.color_convert = grayscale_convert;
  158167. else if (cinfo->in_color_space == JCS_RGB) {
  158168. cconvert->pub.start_pass = rgb_ycc_start;
  158169. cconvert->pub.color_convert = rgb_gray_convert;
  158170. } else if (cinfo->in_color_space == JCS_YCbCr)
  158171. cconvert->pub.color_convert = grayscale_convert;
  158172. else
  158173. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158174. break;
  158175. case JCS_RGB:
  158176. if (cinfo->num_components != 3)
  158177. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158178. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  158179. cconvert->pub.color_convert = null_convert;
  158180. else
  158181. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158182. break;
  158183. case JCS_YCbCr:
  158184. if (cinfo->num_components != 3)
  158185. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158186. if (cinfo->in_color_space == JCS_RGB) {
  158187. cconvert->pub.start_pass = rgb_ycc_start;
  158188. cconvert->pub.color_convert = rgb_ycc_convert;
  158189. } else if (cinfo->in_color_space == JCS_YCbCr)
  158190. cconvert->pub.color_convert = null_convert;
  158191. else
  158192. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158193. break;
  158194. case JCS_CMYK:
  158195. if (cinfo->num_components != 4)
  158196. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158197. if (cinfo->in_color_space == JCS_CMYK)
  158198. cconvert->pub.color_convert = null_convert;
  158199. else
  158200. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158201. break;
  158202. case JCS_YCCK:
  158203. if (cinfo->num_components != 4)
  158204. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158205. if (cinfo->in_color_space == JCS_CMYK) {
  158206. cconvert->pub.start_pass = rgb_ycc_start;
  158207. cconvert->pub.color_convert = cmyk_ycck_convert;
  158208. } else if (cinfo->in_color_space == JCS_YCCK)
  158209. cconvert->pub.color_convert = null_convert;
  158210. else
  158211. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158212. break;
  158213. default: /* allow null conversion of JCS_UNKNOWN */
  158214. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  158215. cinfo->num_components != cinfo->input_components)
  158216. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  158217. cconvert->pub.color_convert = null_convert;
  158218. break;
  158219. }
  158220. }
  158221. /********* End of inlined file: jccolor.c *********/
  158222. #undef FIX
  158223. /********* Start of inlined file: jcdctmgr.c *********/
  158224. #define JPEG_INTERNALS
  158225. /********* Start of inlined file: jdct.h *********/
  158226. /*
  158227. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  158228. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  158229. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  158230. * implementations use an array of type FAST_FLOAT, instead.)
  158231. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  158232. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  158233. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  158234. * convention improves accuracy in integer implementations and saves some
  158235. * work in floating-point ones.
  158236. * Quantization of the output coefficients is done by jcdctmgr.c.
  158237. */
  158238. #ifndef __jdct_h__
  158239. #define __jdct_h__
  158240. #if BITS_IN_JSAMPLE == 8
  158241. typedef int DCTELEM; /* 16 or 32 bits is fine */
  158242. #else
  158243. typedef INT32 DCTELEM; /* must have 32 bits */
  158244. #endif
  158245. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  158246. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  158247. /*
  158248. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  158249. * to an output sample array. The routine must dequantize the input data as
  158250. * well as perform the IDCT; for dequantization, it uses the multiplier table
  158251. * pointed to by compptr->dct_table. The output data is to be placed into the
  158252. * sample array starting at a specified column. (Any row offset needed will
  158253. * be applied to the array pointer before it is passed to the IDCT code.)
  158254. * Note that the number of samples emitted by the IDCT routine is
  158255. * DCT_scaled_size * DCT_scaled_size.
  158256. */
  158257. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  158258. /*
  158259. * Each IDCT routine has its own ideas about the best dct_table element type.
  158260. */
  158261. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  158262. #if BITS_IN_JSAMPLE == 8
  158263. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  158264. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  158265. #else
  158266. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  158267. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  158268. #endif
  158269. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  158270. /*
  158271. * Each IDCT routine is responsible for range-limiting its results and
  158272. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  158273. * be quite far out of range if the input data is corrupt, so a bulletproof
  158274. * range-limiting step is required. We use a mask-and-table-lookup method
  158275. * to do the combined operations quickly. See the comments with
  158276. * prepare_range_limit_table (in jdmaster.c) for more info.
  158277. */
  158278. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  158279. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  158280. /* Short forms of external names for systems with brain-damaged linkers. */
  158281. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158282. #define jpeg_fdct_islow jFDislow
  158283. #define jpeg_fdct_ifast jFDifast
  158284. #define jpeg_fdct_float jFDfloat
  158285. #define jpeg_idct_islow jRDislow
  158286. #define jpeg_idct_ifast jRDifast
  158287. #define jpeg_idct_float jRDfloat
  158288. #define jpeg_idct_4x4 jRD4x4
  158289. #define jpeg_idct_2x2 jRD2x2
  158290. #define jpeg_idct_1x1 jRD1x1
  158291. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158292. /* Extern declarations for the forward and inverse DCT routines. */
  158293. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  158294. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  158295. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  158296. EXTERN(void) jpeg_idct_islow
  158297. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158298. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158299. EXTERN(void) jpeg_idct_ifast
  158300. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158301. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158302. EXTERN(void) jpeg_idct_float
  158303. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158304. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158305. EXTERN(void) jpeg_idct_4x4
  158306. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158307. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158308. EXTERN(void) jpeg_idct_2x2
  158309. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158310. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158311. EXTERN(void) jpeg_idct_1x1
  158312. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  158313. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  158314. /*
  158315. * Macros for handling fixed-point arithmetic; these are used by many
  158316. * but not all of the DCT/IDCT modules.
  158317. *
  158318. * All values are expected to be of type INT32.
  158319. * Fractional constants are scaled left by CONST_BITS bits.
  158320. * CONST_BITS is defined within each module using these macros,
  158321. * and may differ from one module to the next.
  158322. */
  158323. #define ONE ((INT32) 1)
  158324. #define CONST_SCALE (ONE << CONST_BITS)
  158325. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  158326. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  158327. * thus causing a lot of useless floating-point operations at run time.
  158328. */
  158329. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  158330. /* Descale and correctly round an INT32 value that's scaled by N bits.
  158331. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  158332. * the fudge factor is correct for either sign of X.
  158333. */
  158334. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  158335. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  158336. * This macro is used only when the two inputs will actually be no more than
  158337. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  158338. * full 32x32 multiply. This provides a useful speedup on many machines.
  158339. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  158340. * in C, but some C compilers will do the right thing if you provide the
  158341. * correct combination of casts.
  158342. */
  158343. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158344. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  158345. #endif
  158346. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  158347. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  158348. #endif
  158349. #ifndef MULTIPLY16C16 /* default definition */
  158350. #define MULTIPLY16C16(var,const) ((var) * (const))
  158351. #endif
  158352. /* Same except both inputs are variables. */
  158353. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  158354. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  158355. #endif
  158356. #ifndef MULTIPLY16V16 /* default definition */
  158357. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  158358. #endif
  158359. #endif
  158360. /********* End of inlined file: jdct.h *********/
  158361. /* Private declarations for DCT subsystem */
  158362. /* Private subobject for this module */
  158363. typedef struct {
  158364. struct jpeg_forward_dct pub; /* public fields */
  158365. /* Pointer to the DCT routine actually in use */
  158366. forward_DCT_method_ptr do_dct;
  158367. /* The actual post-DCT divisors --- not identical to the quant table
  158368. * entries, because of scaling (especially for an unnormalized DCT).
  158369. * Each table is given in normal array order.
  158370. */
  158371. DCTELEM * divisors[NUM_QUANT_TBLS];
  158372. #ifdef DCT_FLOAT_SUPPORTED
  158373. /* Same as above for the floating-point case. */
  158374. float_DCT_method_ptr do_float_dct;
  158375. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  158376. #endif
  158377. } my_fdct_controller;
  158378. typedef my_fdct_controller * my_fdct_ptr;
  158379. /*
  158380. * Initialize for a processing pass.
  158381. * Verify that all referenced Q-tables are present, and set up
  158382. * the divisor table for each one.
  158383. * In the current implementation, DCT of all components is done during
  158384. * the first pass, even if only some components will be output in the
  158385. * first scan. Hence all components should be examined here.
  158386. */
  158387. METHODDEF(void)
  158388. start_pass_fdctmgr (j_compress_ptr cinfo)
  158389. {
  158390. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158391. int ci, qtblno, i;
  158392. jpeg_component_info *compptr;
  158393. JQUANT_TBL * qtbl;
  158394. DCTELEM * dtbl;
  158395. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158396. ci++, compptr++) {
  158397. qtblno = compptr->quant_tbl_no;
  158398. /* Make sure specified quantization table is present */
  158399. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  158400. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  158401. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  158402. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  158403. /* Compute divisors for this quant table */
  158404. /* We may do this more than once for same table, but it's not a big deal */
  158405. switch (cinfo->dct_method) {
  158406. #ifdef DCT_ISLOW_SUPPORTED
  158407. case JDCT_ISLOW:
  158408. /* For LL&M IDCT method, divisors are equal to raw quantization
  158409. * coefficients multiplied by 8 (to counteract scaling).
  158410. */
  158411. if (fdct->divisors[qtblno] == NULL) {
  158412. fdct->divisors[qtblno] = (DCTELEM *)
  158413. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158414. DCTSIZE2 * SIZEOF(DCTELEM));
  158415. }
  158416. dtbl = fdct->divisors[qtblno];
  158417. for (i = 0; i < DCTSIZE2; i++) {
  158418. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  158419. }
  158420. break;
  158421. #endif
  158422. #ifdef DCT_IFAST_SUPPORTED
  158423. case JDCT_IFAST:
  158424. {
  158425. /* For AA&N IDCT method, divisors are equal to quantization
  158426. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158427. * scalefactor[0] = 1
  158428. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158429. * We apply a further scale factor of 8.
  158430. */
  158431. #define CONST_BITS 14
  158432. static const INT16 aanscales[DCTSIZE2] = {
  158433. /* precomputed values scaled up by 14 bits */
  158434. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158435. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  158436. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  158437. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  158438. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  158439. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  158440. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  158441. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  158442. };
  158443. SHIFT_TEMPS
  158444. if (fdct->divisors[qtblno] == NULL) {
  158445. fdct->divisors[qtblno] = (DCTELEM *)
  158446. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158447. DCTSIZE2 * SIZEOF(DCTELEM));
  158448. }
  158449. dtbl = fdct->divisors[qtblno];
  158450. for (i = 0; i < DCTSIZE2; i++) {
  158451. dtbl[i] = (DCTELEM)
  158452. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  158453. (INT32) aanscales[i]),
  158454. CONST_BITS-3);
  158455. }
  158456. }
  158457. break;
  158458. #endif
  158459. #ifdef DCT_FLOAT_SUPPORTED
  158460. case JDCT_FLOAT:
  158461. {
  158462. /* For float AA&N IDCT method, divisors are equal to quantization
  158463. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  158464. * scalefactor[0] = 1
  158465. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  158466. * We apply a further scale factor of 8.
  158467. * What's actually stored is 1/divisor so that the inner loop can
  158468. * use a multiplication rather than a division.
  158469. */
  158470. FAST_FLOAT * fdtbl;
  158471. int row, col;
  158472. static const double aanscalefactor[DCTSIZE] = {
  158473. 1.0, 1.387039845, 1.306562965, 1.175875602,
  158474. 1.0, 0.785694958, 0.541196100, 0.275899379
  158475. };
  158476. if (fdct->float_divisors[qtblno] == NULL) {
  158477. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  158478. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158479. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  158480. }
  158481. fdtbl = fdct->float_divisors[qtblno];
  158482. i = 0;
  158483. for (row = 0; row < DCTSIZE; row++) {
  158484. for (col = 0; col < DCTSIZE; col++) {
  158485. fdtbl[i] = (FAST_FLOAT)
  158486. (1.0 / (((double) qtbl->quantval[i] *
  158487. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  158488. i++;
  158489. }
  158490. }
  158491. }
  158492. break;
  158493. #endif
  158494. default:
  158495. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158496. break;
  158497. }
  158498. }
  158499. }
  158500. /*
  158501. * Perform forward DCT on one or more blocks of a component.
  158502. *
  158503. * The input samples are taken from the sample_data[] array starting at
  158504. * position start_row/start_col, and moving to the right for any additional
  158505. * blocks. The quantized coefficients are returned in coef_blocks[].
  158506. */
  158507. METHODDEF(void)
  158508. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158509. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158510. JDIMENSION start_row, JDIMENSION start_col,
  158511. JDIMENSION num_blocks)
  158512. /* This version is used for integer DCT implementations. */
  158513. {
  158514. /* This routine is heavily used, so it's worth coding it tightly. */
  158515. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158516. forward_DCT_method_ptr do_dct = fdct->do_dct;
  158517. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  158518. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158519. JDIMENSION bi;
  158520. sample_data += start_row; /* fold in the vertical offset once */
  158521. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158522. /* Load data into workspace, applying unsigned->signed conversion */
  158523. { register DCTELEM *workspaceptr;
  158524. register JSAMPROW elemptr;
  158525. register int elemr;
  158526. workspaceptr = workspace;
  158527. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158528. elemptr = sample_data[elemr] + start_col;
  158529. #if DCTSIZE == 8 /* unroll the inner loop */
  158530. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158531. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158532. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158533. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158534. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158535. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158536. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158537. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158538. #else
  158539. { register int elemc;
  158540. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158541. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  158542. }
  158543. }
  158544. #endif
  158545. }
  158546. }
  158547. /* Perform the DCT */
  158548. (*do_dct) (workspace);
  158549. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158550. { register DCTELEM temp, qval;
  158551. register int i;
  158552. register JCOEFPTR output_ptr = coef_blocks[bi];
  158553. for (i = 0; i < DCTSIZE2; i++) {
  158554. qval = divisors[i];
  158555. temp = workspace[i];
  158556. /* Divide the coefficient value by qval, ensuring proper rounding.
  158557. * Since C does not specify the direction of rounding for negative
  158558. * quotients, we have to force the dividend positive for portability.
  158559. *
  158560. * In most files, at least half of the output values will be zero
  158561. * (at default quantization settings, more like three-quarters...)
  158562. * so we should ensure that this case is fast. On many machines,
  158563. * a comparison is enough cheaper than a divide to make a special test
  158564. * a win. Since both inputs will be nonnegative, we need only test
  158565. * for a < b to discover whether a/b is 0.
  158566. * If your machine's division is fast enough, define FAST_DIVIDE.
  158567. */
  158568. #ifdef FAST_DIVIDE
  158569. #define DIVIDE_BY(a,b) a /= b
  158570. #else
  158571. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  158572. #endif
  158573. if (temp < 0) {
  158574. temp = -temp;
  158575. temp += qval>>1; /* for rounding */
  158576. DIVIDE_BY(temp, qval);
  158577. temp = -temp;
  158578. } else {
  158579. temp += qval>>1; /* for rounding */
  158580. DIVIDE_BY(temp, qval);
  158581. }
  158582. output_ptr[i] = (JCOEF) temp;
  158583. }
  158584. }
  158585. }
  158586. }
  158587. #ifdef DCT_FLOAT_SUPPORTED
  158588. METHODDEF(void)
  158589. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  158590. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  158591. JDIMENSION start_row, JDIMENSION start_col,
  158592. JDIMENSION num_blocks)
  158593. /* This version is used for floating-point DCT implementations. */
  158594. {
  158595. /* This routine is heavily used, so it's worth coding it tightly. */
  158596. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  158597. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  158598. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  158599. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  158600. JDIMENSION bi;
  158601. sample_data += start_row; /* fold in the vertical offset once */
  158602. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  158603. /* Load data into workspace, applying unsigned->signed conversion */
  158604. { register FAST_FLOAT *workspaceptr;
  158605. register JSAMPROW elemptr;
  158606. register int elemr;
  158607. workspaceptr = workspace;
  158608. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  158609. elemptr = sample_data[elemr] + start_col;
  158610. #if DCTSIZE == 8 /* unroll the inner loop */
  158611. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158612. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158613. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158614. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158615. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158616. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158617. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158618. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158619. #else
  158620. { register int elemc;
  158621. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  158622. *workspaceptr++ = (FAST_FLOAT)
  158623. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  158624. }
  158625. }
  158626. #endif
  158627. }
  158628. }
  158629. /* Perform the DCT */
  158630. (*do_dct) (workspace);
  158631. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  158632. { register FAST_FLOAT temp;
  158633. register int i;
  158634. register JCOEFPTR output_ptr = coef_blocks[bi];
  158635. for (i = 0; i < DCTSIZE2; i++) {
  158636. /* Apply the quantization and scaling factor */
  158637. temp = workspace[i] * divisors[i];
  158638. /* Round to nearest integer.
  158639. * Since C does not specify the direction of rounding for negative
  158640. * quotients, we have to force the dividend positive for portability.
  158641. * The maximum coefficient size is +-16K (for 12-bit data), so this
  158642. * code should work for either 16-bit or 32-bit ints.
  158643. */
  158644. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  158645. }
  158646. }
  158647. }
  158648. }
  158649. #endif /* DCT_FLOAT_SUPPORTED */
  158650. /*
  158651. * Initialize FDCT manager.
  158652. */
  158653. GLOBAL(void)
  158654. jinit_forward_dct (j_compress_ptr cinfo)
  158655. {
  158656. my_fdct_ptr fdct;
  158657. int i;
  158658. fdct = (my_fdct_ptr)
  158659. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158660. SIZEOF(my_fdct_controller));
  158661. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  158662. fdct->pub.start_pass = start_pass_fdctmgr;
  158663. switch (cinfo->dct_method) {
  158664. #ifdef DCT_ISLOW_SUPPORTED
  158665. case JDCT_ISLOW:
  158666. fdct->pub.forward_DCT = forward_DCT;
  158667. fdct->do_dct = jpeg_fdct_islow;
  158668. break;
  158669. #endif
  158670. #ifdef DCT_IFAST_SUPPORTED
  158671. case JDCT_IFAST:
  158672. fdct->pub.forward_DCT = forward_DCT;
  158673. fdct->do_dct = jpeg_fdct_ifast;
  158674. break;
  158675. #endif
  158676. #ifdef DCT_FLOAT_SUPPORTED
  158677. case JDCT_FLOAT:
  158678. fdct->pub.forward_DCT = forward_DCT_float;
  158679. fdct->do_float_dct = jpeg_fdct_float;
  158680. break;
  158681. #endif
  158682. default:
  158683. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158684. break;
  158685. }
  158686. /* Mark divisor tables unallocated */
  158687. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  158688. fdct->divisors[i] = NULL;
  158689. #ifdef DCT_FLOAT_SUPPORTED
  158690. fdct->float_divisors[i] = NULL;
  158691. #endif
  158692. }
  158693. }
  158694. /********* End of inlined file: jcdctmgr.c *********/
  158695. #undef CONST_BITS
  158696. /********* Start of inlined file: jchuff.c *********/
  158697. #define JPEG_INTERNALS
  158698. /********* Start of inlined file: jchuff.h *********/
  158699. /* The legal range of a DCT coefficient is
  158700. * -1024 .. +1023 for 8-bit data;
  158701. * -16384 .. +16383 for 12-bit data.
  158702. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  158703. */
  158704. #ifndef _jchuff_h_
  158705. #define _jchuff_h_
  158706. #if BITS_IN_JSAMPLE == 8
  158707. #define MAX_COEF_BITS 10
  158708. #else
  158709. #define MAX_COEF_BITS 14
  158710. #endif
  158711. /* Derived data constructed for each Huffman table */
  158712. typedef struct {
  158713. unsigned int ehufco[256]; /* code for each symbol */
  158714. char ehufsi[256]; /* length of code for each symbol */
  158715. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  158716. } c_derived_tbl;
  158717. /* Short forms of external names for systems with brain-damaged linkers. */
  158718. #ifdef NEED_SHORT_EXTERNAL_NAMES
  158719. #define jpeg_make_c_derived_tbl jMkCDerived
  158720. #define jpeg_gen_optimal_table jGenOptTbl
  158721. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  158722. /* Expand a Huffman table definition into the derived format */
  158723. EXTERN(void) jpeg_make_c_derived_tbl
  158724. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  158725. c_derived_tbl ** pdtbl));
  158726. /* Generate an optimal table definition given the specified counts */
  158727. EXTERN(void) jpeg_gen_optimal_table
  158728. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  158729. #endif
  158730. /********* End of inlined file: jchuff.h *********/
  158731. /* Declarations shared with jcphuff.c */
  158732. /* Expanded entropy encoder object for Huffman encoding.
  158733. *
  158734. * The savable_state subrecord contains fields that change within an MCU,
  158735. * but must not be updated permanently until we complete the MCU.
  158736. */
  158737. typedef struct {
  158738. INT32 put_buffer; /* current bit-accumulation buffer */
  158739. int put_bits; /* # of bits now in it */
  158740. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  158741. } savable_state;
  158742. /* This macro is to work around compilers with missing or broken
  158743. * structure assignment. You'll need to fix this code if you have
  158744. * such a compiler and you change MAX_COMPS_IN_SCAN.
  158745. */
  158746. #ifndef NO_STRUCT_ASSIGN
  158747. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  158748. #else
  158749. #if MAX_COMPS_IN_SCAN == 4
  158750. #define ASSIGN_STATE(dest,src) \
  158751. ((dest).put_buffer = (src).put_buffer, \
  158752. (dest).put_bits = (src).put_bits, \
  158753. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  158754. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  158755. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  158756. (dest).last_dc_val[3] = (src).last_dc_val[3])
  158757. #endif
  158758. #endif
  158759. typedef struct {
  158760. struct jpeg_entropy_encoder pub; /* public fields */
  158761. savable_state saved; /* Bit buffer & DC state at start of MCU */
  158762. /* These fields are NOT loaded into local working state. */
  158763. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  158764. int next_restart_num; /* next restart number to write (0-7) */
  158765. /* Pointers to derived tables (these workspaces have image lifespan) */
  158766. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  158767. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  158768. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  158769. long * dc_count_ptrs[NUM_HUFF_TBLS];
  158770. long * ac_count_ptrs[NUM_HUFF_TBLS];
  158771. #endif
  158772. } huff_entropy_encoder;
  158773. typedef huff_entropy_encoder * huff_entropy_ptr;
  158774. /* Working state while writing an MCU.
  158775. * This struct contains all the fields that are needed by subroutines.
  158776. */
  158777. typedef struct {
  158778. JOCTET * next_output_byte; /* => next byte to write in buffer */
  158779. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  158780. savable_state cur; /* Current bit buffer & DC state */
  158781. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  158782. } working_state;
  158783. /* Forward declarations */
  158784. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  158785. JBLOCKROW *MCU_data));
  158786. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  158787. #ifdef ENTROPY_OPT_SUPPORTED
  158788. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  158789. JBLOCKROW *MCU_data));
  158790. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  158791. #endif
  158792. /*
  158793. * Initialize for a Huffman-compressed scan.
  158794. * If gather_statistics is TRUE, we do not output anything during the scan,
  158795. * just count the Huffman symbols used and generate Huffman code tables.
  158796. */
  158797. METHODDEF(void)
  158798. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  158799. {
  158800. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  158801. int ci, dctbl, actbl;
  158802. jpeg_component_info * compptr;
  158803. if (gather_statistics) {
  158804. #ifdef ENTROPY_OPT_SUPPORTED
  158805. entropy->pub.encode_mcu = encode_mcu_gather;
  158806. entropy->pub.finish_pass = finish_pass_gather;
  158807. #else
  158808. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158809. #endif
  158810. } else {
  158811. entropy->pub.encode_mcu = encode_mcu_huff;
  158812. entropy->pub.finish_pass = finish_pass_huff;
  158813. }
  158814. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158815. compptr = cinfo->cur_comp_info[ci];
  158816. dctbl = compptr->dc_tbl_no;
  158817. actbl = compptr->ac_tbl_no;
  158818. if (gather_statistics) {
  158819. #ifdef ENTROPY_OPT_SUPPORTED
  158820. /* Check for invalid table indexes */
  158821. /* (make_c_derived_tbl does this in the other path) */
  158822. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  158823. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  158824. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  158825. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  158826. /* Allocate and zero the statistics tables */
  158827. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  158828. if (entropy->dc_count_ptrs[dctbl] == NULL)
  158829. entropy->dc_count_ptrs[dctbl] = (long *)
  158830. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158831. 257 * SIZEOF(long));
  158832. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  158833. if (entropy->ac_count_ptrs[actbl] == NULL)
  158834. entropy->ac_count_ptrs[actbl] = (long *)
  158835. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158836. 257 * SIZEOF(long));
  158837. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  158838. #endif
  158839. } else {
  158840. /* Compute derived values for Huffman tables */
  158841. /* We may do this more than once for a table, but it's not expensive */
  158842. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  158843. & entropy->dc_derived_tbls[dctbl]);
  158844. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  158845. & entropy->ac_derived_tbls[actbl]);
  158846. }
  158847. /* Initialize DC predictions to 0 */
  158848. entropy->saved.last_dc_val[ci] = 0;
  158849. }
  158850. /* Initialize bit buffer to empty */
  158851. entropy->saved.put_buffer = 0;
  158852. entropy->saved.put_bits = 0;
  158853. /* Initialize restart stuff */
  158854. entropy->restarts_to_go = cinfo->restart_interval;
  158855. entropy->next_restart_num = 0;
  158856. }
  158857. /*
  158858. * Compute the derived values for a Huffman table.
  158859. * This routine also performs some validation checks on the table.
  158860. *
  158861. * Note this is also used by jcphuff.c.
  158862. */
  158863. GLOBAL(void)
  158864. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  158865. c_derived_tbl ** pdtbl)
  158866. {
  158867. JHUFF_TBL *htbl;
  158868. c_derived_tbl *dtbl;
  158869. int p, i, l, lastp, si, maxsymbol;
  158870. char huffsize[257];
  158871. unsigned int huffcode[257];
  158872. unsigned int code;
  158873. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  158874. * paralleling the order of the symbols themselves in htbl->huffval[].
  158875. */
  158876. /* Find the input Huffman table */
  158877. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  158878. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158879. htbl =
  158880. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  158881. if (htbl == NULL)
  158882. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  158883. /* Allocate a workspace if we haven't already done so. */
  158884. if (*pdtbl == NULL)
  158885. *pdtbl = (c_derived_tbl *)
  158886. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158887. SIZEOF(c_derived_tbl));
  158888. dtbl = *pdtbl;
  158889. /* Figure C.1: make table of Huffman code length for each symbol */
  158890. p = 0;
  158891. for (l = 1; l <= 16; l++) {
  158892. i = (int) htbl->bits[l];
  158893. if (i < 0 || p + i > 256) /* protect against table overrun */
  158894. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158895. while (i--)
  158896. huffsize[p++] = (char) l;
  158897. }
  158898. huffsize[p] = 0;
  158899. lastp = p;
  158900. /* Figure C.2: generate the codes themselves */
  158901. /* We also validate that the counts represent a legal Huffman code tree. */
  158902. code = 0;
  158903. si = huffsize[0];
  158904. p = 0;
  158905. while (huffsize[p]) {
  158906. while (((int) huffsize[p]) == si) {
  158907. huffcode[p++] = code;
  158908. code++;
  158909. }
  158910. /* code is now 1 more than the last code used for codelength si; but
  158911. * it must still fit in si bits, since no code is allowed to be all ones.
  158912. */
  158913. if (((INT32) code) >= (((INT32) 1) << si))
  158914. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158915. code <<= 1;
  158916. si++;
  158917. }
  158918. /* Figure C.3: generate encoding tables */
  158919. /* These are code and size indexed by symbol value */
  158920. /* Set all codeless symbols to have code length 0;
  158921. * this lets us detect duplicate VAL entries here, and later
  158922. * allows emit_bits to detect any attempt to emit such symbols.
  158923. */
  158924. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  158925. /* This is also a convenient place to check for out-of-range
  158926. * and duplicated VAL entries. We allow 0..255 for AC symbols
  158927. * but only 0..15 for DC. (We could constrain them further
  158928. * based on data depth and mode, but this seems enough.)
  158929. */
  158930. maxsymbol = isDC ? 15 : 255;
  158931. for (p = 0; p < lastp; p++) {
  158932. i = htbl->huffval[p];
  158933. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  158934. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158935. dtbl->ehufco[i] = huffcode[p];
  158936. dtbl->ehufsi[i] = huffsize[p];
  158937. }
  158938. }
  158939. /* Outputting bytes to the file */
  158940. /* Emit a byte, taking 'action' if must suspend. */
  158941. #define emit_byte(state,val,action) \
  158942. { *(state)->next_output_byte++ = (JOCTET) (val); \
  158943. if (--(state)->free_in_buffer == 0) \
  158944. if (! dump_buffer(state)) \
  158945. { action; } }
  158946. LOCAL(boolean)
  158947. dump_buffer (working_state * state)
  158948. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  158949. {
  158950. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  158951. if (! (*dest->empty_output_buffer) (state->cinfo))
  158952. return FALSE;
  158953. /* After a successful buffer dump, must reset buffer pointers */
  158954. state->next_output_byte = dest->next_output_byte;
  158955. state->free_in_buffer = dest->free_in_buffer;
  158956. return TRUE;
  158957. }
  158958. /* Outputting bits to the file */
  158959. /* Only the right 24 bits of put_buffer are used; the valid bits are
  158960. * left-justified in this part. At most 16 bits can be passed to emit_bits
  158961. * in one call, and we never retain more than 7 bits in put_buffer
  158962. * between calls, so 24 bits are sufficient.
  158963. */
  158964. INLINE
  158965. LOCAL(boolean)
  158966. emit_bits (working_state * state, unsigned int code, int size)
  158967. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  158968. {
  158969. /* This routine is heavily used, so it's worth coding tightly. */
  158970. register INT32 put_buffer = (INT32) code;
  158971. register int put_bits = state->cur.put_bits;
  158972. /* if size is 0, caller used an invalid Huffman table entry */
  158973. if (size == 0)
  158974. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  158975. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  158976. put_bits += size; /* new number of bits in buffer */
  158977. put_buffer <<= 24 - put_bits; /* align incoming bits */
  158978. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  158979. while (put_bits >= 8) {
  158980. int c = (int) ((put_buffer >> 16) & 0xFF);
  158981. emit_byte(state, c, return FALSE);
  158982. if (c == 0xFF) { /* need to stuff a zero byte? */
  158983. emit_byte(state, 0, return FALSE);
  158984. }
  158985. put_buffer <<= 8;
  158986. put_bits -= 8;
  158987. }
  158988. state->cur.put_buffer = put_buffer; /* update state variables */
  158989. state->cur.put_bits = put_bits;
  158990. return TRUE;
  158991. }
  158992. LOCAL(boolean)
  158993. flush_bits (working_state * state)
  158994. {
  158995. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  158996. return FALSE;
  158997. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  158998. state->cur.put_bits = 0;
  158999. return TRUE;
  159000. }
  159001. /* Encode a single block's worth of coefficients */
  159002. LOCAL(boolean)
  159003. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  159004. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  159005. {
  159006. register int temp, temp2;
  159007. register int nbits;
  159008. register int k, r, i;
  159009. /* Encode the DC coefficient difference per section F.1.2.1 */
  159010. temp = temp2 = block[0] - last_dc_val;
  159011. if (temp < 0) {
  159012. temp = -temp; /* temp is abs value of input */
  159013. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159014. /* This code assumes we are on a two's complement machine */
  159015. temp2--;
  159016. }
  159017. /* Find the number of bits needed for the magnitude of the coefficient */
  159018. nbits = 0;
  159019. while (temp) {
  159020. nbits++;
  159021. temp >>= 1;
  159022. }
  159023. /* Check for out-of-range coefficient values.
  159024. * Since we're encoding a difference, the range limit is twice as much.
  159025. */
  159026. if (nbits > MAX_COEF_BITS+1)
  159027. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159028. /* Emit the Huffman-coded symbol for the number of bits */
  159029. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  159030. return FALSE;
  159031. /* Emit that number of bits of the value, if positive, */
  159032. /* or the complement of its magnitude, if negative. */
  159033. if (nbits) /* emit_bits rejects calls with size 0 */
  159034. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159035. return FALSE;
  159036. /* Encode the AC coefficients per section F.1.2.2 */
  159037. r = 0; /* r = run length of zeros */
  159038. for (k = 1; k < DCTSIZE2; k++) {
  159039. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159040. r++;
  159041. } else {
  159042. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159043. while (r > 15) {
  159044. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  159045. return FALSE;
  159046. r -= 16;
  159047. }
  159048. temp2 = temp;
  159049. if (temp < 0) {
  159050. temp = -temp; /* temp is abs value of input */
  159051. /* This code assumes we are on a two's complement machine */
  159052. temp2--;
  159053. }
  159054. /* Find the number of bits needed for the magnitude of the coefficient */
  159055. nbits = 1; /* there must be at least one 1 bit */
  159056. while ((temp >>= 1))
  159057. nbits++;
  159058. /* Check for out-of-range coefficient values */
  159059. if (nbits > MAX_COEF_BITS)
  159060. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  159061. /* Emit Huffman symbol for run length / number of bits */
  159062. i = (r << 4) + nbits;
  159063. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  159064. return FALSE;
  159065. /* Emit that number of bits of the value, if positive, */
  159066. /* or the complement of its magnitude, if negative. */
  159067. if (! emit_bits(state, (unsigned int) temp2, nbits))
  159068. return FALSE;
  159069. r = 0;
  159070. }
  159071. }
  159072. /* If the last coef(s) were zero, emit an end-of-block code */
  159073. if (r > 0)
  159074. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  159075. return FALSE;
  159076. return TRUE;
  159077. }
  159078. /*
  159079. * Emit a restart marker & resynchronize predictions.
  159080. */
  159081. LOCAL(boolean)
  159082. emit_restart (working_state * state, int restart_num)
  159083. {
  159084. int ci;
  159085. if (! flush_bits(state))
  159086. return FALSE;
  159087. emit_byte(state, 0xFF, return FALSE);
  159088. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  159089. /* Re-initialize DC predictions to 0 */
  159090. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  159091. state->cur.last_dc_val[ci] = 0;
  159092. /* The restart counter is not updated until we successfully write the MCU. */
  159093. return TRUE;
  159094. }
  159095. /*
  159096. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  159097. */
  159098. METHODDEF(boolean)
  159099. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159100. {
  159101. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159102. working_state state;
  159103. int blkn, ci;
  159104. jpeg_component_info * compptr;
  159105. /* Load up working state */
  159106. state.next_output_byte = cinfo->dest->next_output_byte;
  159107. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159108. ASSIGN_STATE(state.cur, entropy->saved);
  159109. state.cinfo = cinfo;
  159110. /* Emit restart marker if needed */
  159111. if (cinfo->restart_interval) {
  159112. if (entropy->restarts_to_go == 0)
  159113. if (! emit_restart(&state, entropy->next_restart_num))
  159114. return FALSE;
  159115. }
  159116. /* Encode the MCU data blocks */
  159117. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159118. ci = cinfo->MCU_membership[blkn];
  159119. compptr = cinfo->cur_comp_info[ci];
  159120. if (! encode_one_block(&state,
  159121. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  159122. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  159123. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  159124. return FALSE;
  159125. /* Update last_dc_val */
  159126. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  159127. }
  159128. /* Completed MCU, so update state */
  159129. cinfo->dest->next_output_byte = state.next_output_byte;
  159130. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159131. ASSIGN_STATE(entropy->saved, state.cur);
  159132. /* Update restart-interval state too */
  159133. if (cinfo->restart_interval) {
  159134. if (entropy->restarts_to_go == 0) {
  159135. entropy->restarts_to_go = cinfo->restart_interval;
  159136. entropy->next_restart_num++;
  159137. entropy->next_restart_num &= 7;
  159138. }
  159139. entropy->restarts_to_go--;
  159140. }
  159141. return TRUE;
  159142. }
  159143. /*
  159144. * Finish up at the end of a Huffman-compressed scan.
  159145. */
  159146. METHODDEF(void)
  159147. finish_pass_huff (j_compress_ptr cinfo)
  159148. {
  159149. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159150. working_state state;
  159151. /* Load up working state ... flush_bits needs it */
  159152. state.next_output_byte = cinfo->dest->next_output_byte;
  159153. state.free_in_buffer = cinfo->dest->free_in_buffer;
  159154. ASSIGN_STATE(state.cur, entropy->saved);
  159155. state.cinfo = cinfo;
  159156. /* Flush out the last data */
  159157. if (! flush_bits(&state))
  159158. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159159. /* Update state */
  159160. cinfo->dest->next_output_byte = state.next_output_byte;
  159161. cinfo->dest->free_in_buffer = state.free_in_buffer;
  159162. ASSIGN_STATE(entropy->saved, state.cur);
  159163. }
  159164. /*
  159165. * Huffman coding optimization.
  159166. *
  159167. * We first scan the supplied data and count the number of uses of each symbol
  159168. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  159169. * Then we build a Huffman coding tree for the observed counts.
  159170. * Symbols which are not needed at all for the particular image are not
  159171. * assigned any code, which saves space in the DHT marker as well as in
  159172. * the compressed data.
  159173. */
  159174. #ifdef ENTROPY_OPT_SUPPORTED
  159175. /* Process a single block's worth of coefficients */
  159176. LOCAL(void)
  159177. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  159178. long dc_counts[], long ac_counts[])
  159179. {
  159180. register int temp;
  159181. register int nbits;
  159182. register int k, r;
  159183. /* Encode the DC coefficient difference per section F.1.2.1 */
  159184. temp = block[0] - last_dc_val;
  159185. if (temp < 0)
  159186. temp = -temp;
  159187. /* Find the number of bits needed for the magnitude of the coefficient */
  159188. nbits = 0;
  159189. while (temp) {
  159190. nbits++;
  159191. temp >>= 1;
  159192. }
  159193. /* Check for out-of-range coefficient values.
  159194. * Since we're encoding a difference, the range limit is twice as much.
  159195. */
  159196. if (nbits > MAX_COEF_BITS+1)
  159197. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159198. /* Count the Huffman symbol for the number of bits */
  159199. dc_counts[nbits]++;
  159200. /* Encode the AC coefficients per section F.1.2.2 */
  159201. r = 0; /* r = run length of zeros */
  159202. for (k = 1; k < DCTSIZE2; k++) {
  159203. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  159204. r++;
  159205. } else {
  159206. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159207. while (r > 15) {
  159208. ac_counts[0xF0]++;
  159209. r -= 16;
  159210. }
  159211. /* Find the number of bits needed for the magnitude of the coefficient */
  159212. if (temp < 0)
  159213. temp = -temp;
  159214. /* Find the number of bits needed for the magnitude of the coefficient */
  159215. nbits = 1; /* there must be at least one 1 bit */
  159216. while ((temp >>= 1))
  159217. nbits++;
  159218. /* Check for out-of-range coefficient values */
  159219. if (nbits > MAX_COEF_BITS)
  159220. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159221. /* Count Huffman symbol for run length / number of bits */
  159222. ac_counts[(r << 4) + nbits]++;
  159223. r = 0;
  159224. }
  159225. }
  159226. /* If the last coef(s) were zero, emit an end-of-block code */
  159227. if (r > 0)
  159228. ac_counts[0]++;
  159229. }
  159230. /*
  159231. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  159232. * No data is actually output, so no suspension return is possible.
  159233. */
  159234. METHODDEF(boolean)
  159235. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159236. {
  159237. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159238. int blkn, ci;
  159239. jpeg_component_info * compptr;
  159240. /* Take care of restart intervals if needed */
  159241. if (cinfo->restart_interval) {
  159242. if (entropy->restarts_to_go == 0) {
  159243. /* Re-initialize DC predictions to 0 */
  159244. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  159245. entropy->saved.last_dc_val[ci] = 0;
  159246. /* Update restart state */
  159247. entropy->restarts_to_go = cinfo->restart_interval;
  159248. }
  159249. entropy->restarts_to_go--;
  159250. }
  159251. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159252. ci = cinfo->MCU_membership[blkn];
  159253. compptr = cinfo->cur_comp_info[ci];
  159254. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  159255. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  159256. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  159257. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  159258. }
  159259. return TRUE;
  159260. }
  159261. /*
  159262. * Generate the best Huffman code table for the given counts, fill htbl.
  159263. * Note this is also used by jcphuff.c.
  159264. *
  159265. * The JPEG standard requires that no symbol be assigned a codeword of all
  159266. * one bits (so that padding bits added at the end of a compressed segment
  159267. * can't look like a valid code). Because of the canonical ordering of
  159268. * codewords, this just means that there must be an unused slot in the
  159269. * longest codeword length category. Section K.2 of the JPEG spec suggests
  159270. * reserving such a slot by pretending that symbol 256 is a valid symbol
  159271. * with count 1. In theory that's not optimal; giving it count zero but
  159272. * including it in the symbol set anyway should give a better Huffman code.
  159273. * But the theoretically better code actually seems to come out worse in
  159274. * practice, because it produces more all-ones bytes (which incur stuffed
  159275. * zero bytes in the final file). In any case the difference is tiny.
  159276. *
  159277. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  159278. * If some symbols have a very small but nonzero probability, the Huffman tree
  159279. * must be adjusted to meet the code length restriction. We currently use
  159280. * the adjustment method suggested in JPEG section K.2. This method is *not*
  159281. * optimal; it may not choose the best possible limited-length code. But
  159282. * typically only very-low-frequency symbols will be given less-than-optimal
  159283. * lengths, so the code is almost optimal. Experimental comparisons against
  159284. * an optimal limited-length-code algorithm indicate that the difference is
  159285. * microscopic --- usually less than a hundredth of a percent of total size.
  159286. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  159287. */
  159288. GLOBAL(void)
  159289. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  159290. {
  159291. #define MAX_CLEN 32 /* assumed maximum initial code length */
  159292. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  159293. int codesize[257]; /* codesize[k] = code length of symbol k */
  159294. int others[257]; /* next symbol in current branch of tree */
  159295. int c1, c2;
  159296. int p, i, j;
  159297. long v;
  159298. /* This algorithm is explained in section K.2 of the JPEG standard */
  159299. MEMZERO(bits, SIZEOF(bits));
  159300. MEMZERO(codesize, SIZEOF(codesize));
  159301. for (i = 0; i < 257; i++)
  159302. others[i] = -1; /* init links to empty */
  159303. freq[256] = 1; /* make sure 256 has a nonzero count */
  159304. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  159305. * that no real symbol is given code-value of all ones, because 256
  159306. * will be placed last in the largest codeword category.
  159307. */
  159308. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  159309. for (;;) {
  159310. /* Find the smallest nonzero frequency, set c1 = its symbol */
  159311. /* In case of ties, take the larger symbol number */
  159312. c1 = -1;
  159313. v = 1000000000L;
  159314. for (i = 0; i <= 256; i++) {
  159315. if (freq[i] && freq[i] <= v) {
  159316. v = freq[i];
  159317. c1 = i;
  159318. }
  159319. }
  159320. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  159321. /* In case of ties, take the larger symbol number */
  159322. c2 = -1;
  159323. v = 1000000000L;
  159324. for (i = 0; i <= 256; i++) {
  159325. if (freq[i] && freq[i] <= v && i != c1) {
  159326. v = freq[i];
  159327. c2 = i;
  159328. }
  159329. }
  159330. /* Done if we've merged everything into one frequency */
  159331. if (c2 < 0)
  159332. break;
  159333. /* Else merge the two counts/trees */
  159334. freq[c1] += freq[c2];
  159335. freq[c2] = 0;
  159336. /* Increment the codesize of everything in c1's tree branch */
  159337. codesize[c1]++;
  159338. while (others[c1] >= 0) {
  159339. c1 = others[c1];
  159340. codesize[c1]++;
  159341. }
  159342. others[c1] = c2; /* chain c2 onto c1's tree branch */
  159343. /* Increment the codesize of everything in c2's tree branch */
  159344. codesize[c2]++;
  159345. while (others[c2] >= 0) {
  159346. c2 = others[c2];
  159347. codesize[c2]++;
  159348. }
  159349. }
  159350. /* Now count the number of symbols of each code length */
  159351. for (i = 0; i <= 256; i++) {
  159352. if (codesize[i]) {
  159353. /* The JPEG standard seems to think that this can't happen, */
  159354. /* but I'm paranoid... */
  159355. if (codesize[i] > MAX_CLEN)
  159356. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  159357. bits[codesize[i]]++;
  159358. }
  159359. }
  159360. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  159361. * Huffman procedure assigned any such lengths, we must adjust the coding.
  159362. * Here is what the JPEG spec says about how this next bit works:
  159363. * Since symbols are paired for the longest Huffman code, the symbols are
  159364. * removed from this length category two at a time. The prefix for the pair
  159365. * (which is one bit shorter) is allocated to one of the pair; then,
  159366. * skipping the BITS entry for that prefix length, a code word from the next
  159367. * shortest nonzero BITS entry is converted into a prefix for two code words
  159368. * one bit longer.
  159369. */
  159370. for (i = MAX_CLEN; i > 16; i--) {
  159371. while (bits[i] > 0) {
  159372. j = i - 2; /* find length of new prefix to be used */
  159373. while (bits[j] == 0)
  159374. j--;
  159375. bits[i] -= 2; /* remove two symbols */
  159376. bits[i-1]++; /* one goes in this length */
  159377. bits[j+1] += 2; /* two new symbols in this length */
  159378. bits[j]--; /* symbol of this length is now a prefix */
  159379. }
  159380. }
  159381. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  159382. while (bits[i] == 0) /* find largest codelength still in use */
  159383. i--;
  159384. bits[i]--;
  159385. /* Return final symbol counts (only for lengths 0..16) */
  159386. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  159387. /* Return a list of the symbols sorted by code length */
  159388. /* It's not real clear to me why we don't need to consider the codelength
  159389. * changes made above, but the JPEG spec seems to think this works.
  159390. */
  159391. p = 0;
  159392. for (i = 1; i <= MAX_CLEN; i++) {
  159393. for (j = 0; j <= 255; j++) {
  159394. if (codesize[j] == i) {
  159395. htbl->huffval[p] = (UINT8) j;
  159396. p++;
  159397. }
  159398. }
  159399. }
  159400. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  159401. htbl->sent_table = FALSE;
  159402. }
  159403. /*
  159404. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159405. */
  159406. METHODDEF(void)
  159407. finish_pass_gather (j_compress_ptr cinfo)
  159408. {
  159409. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  159410. int ci, dctbl, actbl;
  159411. jpeg_component_info * compptr;
  159412. JHUFF_TBL **htblptr;
  159413. boolean did_dc[NUM_HUFF_TBLS];
  159414. boolean did_ac[NUM_HUFF_TBLS];
  159415. /* It's important not to apply jpeg_gen_optimal_table more than once
  159416. * per table, because it clobbers the input frequency counts!
  159417. */
  159418. MEMZERO(did_dc, SIZEOF(did_dc));
  159419. MEMZERO(did_ac, SIZEOF(did_ac));
  159420. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159421. compptr = cinfo->cur_comp_info[ci];
  159422. dctbl = compptr->dc_tbl_no;
  159423. actbl = compptr->ac_tbl_no;
  159424. if (! did_dc[dctbl]) {
  159425. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  159426. if (*htblptr == NULL)
  159427. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159428. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  159429. did_dc[dctbl] = TRUE;
  159430. }
  159431. if (! did_ac[actbl]) {
  159432. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  159433. if (*htblptr == NULL)
  159434. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159435. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  159436. did_ac[actbl] = TRUE;
  159437. }
  159438. }
  159439. }
  159440. #endif /* ENTROPY_OPT_SUPPORTED */
  159441. /*
  159442. * Module initialization routine for Huffman entropy encoding.
  159443. */
  159444. GLOBAL(void)
  159445. jinit_huff_encoder (j_compress_ptr cinfo)
  159446. {
  159447. huff_entropy_ptr entropy;
  159448. int i;
  159449. entropy = (huff_entropy_ptr)
  159450. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159451. SIZEOF(huff_entropy_encoder));
  159452. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159453. entropy->pub.start_pass = start_pass_huff;
  159454. /* Mark tables unallocated */
  159455. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159456. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  159457. #ifdef ENTROPY_OPT_SUPPORTED
  159458. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  159459. #endif
  159460. }
  159461. }
  159462. /********* End of inlined file: jchuff.c *********/
  159463. #undef emit_byte
  159464. /********* Start of inlined file: jcinit.c *********/
  159465. #define JPEG_INTERNALS
  159466. /*
  159467. * Master selection of compression modules.
  159468. * This is done once at the start of processing an image. We determine
  159469. * which modules will be used and give them appropriate initialization calls.
  159470. */
  159471. GLOBAL(void)
  159472. jinit_compress_master (j_compress_ptr cinfo)
  159473. {
  159474. /* Initialize master control (includes parameter checking/processing) */
  159475. jinit_c_master_control(cinfo, FALSE /* full compression */);
  159476. /* Preprocessing */
  159477. if (! cinfo->raw_data_in) {
  159478. jinit_color_converter(cinfo);
  159479. jinit_downsampler(cinfo);
  159480. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  159481. }
  159482. /* Forward DCT */
  159483. jinit_forward_dct(cinfo);
  159484. /* Entropy encoding: either Huffman or arithmetic coding. */
  159485. if (cinfo->arith_code) {
  159486. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  159487. } else {
  159488. if (cinfo->progressive_mode) {
  159489. #ifdef C_PROGRESSIVE_SUPPORTED
  159490. jinit_phuff_encoder(cinfo);
  159491. #else
  159492. ERREXIT(cinfo, JERR_NOT_COMPILED);
  159493. #endif
  159494. } else
  159495. jinit_huff_encoder(cinfo);
  159496. }
  159497. /* Need a full-image coefficient buffer in any multi-pass mode. */
  159498. jinit_c_coef_controller(cinfo,
  159499. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  159500. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  159501. jinit_marker_writer(cinfo);
  159502. /* We can now tell the memory manager to allocate virtual arrays. */
  159503. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  159504. /* Write the datastream header (SOI) immediately.
  159505. * Frame and scan headers are postponed till later.
  159506. * This lets application insert special markers after the SOI.
  159507. */
  159508. (*cinfo->marker->write_file_header) (cinfo);
  159509. }
  159510. /********* End of inlined file: jcinit.c *********/
  159511. /********* Start of inlined file: jcmainct.c *********/
  159512. #define JPEG_INTERNALS
  159513. /* Note: currently, there is no operating mode in which a full-image buffer
  159514. * is needed at this step. If there were, that mode could not be used with
  159515. * "raw data" input, since this module is bypassed in that case. However,
  159516. * we've left the code here for possible use in special applications.
  159517. */
  159518. #undef FULL_MAIN_BUFFER_SUPPORTED
  159519. /* Private buffer controller object */
  159520. typedef struct {
  159521. struct jpeg_c_main_controller pub; /* public fields */
  159522. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  159523. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  159524. boolean suspended; /* remember if we suspended output */
  159525. J_BUF_MODE pass_mode; /* current operating mode */
  159526. /* If using just a strip buffer, this points to the entire set of buffers
  159527. * (we allocate one for each component). In the full-image case, this
  159528. * points to the currently accessible strips of the virtual arrays.
  159529. */
  159530. JSAMPARRAY buffer[MAX_COMPONENTS];
  159531. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159532. /* If using full-image storage, this array holds pointers to virtual-array
  159533. * control blocks for each component. Unused if not full-image storage.
  159534. */
  159535. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  159536. #endif
  159537. } my_main_controller;
  159538. typedef my_main_controller * my_main_ptr;
  159539. /* Forward declarations */
  159540. METHODDEF(void) process_data_simple_main
  159541. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159542. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159543. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159544. METHODDEF(void) process_data_buffer_main
  159545. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  159546. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  159547. #endif
  159548. /*
  159549. * Initialize for a processing pass.
  159550. */
  159551. METHODDEF(void)
  159552. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159553. {
  159554. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159555. /* Do nothing in raw-data mode. */
  159556. if (cinfo->raw_data_in)
  159557. return;
  159558. main_->cur_iMCU_row = 0; /* initialize counters */
  159559. main_->rowgroup_ctr = 0;
  159560. main_->suspended = FALSE;
  159561. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  159562. switch (pass_mode) {
  159563. case JBUF_PASS_THRU:
  159564. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159565. if (main_->whole_image[0] != NULL)
  159566. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159567. #endif
  159568. main_->pub.process_data = process_data_simple_main;
  159569. break;
  159570. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159571. case JBUF_SAVE_SOURCE:
  159572. case JBUF_CRANK_DEST:
  159573. case JBUF_SAVE_AND_PASS:
  159574. if (main_->whole_image[0] == NULL)
  159575. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159576. main_->pub.process_data = process_data_buffer_main;
  159577. break;
  159578. #endif
  159579. default:
  159580. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159581. break;
  159582. }
  159583. }
  159584. /*
  159585. * Process some data.
  159586. * This routine handles the simple pass-through mode,
  159587. * where we have only a strip buffer.
  159588. */
  159589. METHODDEF(void)
  159590. process_data_simple_main (j_compress_ptr cinfo,
  159591. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159592. JDIMENSION in_rows_avail)
  159593. {
  159594. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  159595. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159596. /* Read input data if we haven't filled the main buffer yet */
  159597. if (main_->rowgroup_ctr < DCTSIZE)
  159598. (*cinfo->prep->pre_process_data) (cinfo,
  159599. input_buf, in_row_ctr, in_rows_avail,
  159600. main_->buffer, &main_->rowgroup_ctr,
  159601. (JDIMENSION) DCTSIZE);
  159602. /* If we don't have a full iMCU row buffered, return to application for
  159603. * more data. Note that preprocessor will always pad to fill the iMCU row
  159604. * at the bottom of the image.
  159605. */
  159606. if (main_->rowgroup_ctr != DCTSIZE)
  159607. return;
  159608. /* Send the completed row to the compressor */
  159609. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  159610. /* If compressor did not consume the whole row, then we must need to
  159611. * suspend processing and return to the application. In this situation
  159612. * we pretend we didn't yet consume the last input row; otherwise, if
  159613. * it happened to be the last row of the image, the application would
  159614. * think we were done.
  159615. */
  159616. if (! main_->suspended) {
  159617. (*in_row_ctr)--;
  159618. main_->suspended = TRUE;
  159619. }
  159620. return;
  159621. }
  159622. /* We did finish the row. Undo our little suspension hack if a previous
  159623. * call suspended; then mark the main buffer empty.
  159624. */
  159625. if (main_->suspended) {
  159626. (*in_row_ctr)++;
  159627. main_->suspended = FALSE;
  159628. }
  159629. main_->rowgroup_ctr = 0;
  159630. main_->cur_iMCU_row++;
  159631. }
  159632. }
  159633. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159634. /*
  159635. * Process some data.
  159636. * This routine handles all of the modes that use a full-size buffer.
  159637. */
  159638. METHODDEF(void)
  159639. process_data_buffer_main (j_compress_ptr cinfo,
  159640. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159641. JDIMENSION in_rows_avail)
  159642. {
  159643. my_main_ptr main = (my_main_ptr) cinfo->main;
  159644. int ci;
  159645. jpeg_component_info *compptr;
  159646. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  159647. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  159648. /* Realign the virtual buffers if at the start of an iMCU row. */
  159649. if (main->rowgroup_ctr == 0) {
  159650. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159651. ci++, compptr++) {
  159652. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  159653. ((j_common_ptr) cinfo, main->whole_image[ci],
  159654. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  159655. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  159656. }
  159657. /* In a read pass, pretend we just read some source data. */
  159658. if (! writing) {
  159659. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  159660. main->rowgroup_ctr = DCTSIZE;
  159661. }
  159662. }
  159663. /* If a write pass, read input data until the current iMCU row is full. */
  159664. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  159665. if (writing) {
  159666. (*cinfo->prep->pre_process_data) (cinfo,
  159667. input_buf, in_row_ctr, in_rows_avail,
  159668. main->buffer, &main->rowgroup_ctr,
  159669. (JDIMENSION) DCTSIZE);
  159670. /* Return to application if we need more data to fill the iMCU row. */
  159671. if (main->rowgroup_ctr < DCTSIZE)
  159672. return;
  159673. }
  159674. /* Emit data, unless this is a sink-only pass. */
  159675. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  159676. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  159677. /* If compressor did not consume the whole row, then we must need to
  159678. * suspend processing and return to the application. In this situation
  159679. * we pretend we didn't yet consume the last input row; otherwise, if
  159680. * it happened to be the last row of the image, the application would
  159681. * think we were done.
  159682. */
  159683. if (! main->suspended) {
  159684. (*in_row_ctr)--;
  159685. main->suspended = TRUE;
  159686. }
  159687. return;
  159688. }
  159689. /* We did finish the row. Undo our little suspension hack if a previous
  159690. * call suspended; then mark the main buffer empty.
  159691. */
  159692. if (main->suspended) {
  159693. (*in_row_ctr)++;
  159694. main->suspended = FALSE;
  159695. }
  159696. }
  159697. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  159698. main->rowgroup_ctr = 0;
  159699. main->cur_iMCU_row++;
  159700. }
  159701. }
  159702. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  159703. /*
  159704. * Initialize main buffer controller.
  159705. */
  159706. GLOBAL(void)
  159707. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  159708. {
  159709. my_main_ptr main_;
  159710. int ci;
  159711. jpeg_component_info *compptr;
  159712. main_ = (my_main_ptr)
  159713. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159714. SIZEOF(my_main_controller));
  159715. cinfo->main = (struct jpeg_c_main_controller *) main_;
  159716. main_->pub.start_pass = start_pass_main;
  159717. /* We don't need to create a buffer in raw-data mode. */
  159718. if (cinfo->raw_data_in)
  159719. return;
  159720. /* Create the buffer. It holds downsampled data, so each component
  159721. * may be of a different size.
  159722. */
  159723. if (need_full_buffer) {
  159724. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159725. /* Allocate a full-image virtual array for each component */
  159726. /* Note we pad the bottom to a multiple of the iMCU height */
  159727. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159728. ci++, compptr++) {
  159729. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  159730. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  159731. compptr->width_in_blocks * DCTSIZE,
  159732. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  159733. (long) compptr->v_samp_factor) * DCTSIZE,
  159734. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159735. }
  159736. #else
  159737. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159738. #endif
  159739. } else {
  159740. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  159741. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  159742. #endif
  159743. /* Allocate a strip buffer for each component */
  159744. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159745. ci++, compptr++) {
  159746. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  159747. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159748. compptr->width_in_blocks * DCTSIZE,
  159749. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  159750. }
  159751. }
  159752. }
  159753. /********* End of inlined file: jcmainct.c *********/
  159754. /********* Start of inlined file: jcmarker.c *********/
  159755. #define JPEG_INTERNALS
  159756. /* Private state */
  159757. typedef struct {
  159758. struct jpeg_marker_writer pub; /* public fields */
  159759. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  159760. } my_marker_writer;
  159761. typedef my_marker_writer * my_marker_ptr;
  159762. /*
  159763. * Basic output routines.
  159764. *
  159765. * Note that we do not support suspension while writing a marker.
  159766. * Therefore, an application using suspension must ensure that there is
  159767. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  159768. * calling jpeg_start_compress, and enough space to write the trailing EOI
  159769. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  159770. * modes are not supported at all with suspension, so those two are the only
  159771. * points where markers will be written.
  159772. */
  159773. LOCAL(void)
  159774. emit_byte (j_compress_ptr cinfo, int val)
  159775. /* Emit a byte */
  159776. {
  159777. struct jpeg_destination_mgr * dest = cinfo->dest;
  159778. *(dest->next_output_byte)++ = (JOCTET) val;
  159779. if (--dest->free_in_buffer == 0) {
  159780. if (! (*dest->empty_output_buffer) (cinfo))
  159781. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  159782. }
  159783. }
  159784. LOCAL(void)
  159785. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  159786. /* Emit a marker code */
  159787. {
  159788. emit_byte(cinfo, 0xFF);
  159789. emit_byte(cinfo, (int) mark);
  159790. }
  159791. LOCAL(void)
  159792. emit_2bytes (j_compress_ptr cinfo, int value)
  159793. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  159794. {
  159795. emit_byte(cinfo, (value >> 8) & 0xFF);
  159796. emit_byte(cinfo, value & 0xFF);
  159797. }
  159798. /*
  159799. * Routines to write specific marker types.
  159800. */
  159801. LOCAL(int)
  159802. emit_dqt (j_compress_ptr cinfo, int index)
  159803. /* Emit a DQT marker */
  159804. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  159805. {
  159806. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  159807. int prec;
  159808. int i;
  159809. if (qtbl == NULL)
  159810. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  159811. prec = 0;
  159812. for (i = 0; i < DCTSIZE2; i++) {
  159813. if (qtbl->quantval[i] > 255)
  159814. prec = 1;
  159815. }
  159816. if (! qtbl->sent_table) {
  159817. emit_marker(cinfo, M_DQT);
  159818. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  159819. emit_byte(cinfo, index + (prec<<4));
  159820. for (i = 0; i < DCTSIZE2; i++) {
  159821. /* The table entries must be emitted in zigzag order. */
  159822. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  159823. if (prec)
  159824. emit_byte(cinfo, (int) (qval >> 8));
  159825. emit_byte(cinfo, (int) (qval & 0xFF));
  159826. }
  159827. qtbl->sent_table = TRUE;
  159828. }
  159829. return prec;
  159830. }
  159831. LOCAL(void)
  159832. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  159833. /* Emit a DHT marker */
  159834. {
  159835. JHUFF_TBL * htbl;
  159836. int length, i;
  159837. if (is_ac) {
  159838. htbl = cinfo->ac_huff_tbl_ptrs[index];
  159839. index += 0x10; /* output index has AC bit set */
  159840. } else {
  159841. htbl = cinfo->dc_huff_tbl_ptrs[index];
  159842. }
  159843. if (htbl == NULL)
  159844. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  159845. if (! htbl->sent_table) {
  159846. emit_marker(cinfo, M_DHT);
  159847. length = 0;
  159848. for (i = 1; i <= 16; i++)
  159849. length += htbl->bits[i];
  159850. emit_2bytes(cinfo, length + 2 + 1 + 16);
  159851. emit_byte(cinfo, index);
  159852. for (i = 1; i <= 16; i++)
  159853. emit_byte(cinfo, htbl->bits[i]);
  159854. for (i = 0; i < length; i++)
  159855. emit_byte(cinfo, htbl->huffval[i]);
  159856. htbl->sent_table = TRUE;
  159857. }
  159858. }
  159859. LOCAL(void)
  159860. emit_dac (j_compress_ptr cinfo)
  159861. /* Emit a DAC marker */
  159862. /* Since the useful info is so small, we want to emit all the tables in */
  159863. /* one DAC marker. Therefore this routine does its own scan of the table. */
  159864. {
  159865. #ifdef C_ARITH_CODING_SUPPORTED
  159866. char dc_in_use[NUM_ARITH_TBLS];
  159867. char ac_in_use[NUM_ARITH_TBLS];
  159868. int length, i;
  159869. jpeg_component_info *compptr;
  159870. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159871. dc_in_use[i] = ac_in_use[i] = 0;
  159872. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159873. compptr = cinfo->cur_comp_info[i];
  159874. dc_in_use[compptr->dc_tbl_no] = 1;
  159875. ac_in_use[compptr->ac_tbl_no] = 1;
  159876. }
  159877. length = 0;
  159878. for (i = 0; i < NUM_ARITH_TBLS; i++)
  159879. length += dc_in_use[i] + ac_in_use[i];
  159880. emit_marker(cinfo, M_DAC);
  159881. emit_2bytes(cinfo, length*2 + 2);
  159882. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  159883. if (dc_in_use[i]) {
  159884. emit_byte(cinfo, i);
  159885. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  159886. }
  159887. if (ac_in_use[i]) {
  159888. emit_byte(cinfo, i + 0x10);
  159889. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  159890. }
  159891. }
  159892. #endif /* C_ARITH_CODING_SUPPORTED */
  159893. }
  159894. LOCAL(void)
  159895. emit_dri (j_compress_ptr cinfo)
  159896. /* Emit a DRI marker */
  159897. {
  159898. emit_marker(cinfo, M_DRI);
  159899. emit_2bytes(cinfo, 4); /* fixed length */
  159900. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  159901. }
  159902. LOCAL(void)
  159903. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  159904. /* Emit a SOF marker */
  159905. {
  159906. int ci;
  159907. jpeg_component_info *compptr;
  159908. emit_marker(cinfo, code);
  159909. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  159910. /* Make sure image isn't bigger than SOF field can handle */
  159911. if ((long) cinfo->image_height > 65535L ||
  159912. (long) cinfo->image_width > 65535L)
  159913. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  159914. emit_byte(cinfo, cinfo->data_precision);
  159915. emit_2bytes(cinfo, (int) cinfo->image_height);
  159916. emit_2bytes(cinfo, (int) cinfo->image_width);
  159917. emit_byte(cinfo, cinfo->num_components);
  159918. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159919. ci++, compptr++) {
  159920. emit_byte(cinfo, compptr->component_id);
  159921. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  159922. emit_byte(cinfo, compptr->quant_tbl_no);
  159923. }
  159924. }
  159925. LOCAL(void)
  159926. emit_sos (j_compress_ptr cinfo)
  159927. /* Emit a SOS marker */
  159928. {
  159929. int i, td, ta;
  159930. jpeg_component_info *compptr;
  159931. emit_marker(cinfo, M_SOS);
  159932. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  159933. emit_byte(cinfo, cinfo->comps_in_scan);
  159934. for (i = 0; i < cinfo->comps_in_scan; i++) {
  159935. compptr = cinfo->cur_comp_info[i];
  159936. emit_byte(cinfo, compptr->component_id);
  159937. td = compptr->dc_tbl_no;
  159938. ta = compptr->ac_tbl_no;
  159939. if (cinfo->progressive_mode) {
  159940. /* Progressive mode: only DC or only AC tables are used in one scan;
  159941. * furthermore, Huffman coding of DC refinement uses no table at all.
  159942. * We emit 0 for unused field(s); this is recommended by the P&M text
  159943. * but does not seem to be specified in the standard.
  159944. */
  159945. if (cinfo->Ss == 0) {
  159946. ta = 0; /* DC scan */
  159947. if (cinfo->Ah != 0 && !cinfo->arith_code)
  159948. td = 0; /* no DC table either */
  159949. } else {
  159950. td = 0; /* AC scan */
  159951. }
  159952. }
  159953. emit_byte(cinfo, (td << 4) + ta);
  159954. }
  159955. emit_byte(cinfo, cinfo->Ss);
  159956. emit_byte(cinfo, cinfo->Se);
  159957. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  159958. }
  159959. LOCAL(void)
  159960. emit_jfif_app0 (j_compress_ptr cinfo)
  159961. /* Emit a JFIF-compliant APP0 marker */
  159962. {
  159963. /*
  159964. * Length of APP0 block (2 bytes)
  159965. * Block ID (4 bytes - ASCII "JFIF")
  159966. * Zero byte (1 byte to terminate the ID string)
  159967. * Version Major, Minor (2 bytes - major first)
  159968. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  159969. * Xdpu (2 bytes - dots per unit horizontal)
  159970. * Ydpu (2 bytes - dots per unit vertical)
  159971. * Thumbnail X size (1 byte)
  159972. * Thumbnail Y size (1 byte)
  159973. */
  159974. emit_marker(cinfo, M_APP0);
  159975. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  159976. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  159977. emit_byte(cinfo, 0x46);
  159978. emit_byte(cinfo, 0x49);
  159979. emit_byte(cinfo, 0x46);
  159980. emit_byte(cinfo, 0);
  159981. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  159982. emit_byte(cinfo, cinfo->JFIF_minor_version);
  159983. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  159984. emit_2bytes(cinfo, (int) cinfo->X_density);
  159985. emit_2bytes(cinfo, (int) cinfo->Y_density);
  159986. emit_byte(cinfo, 0); /* No thumbnail image */
  159987. emit_byte(cinfo, 0);
  159988. }
  159989. LOCAL(void)
  159990. emit_adobe_app14 (j_compress_ptr cinfo)
  159991. /* Emit an Adobe APP14 marker */
  159992. {
  159993. /*
  159994. * Length of APP14 block (2 bytes)
  159995. * Block ID (5 bytes - ASCII "Adobe")
  159996. * Version Number (2 bytes - currently 100)
  159997. * Flags0 (2 bytes - currently 0)
  159998. * Flags1 (2 bytes - currently 0)
  159999. * Color transform (1 byte)
  160000. *
  160001. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  160002. * now in circulation seem to use Version = 100, so that's what we write.
  160003. *
  160004. * We write the color transform byte as 1 if the JPEG color space is
  160005. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  160006. * whether the encoder performed a transformation, which is pretty useless.
  160007. */
  160008. emit_marker(cinfo, M_APP14);
  160009. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  160010. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  160011. emit_byte(cinfo, 0x64);
  160012. emit_byte(cinfo, 0x6F);
  160013. emit_byte(cinfo, 0x62);
  160014. emit_byte(cinfo, 0x65);
  160015. emit_2bytes(cinfo, 100); /* Version */
  160016. emit_2bytes(cinfo, 0); /* Flags0 */
  160017. emit_2bytes(cinfo, 0); /* Flags1 */
  160018. switch (cinfo->jpeg_color_space) {
  160019. case JCS_YCbCr:
  160020. emit_byte(cinfo, 1); /* Color transform = 1 */
  160021. break;
  160022. case JCS_YCCK:
  160023. emit_byte(cinfo, 2); /* Color transform = 2 */
  160024. break;
  160025. default:
  160026. emit_byte(cinfo, 0); /* Color transform = 0 */
  160027. break;
  160028. }
  160029. }
  160030. /*
  160031. * These routines allow writing an arbitrary marker with parameters.
  160032. * The only intended use is to emit COM or APPn markers after calling
  160033. * write_file_header and before calling write_frame_header.
  160034. * Other uses are not guaranteed to produce desirable results.
  160035. * Counting the parameter bytes properly is the caller's responsibility.
  160036. */
  160037. METHODDEF(void)
  160038. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  160039. /* Emit an arbitrary marker header */
  160040. {
  160041. if (datalen > (unsigned int) 65533) /* safety check */
  160042. ERREXIT(cinfo, JERR_BAD_LENGTH);
  160043. emit_marker(cinfo, (JPEG_MARKER) marker);
  160044. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  160045. }
  160046. METHODDEF(void)
  160047. write_marker_byte (j_compress_ptr cinfo, int val)
  160048. /* Emit one byte of marker parameters following write_marker_header */
  160049. {
  160050. emit_byte(cinfo, val);
  160051. }
  160052. /*
  160053. * Write datastream header.
  160054. * This consists of an SOI and optional APPn markers.
  160055. * We recommend use of the JFIF marker, but not the Adobe marker,
  160056. * when using YCbCr or grayscale data. The JFIF marker should NOT
  160057. * be used for any other JPEG colorspace. The Adobe marker is helpful
  160058. * to distinguish RGB, CMYK, and YCCK colorspaces.
  160059. * Note that an application can write additional header markers after
  160060. * jpeg_start_compress returns.
  160061. */
  160062. METHODDEF(void)
  160063. write_file_header (j_compress_ptr cinfo)
  160064. {
  160065. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160066. emit_marker(cinfo, M_SOI); /* first the SOI */
  160067. /* SOI is defined to reset restart interval to 0 */
  160068. marker->last_restart_interval = 0;
  160069. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  160070. emit_jfif_app0(cinfo);
  160071. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  160072. emit_adobe_app14(cinfo);
  160073. }
  160074. /*
  160075. * Write frame header.
  160076. * This consists of DQT and SOFn markers.
  160077. * Note that we do not emit the SOF until we have emitted the DQT(s).
  160078. * This avoids compatibility problems with incorrect implementations that
  160079. * try to error-check the quant table numbers as soon as they see the SOF.
  160080. */
  160081. METHODDEF(void)
  160082. write_frame_header (j_compress_ptr cinfo)
  160083. {
  160084. int ci, prec;
  160085. boolean is_baseline;
  160086. jpeg_component_info *compptr;
  160087. /* Emit DQT for each quantization table.
  160088. * Note that emit_dqt() suppresses any duplicate tables.
  160089. */
  160090. prec = 0;
  160091. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160092. ci++, compptr++) {
  160093. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  160094. }
  160095. /* now prec is nonzero iff there are any 16-bit quant tables. */
  160096. /* Check for a non-baseline specification.
  160097. * Note we assume that Huffman table numbers won't be changed later.
  160098. */
  160099. if (cinfo->arith_code || cinfo->progressive_mode ||
  160100. cinfo->data_precision != 8) {
  160101. is_baseline = FALSE;
  160102. } else {
  160103. is_baseline = TRUE;
  160104. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160105. ci++, compptr++) {
  160106. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  160107. is_baseline = FALSE;
  160108. }
  160109. if (prec && is_baseline) {
  160110. is_baseline = FALSE;
  160111. /* If it's baseline except for quantizer size, warn the user */
  160112. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  160113. }
  160114. }
  160115. /* Emit the proper SOF marker */
  160116. if (cinfo->arith_code) {
  160117. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  160118. } else {
  160119. if (cinfo->progressive_mode)
  160120. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  160121. else if (is_baseline)
  160122. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  160123. else
  160124. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  160125. }
  160126. }
  160127. /*
  160128. * Write scan header.
  160129. * This consists of DHT or DAC markers, optional DRI, and SOS.
  160130. * Compressed data will be written following the SOS.
  160131. */
  160132. METHODDEF(void)
  160133. write_scan_header (j_compress_ptr cinfo)
  160134. {
  160135. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  160136. int i;
  160137. jpeg_component_info *compptr;
  160138. if (cinfo->arith_code) {
  160139. /* Emit arith conditioning info. We may have some duplication
  160140. * if the file has multiple scans, but it's so small it's hardly
  160141. * worth worrying about.
  160142. */
  160143. emit_dac(cinfo);
  160144. } else {
  160145. /* Emit Huffman tables.
  160146. * Note that emit_dht() suppresses any duplicate tables.
  160147. */
  160148. for (i = 0; i < cinfo->comps_in_scan; i++) {
  160149. compptr = cinfo->cur_comp_info[i];
  160150. if (cinfo->progressive_mode) {
  160151. /* Progressive mode: only DC or only AC tables are used in one scan */
  160152. if (cinfo->Ss == 0) {
  160153. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  160154. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160155. } else {
  160156. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160157. }
  160158. } else {
  160159. /* Sequential mode: need both DC and AC tables */
  160160. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  160161. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  160162. }
  160163. }
  160164. }
  160165. /* Emit DRI if required --- note that DRI value could change for each scan.
  160166. * We avoid wasting space with unnecessary DRIs, however.
  160167. */
  160168. if (cinfo->restart_interval != marker->last_restart_interval) {
  160169. emit_dri(cinfo);
  160170. marker->last_restart_interval = cinfo->restart_interval;
  160171. }
  160172. emit_sos(cinfo);
  160173. }
  160174. /*
  160175. * Write datastream trailer.
  160176. */
  160177. METHODDEF(void)
  160178. write_file_trailer (j_compress_ptr cinfo)
  160179. {
  160180. emit_marker(cinfo, M_EOI);
  160181. }
  160182. /*
  160183. * Write an abbreviated table-specification datastream.
  160184. * This consists of SOI, DQT and DHT tables, and EOI.
  160185. * Any table that is defined and not marked sent_table = TRUE will be
  160186. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  160187. */
  160188. METHODDEF(void)
  160189. write_tables_only (j_compress_ptr cinfo)
  160190. {
  160191. int i;
  160192. emit_marker(cinfo, M_SOI);
  160193. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  160194. if (cinfo->quant_tbl_ptrs[i] != NULL)
  160195. (void) emit_dqt(cinfo, i);
  160196. }
  160197. if (! cinfo->arith_code) {
  160198. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  160199. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  160200. emit_dht(cinfo, i, FALSE);
  160201. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  160202. emit_dht(cinfo, i, TRUE);
  160203. }
  160204. }
  160205. emit_marker(cinfo, M_EOI);
  160206. }
  160207. /*
  160208. * Initialize the marker writer module.
  160209. */
  160210. GLOBAL(void)
  160211. jinit_marker_writer (j_compress_ptr cinfo)
  160212. {
  160213. my_marker_ptr marker;
  160214. /* Create the subobject */
  160215. marker = (my_marker_ptr)
  160216. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160217. SIZEOF(my_marker_writer));
  160218. cinfo->marker = (struct jpeg_marker_writer *) marker;
  160219. /* Initialize method pointers */
  160220. marker->pub.write_file_header = write_file_header;
  160221. marker->pub.write_frame_header = write_frame_header;
  160222. marker->pub.write_scan_header = write_scan_header;
  160223. marker->pub.write_file_trailer = write_file_trailer;
  160224. marker->pub.write_tables_only = write_tables_only;
  160225. marker->pub.write_marker_header = write_marker_header;
  160226. marker->pub.write_marker_byte = write_marker_byte;
  160227. /* Initialize private state */
  160228. marker->last_restart_interval = 0;
  160229. }
  160230. /********* End of inlined file: jcmarker.c *********/
  160231. /********* Start of inlined file: jcmaster.c *********/
  160232. #define JPEG_INTERNALS
  160233. /* Private state */
  160234. typedef enum {
  160235. main_pass, /* input data, also do first output step */
  160236. huff_opt_pass, /* Huffman code optimization pass */
  160237. output_pass /* data output pass */
  160238. } c_pass_type;
  160239. typedef struct {
  160240. struct jpeg_comp_master pub; /* public fields */
  160241. c_pass_type pass_type; /* the type of the current pass */
  160242. int pass_number; /* # of passes completed */
  160243. int total_passes; /* total # of passes needed */
  160244. int scan_number; /* current index in scan_info[] */
  160245. } my_comp_master;
  160246. typedef my_comp_master * my_master_ptr;
  160247. /*
  160248. * Support routines that do various essential calculations.
  160249. */
  160250. LOCAL(void)
  160251. initial_setup (j_compress_ptr cinfo)
  160252. /* Do computations that are needed before master selection phase */
  160253. {
  160254. int ci;
  160255. jpeg_component_info *compptr;
  160256. long samplesperrow;
  160257. JDIMENSION jd_samplesperrow;
  160258. /* Sanity check on image dimensions */
  160259. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  160260. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  160261. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  160262. /* Make sure image isn't bigger than I can handle */
  160263. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  160264. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  160265. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  160266. /* Width of an input scanline must be representable as JDIMENSION. */
  160267. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  160268. jd_samplesperrow = (JDIMENSION) samplesperrow;
  160269. if ((long) jd_samplesperrow != samplesperrow)
  160270. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  160271. /* For now, precision must match compiled-in value... */
  160272. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  160273. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  160274. /* Check that number of components won't exceed internal array sizes */
  160275. if (cinfo->num_components > MAX_COMPONENTS)
  160276. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160277. MAX_COMPONENTS);
  160278. /* Compute maximum sampling factors; check factor validity */
  160279. cinfo->max_h_samp_factor = 1;
  160280. cinfo->max_v_samp_factor = 1;
  160281. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160282. ci++, compptr++) {
  160283. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  160284. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  160285. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  160286. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  160287. compptr->h_samp_factor);
  160288. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  160289. compptr->v_samp_factor);
  160290. }
  160291. /* Compute dimensions of components */
  160292. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160293. ci++, compptr++) {
  160294. /* Fill in the correct component_index value; don't rely on application */
  160295. compptr->component_index = ci;
  160296. /* For compression, we never do DCT scaling. */
  160297. compptr->DCT_scaled_size = DCTSIZE;
  160298. /* Size in DCT blocks */
  160299. compptr->width_in_blocks = (JDIMENSION)
  160300. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160301. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  160302. compptr->height_in_blocks = (JDIMENSION)
  160303. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160304. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  160305. /* Size in samples */
  160306. compptr->downsampled_width = (JDIMENSION)
  160307. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  160308. (long) cinfo->max_h_samp_factor);
  160309. compptr->downsampled_height = (JDIMENSION)
  160310. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  160311. (long) cinfo->max_v_samp_factor);
  160312. /* Mark component needed (this flag isn't actually used for compression) */
  160313. compptr->component_needed = TRUE;
  160314. }
  160315. /* Compute number of fully interleaved MCU rows (number of times that
  160316. * main controller will call coefficient controller).
  160317. */
  160318. cinfo->total_iMCU_rows = (JDIMENSION)
  160319. jdiv_round_up((long) cinfo->image_height,
  160320. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160321. }
  160322. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160323. LOCAL(void)
  160324. validate_script (j_compress_ptr cinfo)
  160325. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  160326. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  160327. */
  160328. {
  160329. const jpeg_scan_info * scanptr;
  160330. int scanno, ncomps, ci, coefi, thisi;
  160331. int Ss, Se, Ah, Al;
  160332. boolean component_sent[MAX_COMPONENTS];
  160333. #ifdef C_PROGRESSIVE_SUPPORTED
  160334. int * last_bitpos_ptr;
  160335. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  160336. /* -1 until that coefficient has been seen; then last Al for it */
  160337. #endif
  160338. if (cinfo->num_scans <= 0)
  160339. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  160340. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  160341. * for progressive JPEG, no scan can have this.
  160342. */
  160343. scanptr = cinfo->scan_info;
  160344. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  160345. #ifdef C_PROGRESSIVE_SUPPORTED
  160346. cinfo->progressive_mode = TRUE;
  160347. last_bitpos_ptr = & last_bitpos[0][0];
  160348. for (ci = 0; ci < cinfo->num_components; ci++)
  160349. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  160350. *last_bitpos_ptr++ = -1;
  160351. #else
  160352. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160353. #endif
  160354. } else {
  160355. cinfo->progressive_mode = FALSE;
  160356. for (ci = 0; ci < cinfo->num_components; ci++)
  160357. component_sent[ci] = FALSE;
  160358. }
  160359. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  160360. /* Validate component indexes */
  160361. ncomps = scanptr->comps_in_scan;
  160362. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  160363. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  160364. for (ci = 0; ci < ncomps; ci++) {
  160365. thisi = scanptr->component_index[ci];
  160366. if (thisi < 0 || thisi >= cinfo->num_components)
  160367. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160368. /* Components must appear in SOF order within each scan */
  160369. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  160370. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160371. }
  160372. /* Validate progression parameters */
  160373. Ss = scanptr->Ss;
  160374. Se = scanptr->Se;
  160375. Ah = scanptr->Ah;
  160376. Al = scanptr->Al;
  160377. if (cinfo->progressive_mode) {
  160378. #ifdef C_PROGRESSIVE_SUPPORTED
  160379. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  160380. * seems wrong: the upper bound ought to depend on data precision.
  160381. * Perhaps they really meant 0..N+1 for N-bit precision.
  160382. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  160383. * out-of-range reconstructed DC values during the first DC scan,
  160384. * which might cause problems for some decoders.
  160385. */
  160386. #if BITS_IN_JSAMPLE == 8
  160387. #define MAX_AH_AL 10
  160388. #else
  160389. #define MAX_AH_AL 13
  160390. #endif
  160391. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  160392. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  160393. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160394. if (Ss == 0) {
  160395. if (Se != 0) /* DC and AC together not OK */
  160396. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160397. } else {
  160398. if (ncomps != 1) /* AC scans must be for only one component */
  160399. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160400. }
  160401. for (ci = 0; ci < ncomps; ci++) {
  160402. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  160403. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  160404. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160405. for (coefi = Ss; coefi <= Se; coefi++) {
  160406. if (last_bitpos_ptr[coefi] < 0) {
  160407. /* first scan of this coefficient */
  160408. if (Ah != 0)
  160409. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160410. } else {
  160411. /* not first scan */
  160412. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  160413. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160414. }
  160415. last_bitpos_ptr[coefi] = Al;
  160416. }
  160417. }
  160418. #endif
  160419. } else {
  160420. /* For sequential JPEG, all progression parameters must be these: */
  160421. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  160422. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  160423. /* Make sure components are not sent twice */
  160424. for (ci = 0; ci < ncomps; ci++) {
  160425. thisi = scanptr->component_index[ci];
  160426. if (component_sent[thisi])
  160427. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  160428. component_sent[thisi] = TRUE;
  160429. }
  160430. }
  160431. }
  160432. /* Now verify that everything got sent. */
  160433. if (cinfo->progressive_mode) {
  160434. #ifdef C_PROGRESSIVE_SUPPORTED
  160435. /* For progressive mode, we only check that at least some DC data
  160436. * got sent for each component; the spec does not require that all bits
  160437. * of all coefficients be transmitted. Would it be wiser to enforce
  160438. * transmission of all coefficient bits??
  160439. */
  160440. for (ci = 0; ci < cinfo->num_components; ci++) {
  160441. if (last_bitpos[ci][0] < 0)
  160442. ERREXIT(cinfo, JERR_MISSING_DATA);
  160443. }
  160444. #endif
  160445. } else {
  160446. for (ci = 0; ci < cinfo->num_components; ci++) {
  160447. if (! component_sent[ci])
  160448. ERREXIT(cinfo, JERR_MISSING_DATA);
  160449. }
  160450. }
  160451. }
  160452. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  160453. LOCAL(void)
  160454. select_scan_parameters (j_compress_ptr cinfo)
  160455. /* Set up the scan parameters for the current scan */
  160456. {
  160457. int ci;
  160458. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160459. if (cinfo->scan_info != NULL) {
  160460. /* Prepare for current scan --- the script is already validated */
  160461. my_master_ptr master = (my_master_ptr) cinfo->master;
  160462. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  160463. cinfo->comps_in_scan = scanptr->comps_in_scan;
  160464. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  160465. cinfo->cur_comp_info[ci] =
  160466. &cinfo->comp_info[scanptr->component_index[ci]];
  160467. }
  160468. cinfo->Ss = scanptr->Ss;
  160469. cinfo->Se = scanptr->Se;
  160470. cinfo->Ah = scanptr->Ah;
  160471. cinfo->Al = scanptr->Al;
  160472. }
  160473. else
  160474. #endif
  160475. {
  160476. /* Prepare for single sequential-JPEG scan containing all components */
  160477. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  160478. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  160479. MAX_COMPS_IN_SCAN);
  160480. cinfo->comps_in_scan = cinfo->num_components;
  160481. for (ci = 0; ci < cinfo->num_components; ci++) {
  160482. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  160483. }
  160484. cinfo->Ss = 0;
  160485. cinfo->Se = DCTSIZE2-1;
  160486. cinfo->Ah = 0;
  160487. cinfo->Al = 0;
  160488. }
  160489. }
  160490. LOCAL(void)
  160491. per_scan_setup (j_compress_ptr cinfo)
  160492. /* Do computations that are needed before processing a JPEG scan */
  160493. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  160494. {
  160495. int ci, mcublks, tmp;
  160496. jpeg_component_info *compptr;
  160497. if (cinfo->comps_in_scan == 1) {
  160498. /* Noninterleaved (single-component) scan */
  160499. compptr = cinfo->cur_comp_info[0];
  160500. /* Overall image size in MCUs */
  160501. cinfo->MCUs_per_row = compptr->width_in_blocks;
  160502. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  160503. /* For noninterleaved scan, always one block per MCU */
  160504. compptr->MCU_width = 1;
  160505. compptr->MCU_height = 1;
  160506. compptr->MCU_blocks = 1;
  160507. compptr->MCU_sample_width = DCTSIZE;
  160508. compptr->last_col_width = 1;
  160509. /* For noninterleaved scans, it is convenient to define last_row_height
  160510. * as the number of block rows present in the last iMCU row.
  160511. */
  160512. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  160513. if (tmp == 0) tmp = compptr->v_samp_factor;
  160514. compptr->last_row_height = tmp;
  160515. /* Prepare array describing MCU composition */
  160516. cinfo->blocks_in_MCU = 1;
  160517. cinfo->MCU_membership[0] = 0;
  160518. } else {
  160519. /* Interleaved (multi-component) scan */
  160520. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  160521. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  160522. MAX_COMPS_IN_SCAN);
  160523. /* Overall image size in MCUs */
  160524. cinfo->MCUs_per_row = (JDIMENSION)
  160525. jdiv_round_up((long) cinfo->image_width,
  160526. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  160527. cinfo->MCU_rows_in_scan = (JDIMENSION)
  160528. jdiv_round_up((long) cinfo->image_height,
  160529. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  160530. cinfo->blocks_in_MCU = 0;
  160531. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160532. compptr = cinfo->cur_comp_info[ci];
  160533. /* Sampling factors give # of blocks of component in each MCU */
  160534. compptr->MCU_width = compptr->h_samp_factor;
  160535. compptr->MCU_height = compptr->v_samp_factor;
  160536. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  160537. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  160538. /* Figure number of non-dummy blocks in last MCU column & row */
  160539. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  160540. if (tmp == 0) tmp = compptr->MCU_width;
  160541. compptr->last_col_width = tmp;
  160542. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  160543. if (tmp == 0) tmp = compptr->MCU_height;
  160544. compptr->last_row_height = tmp;
  160545. /* Prepare array describing MCU composition */
  160546. mcublks = compptr->MCU_blocks;
  160547. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  160548. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  160549. while (mcublks-- > 0) {
  160550. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  160551. }
  160552. }
  160553. }
  160554. /* Convert restart specified in rows to actual MCU count. */
  160555. /* Note that count must fit in 16 bits, so we provide limiting. */
  160556. if (cinfo->restart_in_rows > 0) {
  160557. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  160558. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  160559. }
  160560. }
  160561. /*
  160562. * Per-pass setup.
  160563. * This is called at the beginning of each pass. We determine which modules
  160564. * will be active during this pass and give them appropriate start_pass calls.
  160565. * We also set is_last_pass to indicate whether any more passes will be
  160566. * required.
  160567. */
  160568. METHODDEF(void)
  160569. prepare_for_pass (j_compress_ptr cinfo)
  160570. {
  160571. my_master_ptr master = (my_master_ptr) cinfo->master;
  160572. switch (master->pass_type) {
  160573. case main_pass:
  160574. /* Initial pass: will collect input data, and do either Huffman
  160575. * optimization or data output for the first scan.
  160576. */
  160577. select_scan_parameters(cinfo);
  160578. per_scan_setup(cinfo);
  160579. if (! cinfo->raw_data_in) {
  160580. (*cinfo->cconvert->start_pass) (cinfo);
  160581. (*cinfo->downsample->start_pass) (cinfo);
  160582. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  160583. }
  160584. (*cinfo->fdct->start_pass) (cinfo);
  160585. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  160586. (*cinfo->coef->start_pass) (cinfo,
  160587. (master->total_passes > 1 ?
  160588. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  160589. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  160590. if (cinfo->optimize_coding) {
  160591. /* No immediate data output; postpone writing frame/scan headers */
  160592. master->pub.call_pass_startup = FALSE;
  160593. } else {
  160594. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  160595. master->pub.call_pass_startup = TRUE;
  160596. }
  160597. break;
  160598. #ifdef ENTROPY_OPT_SUPPORTED
  160599. case huff_opt_pass:
  160600. /* Do Huffman optimization for a scan after the first one. */
  160601. select_scan_parameters(cinfo);
  160602. per_scan_setup(cinfo);
  160603. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  160604. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  160605. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160606. master->pub.call_pass_startup = FALSE;
  160607. break;
  160608. }
  160609. /* Special case: Huffman DC refinement scans need no Huffman table
  160610. * and therefore we can skip the optimization pass for them.
  160611. */
  160612. master->pass_type = output_pass;
  160613. master->pass_number++;
  160614. /*FALLTHROUGH*/
  160615. #endif
  160616. case output_pass:
  160617. /* Do a data-output pass. */
  160618. /* We need not repeat per-scan setup if prior optimization pass did it. */
  160619. if (! cinfo->optimize_coding) {
  160620. select_scan_parameters(cinfo);
  160621. per_scan_setup(cinfo);
  160622. }
  160623. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  160624. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  160625. /* We emit frame/scan headers now */
  160626. if (master->scan_number == 0)
  160627. (*cinfo->marker->write_frame_header) (cinfo);
  160628. (*cinfo->marker->write_scan_header) (cinfo);
  160629. master->pub.call_pass_startup = FALSE;
  160630. break;
  160631. default:
  160632. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160633. }
  160634. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  160635. /* Set up progress monitor's pass info if present */
  160636. if (cinfo->progress != NULL) {
  160637. cinfo->progress->completed_passes = master->pass_number;
  160638. cinfo->progress->total_passes = master->total_passes;
  160639. }
  160640. }
  160641. /*
  160642. * Special start-of-pass hook.
  160643. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  160644. * In single-pass processing, we need this hook because we don't want to
  160645. * write frame/scan headers during jpeg_start_compress; we want to let the
  160646. * application write COM markers etc. between jpeg_start_compress and the
  160647. * jpeg_write_scanlines loop.
  160648. * In multi-pass processing, this routine is not used.
  160649. */
  160650. METHODDEF(void)
  160651. pass_startup (j_compress_ptr cinfo)
  160652. {
  160653. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  160654. (*cinfo->marker->write_frame_header) (cinfo);
  160655. (*cinfo->marker->write_scan_header) (cinfo);
  160656. }
  160657. /*
  160658. * Finish up at end of pass.
  160659. */
  160660. METHODDEF(void)
  160661. finish_pass_master (j_compress_ptr cinfo)
  160662. {
  160663. my_master_ptr master = (my_master_ptr) cinfo->master;
  160664. /* The entropy coder always needs an end-of-pass call,
  160665. * either to analyze statistics or to flush its output buffer.
  160666. */
  160667. (*cinfo->entropy->finish_pass) (cinfo);
  160668. /* Update state for next pass */
  160669. switch (master->pass_type) {
  160670. case main_pass:
  160671. /* next pass is either output of scan 0 (after optimization)
  160672. * or output of scan 1 (if no optimization).
  160673. */
  160674. master->pass_type = output_pass;
  160675. if (! cinfo->optimize_coding)
  160676. master->scan_number++;
  160677. break;
  160678. case huff_opt_pass:
  160679. /* next pass is always output of current scan */
  160680. master->pass_type = output_pass;
  160681. break;
  160682. case output_pass:
  160683. /* next pass is either optimization or output of next scan */
  160684. if (cinfo->optimize_coding)
  160685. master->pass_type = huff_opt_pass;
  160686. master->scan_number++;
  160687. break;
  160688. }
  160689. master->pass_number++;
  160690. }
  160691. /*
  160692. * Initialize master compression control.
  160693. */
  160694. GLOBAL(void)
  160695. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  160696. {
  160697. my_master_ptr master;
  160698. master = (my_master_ptr)
  160699. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160700. SIZEOF(my_comp_master));
  160701. cinfo->master = (struct jpeg_comp_master *) master;
  160702. master->pub.prepare_for_pass = prepare_for_pass;
  160703. master->pub.pass_startup = pass_startup;
  160704. master->pub.finish_pass = finish_pass_master;
  160705. master->pub.is_last_pass = FALSE;
  160706. /* Validate parameters, determine derived values */
  160707. initial_setup(cinfo);
  160708. if (cinfo->scan_info != NULL) {
  160709. #ifdef C_MULTISCAN_FILES_SUPPORTED
  160710. validate_script(cinfo);
  160711. #else
  160712. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160713. #endif
  160714. } else {
  160715. cinfo->progressive_mode = FALSE;
  160716. cinfo->num_scans = 1;
  160717. }
  160718. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  160719. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  160720. /* Initialize my private state */
  160721. if (transcode_only) {
  160722. /* no main pass in transcoding */
  160723. if (cinfo->optimize_coding)
  160724. master->pass_type = huff_opt_pass;
  160725. else
  160726. master->pass_type = output_pass;
  160727. } else {
  160728. /* for normal compression, first pass is always this type: */
  160729. master->pass_type = main_pass;
  160730. }
  160731. master->scan_number = 0;
  160732. master->pass_number = 0;
  160733. if (cinfo->optimize_coding)
  160734. master->total_passes = cinfo->num_scans * 2;
  160735. else
  160736. master->total_passes = cinfo->num_scans;
  160737. }
  160738. /********* End of inlined file: jcmaster.c *********/
  160739. /********* Start of inlined file: jcomapi.c *********/
  160740. #define JPEG_INTERNALS
  160741. /*
  160742. * Abort processing of a JPEG compression or decompression operation,
  160743. * but don't destroy the object itself.
  160744. *
  160745. * For this, we merely clean up all the nonpermanent memory pools.
  160746. * Note that temp files (virtual arrays) are not allowed to belong to
  160747. * the permanent pool, so we will be able to close all temp files here.
  160748. * Closing a data source or destination, if necessary, is the application's
  160749. * responsibility.
  160750. */
  160751. GLOBAL(void)
  160752. jpeg_abort (j_common_ptr cinfo)
  160753. {
  160754. int pool;
  160755. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  160756. if (cinfo->mem == NULL)
  160757. return;
  160758. /* Releasing pools in reverse order might help avoid fragmentation
  160759. * with some (brain-damaged) malloc libraries.
  160760. */
  160761. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  160762. (*cinfo->mem->free_pool) (cinfo, pool);
  160763. }
  160764. /* Reset overall state for possible reuse of object */
  160765. if (cinfo->is_decompressor) {
  160766. cinfo->global_state = DSTATE_START;
  160767. /* Try to keep application from accessing now-deleted marker list.
  160768. * A bit kludgy to do it here, but this is the most central place.
  160769. */
  160770. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  160771. } else {
  160772. cinfo->global_state = CSTATE_START;
  160773. }
  160774. }
  160775. /*
  160776. * Destruction of a JPEG object.
  160777. *
  160778. * Everything gets deallocated except the master jpeg_compress_struct itself
  160779. * and the error manager struct. Both of these are supplied by the application
  160780. * and must be freed, if necessary, by the application. (Often they are on
  160781. * the stack and so don't need to be freed anyway.)
  160782. * Closing a data source or destination, if necessary, is the application's
  160783. * responsibility.
  160784. */
  160785. GLOBAL(void)
  160786. jpeg_destroy (j_common_ptr cinfo)
  160787. {
  160788. /* We need only tell the memory manager to release everything. */
  160789. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  160790. if (cinfo->mem != NULL)
  160791. (*cinfo->mem->self_destruct) (cinfo);
  160792. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  160793. cinfo->global_state = 0; /* mark it destroyed */
  160794. }
  160795. /*
  160796. * Convenience routines for allocating quantization and Huffman tables.
  160797. * (Would jutils.c be a more reasonable place to put these?)
  160798. */
  160799. GLOBAL(JQUANT_TBL *)
  160800. jpeg_alloc_quant_table (j_common_ptr cinfo)
  160801. {
  160802. JQUANT_TBL *tbl;
  160803. tbl = (JQUANT_TBL *)
  160804. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  160805. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160806. return tbl;
  160807. }
  160808. GLOBAL(JHUFF_TBL *)
  160809. jpeg_alloc_huff_table (j_common_ptr cinfo)
  160810. {
  160811. JHUFF_TBL *tbl;
  160812. tbl = (JHUFF_TBL *)
  160813. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  160814. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  160815. return tbl;
  160816. }
  160817. /********* End of inlined file: jcomapi.c *********/
  160818. /********* Start of inlined file: jcparam.c *********/
  160819. #define JPEG_INTERNALS
  160820. /*
  160821. * Quantization table setup routines
  160822. */
  160823. GLOBAL(void)
  160824. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  160825. const unsigned int *basic_table,
  160826. int scale_factor, boolean force_baseline)
  160827. /* Define a quantization table equal to the basic_table times
  160828. * a scale factor (given as a percentage).
  160829. * If force_baseline is TRUE, the computed quantization table entries
  160830. * are limited to 1..255 for JPEG baseline compatibility.
  160831. */
  160832. {
  160833. JQUANT_TBL ** qtblptr;
  160834. int i;
  160835. long temp;
  160836. /* Safety check to ensure start_compress not called yet. */
  160837. if (cinfo->global_state != CSTATE_START)
  160838. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160839. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  160840. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  160841. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  160842. if (*qtblptr == NULL)
  160843. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  160844. for (i = 0; i < DCTSIZE2; i++) {
  160845. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  160846. /* limit the values to the valid range */
  160847. if (temp <= 0L) temp = 1L;
  160848. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  160849. if (force_baseline && temp > 255L)
  160850. temp = 255L; /* limit to baseline range if requested */
  160851. (*qtblptr)->quantval[i] = (UINT16) temp;
  160852. }
  160853. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160854. (*qtblptr)->sent_table = FALSE;
  160855. }
  160856. GLOBAL(void)
  160857. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  160858. boolean force_baseline)
  160859. /* Set or change the 'quality' (quantization) setting, using default tables
  160860. * and a straight percentage-scaling quality scale. In most cases it's better
  160861. * to use jpeg_set_quality (below); this entry point is provided for
  160862. * applications that insist on a linear percentage scaling.
  160863. */
  160864. {
  160865. /* These are the sample quantization tables given in JPEG spec section K.1.
  160866. * The spec says that the values given produce "good" quality, and
  160867. * when divided by 2, "very good" quality.
  160868. */
  160869. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  160870. 16, 11, 10, 16, 24, 40, 51, 61,
  160871. 12, 12, 14, 19, 26, 58, 60, 55,
  160872. 14, 13, 16, 24, 40, 57, 69, 56,
  160873. 14, 17, 22, 29, 51, 87, 80, 62,
  160874. 18, 22, 37, 56, 68, 109, 103, 77,
  160875. 24, 35, 55, 64, 81, 104, 113, 92,
  160876. 49, 64, 78, 87, 103, 121, 120, 101,
  160877. 72, 92, 95, 98, 112, 100, 103, 99
  160878. };
  160879. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  160880. 17, 18, 24, 47, 99, 99, 99, 99,
  160881. 18, 21, 26, 66, 99, 99, 99, 99,
  160882. 24, 26, 56, 99, 99, 99, 99, 99,
  160883. 47, 66, 99, 99, 99, 99, 99, 99,
  160884. 99, 99, 99, 99, 99, 99, 99, 99,
  160885. 99, 99, 99, 99, 99, 99, 99, 99,
  160886. 99, 99, 99, 99, 99, 99, 99, 99,
  160887. 99, 99, 99, 99, 99, 99, 99, 99
  160888. };
  160889. /* Set up two quantization tables using the specified scaling */
  160890. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  160891. scale_factor, force_baseline);
  160892. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  160893. scale_factor, force_baseline);
  160894. }
  160895. GLOBAL(int)
  160896. jpeg_quality_scaling (int quality)
  160897. /* Convert a user-specified quality rating to a percentage scaling factor
  160898. * for an underlying quantization table, using our recommended scaling curve.
  160899. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  160900. */
  160901. {
  160902. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  160903. if (quality <= 0) quality = 1;
  160904. if (quality > 100) quality = 100;
  160905. /* The basic table is used as-is (scaling 100) for a quality of 50.
  160906. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  160907. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  160908. * to make all the table entries 1 (hence, minimum quantization loss).
  160909. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  160910. */
  160911. if (quality < 50)
  160912. quality = 5000 / quality;
  160913. else
  160914. quality = 200 - quality*2;
  160915. return quality;
  160916. }
  160917. GLOBAL(void)
  160918. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  160919. /* Set or change the 'quality' (quantization) setting, using default tables.
  160920. * This is the standard quality-adjusting entry point for typical user
  160921. * interfaces; only those who want detailed control over quantization tables
  160922. * would use the preceding three routines directly.
  160923. */
  160924. {
  160925. /* Convert user 0-100 rating to percentage scaling */
  160926. quality = jpeg_quality_scaling(quality);
  160927. /* Set up standard quality tables */
  160928. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  160929. }
  160930. /*
  160931. * Huffman table setup routines
  160932. */
  160933. LOCAL(void)
  160934. add_huff_table (j_compress_ptr cinfo,
  160935. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  160936. /* Define a Huffman table */
  160937. {
  160938. int nsymbols, len;
  160939. if (*htblptr == NULL)
  160940. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  160941. /* Copy the number-of-symbols-of-each-code-length counts */
  160942. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  160943. /* Validate the counts. We do this here mainly so we can copy the right
  160944. * number of symbols from the val[] array, without risking marching off
  160945. * the end of memory. jchuff.c will do a more thorough test later.
  160946. */
  160947. nsymbols = 0;
  160948. for (len = 1; len <= 16; len++)
  160949. nsymbols += bits[len];
  160950. if (nsymbols < 1 || nsymbols > 256)
  160951. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  160952. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  160953. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  160954. (*htblptr)->sent_table = FALSE;
  160955. }
  160956. LOCAL(void)
  160957. std_huff_tables (j_compress_ptr cinfo)
  160958. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  160959. /* IMPORTANT: these are only valid for 8-bit data precision! */
  160960. {
  160961. static const UINT8 bits_dc_luminance[17] =
  160962. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  160963. static const UINT8 val_dc_luminance[] =
  160964. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160965. static const UINT8 bits_dc_chrominance[17] =
  160966. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  160967. static const UINT8 val_dc_chrominance[] =
  160968. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  160969. static const UINT8 bits_ac_luminance[17] =
  160970. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  160971. static const UINT8 val_ac_luminance[] =
  160972. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  160973. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  160974. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  160975. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  160976. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  160977. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  160978. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  160979. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  160980. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  160981. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  160982. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  160983. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  160984. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  160985. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  160986. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  160987. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  160988. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  160989. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  160990. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  160991. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  160992. 0xf9, 0xfa };
  160993. static const UINT8 bits_ac_chrominance[17] =
  160994. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  160995. static const UINT8 val_ac_chrominance[] =
  160996. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  160997. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  160998. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  160999. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  161000. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  161001. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  161002. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  161003. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  161004. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  161005. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  161006. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  161007. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  161008. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  161009. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  161010. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  161011. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  161012. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  161013. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  161014. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  161015. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  161016. 0xf9, 0xfa };
  161017. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  161018. bits_dc_luminance, val_dc_luminance);
  161019. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  161020. bits_ac_luminance, val_ac_luminance);
  161021. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  161022. bits_dc_chrominance, val_dc_chrominance);
  161023. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  161024. bits_ac_chrominance, val_ac_chrominance);
  161025. }
  161026. /*
  161027. * Default parameter setup for compression.
  161028. *
  161029. * Applications that don't choose to use this routine must do their
  161030. * own setup of all these parameters. Alternately, you can call this
  161031. * to establish defaults and then alter parameters selectively. This
  161032. * is the recommended approach since, if we add any new parameters,
  161033. * your code will still work (they'll be set to reasonable defaults).
  161034. */
  161035. GLOBAL(void)
  161036. jpeg_set_defaults (j_compress_ptr cinfo)
  161037. {
  161038. int i;
  161039. /* Safety check to ensure start_compress not called yet. */
  161040. if (cinfo->global_state != CSTATE_START)
  161041. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161042. /* Allocate comp_info array large enough for maximum component count.
  161043. * Array is made permanent in case application wants to compress
  161044. * multiple images at same param settings.
  161045. */
  161046. if (cinfo->comp_info == NULL)
  161047. cinfo->comp_info = (jpeg_component_info *)
  161048. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161049. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  161050. /* Initialize everything not dependent on the color space */
  161051. cinfo->data_precision = BITS_IN_JSAMPLE;
  161052. /* Set up two quantization tables using default quality of 75 */
  161053. jpeg_set_quality(cinfo, 75, TRUE);
  161054. /* Set up two Huffman tables */
  161055. std_huff_tables(cinfo);
  161056. /* Initialize default arithmetic coding conditioning */
  161057. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  161058. cinfo->arith_dc_L[i] = 0;
  161059. cinfo->arith_dc_U[i] = 1;
  161060. cinfo->arith_ac_K[i] = 5;
  161061. }
  161062. /* Default is no multiple-scan output */
  161063. cinfo->scan_info = NULL;
  161064. cinfo->num_scans = 0;
  161065. /* Expect normal source image, not raw downsampled data */
  161066. cinfo->raw_data_in = FALSE;
  161067. /* Use Huffman coding, not arithmetic coding, by default */
  161068. cinfo->arith_code = FALSE;
  161069. /* By default, don't do extra passes to optimize entropy coding */
  161070. cinfo->optimize_coding = FALSE;
  161071. /* The standard Huffman tables are only valid for 8-bit data precision.
  161072. * If the precision is higher, force optimization on so that usable
  161073. * tables will be computed. This test can be removed if default tables
  161074. * are supplied that are valid for the desired precision.
  161075. */
  161076. if (cinfo->data_precision > 8)
  161077. cinfo->optimize_coding = TRUE;
  161078. /* By default, use the simpler non-cosited sampling alignment */
  161079. cinfo->CCIR601_sampling = FALSE;
  161080. /* No input smoothing */
  161081. cinfo->smoothing_factor = 0;
  161082. /* DCT algorithm preference */
  161083. cinfo->dct_method = JDCT_DEFAULT;
  161084. /* No restart markers */
  161085. cinfo->restart_interval = 0;
  161086. cinfo->restart_in_rows = 0;
  161087. /* Fill in default JFIF marker parameters. Note that whether the marker
  161088. * will actually be written is determined by jpeg_set_colorspace.
  161089. *
  161090. * By default, the library emits JFIF version code 1.01.
  161091. * An application that wants to emit JFIF 1.02 extension markers should set
  161092. * JFIF_minor_version to 2. We could probably get away with just defaulting
  161093. * to 1.02, but there may still be some decoders in use that will complain
  161094. * about that; saying 1.01 should minimize compatibility problems.
  161095. */
  161096. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  161097. cinfo->JFIF_minor_version = 1;
  161098. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  161099. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  161100. cinfo->Y_density = 1;
  161101. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  161102. jpeg_default_colorspace(cinfo);
  161103. }
  161104. /*
  161105. * Select an appropriate JPEG colorspace for in_color_space.
  161106. */
  161107. GLOBAL(void)
  161108. jpeg_default_colorspace (j_compress_ptr cinfo)
  161109. {
  161110. switch (cinfo->in_color_space) {
  161111. case JCS_GRAYSCALE:
  161112. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  161113. break;
  161114. case JCS_RGB:
  161115. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161116. break;
  161117. case JCS_YCbCr:
  161118. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  161119. break;
  161120. case JCS_CMYK:
  161121. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  161122. break;
  161123. case JCS_YCCK:
  161124. jpeg_set_colorspace(cinfo, JCS_YCCK);
  161125. break;
  161126. case JCS_UNKNOWN:
  161127. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  161128. break;
  161129. default:
  161130. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  161131. }
  161132. }
  161133. /*
  161134. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  161135. */
  161136. GLOBAL(void)
  161137. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  161138. {
  161139. jpeg_component_info * compptr;
  161140. int ci;
  161141. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  161142. (compptr = &cinfo->comp_info[index], \
  161143. compptr->component_id = (id), \
  161144. compptr->h_samp_factor = (hsamp), \
  161145. compptr->v_samp_factor = (vsamp), \
  161146. compptr->quant_tbl_no = (quant), \
  161147. compptr->dc_tbl_no = (dctbl), \
  161148. compptr->ac_tbl_no = (actbl) )
  161149. /* Safety check to ensure start_compress not called yet. */
  161150. if (cinfo->global_state != CSTATE_START)
  161151. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161152. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  161153. * tables 1 for chrominance components.
  161154. */
  161155. cinfo->jpeg_color_space = colorspace;
  161156. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  161157. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  161158. switch (colorspace) {
  161159. case JCS_GRAYSCALE:
  161160. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161161. cinfo->num_components = 1;
  161162. /* JFIF specifies component ID 1 */
  161163. SET_COMP(0, 1, 1,1, 0, 0,0);
  161164. break;
  161165. case JCS_RGB:
  161166. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  161167. cinfo->num_components = 3;
  161168. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  161169. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  161170. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  161171. break;
  161172. case JCS_YCbCr:
  161173. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  161174. cinfo->num_components = 3;
  161175. /* JFIF specifies component IDs 1,2,3 */
  161176. /* We default to 2x2 subsamples of chrominance */
  161177. SET_COMP(0, 1, 2,2, 0, 0,0);
  161178. SET_COMP(1, 2, 1,1, 1, 1,1);
  161179. SET_COMP(2, 3, 1,1, 1, 1,1);
  161180. break;
  161181. case JCS_CMYK:
  161182. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  161183. cinfo->num_components = 4;
  161184. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  161185. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  161186. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  161187. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  161188. break;
  161189. case JCS_YCCK:
  161190. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  161191. cinfo->num_components = 4;
  161192. SET_COMP(0, 1, 2,2, 0, 0,0);
  161193. SET_COMP(1, 2, 1,1, 1, 1,1);
  161194. SET_COMP(2, 3, 1,1, 1, 1,1);
  161195. SET_COMP(3, 4, 2,2, 0, 0,0);
  161196. break;
  161197. case JCS_UNKNOWN:
  161198. cinfo->num_components = cinfo->input_components;
  161199. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  161200. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  161201. MAX_COMPONENTS);
  161202. for (ci = 0; ci < cinfo->num_components; ci++) {
  161203. SET_COMP(ci, ci, 1,1, 0, 0,0);
  161204. }
  161205. break;
  161206. default:
  161207. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  161208. }
  161209. }
  161210. #ifdef C_PROGRESSIVE_SUPPORTED
  161211. LOCAL(jpeg_scan_info *)
  161212. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  161213. int Ss, int Se, int Ah, int Al)
  161214. /* Support routine: generate one scan for specified component */
  161215. {
  161216. scanptr->comps_in_scan = 1;
  161217. scanptr->component_index[0] = ci;
  161218. scanptr->Ss = Ss;
  161219. scanptr->Se = Se;
  161220. scanptr->Ah = Ah;
  161221. scanptr->Al = Al;
  161222. scanptr++;
  161223. return scanptr;
  161224. }
  161225. LOCAL(jpeg_scan_info *)
  161226. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  161227. int Ss, int Se, int Ah, int Al)
  161228. /* Support routine: generate one scan for each component */
  161229. {
  161230. int ci;
  161231. for (ci = 0; ci < ncomps; ci++) {
  161232. scanptr->comps_in_scan = 1;
  161233. scanptr->component_index[0] = ci;
  161234. scanptr->Ss = Ss;
  161235. scanptr->Se = Se;
  161236. scanptr->Ah = Ah;
  161237. scanptr->Al = Al;
  161238. scanptr++;
  161239. }
  161240. return scanptr;
  161241. }
  161242. LOCAL(jpeg_scan_info *)
  161243. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  161244. /* Support routine: generate interleaved DC scan if possible, else N scans */
  161245. {
  161246. int ci;
  161247. if (ncomps <= MAX_COMPS_IN_SCAN) {
  161248. /* Single interleaved DC scan */
  161249. scanptr->comps_in_scan = ncomps;
  161250. for (ci = 0; ci < ncomps; ci++)
  161251. scanptr->component_index[ci] = ci;
  161252. scanptr->Ss = scanptr->Se = 0;
  161253. scanptr->Ah = Ah;
  161254. scanptr->Al = Al;
  161255. scanptr++;
  161256. } else {
  161257. /* Noninterleaved DC scan for each component */
  161258. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  161259. }
  161260. return scanptr;
  161261. }
  161262. /*
  161263. * Create a recommended progressive-JPEG script.
  161264. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  161265. */
  161266. GLOBAL(void)
  161267. jpeg_simple_progression (j_compress_ptr cinfo)
  161268. {
  161269. int ncomps = cinfo->num_components;
  161270. int nscans;
  161271. jpeg_scan_info * scanptr;
  161272. /* Safety check to ensure start_compress not called yet. */
  161273. if (cinfo->global_state != CSTATE_START)
  161274. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161275. /* Figure space needed for script. Calculation must match code below! */
  161276. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161277. /* Custom script for YCbCr color images. */
  161278. nscans = 10;
  161279. } else {
  161280. /* All-purpose script for other color spaces. */
  161281. if (ncomps > MAX_COMPS_IN_SCAN)
  161282. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  161283. else
  161284. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  161285. }
  161286. /* Allocate space for script.
  161287. * We need to put it in the permanent pool in case the application performs
  161288. * multiple compressions without changing the settings. To avoid a memory
  161289. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  161290. * object, we try to re-use previously allocated space, and we allocate
  161291. * enough space to handle YCbCr even if initially asked for grayscale.
  161292. */
  161293. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  161294. cinfo->script_space_size = MAX(nscans, 10);
  161295. cinfo->script_space = (jpeg_scan_info *)
  161296. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161297. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  161298. }
  161299. scanptr = cinfo->script_space;
  161300. cinfo->scan_info = scanptr;
  161301. cinfo->num_scans = nscans;
  161302. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  161303. /* Custom script for YCbCr color images. */
  161304. /* Initial DC scan */
  161305. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161306. /* Initial AC scan: get some luma data out in a hurry */
  161307. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  161308. /* Chroma data is too small to be worth expending many scans on */
  161309. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  161310. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  161311. /* Complete spectral selection for luma AC */
  161312. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  161313. /* Refine next bit of luma AC */
  161314. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  161315. /* Finish DC successive approximation */
  161316. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161317. /* Finish AC successive approximation */
  161318. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  161319. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  161320. /* Luma bottom bit comes last since it's usually largest scan */
  161321. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  161322. } else {
  161323. /* All-purpose script for other color spaces. */
  161324. /* Successive approximation first pass */
  161325. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  161326. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  161327. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  161328. /* Successive approximation second pass */
  161329. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  161330. /* Successive approximation final pass */
  161331. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  161332. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  161333. }
  161334. }
  161335. #endif /* C_PROGRESSIVE_SUPPORTED */
  161336. /********* End of inlined file: jcparam.c *********/
  161337. /********* Start of inlined file: jcphuff.c *********/
  161338. #define JPEG_INTERNALS
  161339. #ifdef C_PROGRESSIVE_SUPPORTED
  161340. /* Expanded entropy encoder object for progressive Huffman encoding. */
  161341. typedef struct {
  161342. struct jpeg_entropy_encoder pub; /* public fields */
  161343. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  161344. boolean gather_statistics;
  161345. /* Bit-level coding status.
  161346. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  161347. */
  161348. JOCTET * next_output_byte; /* => next byte to write in buffer */
  161349. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  161350. INT32 put_buffer; /* current bit-accumulation buffer */
  161351. int put_bits; /* # of bits now in it */
  161352. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  161353. /* Coding status for DC components */
  161354. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  161355. /* Coding status for AC components */
  161356. int ac_tbl_no; /* the table number of the single component */
  161357. unsigned int EOBRUN; /* run length of EOBs */
  161358. unsigned int BE; /* # of buffered correction bits before MCU */
  161359. char * bit_buffer; /* buffer for correction bits (1 per char) */
  161360. /* packing correction bits tightly would save some space but cost time... */
  161361. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  161362. int next_restart_num; /* next restart number to write (0-7) */
  161363. /* Pointers to derived tables (these workspaces have image lifespan).
  161364. * Since any one scan codes only DC or only AC, we only need one set
  161365. * of tables, not one for DC and one for AC.
  161366. */
  161367. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  161368. /* Statistics tables for optimization; again, one set is enough */
  161369. long * count_ptrs[NUM_HUFF_TBLS];
  161370. } phuff_entropy_encoder;
  161371. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  161372. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  161373. * buffer can hold. Larger sizes may slightly improve compression, but
  161374. * 1000 is already well into the realm of overkill.
  161375. * The minimum safe size is 64 bits.
  161376. */
  161377. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  161378. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  161379. * We assume that int right shift is unsigned if INT32 right shift is,
  161380. * which should be safe.
  161381. */
  161382. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161383. #define ISHIFT_TEMPS int ishift_temp;
  161384. #define IRIGHT_SHIFT(x,shft) \
  161385. ((ishift_temp = (x)) < 0 ? \
  161386. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  161387. (ishift_temp >> (shft)))
  161388. #else
  161389. #define ISHIFT_TEMPS
  161390. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  161391. #endif
  161392. /* Forward declarations */
  161393. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  161394. JBLOCKROW *MCU_data));
  161395. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  161396. JBLOCKROW *MCU_data));
  161397. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  161398. JBLOCKROW *MCU_data));
  161399. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  161400. JBLOCKROW *MCU_data));
  161401. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  161402. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  161403. /*
  161404. * Initialize for a Huffman-compressed scan using progressive JPEG.
  161405. */
  161406. METHODDEF(void)
  161407. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  161408. {
  161409. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161410. boolean is_DC_band;
  161411. int ci, tbl;
  161412. jpeg_component_info * compptr;
  161413. entropy->cinfo = cinfo;
  161414. entropy->gather_statistics = gather_statistics;
  161415. is_DC_band = (cinfo->Ss == 0);
  161416. /* We assume jcmaster.c already validated the scan parameters. */
  161417. /* Select execution routines */
  161418. if (cinfo->Ah == 0) {
  161419. if (is_DC_band)
  161420. entropy->pub.encode_mcu = encode_mcu_DC_first;
  161421. else
  161422. entropy->pub.encode_mcu = encode_mcu_AC_first;
  161423. } else {
  161424. if (is_DC_band)
  161425. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  161426. else {
  161427. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  161428. /* AC refinement needs a correction bit buffer */
  161429. if (entropy->bit_buffer == NULL)
  161430. entropy->bit_buffer = (char *)
  161431. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161432. MAX_CORR_BITS * SIZEOF(char));
  161433. }
  161434. }
  161435. if (gather_statistics)
  161436. entropy->pub.finish_pass = finish_pass_gather_phuff;
  161437. else
  161438. entropy->pub.finish_pass = finish_pass_phuff;
  161439. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  161440. * for AC coefficients.
  161441. */
  161442. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161443. compptr = cinfo->cur_comp_info[ci];
  161444. /* Initialize DC predictions to 0 */
  161445. entropy->last_dc_val[ci] = 0;
  161446. /* Get table index */
  161447. if (is_DC_band) {
  161448. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161449. continue;
  161450. tbl = compptr->dc_tbl_no;
  161451. } else {
  161452. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  161453. }
  161454. if (gather_statistics) {
  161455. /* Check for invalid table index */
  161456. /* (make_c_derived_tbl does this in the other path) */
  161457. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  161458. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  161459. /* Allocate and zero the statistics tables */
  161460. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  161461. if (entropy->count_ptrs[tbl] == NULL)
  161462. entropy->count_ptrs[tbl] = (long *)
  161463. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161464. 257 * SIZEOF(long));
  161465. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  161466. } else {
  161467. /* Compute derived values for Huffman table */
  161468. /* We may do this more than once for a table, but it's not expensive */
  161469. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  161470. & entropy->derived_tbls[tbl]);
  161471. }
  161472. }
  161473. /* Initialize AC stuff */
  161474. entropy->EOBRUN = 0;
  161475. entropy->BE = 0;
  161476. /* Initialize bit buffer to empty */
  161477. entropy->put_buffer = 0;
  161478. entropy->put_bits = 0;
  161479. /* Initialize restart stuff */
  161480. entropy->restarts_to_go = cinfo->restart_interval;
  161481. entropy->next_restart_num = 0;
  161482. }
  161483. /* Outputting bytes to the file.
  161484. * NB: these must be called only when actually outputting,
  161485. * that is, entropy->gather_statistics == FALSE.
  161486. */
  161487. /* Emit a byte */
  161488. #define emit_byte(entropy,val) \
  161489. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  161490. if (--(entropy)->free_in_buffer == 0) \
  161491. dump_buffer_p(entropy); }
  161492. LOCAL(void)
  161493. dump_buffer_p (phuff_entropy_ptr entropy)
  161494. /* Empty the output buffer; we do not support suspension in this module. */
  161495. {
  161496. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  161497. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  161498. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  161499. /* After a successful buffer dump, must reset buffer pointers */
  161500. entropy->next_output_byte = dest->next_output_byte;
  161501. entropy->free_in_buffer = dest->free_in_buffer;
  161502. }
  161503. /* Outputting bits to the file */
  161504. /* Only the right 24 bits of put_buffer are used; the valid bits are
  161505. * left-justified in this part. At most 16 bits can be passed to emit_bits
  161506. * in one call, and we never retain more than 7 bits in put_buffer
  161507. * between calls, so 24 bits are sufficient.
  161508. */
  161509. INLINE
  161510. LOCAL(void)
  161511. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  161512. /* Emit some bits, unless we are in gather mode */
  161513. {
  161514. /* This routine is heavily used, so it's worth coding tightly. */
  161515. register INT32 put_buffer = (INT32) code;
  161516. register int put_bits = entropy->put_bits;
  161517. /* if size is 0, caller used an invalid Huffman table entry */
  161518. if (size == 0)
  161519. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161520. if (entropy->gather_statistics)
  161521. return; /* do nothing if we're only getting stats */
  161522. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  161523. put_bits += size; /* new number of bits in buffer */
  161524. put_buffer <<= 24 - put_bits; /* align incoming bits */
  161525. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  161526. while (put_bits >= 8) {
  161527. int c = (int) ((put_buffer >> 16) & 0xFF);
  161528. emit_byte(entropy, c);
  161529. if (c == 0xFF) { /* need to stuff a zero byte? */
  161530. emit_byte(entropy, 0);
  161531. }
  161532. put_buffer <<= 8;
  161533. put_bits -= 8;
  161534. }
  161535. entropy->put_buffer = put_buffer; /* update variables */
  161536. entropy->put_bits = put_bits;
  161537. }
  161538. LOCAL(void)
  161539. flush_bits_p (phuff_entropy_ptr entropy)
  161540. {
  161541. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  161542. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  161543. entropy->put_bits = 0;
  161544. }
  161545. /*
  161546. * Emit (or just count) a Huffman symbol.
  161547. */
  161548. INLINE
  161549. LOCAL(void)
  161550. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  161551. {
  161552. if (entropy->gather_statistics)
  161553. entropy->count_ptrs[tbl_no][symbol]++;
  161554. else {
  161555. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  161556. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  161557. }
  161558. }
  161559. /*
  161560. * Emit bits from a correction bit buffer.
  161561. */
  161562. LOCAL(void)
  161563. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  161564. unsigned int nbits)
  161565. {
  161566. if (entropy->gather_statistics)
  161567. return; /* no real work */
  161568. while (nbits > 0) {
  161569. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  161570. bufstart++;
  161571. nbits--;
  161572. }
  161573. }
  161574. /*
  161575. * Emit any pending EOBRUN symbol.
  161576. */
  161577. LOCAL(void)
  161578. emit_eobrun (phuff_entropy_ptr entropy)
  161579. {
  161580. register int temp, nbits;
  161581. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  161582. temp = entropy->EOBRUN;
  161583. nbits = 0;
  161584. while ((temp >>= 1))
  161585. nbits++;
  161586. /* safety check: shouldn't happen given limited correction-bit buffer */
  161587. if (nbits > 14)
  161588. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  161589. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  161590. if (nbits)
  161591. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  161592. entropy->EOBRUN = 0;
  161593. /* Emit any buffered correction bits */
  161594. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  161595. entropy->BE = 0;
  161596. }
  161597. }
  161598. /*
  161599. * Emit a restart marker & resynchronize predictions.
  161600. */
  161601. LOCAL(void)
  161602. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  161603. {
  161604. int ci;
  161605. emit_eobrun(entropy);
  161606. if (! entropy->gather_statistics) {
  161607. flush_bits_p(entropy);
  161608. emit_byte(entropy, 0xFF);
  161609. emit_byte(entropy, JPEG_RST0 + restart_num);
  161610. }
  161611. if (entropy->cinfo->Ss == 0) {
  161612. /* Re-initialize DC predictions to 0 */
  161613. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  161614. entropy->last_dc_val[ci] = 0;
  161615. } else {
  161616. /* Re-initialize all AC-related fields to 0 */
  161617. entropy->EOBRUN = 0;
  161618. entropy->BE = 0;
  161619. }
  161620. }
  161621. /*
  161622. * MCU encoding for DC initial scan (either spectral selection,
  161623. * or first pass of successive approximation).
  161624. */
  161625. METHODDEF(boolean)
  161626. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161627. {
  161628. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161629. register int temp, temp2;
  161630. register int nbits;
  161631. int blkn, ci;
  161632. int Al = cinfo->Al;
  161633. JBLOCKROW block;
  161634. jpeg_component_info * compptr;
  161635. ISHIFT_TEMPS
  161636. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161637. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161638. /* Emit restart marker if needed */
  161639. if (cinfo->restart_interval)
  161640. if (entropy->restarts_to_go == 0)
  161641. emit_restart_p(entropy, entropy->next_restart_num);
  161642. /* Encode the MCU data blocks */
  161643. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161644. block = MCU_data[blkn];
  161645. ci = cinfo->MCU_membership[blkn];
  161646. compptr = cinfo->cur_comp_info[ci];
  161647. /* Compute the DC value after the required point transform by Al.
  161648. * This is simply an arithmetic right shift.
  161649. */
  161650. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  161651. /* DC differences are figured on the point-transformed values. */
  161652. temp = temp2 - entropy->last_dc_val[ci];
  161653. entropy->last_dc_val[ci] = temp2;
  161654. /* Encode the DC coefficient difference per section G.1.2.1 */
  161655. temp2 = temp;
  161656. if (temp < 0) {
  161657. temp = -temp; /* temp is abs value of input */
  161658. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  161659. /* This code assumes we are on a two's complement machine */
  161660. temp2--;
  161661. }
  161662. /* Find the number of bits needed for the magnitude of the coefficient */
  161663. nbits = 0;
  161664. while (temp) {
  161665. nbits++;
  161666. temp >>= 1;
  161667. }
  161668. /* Check for out-of-range coefficient values.
  161669. * Since we're encoding a difference, the range limit is twice as much.
  161670. */
  161671. if (nbits > MAX_COEF_BITS+1)
  161672. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161673. /* Count/emit the Huffman-coded symbol for the number of bits */
  161674. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  161675. /* Emit that number of bits of the value, if positive, */
  161676. /* or the complement of its magnitude, if negative. */
  161677. if (nbits) /* emit_bits rejects calls with size 0 */
  161678. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161679. }
  161680. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161681. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161682. /* Update restart-interval state too */
  161683. if (cinfo->restart_interval) {
  161684. if (entropy->restarts_to_go == 0) {
  161685. entropy->restarts_to_go = cinfo->restart_interval;
  161686. entropy->next_restart_num++;
  161687. entropy->next_restart_num &= 7;
  161688. }
  161689. entropy->restarts_to_go--;
  161690. }
  161691. return TRUE;
  161692. }
  161693. /*
  161694. * MCU encoding for AC initial scan (either spectral selection,
  161695. * or first pass of successive approximation).
  161696. */
  161697. METHODDEF(boolean)
  161698. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161699. {
  161700. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161701. register int temp, temp2;
  161702. register int nbits;
  161703. register int r, k;
  161704. int Se = cinfo->Se;
  161705. int Al = cinfo->Al;
  161706. JBLOCKROW block;
  161707. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161708. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161709. /* Emit restart marker if needed */
  161710. if (cinfo->restart_interval)
  161711. if (entropy->restarts_to_go == 0)
  161712. emit_restart_p(entropy, entropy->next_restart_num);
  161713. /* Encode the MCU data block */
  161714. block = MCU_data[0];
  161715. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  161716. r = 0; /* r = run length of zeros */
  161717. for (k = cinfo->Ss; k <= Se; k++) {
  161718. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  161719. r++;
  161720. continue;
  161721. }
  161722. /* We must apply the point transform by Al. For AC coefficients this
  161723. * is an integer division with rounding towards 0. To do this portably
  161724. * in C, we shift after obtaining the absolute value; so the code is
  161725. * interwoven with finding the abs value (temp) and output bits (temp2).
  161726. */
  161727. if (temp < 0) {
  161728. temp = -temp; /* temp is abs value of input */
  161729. temp >>= Al; /* apply the point transform */
  161730. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  161731. temp2 = ~temp;
  161732. } else {
  161733. temp >>= Al; /* apply the point transform */
  161734. temp2 = temp;
  161735. }
  161736. /* Watch out for case that nonzero coef is zero after point transform */
  161737. if (temp == 0) {
  161738. r++;
  161739. continue;
  161740. }
  161741. /* Emit any pending EOBRUN */
  161742. if (entropy->EOBRUN > 0)
  161743. emit_eobrun(entropy);
  161744. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  161745. while (r > 15) {
  161746. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161747. r -= 16;
  161748. }
  161749. /* Find the number of bits needed for the magnitude of the coefficient */
  161750. nbits = 1; /* there must be at least one 1 bit */
  161751. while ((temp >>= 1))
  161752. nbits++;
  161753. /* Check for out-of-range coefficient values */
  161754. if (nbits > MAX_COEF_BITS)
  161755. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  161756. /* Count/emit Huffman symbol for run length / number of bits */
  161757. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  161758. /* Emit that number of bits of the value, if positive, */
  161759. /* or the complement of its magnitude, if negative. */
  161760. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  161761. r = 0; /* reset zero run length */
  161762. }
  161763. if (r > 0) { /* If there are trailing zeroes, */
  161764. entropy->EOBRUN++; /* count an EOB */
  161765. if (entropy->EOBRUN == 0x7FFF)
  161766. emit_eobrun(entropy); /* force it out to avoid overflow */
  161767. }
  161768. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161769. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161770. /* Update restart-interval state too */
  161771. if (cinfo->restart_interval) {
  161772. if (entropy->restarts_to_go == 0) {
  161773. entropy->restarts_to_go = cinfo->restart_interval;
  161774. entropy->next_restart_num++;
  161775. entropy->next_restart_num &= 7;
  161776. }
  161777. entropy->restarts_to_go--;
  161778. }
  161779. return TRUE;
  161780. }
  161781. /*
  161782. * MCU encoding for DC successive approximation refinement scan.
  161783. * Note: we assume such scans can be multi-component, although the spec
  161784. * is not very clear on the point.
  161785. */
  161786. METHODDEF(boolean)
  161787. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161788. {
  161789. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161790. register int temp;
  161791. int blkn;
  161792. int Al = cinfo->Al;
  161793. JBLOCKROW block;
  161794. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161795. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161796. /* Emit restart marker if needed */
  161797. if (cinfo->restart_interval)
  161798. if (entropy->restarts_to_go == 0)
  161799. emit_restart_p(entropy, entropy->next_restart_num);
  161800. /* Encode the MCU data blocks */
  161801. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  161802. block = MCU_data[blkn];
  161803. /* We simply emit the Al'th bit of the DC coefficient value. */
  161804. temp = (*block)[0];
  161805. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  161806. }
  161807. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161808. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161809. /* Update restart-interval state too */
  161810. if (cinfo->restart_interval) {
  161811. if (entropy->restarts_to_go == 0) {
  161812. entropy->restarts_to_go = cinfo->restart_interval;
  161813. entropy->next_restart_num++;
  161814. entropy->next_restart_num &= 7;
  161815. }
  161816. entropy->restarts_to_go--;
  161817. }
  161818. return TRUE;
  161819. }
  161820. /*
  161821. * MCU encoding for AC successive approximation refinement scan.
  161822. */
  161823. METHODDEF(boolean)
  161824. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  161825. {
  161826. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161827. register int temp;
  161828. register int r, k;
  161829. int EOB;
  161830. char *BR_buffer;
  161831. unsigned int BR;
  161832. int Se = cinfo->Se;
  161833. int Al = cinfo->Al;
  161834. JBLOCKROW block;
  161835. int absvalues[DCTSIZE2];
  161836. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161837. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161838. /* Emit restart marker if needed */
  161839. if (cinfo->restart_interval)
  161840. if (entropy->restarts_to_go == 0)
  161841. emit_restart_p(entropy, entropy->next_restart_num);
  161842. /* Encode the MCU data block */
  161843. block = MCU_data[0];
  161844. /* It is convenient to make a pre-pass to determine the transformed
  161845. * coefficients' absolute values and the EOB position.
  161846. */
  161847. EOB = 0;
  161848. for (k = cinfo->Ss; k <= Se; k++) {
  161849. temp = (*block)[jpeg_natural_order[k]];
  161850. /* We must apply the point transform by Al. For AC coefficients this
  161851. * is an integer division with rounding towards 0. To do this portably
  161852. * in C, we shift after obtaining the absolute value.
  161853. */
  161854. if (temp < 0)
  161855. temp = -temp; /* temp is abs value of input */
  161856. temp >>= Al; /* apply the point transform */
  161857. absvalues[k] = temp; /* save abs value for main pass */
  161858. if (temp == 1)
  161859. EOB = k; /* EOB = index of last newly-nonzero coef */
  161860. }
  161861. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  161862. r = 0; /* r = run length of zeros */
  161863. BR = 0; /* BR = count of buffered bits added now */
  161864. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  161865. for (k = cinfo->Ss; k <= Se; k++) {
  161866. if ((temp = absvalues[k]) == 0) {
  161867. r++;
  161868. continue;
  161869. }
  161870. /* Emit any required ZRLs, but not if they can be folded into EOB */
  161871. while (r > 15 && k <= EOB) {
  161872. /* emit any pending EOBRUN and the BE correction bits */
  161873. emit_eobrun(entropy);
  161874. /* Emit ZRL */
  161875. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  161876. r -= 16;
  161877. /* Emit buffered correction bits that must be associated with ZRL */
  161878. emit_buffered_bits(entropy, BR_buffer, BR);
  161879. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161880. BR = 0;
  161881. }
  161882. /* If the coef was previously nonzero, it only needs a correction bit.
  161883. * NOTE: a straight translation of the spec's figure G.7 would suggest
  161884. * that we also need to test r > 15. But if r > 15, we can only get here
  161885. * if k > EOB, which implies that this coefficient is not 1.
  161886. */
  161887. if (temp > 1) {
  161888. /* The correction bit is the next bit of the absolute value. */
  161889. BR_buffer[BR++] = (char) (temp & 1);
  161890. continue;
  161891. }
  161892. /* Emit any pending EOBRUN and the BE correction bits */
  161893. emit_eobrun(entropy);
  161894. /* Count/emit Huffman symbol for run length / number of bits */
  161895. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  161896. /* Emit output bit for newly-nonzero coef */
  161897. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  161898. emit_bits_p(entropy, (unsigned int) temp, 1);
  161899. /* Emit buffered correction bits that must be associated with this code */
  161900. emit_buffered_bits(entropy, BR_buffer, BR);
  161901. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  161902. BR = 0;
  161903. r = 0; /* reset zero run length */
  161904. }
  161905. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  161906. entropy->EOBRUN++; /* count an EOB */
  161907. entropy->BE += BR; /* concat my correction bits to older ones */
  161908. /* We force out the EOB if we risk either:
  161909. * 1. overflow of the EOB counter;
  161910. * 2. overflow of the correction bit buffer during the next MCU.
  161911. */
  161912. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  161913. emit_eobrun(entropy);
  161914. }
  161915. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161916. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161917. /* Update restart-interval state too */
  161918. if (cinfo->restart_interval) {
  161919. if (entropy->restarts_to_go == 0) {
  161920. entropy->restarts_to_go = cinfo->restart_interval;
  161921. entropy->next_restart_num++;
  161922. entropy->next_restart_num &= 7;
  161923. }
  161924. entropy->restarts_to_go--;
  161925. }
  161926. return TRUE;
  161927. }
  161928. /*
  161929. * Finish up at the end of a Huffman-compressed progressive scan.
  161930. */
  161931. METHODDEF(void)
  161932. finish_pass_phuff (j_compress_ptr cinfo)
  161933. {
  161934. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161935. entropy->next_output_byte = cinfo->dest->next_output_byte;
  161936. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  161937. /* Flush out any buffered data */
  161938. emit_eobrun(entropy);
  161939. flush_bits_p(entropy);
  161940. cinfo->dest->next_output_byte = entropy->next_output_byte;
  161941. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  161942. }
  161943. /*
  161944. * Finish up a statistics-gathering pass and create the new Huffman tables.
  161945. */
  161946. METHODDEF(void)
  161947. finish_pass_gather_phuff (j_compress_ptr cinfo)
  161948. {
  161949. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  161950. boolean is_DC_band;
  161951. int ci, tbl;
  161952. jpeg_component_info * compptr;
  161953. JHUFF_TBL **htblptr;
  161954. boolean did[NUM_HUFF_TBLS];
  161955. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  161956. emit_eobrun(entropy);
  161957. is_DC_band = (cinfo->Ss == 0);
  161958. /* It's important not to apply jpeg_gen_optimal_table more than once
  161959. * per table, because it clobbers the input frequency counts!
  161960. */
  161961. MEMZERO(did, SIZEOF(did));
  161962. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161963. compptr = cinfo->cur_comp_info[ci];
  161964. if (is_DC_band) {
  161965. if (cinfo->Ah != 0) /* DC refinement needs no table */
  161966. continue;
  161967. tbl = compptr->dc_tbl_no;
  161968. } else {
  161969. tbl = compptr->ac_tbl_no;
  161970. }
  161971. if (! did[tbl]) {
  161972. if (is_DC_band)
  161973. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  161974. else
  161975. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  161976. if (*htblptr == NULL)
  161977. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  161978. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  161979. did[tbl] = TRUE;
  161980. }
  161981. }
  161982. }
  161983. /*
  161984. * Module initialization routine for progressive Huffman entropy encoding.
  161985. */
  161986. GLOBAL(void)
  161987. jinit_phuff_encoder (j_compress_ptr cinfo)
  161988. {
  161989. phuff_entropy_ptr entropy;
  161990. int i;
  161991. entropy = (phuff_entropy_ptr)
  161992. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  161993. SIZEOF(phuff_entropy_encoder));
  161994. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  161995. entropy->pub.start_pass = start_pass_phuff;
  161996. /* Mark tables unallocated */
  161997. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161998. entropy->derived_tbls[i] = NULL;
  161999. entropy->count_ptrs[i] = NULL;
  162000. }
  162001. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  162002. }
  162003. #endif /* C_PROGRESSIVE_SUPPORTED */
  162004. /********* End of inlined file: jcphuff.c *********/
  162005. /********* Start of inlined file: jcprepct.c *********/
  162006. #define JPEG_INTERNALS
  162007. /* At present, jcsample.c can request context rows only for smoothing.
  162008. * In the future, we might also need context rows for CCIR601 sampling
  162009. * or other more-complex downsampling procedures. The code to support
  162010. * context rows should be compiled only if needed.
  162011. */
  162012. #ifdef INPUT_SMOOTHING_SUPPORTED
  162013. #define CONTEXT_ROWS_SUPPORTED
  162014. #endif
  162015. /*
  162016. * For the simple (no-context-row) case, we just need to buffer one
  162017. * row group's worth of pixels for the downsampling step. At the bottom of
  162018. * the image, we pad to a full row group by replicating the last pixel row.
  162019. * The downsampler's last output row is then replicated if needed to pad
  162020. * out to a full iMCU row.
  162021. *
  162022. * When providing context rows, we must buffer three row groups' worth of
  162023. * pixels. Three row groups are physically allocated, but the row pointer
  162024. * arrays are made five row groups high, with the extra pointers above and
  162025. * below "wrapping around" to point to the last and first real row groups.
  162026. * This allows the downsampler to access the proper context rows.
  162027. * At the top and bottom of the image, we create dummy context rows by
  162028. * copying the first or last real pixel row. This copying could be avoided
  162029. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  162030. * trouble on the compression side.
  162031. */
  162032. /* Private buffer controller object */
  162033. typedef struct {
  162034. struct jpeg_c_prep_controller pub; /* public fields */
  162035. /* Downsampling input buffer. This buffer holds color-converted data
  162036. * until we have enough to do a downsample step.
  162037. */
  162038. JSAMPARRAY color_buf[MAX_COMPONENTS];
  162039. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  162040. int next_buf_row; /* index of next row to store in color_buf */
  162041. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  162042. int this_row_group; /* starting row index of group to process */
  162043. int next_buf_stop; /* downsample when we reach this index */
  162044. #endif
  162045. } my_prep_controller;
  162046. typedef my_prep_controller * my_prep_ptr;
  162047. /*
  162048. * Initialize for a processing pass.
  162049. */
  162050. METHODDEF(void)
  162051. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162052. {
  162053. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162054. if (pass_mode != JBUF_PASS_THRU)
  162055. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162056. /* Initialize total-height counter for detecting bottom of image */
  162057. prep->rows_to_go = cinfo->image_height;
  162058. /* Mark the conversion buffer empty */
  162059. prep->next_buf_row = 0;
  162060. #ifdef CONTEXT_ROWS_SUPPORTED
  162061. /* Preset additional state variables for context mode.
  162062. * These aren't used in non-context mode, so we needn't test which mode.
  162063. */
  162064. prep->this_row_group = 0;
  162065. /* Set next_buf_stop to stop after two row groups have been read in. */
  162066. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  162067. #endif
  162068. }
  162069. /*
  162070. * Expand an image vertically from height input_rows to height output_rows,
  162071. * by duplicating the bottom row.
  162072. */
  162073. LOCAL(void)
  162074. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  162075. int input_rows, int output_rows)
  162076. {
  162077. register int row;
  162078. for (row = input_rows; row < output_rows; row++) {
  162079. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  162080. 1, num_cols);
  162081. }
  162082. }
  162083. /*
  162084. * Process some data in the simple no-context case.
  162085. *
  162086. * Preprocessor output data is counted in "row groups". A row group
  162087. * is defined to be v_samp_factor sample rows of each component.
  162088. * Downsampling will produce this much data from each max_v_samp_factor
  162089. * input rows.
  162090. */
  162091. METHODDEF(void)
  162092. pre_process_data (j_compress_ptr cinfo,
  162093. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162094. JDIMENSION in_rows_avail,
  162095. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162096. JDIMENSION out_row_groups_avail)
  162097. {
  162098. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162099. int numrows, ci;
  162100. JDIMENSION inrows;
  162101. jpeg_component_info * compptr;
  162102. while (*in_row_ctr < in_rows_avail &&
  162103. *out_row_group_ctr < out_row_groups_avail) {
  162104. /* Do color conversion to fill the conversion buffer. */
  162105. inrows = in_rows_avail - *in_row_ctr;
  162106. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  162107. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162108. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162109. prep->color_buf,
  162110. (JDIMENSION) prep->next_buf_row,
  162111. numrows);
  162112. *in_row_ctr += numrows;
  162113. prep->next_buf_row += numrows;
  162114. prep->rows_to_go -= numrows;
  162115. /* If at bottom of image, pad to fill the conversion buffer. */
  162116. if (prep->rows_to_go == 0 &&
  162117. prep->next_buf_row < cinfo->max_v_samp_factor) {
  162118. for (ci = 0; ci < cinfo->num_components; ci++) {
  162119. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162120. prep->next_buf_row, cinfo->max_v_samp_factor);
  162121. }
  162122. prep->next_buf_row = cinfo->max_v_samp_factor;
  162123. }
  162124. /* If we've filled the conversion buffer, empty it. */
  162125. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  162126. (*cinfo->downsample->downsample) (cinfo,
  162127. prep->color_buf, (JDIMENSION) 0,
  162128. output_buf, *out_row_group_ctr);
  162129. prep->next_buf_row = 0;
  162130. (*out_row_group_ctr)++;
  162131. }
  162132. /* If at bottom of image, pad the output to a full iMCU height.
  162133. * Note we assume the caller is providing a one-iMCU-height output buffer!
  162134. */
  162135. if (prep->rows_to_go == 0 &&
  162136. *out_row_group_ctr < out_row_groups_avail) {
  162137. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162138. ci++, compptr++) {
  162139. expand_bottom_edge(output_buf[ci],
  162140. compptr->width_in_blocks * DCTSIZE,
  162141. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  162142. (int) (out_row_groups_avail * compptr->v_samp_factor));
  162143. }
  162144. *out_row_group_ctr = out_row_groups_avail;
  162145. break; /* can exit outer loop without test */
  162146. }
  162147. }
  162148. }
  162149. #ifdef CONTEXT_ROWS_SUPPORTED
  162150. /*
  162151. * Process some data in the context case.
  162152. */
  162153. METHODDEF(void)
  162154. pre_process_context (j_compress_ptr cinfo,
  162155. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  162156. JDIMENSION in_rows_avail,
  162157. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  162158. JDIMENSION out_row_groups_avail)
  162159. {
  162160. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162161. int numrows, ci;
  162162. int buf_height = cinfo->max_v_samp_factor * 3;
  162163. JDIMENSION inrows;
  162164. while (*out_row_group_ctr < out_row_groups_avail) {
  162165. if (*in_row_ctr < in_rows_avail) {
  162166. /* Do color conversion to fill the conversion buffer. */
  162167. inrows = in_rows_avail - *in_row_ctr;
  162168. numrows = prep->next_buf_stop - prep->next_buf_row;
  162169. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  162170. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  162171. prep->color_buf,
  162172. (JDIMENSION) prep->next_buf_row,
  162173. numrows);
  162174. /* Pad at top of image, if first time through */
  162175. if (prep->rows_to_go == cinfo->image_height) {
  162176. for (ci = 0; ci < cinfo->num_components; ci++) {
  162177. int row;
  162178. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  162179. jcopy_sample_rows(prep->color_buf[ci], 0,
  162180. prep->color_buf[ci], -row,
  162181. 1, cinfo->image_width);
  162182. }
  162183. }
  162184. }
  162185. *in_row_ctr += numrows;
  162186. prep->next_buf_row += numrows;
  162187. prep->rows_to_go -= numrows;
  162188. } else {
  162189. /* Return for more data, unless we are at the bottom of the image. */
  162190. if (prep->rows_to_go != 0)
  162191. break;
  162192. /* When at bottom of image, pad to fill the conversion buffer. */
  162193. if (prep->next_buf_row < prep->next_buf_stop) {
  162194. for (ci = 0; ci < cinfo->num_components; ci++) {
  162195. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  162196. prep->next_buf_row, prep->next_buf_stop);
  162197. }
  162198. prep->next_buf_row = prep->next_buf_stop;
  162199. }
  162200. }
  162201. /* If we've gotten enough data, downsample a row group. */
  162202. if (prep->next_buf_row == prep->next_buf_stop) {
  162203. (*cinfo->downsample->downsample) (cinfo,
  162204. prep->color_buf,
  162205. (JDIMENSION) prep->this_row_group,
  162206. output_buf, *out_row_group_ctr);
  162207. (*out_row_group_ctr)++;
  162208. /* Advance pointers with wraparound as necessary. */
  162209. prep->this_row_group += cinfo->max_v_samp_factor;
  162210. if (prep->this_row_group >= buf_height)
  162211. prep->this_row_group = 0;
  162212. if (prep->next_buf_row >= buf_height)
  162213. prep->next_buf_row = 0;
  162214. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  162215. }
  162216. }
  162217. }
  162218. /*
  162219. * Create the wrapped-around downsampling input buffer needed for context mode.
  162220. */
  162221. LOCAL(void)
  162222. create_context_buffer (j_compress_ptr cinfo)
  162223. {
  162224. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  162225. int rgroup_height = cinfo->max_v_samp_factor;
  162226. int ci, i;
  162227. jpeg_component_info * compptr;
  162228. JSAMPARRAY true_buffer, fake_buffer;
  162229. /* Grab enough space for fake row pointers for all the components;
  162230. * we need five row groups' worth of pointers for each component.
  162231. */
  162232. fake_buffer = (JSAMPARRAY)
  162233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162234. (cinfo->num_components * 5 * rgroup_height) *
  162235. SIZEOF(JSAMPROW));
  162236. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162237. ci++, compptr++) {
  162238. /* Allocate the actual buffer space (3 row groups) for this component.
  162239. * We make the buffer wide enough to allow the downsampler to edge-expand
  162240. * horizontally within the buffer, if it so chooses.
  162241. */
  162242. true_buffer = (*cinfo->mem->alloc_sarray)
  162243. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162244. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162245. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162246. (JDIMENSION) (3 * rgroup_height));
  162247. /* Copy true buffer row pointers into the middle of the fake row array */
  162248. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  162249. 3 * rgroup_height * SIZEOF(JSAMPROW));
  162250. /* Fill in the above and below wraparound pointers */
  162251. for (i = 0; i < rgroup_height; i++) {
  162252. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  162253. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  162254. }
  162255. prep->color_buf[ci] = fake_buffer + rgroup_height;
  162256. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  162257. }
  162258. }
  162259. #endif /* CONTEXT_ROWS_SUPPORTED */
  162260. /*
  162261. * Initialize preprocessing controller.
  162262. */
  162263. GLOBAL(void)
  162264. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162265. {
  162266. my_prep_ptr prep;
  162267. int ci;
  162268. jpeg_component_info * compptr;
  162269. if (need_full_buffer) /* safety check */
  162270. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162271. prep = (my_prep_ptr)
  162272. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162273. SIZEOF(my_prep_controller));
  162274. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  162275. prep->pub.start_pass = start_pass_prep;
  162276. /* Allocate the color conversion buffer.
  162277. * We make the buffer wide enough to allow the downsampler to edge-expand
  162278. * horizontally within the buffer, if it so chooses.
  162279. */
  162280. if (cinfo->downsample->need_context_rows) {
  162281. /* Set up to provide context rows */
  162282. #ifdef CONTEXT_ROWS_SUPPORTED
  162283. prep->pub.pre_process_data = pre_process_context;
  162284. create_context_buffer(cinfo);
  162285. #else
  162286. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162287. #endif
  162288. } else {
  162289. /* No context, just make it tall enough for one row group */
  162290. prep->pub.pre_process_data = pre_process_data;
  162291. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162292. ci++, compptr++) {
  162293. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  162294. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162295. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  162296. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  162297. (JDIMENSION) cinfo->max_v_samp_factor);
  162298. }
  162299. }
  162300. }
  162301. /********* End of inlined file: jcprepct.c *********/
  162302. /********* Start of inlined file: jcsample.c *********/
  162303. #define JPEG_INTERNALS
  162304. /* Pointer to routine to downsample a single component */
  162305. typedef JMETHOD(void, downsample1_ptr,
  162306. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162307. JSAMPARRAY input_data, JSAMPARRAY output_data));
  162308. /* Private subobject */
  162309. typedef struct {
  162310. struct jpeg_downsampler pub; /* public fields */
  162311. /* Downsampling method pointers, one per component */
  162312. downsample1_ptr methods[MAX_COMPONENTS];
  162313. } my_downsampler;
  162314. typedef my_downsampler * my_downsample_ptr;
  162315. /*
  162316. * Initialize for a downsampling pass.
  162317. */
  162318. METHODDEF(void)
  162319. start_pass_downsample (j_compress_ptr cinfo)
  162320. {
  162321. /* no work for now */
  162322. }
  162323. /*
  162324. * Expand a component horizontally from width input_cols to width output_cols,
  162325. * by duplicating the rightmost samples.
  162326. */
  162327. LOCAL(void)
  162328. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  162329. JDIMENSION input_cols, JDIMENSION output_cols)
  162330. {
  162331. register JSAMPROW ptr;
  162332. register JSAMPLE pixval;
  162333. register int count;
  162334. int row;
  162335. int numcols = (int) (output_cols - input_cols);
  162336. if (numcols > 0) {
  162337. for (row = 0; row < num_rows; row++) {
  162338. ptr = image_data[row] + input_cols;
  162339. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  162340. for (count = numcols; count > 0; count--)
  162341. *ptr++ = pixval;
  162342. }
  162343. }
  162344. }
  162345. /*
  162346. * Do downsampling for a whole row group (all components).
  162347. *
  162348. * In this version we simply downsample each component independently.
  162349. */
  162350. METHODDEF(void)
  162351. sep_downsample (j_compress_ptr cinfo,
  162352. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  162353. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  162354. {
  162355. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  162356. int ci;
  162357. jpeg_component_info * compptr;
  162358. JSAMPARRAY in_ptr, out_ptr;
  162359. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162360. ci++, compptr++) {
  162361. in_ptr = input_buf[ci] + in_row_index;
  162362. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  162363. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  162364. }
  162365. }
  162366. /*
  162367. * Downsample pixel values of a single component.
  162368. * One row group is processed per call.
  162369. * This version handles arbitrary integral sampling ratios, without smoothing.
  162370. * Note that this version is not actually used for customary sampling ratios.
  162371. */
  162372. METHODDEF(void)
  162373. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162374. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162375. {
  162376. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  162377. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  162378. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162379. JSAMPROW inptr, outptr;
  162380. INT32 outvalue;
  162381. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  162382. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  162383. numpix = h_expand * v_expand;
  162384. numpix2 = numpix/2;
  162385. /* Expand input data enough to let all the output samples be generated
  162386. * by the standard loop. Special-casing padded output would be more
  162387. * efficient.
  162388. */
  162389. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162390. cinfo->image_width, output_cols * h_expand);
  162391. inrow = 0;
  162392. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162393. outptr = output_data[outrow];
  162394. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  162395. outcol++, outcol_h += h_expand) {
  162396. outvalue = 0;
  162397. for (v = 0; v < v_expand; v++) {
  162398. inptr = input_data[inrow+v] + outcol_h;
  162399. for (h = 0; h < h_expand; h++) {
  162400. outvalue += (INT32) GETJSAMPLE(*inptr++);
  162401. }
  162402. }
  162403. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  162404. }
  162405. inrow += v_expand;
  162406. }
  162407. }
  162408. /*
  162409. * Downsample pixel values of a single component.
  162410. * This version handles the special case of a full-size component,
  162411. * without smoothing.
  162412. */
  162413. METHODDEF(void)
  162414. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162415. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162416. {
  162417. /* Copy the data */
  162418. jcopy_sample_rows(input_data, 0, output_data, 0,
  162419. cinfo->max_v_samp_factor, cinfo->image_width);
  162420. /* Edge-expand */
  162421. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  162422. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  162423. }
  162424. /*
  162425. * Downsample pixel values of a single component.
  162426. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  162427. * without smoothing.
  162428. *
  162429. * A note about the "bias" calculations: when rounding fractional values to
  162430. * integer, we do not want to always round 0.5 up to the next integer.
  162431. * If we did that, we'd introduce a noticeable bias towards larger values.
  162432. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  162433. * alternate pixel locations (a simple ordered dither pattern).
  162434. */
  162435. METHODDEF(void)
  162436. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162437. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162438. {
  162439. int outrow;
  162440. JDIMENSION outcol;
  162441. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162442. register JSAMPROW inptr, outptr;
  162443. register int bias;
  162444. /* Expand input data enough to let all the output samples be generated
  162445. * by the standard loop. Special-casing padded output would be more
  162446. * efficient.
  162447. */
  162448. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162449. cinfo->image_width, output_cols * 2);
  162450. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162451. outptr = output_data[outrow];
  162452. inptr = input_data[outrow];
  162453. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  162454. for (outcol = 0; outcol < output_cols; outcol++) {
  162455. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  162456. + bias) >> 1);
  162457. bias ^= 1; /* 0=>1, 1=>0 */
  162458. inptr += 2;
  162459. }
  162460. }
  162461. }
  162462. /*
  162463. * Downsample pixel values of a single component.
  162464. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162465. * without smoothing.
  162466. */
  162467. METHODDEF(void)
  162468. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162469. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162470. {
  162471. int inrow, outrow;
  162472. JDIMENSION outcol;
  162473. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162474. register JSAMPROW inptr0, inptr1, outptr;
  162475. register int bias;
  162476. /* Expand input data enough to let all the output samples be generated
  162477. * by the standard loop. Special-casing padded output would be more
  162478. * efficient.
  162479. */
  162480. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  162481. cinfo->image_width, output_cols * 2);
  162482. inrow = 0;
  162483. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162484. outptr = output_data[outrow];
  162485. inptr0 = input_data[inrow];
  162486. inptr1 = input_data[inrow+1];
  162487. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  162488. for (outcol = 0; outcol < output_cols; outcol++) {
  162489. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162490. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  162491. + bias) >> 2);
  162492. bias ^= 3; /* 1=>2, 2=>1 */
  162493. inptr0 += 2; inptr1 += 2;
  162494. }
  162495. inrow += 2;
  162496. }
  162497. }
  162498. #ifdef INPUT_SMOOTHING_SUPPORTED
  162499. /*
  162500. * Downsample pixel values of a single component.
  162501. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  162502. * with smoothing. One row of context is required.
  162503. */
  162504. METHODDEF(void)
  162505. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162506. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162507. {
  162508. int inrow, outrow;
  162509. JDIMENSION colctr;
  162510. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162511. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  162512. INT32 membersum, neighsum, memberscale, neighscale;
  162513. /* Expand input data enough to let all the output samples be generated
  162514. * by the standard loop. Special-casing padded output would be more
  162515. * efficient.
  162516. */
  162517. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162518. cinfo->image_width, output_cols * 2);
  162519. /* We don't bother to form the individual "smoothed" input pixel values;
  162520. * we can directly compute the output which is the average of the four
  162521. * smoothed values. Each of the four member pixels contributes a fraction
  162522. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  162523. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  162524. * output. The four corner-adjacent neighbor pixels contribute a fraction
  162525. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  162526. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  162527. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  162528. * factors are scaled by 2^16 = 65536.
  162529. * Also recall that SF = smoothing_factor / 1024.
  162530. */
  162531. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  162532. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  162533. inrow = 0;
  162534. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162535. outptr = output_data[outrow];
  162536. inptr0 = input_data[inrow];
  162537. inptr1 = input_data[inrow+1];
  162538. above_ptr = input_data[inrow-1];
  162539. below_ptr = input_data[inrow+2];
  162540. /* Special case for first column: pretend column -1 is same as column 0 */
  162541. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162542. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162543. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162544. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162545. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  162546. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  162547. neighsum += neighsum;
  162548. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  162549. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  162550. membersum = membersum * memberscale + neighsum * neighscale;
  162551. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162552. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162553. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162554. /* sum of pixels directly mapped to this output element */
  162555. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162556. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162557. /* sum of edge-neighbor pixels */
  162558. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162559. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162560. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  162561. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  162562. /* The edge-neighbors count twice as much as corner-neighbors */
  162563. neighsum += neighsum;
  162564. /* Add in the corner-neighbors */
  162565. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  162566. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  162567. /* form final output scaled up by 2^16 */
  162568. membersum = membersum * memberscale + neighsum * neighscale;
  162569. /* round, descale and output it */
  162570. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162571. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  162572. }
  162573. /* Special case for last column */
  162574. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  162575. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  162576. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  162577. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  162578. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  162579. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  162580. neighsum += neighsum;
  162581. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  162582. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  162583. membersum = membersum * memberscale + neighsum * neighscale;
  162584. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162585. inrow += 2;
  162586. }
  162587. }
  162588. /*
  162589. * Downsample pixel values of a single component.
  162590. * This version handles the special case of a full-size component,
  162591. * with smoothing. One row of context is required.
  162592. */
  162593. METHODDEF(void)
  162594. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  162595. JSAMPARRAY input_data, JSAMPARRAY output_data)
  162596. {
  162597. int outrow;
  162598. JDIMENSION colctr;
  162599. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  162600. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  162601. INT32 membersum, neighsum, memberscale, neighscale;
  162602. int colsum, lastcolsum, nextcolsum;
  162603. /* Expand input data enough to let all the output samples be generated
  162604. * by the standard loop. Special-casing padded output would be more
  162605. * efficient.
  162606. */
  162607. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  162608. cinfo->image_width, output_cols);
  162609. /* Each of the eight neighbor pixels contributes a fraction SF to the
  162610. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  162611. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  162612. * Also recall that SF = smoothing_factor / 1024.
  162613. */
  162614. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  162615. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  162616. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  162617. outptr = output_data[outrow];
  162618. inptr = input_data[outrow];
  162619. above_ptr = input_data[outrow-1];
  162620. below_ptr = input_data[outrow+1];
  162621. /* Special case for first column */
  162622. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  162623. GETJSAMPLE(*inptr);
  162624. membersum = GETJSAMPLE(*inptr++);
  162625. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162626. GETJSAMPLE(*inptr);
  162627. neighsum = colsum + (colsum - membersum) + nextcolsum;
  162628. membersum = membersum * memberscale + neighsum * neighscale;
  162629. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162630. lastcolsum = colsum; colsum = nextcolsum;
  162631. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  162632. membersum = GETJSAMPLE(*inptr++);
  162633. above_ptr++; below_ptr++;
  162634. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  162635. GETJSAMPLE(*inptr);
  162636. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  162637. membersum = membersum * memberscale + neighsum * neighscale;
  162638. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  162639. lastcolsum = colsum; colsum = nextcolsum;
  162640. }
  162641. /* Special case for last column */
  162642. membersum = GETJSAMPLE(*inptr);
  162643. neighsum = lastcolsum + (colsum - membersum) + colsum;
  162644. membersum = membersum * memberscale + neighsum * neighscale;
  162645. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  162646. }
  162647. }
  162648. #endif /* INPUT_SMOOTHING_SUPPORTED */
  162649. /*
  162650. * Module initialization routine for downsampling.
  162651. * Note that we must select a routine for each component.
  162652. */
  162653. GLOBAL(void)
  162654. jinit_downsampler (j_compress_ptr cinfo)
  162655. {
  162656. my_downsample_ptr downsample;
  162657. int ci;
  162658. jpeg_component_info * compptr;
  162659. boolean smoothok = TRUE;
  162660. downsample = (my_downsample_ptr)
  162661. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162662. SIZEOF(my_downsampler));
  162663. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  162664. downsample->pub.start_pass = start_pass_downsample;
  162665. downsample->pub.downsample = sep_downsample;
  162666. downsample->pub.need_context_rows = FALSE;
  162667. if (cinfo->CCIR601_sampling)
  162668. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  162669. /* Verify we can handle the sampling factors, and set up method pointers */
  162670. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162671. ci++, compptr++) {
  162672. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  162673. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162674. #ifdef INPUT_SMOOTHING_SUPPORTED
  162675. if (cinfo->smoothing_factor) {
  162676. downsample->methods[ci] = fullsize_smooth_downsample;
  162677. downsample->pub.need_context_rows = TRUE;
  162678. } else
  162679. #endif
  162680. downsample->methods[ci] = fullsize_downsample;
  162681. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162682. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  162683. smoothok = FALSE;
  162684. downsample->methods[ci] = h2v1_downsample;
  162685. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  162686. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  162687. #ifdef INPUT_SMOOTHING_SUPPORTED
  162688. if (cinfo->smoothing_factor) {
  162689. downsample->methods[ci] = h2v2_smooth_downsample;
  162690. downsample->pub.need_context_rows = TRUE;
  162691. } else
  162692. #endif
  162693. downsample->methods[ci] = h2v2_downsample;
  162694. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  162695. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  162696. smoothok = FALSE;
  162697. downsample->methods[ci] = int_downsample;
  162698. } else
  162699. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  162700. }
  162701. #ifdef INPUT_SMOOTHING_SUPPORTED
  162702. if (cinfo->smoothing_factor && !smoothok)
  162703. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  162704. #endif
  162705. }
  162706. /********* End of inlined file: jcsample.c *********/
  162707. /********* Start of inlined file: jctrans.c *********/
  162708. #define JPEG_INTERNALS
  162709. /* Forward declarations */
  162710. LOCAL(void) transencode_master_selection
  162711. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162712. LOCAL(void) transencode_coef_controller
  162713. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  162714. /*
  162715. * Compression initialization for writing raw-coefficient data.
  162716. * Before calling this, all parameters and a data destination must be set up.
  162717. * Call jpeg_finish_compress() to actually write the data.
  162718. *
  162719. * The number of passed virtual arrays must match cinfo->num_components.
  162720. * Note that the virtual arrays need not be filled or even realized at
  162721. * the time write_coefficients is called; indeed, if the virtual arrays
  162722. * were requested from this compression object's memory manager, they
  162723. * typically will be realized during this routine and filled afterwards.
  162724. */
  162725. GLOBAL(void)
  162726. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  162727. {
  162728. if (cinfo->global_state != CSTATE_START)
  162729. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162730. /* Mark all tables to be written */
  162731. jpeg_suppress_tables(cinfo, FALSE);
  162732. /* (Re)initialize error mgr and destination modules */
  162733. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162734. (*cinfo->dest->init_destination) (cinfo);
  162735. /* Perform master selection of active modules */
  162736. transencode_master_selection(cinfo, coef_arrays);
  162737. /* Wait for jpeg_finish_compress() call */
  162738. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  162739. cinfo->global_state = CSTATE_WRCOEFS;
  162740. }
  162741. /*
  162742. * Initialize the compression object with default parameters,
  162743. * then copy from the source object all parameters needed for lossless
  162744. * transcoding. Parameters that can be varied without loss (such as
  162745. * scan script and Huffman optimization) are left in their default states.
  162746. */
  162747. GLOBAL(void)
  162748. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  162749. j_compress_ptr dstinfo)
  162750. {
  162751. JQUANT_TBL ** qtblptr;
  162752. jpeg_component_info *incomp, *outcomp;
  162753. JQUANT_TBL *c_quant, *slot_quant;
  162754. int tblno, ci, coefi;
  162755. /* Safety check to ensure start_compress not called yet. */
  162756. if (dstinfo->global_state != CSTATE_START)
  162757. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  162758. /* Copy fundamental image dimensions */
  162759. dstinfo->image_width = srcinfo->image_width;
  162760. dstinfo->image_height = srcinfo->image_height;
  162761. dstinfo->input_components = srcinfo->num_components;
  162762. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  162763. /* Initialize all parameters to default values */
  162764. jpeg_set_defaults(dstinfo);
  162765. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  162766. * Fix it to get the right header markers for the image colorspace.
  162767. */
  162768. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  162769. dstinfo->data_precision = srcinfo->data_precision;
  162770. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  162771. /* Copy the source's quantization tables. */
  162772. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  162773. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  162774. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  162775. if (*qtblptr == NULL)
  162776. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  162777. MEMCOPY((*qtblptr)->quantval,
  162778. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  162779. SIZEOF((*qtblptr)->quantval));
  162780. (*qtblptr)->sent_table = FALSE;
  162781. }
  162782. }
  162783. /* Copy the source's per-component info.
  162784. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  162785. */
  162786. dstinfo->num_components = srcinfo->num_components;
  162787. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  162788. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  162789. MAX_COMPONENTS);
  162790. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  162791. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  162792. outcomp->component_id = incomp->component_id;
  162793. outcomp->h_samp_factor = incomp->h_samp_factor;
  162794. outcomp->v_samp_factor = incomp->v_samp_factor;
  162795. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  162796. /* Make sure saved quantization table for component matches the qtable
  162797. * slot. If not, the input file re-used this qtable slot.
  162798. * IJG encoder currently cannot duplicate this.
  162799. */
  162800. tblno = outcomp->quant_tbl_no;
  162801. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  162802. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  162803. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  162804. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  162805. c_quant = incomp->quant_table;
  162806. if (c_quant != NULL) {
  162807. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  162808. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  162809. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  162810. }
  162811. }
  162812. /* Note: we do not copy the source's Huffman table assignments;
  162813. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  162814. */
  162815. }
  162816. /* Also copy JFIF version and resolution information, if available.
  162817. * Strictly speaking this isn't "critical" info, but it's nearly
  162818. * always appropriate to copy it if available. In particular,
  162819. * if the application chooses to copy JFIF 1.02 extension markers from
  162820. * the source file, we need to copy the version to make sure we don't
  162821. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  162822. * We will *not*, however, copy version info from mislabeled "2.01" files.
  162823. */
  162824. if (srcinfo->saw_JFIF_marker) {
  162825. if (srcinfo->JFIF_major_version == 1) {
  162826. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  162827. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  162828. }
  162829. dstinfo->density_unit = srcinfo->density_unit;
  162830. dstinfo->X_density = srcinfo->X_density;
  162831. dstinfo->Y_density = srcinfo->Y_density;
  162832. }
  162833. }
  162834. /*
  162835. * Master selection of compression modules for transcoding.
  162836. * This substitutes for jcinit.c's initialization of the full compressor.
  162837. */
  162838. LOCAL(void)
  162839. transencode_master_selection (j_compress_ptr cinfo,
  162840. jvirt_barray_ptr * coef_arrays)
  162841. {
  162842. /* Although we don't actually use input_components for transcoding,
  162843. * jcmaster.c's initial_setup will complain if input_components is 0.
  162844. */
  162845. cinfo->input_components = 1;
  162846. /* Initialize master control (includes parameter checking/processing) */
  162847. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  162848. /* Entropy encoding: either Huffman or arithmetic coding. */
  162849. if (cinfo->arith_code) {
  162850. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  162851. } else {
  162852. if (cinfo->progressive_mode) {
  162853. #ifdef C_PROGRESSIVE_SUPPORTED
  162854. jinit_phuff_encoder(cinfo);
  162855. #else
  162856. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162857. #endif
  162858. } else
  162859. jinit_huff_encoder(cinfo);
  162860. }
  162861. /* We need a special coefficient buffer controller. */
  162862. transencode_coef_controller(cinfo, coef_arrays);
  162863. jinit_marker_writer(cinfo);
  162864. /* We can now tell the memory manager to allocate virtual arrays. */
  162865. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  162866. /* Write the datastream header (SOI, JFIF) immediately.
  162867. * Frame and scan headers are postponed till later.
  162868. * This lets application insert special markers after the SOI.
  162869. */
  162870. (*cinfo->marker->write_file_header) (cinfo);
  162871. }
  162872. /*
  162873. * The rest of this file is a special implementation of the coefficient
  162874. * buffer controller. This is similar to jccoefct.c, but it handles only
  162875. * output from presupplied virtual arrays. Furthermore, we generate any
  162876. * dummy padding blocks on-the-fly rather than expecting them to be present
  162877. * in the arrays.
  162878. */
  162879. /* Private buffer controller object */
  162880. typedef struct {
  162881. struct jpeg_c_coef_controller pub; /* public fields */
  162882. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162883. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162884. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162885. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162886. /* Virtual block array for each component. */
  162887. jvirt_barray_ptr * whole_image;
  162888. /* Workspace for constructing dummy blocks at right/bottom edges. */
  162889. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  162890. } my_coef_controller2;
  162891. typedef my_coef_controller2 * my_coef_ptr2;
  162892. LOCAL(void)
  162893. start_iMCU_row2 (j_compress_ptr cinfo)
  162894. /* Reset within-iMCU-row counters for a new row */
  162895. {
  162896. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162897. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162898. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162899. * But at the bottom of the image, process only what's left.
  162900. */
  162901. if (cinfo->comps_in_scan > 1) {
  162902. coef->MCU_rows_per_iMCU_row = 1;
  162903. } else {
  162904. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162905. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162906. else
  162907. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162908. }
  162909. coef->mcu_ctr = 0;
  162910. coef->MCU_vert_offset = 0;
  162911. }
  162912. /*
  162913. * Initialize for a processing pass.
  162914. */
  162915. METHODDEF(void)
  162916. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162917. {
  162918. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162919. if (pass_mode != JBUF_CRANK_DEST)
  162920. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162921. coef->iMCU_row_num = 0;
  162922. start_iMCU_row2(cinfo);
  162923. }
  162924. /*
  162925. * Process some data.
  162926. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162927. * per call, ie, v_samp_factor block rows for each component in the scan.
  162928. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162929. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162930. *
  162931. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162932. */
  162933. METHODDEF(boolean)
  162934. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162935. {
  162936. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  162937. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162938. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162939. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162940. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  162941. JDIMENSION start_col;
  162942. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162943. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162944. JBLOCKROW buffer_ptr;
  162945. jpeg_component_info *compptr;
  162946. /* Align the virtual buffers for the components used in this scan. */
  162947. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162948. compptr = cinfo->cur_comp_info[ci];
  162949. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162950. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162951. coef->iMCU_row_num * compptr->v_samp_factor,
  162952. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162953. }
  162954. /* Loop to process one whole iMCU row */
  162955. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162956. yoffset++) {
  162957. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162958. MCU_col_num++) {
  162959. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162960. blkn = 0; /* index of current DCT block within MCU */
  162961. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162962. compptr = cinfo->cur_comp_info[ci];
  162963. start_col = MCU_col_num * compptr->MCU_width;
  162964. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162965. : compptr->last_col_width;
  162966. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162967. if (coef->iMCU_row_num < last_iMCU_row ||
  162968. yindex+yoffset < compptr->last_row_height) {
  162969. /* Fill in pointers to real blocks in this row */
  162970. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162971. for (xindex = 0; xindex < blockcnt; xindex++)
  162972. MCU_buffer[blkn++] = buffer_ptr++;
  162973. } else {
  162974. /* At bottom of image, need a whole row of dummy blocks */
  162975. xindex = 0;
  162976. }
  162977. /* Fill in any dummy blocks needed in this row.
  162978. * Dummy blocks are filled in the same way as in jccoefct.c:
  162979. * all zeroes in the AC entries, DC entries equal to previous
  162980. * block's DC value. The init routine has already zeroed the
  162981. * AC entries, so we need only set the DC entries correctly.
  162982. */
  162983. for (; xindex < compptr->MCU_width; xindex++) {
  162984. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  162985. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  162986. blkn++;
  162987. }
  162988. }
  162989. }
  162990. /* Try to write the MCU. */
  162991. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  162992. /* Suspension forced; update state counters and exit */
  162993. coef->MCU_vert_offset = yoffset;
  162994. coef->mcu_ctr = MCU_col_num;
  162995. return FALSE;
  162996. }
  162997. }
  162998. /* Completed an MCU row, but perhaps not an iMCU row */
  162999. coef->mcu_ctr = 0;
  163000. }
  163001. /* Completed the iMCU row, advance counters for next one */
  163002. coef->iMCU_row_num++;
  163003. start_iMCU_row2(cinfo);
  163004. return TRUE;
  163005. }
  163006. /*
  163007. * Initialize coefficient buffer controller.
  163008. *
  163009. * Each passed coefficient array must be the right size for that
  163010. * coefficient: width_in_blocks wide and height_in_blocks high,
  163011. * with unitheight at least v_samp_factor.
  163012. */
  163013. LOCAL(void)
  163014. transencode_coef_controller (j_compress_ptr cinfo,
  163015. jvirt_barray_ptr * coef_arrays)
  163016. {
  163017. my_coef_ptr2 coef;
  163018. JBLOCKROW buffer;
  163019. int i;
  163020. coef = (my_coef_ptr2)
  163021. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163022. SIZEOF(my_coef_controller2));
  163023. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163024. coef->pub.start_pass = start_pass_coef2;
  163025. coef->pub.compress_data = compress_output2;
  163026. /* Save pointer to virtual arrays */
  163027. coef->whole_image = coef_arrays;
  163028. /* Allocate and pre-zero space for dummy DCT blocks. */
  163029. buffer = (JBLOCKROW)
  163030. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163031. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163032. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163033. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163034. coef->dummy_buffer[i] = buffer + i;
  163035. }
  163036. }
  163037. /********* End of inlined file: jctrans.c *********/
  163038. /********* Start of inlined file: jdapistd.c *********/
  163039. #define JPEG_INTERNALS
  163040. /* Forward declarations */
  163041. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  163042. /*
  163043. * Decompression initialization.
  163044. * jpeg_read_header must be completed before calling this.
  163045. *
  163046. * If a multipass operating mode was selected, this will do all but the
  163047. * last pass, and thus may take a great deal of time.
  163048. *
  163049. * Returns FALSE if suspended. The return value need be inspected only if
  163050. * a suspending data source is used.
  163051. */
  163052. GLOBAL(boolean)
  163053. jpeg_start_decompress (j_decompress_ptr cinfo)
  163054. {
  163055. if (cinfo->global_state == DSTATE_READY) {
  163056. /* First call: initialize master control, select active modules */
  163057. jinit_master_decompress(cinfo);
  163058. if (cinfo->buffered_image) {
  163059. /* No more work here; expecting jpeg_start_output next */
  163060. cinfo->global_state = DSTATE_BUFIMAGE;
  163061. return TRUE;
  163062. }
  163063. cinfo->global_state = DSTATE_PRELOAD;
  163064. }
  163065. if (cinfo->global_state == DSTATE_PRELOAD) {
  163066. /* If file has multiple scans, absorb them all into the coef buffer */
  163067. if (cinfo->inputctl->has_multiple_scans) {
  163068. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163069. for (;;) {
  163070. int retcode;
  163071. /* Call progress monitor hook if present */
  163072. if (cinfo->progress != NULL)
  163073. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163074. /* Absorb some more input */
  163075. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163076. if (retcode == JPEG_SUSPENDED)
  163077. return FALSE;
  163078. if (retcode == JPEG_REACHED_EOI)
  163079. break;
  163080. /* Advance progress counter if appropriate */
  163081. if (cinfo->progress != NULL &&
  163082. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  163083. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  163084. /* jdmaster underestimated number of scans; ratchet up one scan */
  163085. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  163086. }
  163087. }
  163088. }
  163089. #else
  163090. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163091. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163092. }
  163093. cinfo->output_scan_number = cinfo->input_scan_number;
  163094. } else if (cinfo->global_state != DSTATE_PRESCAN)
  163095. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163096. /* Perform any dummy output passes, and set up for the final pass */
  163097. return output_pass_setup(cinfo);
  163098. }
  163099. /*
  163100. * Set up for an output pass, and perform any dummy pass(es) needed.
  163101. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  163102. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  163103. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  163104. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  163105. */
  163106. LOCAL(boolean)
  163107. output_pass_setup (j_decompress_ptr cinfo)
  163108. {
  163109. if (cinfo->global_state != DSTATE_PRESCAN) {
  163110. /* First call: do pass setup */
  163111. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163112. cinfo->output_scanline = 0;
  163113. cinfo->global_state = DSTATE_PRESCAN;
  163114. }
  163115. /* Loop over any required dummy passes */
  163116. while (cinfo->master->is_dummy_pass) {
  163117. #ifdef QUANT_2PASS_SUPPORTED
  163118. /* Crank through the dummy pass */
  163119. while (cinfo->output_scanline < cinfo->output_height) {
  163120. JDIMENSION last_scanline;
  163121. /* Call progress monitor hook if present */
  163122. if (cinfo->progress != NULL) {
  163123. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163124. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163125. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163126. }
  163127. /* Process some data */
  163128. last_scanline = cinfo->output_scanline;
  163129. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  163130. &cinfo->output_scanline, (JDIMENSION) 0);
  163131. if (cinfo->output_scanline == last_scanline)
  163132. return FALSE; /* No progress made, must suspend */
  163133. }
  163134. /* Finish up dummy pass, and set up for another one */
  163135. (*cinfo->master->finish_output_pass) (cinfo);
  163136. (*cinfo->master->prepare_for_output_pass) (cinfo);
  163137. cinfo->output_scanline = 0;
  163138. #else
  163139. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163140. #endif /* QUANT_2PASS_SUPPORTED */
  163141. }
  163142. /* Ready for application to drive output pass through
  163143. * jpeg_read_scanlines or jpeg_read_raw_data.
  163144. */
  163145. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  163146. return TRUE;
  163147. }
  163148. /*
  163149. * Read some scanlines of data from the JPEG decompressor.
  163150. *
  163151. * The return value will be the number of lines actually read.
  163152. * This may be less than the number requested in several cases,
  163153. * including bottom of image, data source suspension, and operating
  163154. * modes that emit multiple scanlines at a time.
  163155. *
  163156. * Note: we warn about excess calls to jpeg_read_scanlines() since
  163157. * this likely signals an application programmer error. However,
  163158. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  163159. */
  163160. GLOBAL(JDIMENSION)
  163161. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  163162. JDIMENSION max_lines)
  163163. {
  163164. JDIMENSION row_ctr;
  163165. if (cinfo->global_state != DSTATE_SCANNING)
  163166. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163167. if (cinfo->output_scanline >= cinfo->output_height) {
  163168. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163169. return 0;
  163170. }
  163171. /* Call progress monitor hook if present */
  163172. if (cinfo->progress != NULL) {
  163173. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163174. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163175. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163176. }
  163177. /* Process some data */
  163178. row_ctr = 0;
  163179. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  163180. cinfo->output_scanline += row_ctr;
  163181. return row_ctr;
  163182. }
  163183. /*
  163184. * Alternate entry point to read raw data.
  163185. * Processes exactly one iMCU row per call, unless suspended.
  163186. */
  163187. GLOBAL(JDIMENSION)
  163188. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  163189. JDIMENSION max_lines)
  163190. {
  163191. JDIMENSION lines_per_iMCU_row;
  163192. if (cinfo->global_state != DSTATE_RAW_OK)
  163193. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163194. if (cinfo->output_scanline >= cinfo->output_height) {
  163195. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  163196. return 0;
  163197. }
  163198. /* Call progress monitor hook if present */
  163199. if (cinfo->progress != NULL) {
  163200. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  163201. cinfo->progress->pass_limit = (long) cinfo->output_height;
  163202. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  163203. }
  163204. /* Verify that at least one iMCU row can be returned. */
  163205. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  163206. if (max_lines < lines_per_iMCU_row)
  163207. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  163208. /* Decompress directly into user's buffer. */
  163209. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  163210. return 0; /* suspension forced, can do nothing more */
  163211. /* OK, we processed one iMCU row. */
  163212. cinfo->output_scanline += lines_per_iMCU_row;
  163213. return lines_per_iMCU_row;
  163214. }
  163215. /* Additional entry points for buffered-image mode. */
  163216. #ifdef D_MULTISCAN_FILES_SUPPORTED
  163217. /*
  163218. * Initialize for an output pass in buffered-image mode.
  163219. */
  163220. GLOBAL(boolean)
  163221. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  163222. {
  163223. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  163224. cinfo->global_state != DSTATE_PRESCAN)
  163225. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163226. /* Limit scan number to valid range */
  163227. if (scan_number <= 0)
  163228. scan_number = 1;
  163229. if (cinfo->inputctl->eoi_reached &&
  163230. scan_number > cinfo->input_scan_number)
  163231. scan_number = cinfo->input_scan_number;
  163232. cinfo->output_scan_number = scan_number;
  163233. /* Perform any dummy output passes, and set up for the real pass */
  163234. return output_pass_setup(cinfo);
  163235. }
  163236. /*
  163237. * Finish up after an output pass in buffered-image mode.
  163238. *
  163239. * Returns FALSE if suspended. The return value need be inspected only if
  163240. * a suspending data source is used.
  163241. */
  163242. GLOBAL(boolean)
  163243. jpeg_finish_output (j_decompress_ptr cinfo)
  163244. {
  163245. if ((cinfo->global_state == DSTATE_SCANNING ||
  163246. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  163247. /* Terminate this pass. */
  163248. /* We do not require the whole pass to have been completed. */
  163249. (*cinfo->master->finish_output_pass) (cinfo);
  163250. cinfo->global_state = DSTATE_BUFPOST;
  163251. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  163252. /* BUFPOST = repeat call after a suspension, anything else is error */
  163253. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163254. }
  163255. /* Read markers looking for SOS or EOI */
  163256. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  163257. ! cinfo->inputctl->eoi_reached) {
  163258. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163259. return FALSE; /* Suspend, come back later */
  163260. }
  163261. cinfo->global_state = DSTATE_BUFIMAGE;
  163262. return TRUE;
  163263. }
  163264. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  163265. /********* End of inlined file: jdapistd.c *********/
  163266. /********* Start of inlined file: jdapimin.c *********/
  163267. #define JPEG_INTERNALS
  163268. /*
  163269. * Initialization of a JPEG decompression object.
  163270. * The error manager must already be set up (in case memory manager fails).
  163271. */
  163272. GLOBAL(void)
  163273. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  163274. {
  163275. int i;
  163276. /* Guard against version mismatches between library and caller. */
  163277. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  163278. if (version != JPEG_LIB_VERSION)
  163279. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  163280. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  163281. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  163282. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  163283. /* For debugging purposes, we zero the whole master structure.
  163284. * But the application has already set the err pointer, and may have set
  163285. * client_data, so we have to save and restore those fields.
  163286. * Note: if application hasn't set client_data, tools like Purify may
  163287. * complain here.
  163288. */
  163289. {
  163290. struct jpeg_error_mgr * err = cinfo->err;
  163291. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  163292. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  163293. cinfo->err = err;
  163294. cinfo->client_data = client_data;
  163295. }
  163296. cinfo->is_decompressor = TRUE;
  163297. /* Initialize a memory manager instance for this object */
  163298. jinit_memory_mgr((j_common_ptr) cinfo);
  163299. /* Zero out pointers to permanent structures. */
  163300. cinfo->progress = NULL;
  163301. cinfo->src = NULL;
  163302. for (i = 0; i < NUM_QUANT_TBLS; i++)
  163303. cinfo->quant_tbl_ptrs[i] = NULL;
  163304. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163305. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  163306. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  163307. }
  163308. /* Initialize marker processor so application can override methods
  163309. * for COM, APPn markers before calling jpeg_read_header.
  163310. */
  163311. cinfo->marker_list = NULL;
  163312. jinit_marker_reader(cinfo);
  163313. /* And initialize the overall input controller. */
  163314. jinit_input_controller(cinfo);
  163315. /* OK, I'm ready */
  163316. cinfo->global_state = DSTATE_START;
  163317. }
  163318. /*
  163319. * Destruction of a JPEG decompression object
  163320. */
  163321. GLOBAL(void)
  163322. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  163323. {
  163324. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  163325. }
  163326. /*
  163327. * Abort processing of a JPEG decompression operation,
  163328. * but don't destroy the object itself.
  163329. */
  163330. GLOBAL(void)
  163331. jpeg_abort_decompress (j_decompress_ptr cinfo)
  163332. {
  163333. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  163334. }
  163335. /*
  163336. * Set default decompression parameters.
  163337. */
  163338. LOCAL(void)
  163339. default_decompress_parms (j_decompress_ptr cinfo)
  163340. {
  163341. /* Guess the input colorspace, and set output colorspace accordingly. */
  163342. /* (Wish JPEG committee had provided a real way to specify this...) */
  163343. /* Note application may override our guesses. */
  163344. switch (cinfo->num_components) {
  163345. case 1:
  163346. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  163347. cinfo->out_color_space = JCS_GRAYSCALE;
  163348. break;
  163349. case 3:
  163350. if (cinfo->saw_JFIF_marker) {
  163351. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  163352. } else if (cinfo->saw_Adobe_marker) {
  163353. switch (cinfo->Adobe_transform) {
  163354. case 0:
  163355. cinfo->jpeg_color_space = JCS_RGB;
  163356. break;
  163357. case 1:
  163358. cinfo->jpeg_color_space = JCS_YCbCr;
  163359. break;
  163360. default:
  163361. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163362. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163363. break;
  163364. }
  163365. } else {
  163366. /* Saw no special markers, try to guess from the component IDs */
  163367. int cid0 = cinfo->comp_info[0].component_id;
  163368. int cid1 = cinfo->comp_info[1].component_id;
  163369. int cid2 = cinfo->comp_info[2].component_id;
  163370. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  163371. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  163372. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  163373. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  163374. else {
  163375. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  163376. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  163377. }
  163378. }
  163379. /* Always guess RGB is proper output colorspace. */
  163380. cinfo->out_color_space = JCS_RGB;
  163381. break;
  163382. case 4:
  163383. if (cinfo->saw_Adobe_marker) {
  163384. switch (cinfo->Adobe_transform) {
  163385. case 0:
  163386. cinfo->jpeg_color_space = JCS_CMYK;
  163387. break;
  163388. case 2:
  163389. cinfo->jpeg_color_space = JCS_YCCK;
  163390. break;
  163391. default:
  163392. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  163393. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  163394. break;
  163395. }
  163396. } else {
  163397. /* No special markers, assume straight CMYK. */
  163398. cinfo->jpeg_color_space = JCS_CMYK;
  163399. }
  163400. cinfo->out_color_space = JCS_CMYK;
  163401. break;
  163402. default:
  163403. cinfo->jpeg_color_space = JCS_UNKNOWN;
  163404. cinfo->out_color_space = JCS_UNKNOWN;
  163405. break;
  163406. }
  163407. /* Set defaults for other decompression parameters. */
  163408. cinfo->scale_num = 1; /* 1:1 scaling */
  163409. cinfo->scale_denom = 1;
  163410. cinfo->output_gamma = 1.0;
  163411. cinfo->buffered_image = FALSE;
  163412. cinfo->raw_data_out = FALSE;
  163413. cinfo->dct_method = JDCT_DEFAULT;
  163414. cinfo->do_fancy_upsampling = TRUE;
  163415. cinfo->do_block_smoothing = TRUE;
  163416. cinfo->quantize_colors = FALSE;
  163417. /* We set these in case application only sets quantize_colors. */
  163418. cinfo->dither_mode = JDITHER_FS;
  163419. #ifdef QUANT_2PASS_SUPPORTED
  163420. cinfo->two_pass_quantize = TRUE;
  163421. #else
  163422. cinfo->two_pass_quantize = FALSE;
  163423. #endif
  163424. cinfo->desired_number_of_colors = 256;
  163425. cinfo->colormap = NULL;
  163426. /* Initialize for no mode change in buffered-image mode. */
  163427. cinfo->enable_1pass_quant = FALSE;
  163428. cinfo->enable_external_quant = FALSE;
  163429. cinfo->enable_2pass_quant = FALSE;
  163430. }
  163431. /*
  163432. * Decompression startup: read start of JPEG datastream to see what's there.
  163433. * Need only initialize JPEG object and supply a data source before calling.
  163434. *
  163435. * This routine will read as far as the first SOS marker (ie, actual start of
  163436. * compressed data), and will save all tables and parameters in the JPEG
  163437. * object. It will also initialize the decompression parameters to default
  163438. * values, and finally return JPEG_HEADER_OK. On return, the application may
  163439. * adjust the decompression parameters and then call jpeg_start_decompress.
  163440. * (Or, if the application only wanted to determine the image parameters,
  163441. * the data need not be decompressed. In that case, call jpeg_abort or
  163442. * jpeg_destroy to release any temporary space.)
  163443. * If an abbreviated (tables only) datastream is presented, the routine will
  163444. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  163445. * re-use the JPEG object to read the abbreviated image datastream(s).
  163446. * It is unnecessary (but OK) to call jpeg_abort in this case.
  163447. * The JPEG_SUSPENDED return code only occurs if the data source module
  163448. * requests suspension of the decompressor. In this case the application
  163449. * should load more source data and then re-call jpeg_read_header to resume
  163450. * processing.
  163451. * If a non-suspending data source is used and require_image is TRUE, then the
  163452. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  163453. *
  163454. * This routine is now just a front end to jpeg_consume_input, with some
  163455. * extra error checking.
  163456. */
  163457. GLOBAL(int)
  163458. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  163459. {
  163460. int retcode;
  163461. if (cinfo->global_state != DSTATE_START &&
  163462. cinfo->global_state != DSTATE_INHEADER)
  163463. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163464. retcode = jpeg_consume_input(cinfo);
  163465. switch (retcode) {
  163466. case JPEG_REACHED_SOS:
  163467. retcode = JPEG_HEADER_OK;
  163468. break;
  163469. case JPEG_REACHED_EOI:
  163470. if (require_image) /* Complain if application wanted an image */
  163471. ERREXIT(cinfo, JERR_NO_IMAGE);
  163472. /* Reset to start state; it would be safer to require the application to
  163473. * call jpeg_abort, but we can't change it now for compatibility reasons.
  163474. * A side effect is to free any temporary memory (there shouldn't be any).
  163475. */
  163476. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  163477. retcode = JPEG_HEADER_TABLES_ONLY;
  163478. break;
  163479. case JPEG_SUSPENDED:
  163480. /* no work */
  163481. break;
  163482. }
  163483. return retcode;
  163484. }
  163485. /*
  163486. * Consume data in advance of what the decompressor requires.
  163487. * This can be called at any time once the decompressor object has
  163488. * been created and a data source has been set up.
  163489. *
  163490. * This routine is essentially a state machine that handles a couple
  163491. * of critical state-transition actions, namely initial setup and
  163492. * transition from header scanning to ready-for-start_decompress.
  163493. * All the actual input is done via the input controller's consume_input
  163494. * method.
  163495. */
  163496. GLOBAL(int)
  163497. jpeg_consume_input (j_decompress_ptr cinfo)
  163498. {
  163499. int retcode = JPEG_SUSPENDED;
  163500. /* NB: every possible DSTATE value should be listed in this switch */
  163501. switch (cinfo->global_state) {
  163502. case DSTATE_START:
  163503. /* Start-of-datastream actions: reset appropriate modules */
  163504. (*cinfo->inputctl->reset_input_controller) (cinfo);
  163505. /* Initialize application's data source module */
  163506. (*cinfo->src->init_source) (cinfo);
  163507. cinfo->global_state = DSTATE_INHEADER;
  163508. /*FALLTHROUGH*/
  163509. case DSTATE_INHEADER:
  163510. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163511. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  163512. /* Set up default parameters based on header data */
  163513. default_decompress_parms(cinfo);
  163514. /* Set global state: ready for start_decompress */
  163515. cinfo->global_state = DSTATE_READY;
  163516. }
  163517. break;
  163518. case DSTATE_READY:
  163519. /* Can't advance past first SOS until start_decompress is called */
  163520. retcode = JPEG_REACHED_SOS;
  163521. break;
  163522. case DSTATE_PRELOAD:
  163523. case DSTATE_PRESCAN:
  163524. case DSTATE_SCANNING:
  163525. case DSTATE_RAW_OK:
  163526. case DSTATE_BUFIMAGE:
  163527. case DSTATE_BUFPOST:
  163528. case DSTATE_STOPPING:
  163529. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  163530. break;
  163531. default:
  163532. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163533. }
  163534. return retcode;
  163535. }
  163536. /*
  163537. * Have we finished reading the input file?
  163538. */
  163539. GLOBAL(boolean)
  163540. jpeg_input_complete (j_decompress_ptr cinfo)
  163541. {
  163542. /* Check for valid jpeg object */
  163543. if (cinfo->global_state < DSTATE_START ||
  163544. cinfo->global_state > DSTATE_STOPPING)
  163545. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163546. return cinfo->inputctl->eoi_reached;
  163547. }
  163548. /*
  163549. * Is there more than one scan?
  163550. */
  163551. GLOBAL(boolean)
  163552. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  163553. {
  163554. /* Only valid after jpeg_read_header completes */
  163555. if (cinfo->global_state < DSTATE_READY ||
  163556. cinfo->global_state > DSTATE_STOPPING)
  163557. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163558. return cinfo->inputctl->has_multiple_scans;
  163559. }
  163560. /*
  163561. * Finish JPEG decompression.
  163562. *
  163563. * This will normally just verify the file trailer and release temp storage.
  163564. *
  163565. * Returns FALSE if suspended. The return value need be inspected only if
  163566. * a suspending data source is used.
  163567. */
  163568. GLOBAL(boolean)
  163569. jpeg_finish_decompress (j_decompress_ptr cinfo)
  163570. {
  163571. if ((cinfo->global_state == DSTATE_SCANNING ||
  163572. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  163573. /* Terminate final pass of non-buffered mode */
  163574. if (cinfo->output_scanline < cinfo->output_height)
  163575. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  163576. (*cinfo->master->finish_output_pass) (cinfo);
  163577. cinfo->global_state = DSTATE_STOPPING;
  163578. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  163579. /* Finishing after a buffered-image operation */
  163580. cinfo->global_state = DSTATE_STOPPING;
  163581. } else if (cinfo->global_state != DSTATE_STOPPING) {
  163582. /* STOPPING = repeat call after a suspension, anything else is error */
  163583. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  163584. }
  163585. /* Read until EOI */
  163586. while (! cinfo->inputctl->eoi_reached) {
  163587. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  163588. return FALSE; /* Suspend, come back later */
  163589. }
  163590. /* Do final cleanup */
  163591. (*cinfo->src->term_source) (cinfo);
  163592. /* We can use jpeg_abort to release memory and reset global_state */
  163593. jpeg_abort((j_common_ptr) cinfo);
  163594. return TRUE;
  163595. }
  163596. /********* End of inlined file: jdapimin.c *********/
  163597. /********* Start of inlined file: jdatasrc.c *********/
  163598. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  163599. /********* Start of inlined file: jerror.h *********/
  163600. /*
  163601. * To define the enum list of message codes, include this file without
  163602. * defining macro JMESSAGE. To create a message string table, include it
  163603. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  163604. */
  163605. #ifndef JMESSAGE
  163606. #ifndef JERROR_H
  163607. /* First time through, define the enum list */
  163608. #define JMAKE_ENUM_LIST
  163609. #else
  163610. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  163611. #define JMESSAGE(code,string)
  163612. #endif /* JERROR_H */
  163613. #endif /* JMESSAGE */
  163614. #ifdef JMAKE_ENUM_LIST
  163615. typedef enum {
  163616. #define JMESSAGE(code,string) code ,
  163617. #endif /* JMAKE_ENUM_LIST */
  163618. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  163619. /* For maintenance convenience, list is alphabetical by message code name */
  163620. JMESSAGE(JERR_ARITH_NOTIMPL,
  163621. "Sorry, there are legal restrictions on arithmetic coding")
  163622. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  163623. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  163624. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  163625. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  163626. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  163627. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  163628. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  163629. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  163630. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  163631. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  163632. JMESSAGE(JERR_BAD_LIB_VERSION,
  163633. "Wrong JPEG library version: library is %d, caller expects %d")
  163634. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  163635. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  163636. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  163637. JMESSAGE(JERR_BAD_PROGRESSION,
  163638. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  163639. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  163640. "Invalid progressive parameters at scan script entry %d")
  163641. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  163642. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  163643. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  163644. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  163645. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  163646. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  163647. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  163648. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  163649. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  163650. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  163651. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  163652. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  163653. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  163654. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  163655. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  163656. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  163657. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  163658. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  163659. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  163660. JMESSAGE(JERR_FILE_READ, "Input file read error")
  163661. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  163662. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  163663. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  163664. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  163665. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  163666. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  163667. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  163668. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  163669. "Cannot transcode due to multiple use of quantization table %d")
  163670. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  163671. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  163672. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  163673. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  163674. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  163675. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  163676. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  163677. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  163678. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  163679. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  163680. JMESSAGE(JERR_QUANT_COMPONENTS,
  163681. "Cannot quantize more than %d color components")
  163682. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  163683. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  163684. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  163685. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  163686. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  163687. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  163688. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  163689. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  163690. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  163691. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  163692. JMESSAGE(JERR_TFILE_WRITE,
  163693. "Write failed on temporary file --- out of disk space?")
  163694. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  163695. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  163696. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  163697. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  163698. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  163699. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  163700. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  163701. JMESSAGE(JMSG_VERSION, JVERSION)
  163702. JMESSAGE(JTRC_16BIT_TABLES,
  163703. "Caution: quantization tables are too coarse for baseline JPEG")
  163704. JMESSAGE(JTRC_ADOBE,
  163705. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  163706. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  163707. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  163708. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  163709. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  163710. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  163711. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  163712. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  163713. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  163714. JMESSAGE(JTRC_EOI, "End Of Image")
  163715. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  163716. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  163717. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  163718. "Warning: thumbnail image size does not match data length %u")
  163719. JMESSAGE(JTRC_JFIF_EXTENSION,
  163720. "JFIF extension marker: type 0x%02x, length %u")
  163721. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  163722. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  163723. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  163724. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  163725. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  163726. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  163727. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  163728. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  163729. JMESSAGE(JTRC_RST, "RST%d")
  163730. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  163731. "Smoothing not supported with nonstandard sampling ratios")
  163732. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  163733. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  163734. JMESSAGE(JTRC_SOI, "Start of Image")
  163735. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  163736. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  163737. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  163738. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  163739. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  163740. JMESSAGE(JTRC_THUMB_JPEG,
  163741. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  163742. JMESSAGE(JTRC_THUMB_PALETTE,
  163743. "JFIF extension marker: palette thumbnail image, length %u")
  163744. JMESSAGE(JTRC_THUMB_RGB,
  163745. "JFIF extension marker: RGB thumbnail image, length %u")
  163746. JMESSAGE(JTRC_UNKNOWN_IDS,
  163747. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  163748. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  163749. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  163750. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  163751. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  163752. "Inconsistent progression sequence for component %d coefficient %d")
  163753. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  163754. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  163755. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  163756. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  163757. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  163758. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  163759. JMESSAGE(JWRN_MUST_RESYNC,
  163760. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  163761. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  163762. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  163763. #ifdef JMAKE_ENUM_LIST
  163764. JMSG_LASTMSGCODE
  163765. } J_MESSAGE_CODE;
  163766. #undef JMAKE_ENUM_LIST
  163767. #endif /* JMAKE_ENUM_LIST */
  163768. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  163769. #undef JMESSAGE
  163770. #ifndef JERROR_H
  163771. #define JERROR_H
  163772. /* Macros to simplify using the error and trace message stuff */
  163773. /* The first parameter is either type of cinfo pointer */
  163774. /* Fatal errors (print message and exit) */
  163775. #define ERREXIT(cinfo,code) \
  163776. ((cinfo)->err->msg_code = (code), \
  163777. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163778. #define ERREXIT1(cinfo,code,p1) \
  163779. ((cinfo)->err->msg_code = (code), \
  163780. (cinfo)->err->msg_parm.i[0] = (p1), \
  163781. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163782. #define ERREXIT2(cinfo,code,p1,p2) \
  163783. ((cinfo)->err->msg_code = (code), \
  163784. (cinfo)->err->msg_parm.i[0] = (p1), \
  163785. (cinfo)->err->msg_parm.i[1] = (p2), \
  163786. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163787. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  163788. ((cinfo)->err->msg_code = (code), \
  163789. (cinfo)->err->msg_parm.i[0] = (p1), \
  163790. (cinfo)->err->msg_parm.i[1] = (p2), \
  163791. (cinfo)->err->msg_parm.i[2] = (p3), \
  163792. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163793. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  163794. ((cinfo)->err->msg_code = (code), \
  163795. (cinfo)->err->msg_parm.i[0] = (p1), \
  163796. (cinfo)->err->msg_parm.i[1] = (p2), \
  163797. (cinfo)->err->msg_parm.i[2] = (p3), \
  163798. (cinfo)->err->msg_parm.i[3] = (p4), \
  163799. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163800. #define ERREXITS(cinfo,code,str) \
  163801. ((cinfo)->err->msg_code = (code), \
  163802. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163803. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  163804. #define MAKESTMT(stuff) do { stuff } while (0)
  163805. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  163806. #define WARNMS(cinfo,code) \
  163807. ((cinfo)->err->msg_code = (code), \
  163808. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163809. #define WARNMS1(cinfo,code,p1) \
  163810. ((cinfo)->err->msg_code = (code), \
  163811. (cinfo)->err->msg_parm.i[0] = (p1), \
  163812. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163813. #define WARNMS2(cinfo,code,p1,p2) \
  163814. ((cinfo)->err->msg_code = (code), \
  163815. (cinfo)->err->msg_parm.i[0] = (p1), \
  163816. (cinfo)->err->msg_parm.i[1] = (p2), \
  163817. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  163818. /* Informational/debugging messages */
  163819. #define TRACEMS(cinfo,lvl,code) \
  163820. ((cinfo)->err->msg_code = (code), \
  163821. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163822. #define TRACEMS1(cinfo,lvl,code,p1) \
  163823. ((cinfo)->err->msg_code = (code), \
  163824. (cinfo)->err->msg_parm.i[0] = (p1), \
  163825. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163826. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  163827. ((cinfo)->err->msg_code = (code), \
  163828. (cinfo)->err->msg_parm.i[0] = (p1), \
  163829. (cinfo)->err->msg_parm.i[1] = (p2), \
  163830. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163831. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  163832. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163833. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  163834. (cinfo)->err->msg_code = (code); \
  163835. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163836. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  163837. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163838. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163839. (cinfo)->err->msg_code = (code); \
  163840. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163841. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  163842. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163843. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163844. _mp[4] = (p5); \
  163845. (cinfo)->err->msg_code = (code); \
  163846. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163847. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  163848. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  163849. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  163850. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  163851. (cinfo)->err->msg_code = (code); \
  163852. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  163853. #define TRACEMSS(cinfo,lvl,code,str) \
  163854. ((cinfo)->err->msg_code = (code), \
  163855. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  163856. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  163857. #endif /* JERROR_H */
  163858. /********* End of inlined file: jerror.h *********/
  163859. /* Expanded data source object for stdio input */
  163860. typedef struct {
  163861. struct jpeg_source_mgr pub; /* public fields */
  163862. FILE * infile; /* source stream */
  163863. JOCTET * buffer; /* start of buffer */
  163864. boolean start_of_file; /* have we gotten any data yet? */
  163865. } my_source_mgr;
  163866. typedef my_source_mgr * my_src_ptr;
  163867. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  163868. /*
  163869. * Initialize source --- called by jpeg_read_header
  163870. * before any data is actually read.
  163871. */
  163872. METHODDEF(void)
  163873. init_source (j_decompress_ptr cinfo)
  163874. {
  163875. my_src_ptr src = (my_src_ptr) cinfo->src;
  163876. /* We reset the empty-input-file flag for each image,
  163877. * but we don't clear the input buffer.
  163878. * This is correct behavior for reading a series of images from one source.
  163879. */
  163880. src->start_of_file = TRUE;
  163881. }
  163882. /*
  163883. * Fill the input buffer --- called whenever buffer is emptied.
  163884. *
  163885. * In typical applications, this should read fresh data into the buffer
  163886. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  163887. * reset the pointer & count to the start of the buffer, and return TRUE
  163888. * indicating that the buffer has been reloaded. It is not necessary to
  163889. * fill the buffer entirely, only to obtain at least one more byte.
  163890. *
  163891. * There is no such thing as an EOF return. If the end of the file has been
  163892. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  163893. * the buffer. In most cases, generating a warning message and inserting a
  163894. * fake EOI marker is the best course of action --- this will allow the
  163895. * decompressor to output however much of the image is there. However,
  163896. * the resulting error message is misleading if the real problem is an empty
  163897. * input file, so we handle that case specially.
  163898. *
  163899. * In applications that need to be able to suspend compression due to input
  163900. * not being available yet, a FALSE return indicates that no more data can be
  163901. * obtained right now, but more may be forthcoming later. In this situation,
  163902. * the decompressor will return to its caller (with an indication of the
  163903. * number of scanlines it has read, if any). The application should resume
  163904. * decompression after it has loaded more data into the input buffer. Note
  163905. * that there are substantial restrictions on the use of suspension --- see
  163906. * the documentation.
  163907. *
  163908. * When suspending, the decompressor will back up to a convenient restart point
  163909. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  163910. * indicate where the restart point will be if the current call returns FALSE.
  163911. * Data beyond this point must be rescanned after resumption, so move it to
  163912. * the front of the buffer rather than discarding it.
  163913. */
  163914. METHODDEF(boolean)
  163915. fill_input_buffer (j_decompress_ptr cinfo)
  163916. {
  163917. my_src_ptr src = (my_src_ptr) cinfo->src;
  163918. size_t nbytes;
  163919. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  163920. if (nbytes <= 0) {
  163921. if (src->start_of_file) /* Treat empty input file as fatal error */
  163922. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  163923. WARNMS(cinfo, JWRN_JPEG_EOF);
  163924. /* Insert a fake EOI marker */
  163925. src->buffer[0] = (JOCTET) 0xFF;
  163926. src->buffer[1] = (JOCTET) JPEG_EOI;
  163927. nbytes = 2;
  163928. }
  163929. src->pub.next_input_byte = src->buffer;
  163930. src->pub.bytes_in_buffer = nbytes;
  163931. src->start_of_file = FALSE;
  163932. return TRUE;
  163933. }
  163934. /*
  163935. * Skip data --- used to skip over a potentially large amount of
  163936. * uninteresting data (such as an APPn marker).
  163937. *
  163938. * Writers of suspendable-input applications must note that skip_input_data
  163939. * is not granted the right to give a suspension return. If the skip extends
  163940. * beyond the data currently in the buffer, the buffer can be marked empty so
  163941. * that the next read will cause a fill_input_buffer call that can suspend.
  163942. * Arranging for additional bytes to be discarded before reloading the input
  163943. * buffer is the application writer's problem.
  163944. */
  163945. METHODDEF(void)
  163946. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  163947. {
  163948. my_src_ptr src = (my_src_ptr) cinfo->src;
  163949. /* Just a dumb implementation for now. Could use fseek() except
  163950. * it doesn't work on pipes. Not clear that being smart is worth
  163951. * any trouble anyway --- large skips are infrequent.
  163952. */
  163953. if (num_bytes > 0) {
  163954. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  163955. num_bytes -= (long) src->pub.bytes_in_buffer;
  163956. (void) fill_input_buffer(cinfo);
  163957. /* note we assume that fill_input_buffer will never return FALSE,
  163958. * so suspension need not be handled.
  163959. */
  163960. }
  163961. src->pub.next_input_byte += (size_t) num_bytes;
  163962. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  163963. }
  163964. }
  163965. /*
  163966. * An additional method that can be provided by data source modules is the
  163967. * resync_to_restart method for error recovery in the presence of RST markers.
  163968. * For the moment, this source module just uses the default resync method
  163969. * provided by the JPEG library. That method assumes that no backtracking
  163970. * is possible.
  163971. */
  163972. /*
  163973. * Terminate source --- called by jpeg_finish_decompress
  163974. * after all data has been read. Often a no-op.
  163975. *
  163976. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  163977. * application must deal with any cleanup that should happen even
  163978. * for error exit.
  163979. */
  163980. METHODDEF(void)
  163981. term_source (j_decompress_ptr cinfo)
  163982. {
  163983. /* no work necessary here */
  163984. }
  163985. /*
  163986. * Prepare for input from a stdio stream.
  163987. * The caller must have already opened the stream, and is responsible
  163988. * for closing it after finishing decompression.
  163989. */
  163990. GLOBAL(void)
  163991. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  163992. {
  163993. my_src_ptr src;
  163994. /* The source object and input buffer are made permanent so that a series
  163995. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  163996. * only before the first one. (If we discarded the buffer at the end of
  163997. * one image, we'd likely lose the start of the next one.)
  163998. * This makes it unsafe to use this manager and a different source
  163999. * manager serially with the same JPEG object. Caveat programmer.
  164000. */
  164001. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  164002. cinfo->src = (struct jpeg_source_mgr *)
  164003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164004. SIZEOF(my_source_mgr));
  164005. src = (my_src_ptr) cinfo->src;
  164006. src->buffer = (JOCTET *)
  164007. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164008. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  164009. }
  164010. src = (my_src_ptr) cinfo->src;
  164011. src->pub.init_source = init_source;
  164012. src->pub.fill_input_buffer = fill_input_buffer;
  164013. src->pub.skip_input_data = skip_input_data;
  164014. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  164015. src->pub.term_source = term_source;
  164016. src->infile = infile;
  164017. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  164018. src->pub.next_input_byte = NULL; /* until buffer loaded */
  164019. }
  164020. /********* End of inlined file: jdatasrc.c *********/
  164021. /********* Start of inlined file: jdcoefct.c *********/
  164022. #define JPEG_INTERNALS
  164023. /* Block smoothing is only applicable for progressive JPEG, so: */
  164024. #ifndef D_PROGRESSIVE_SUPPORTED
  164025. #undef BLOCK_SMOOTHING_SUPPORTED
  164026. #endif
  164027. /* Private buffer controller object */
  164028. typedef struct {
  164029. struct jpeg_d_coef_controller pub; /* public fields */
  164030. /* These variables keep track of the current location of the input side. */
  164031. /* cinfo->input_iMCU_row is also used for this. */
  164032. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  164033. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  164034. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  164035. /* The output side's location is represented by cinfo->output_iMCU_row. */
  164036. /* In single-pass modes, it's sufficient to buffer just one MCU.
  164037. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  164038. * and let the entropy decoder write into that workspace each time.
  164039. * (On 80x86, the workspace is FAR even though it's not really very big;
  164040. * this is to keep the module interfaces unchanged when a large coefficient
  164041. * buffer is necessary.)
  164042. * In multi-pass modes, this array points to the current MCU's blocks
  164043. * within the virtual arrays; it is used only by the input side.
  164044. */
  164045. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  164046. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164047. /* In multi-pass modes, we need a virtual block array for each component. */
  164048. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  164049. #endif
  164050. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164051. /* When doing block smoothing, we latch coefficient Al values here */
  164052. int * coef_bits_latch;
  164053. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  164054. #endif
  164055. } my_coef_controller3;
  164056. typedef my_coef_controller3 * my_coef_ptr3;
  164057. /* Forward declarations */
  164058. METHODDEF(int) decompress_onepass
  164059. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164060. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164061. METHODDEF(int) decompress_data
  164062. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164063. #endif
  164064. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164065. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  164066. METHODDEF(int) decompress_smooth_data
  164067. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  164068. #endif
  164069. LOCAL(void)
  164070. start_iMCU_row3 (j_decompress_ptr cinfo)
  164071. /* Reset within-iMCU-row counters for a new row (input side) */
  164072. {
  164073. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164074. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  164075. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  164076. * But at the bottom of the image, process only what's left.
  164077. */
  164078. if (cinfo->comps_in_scan > 1) {
  164079. coef->MCU_rows_per_iMCU_row = 1;
  164080. } else {
  164081. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  164082. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  164083. else
  164084. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  164085. }
  164086. coef->MCU_ctr = 0;
  164087. coef->MCU_vert_offset = 0;
  164088. }
  164089. /*
  164090. * Initialize for an input processing pass.
  164091. */
  164092. METHODDEF(void)
  164093. start_input_pass (j_decompress_ptr cinfo)
  164094. {
  164095. cinfo->input_iMCU_row = 0;
  164096. start_iMCU_row3(cinfo);
  164097. }
  164098. /*
  164099. * Initialize for an output processing pass.
  164100. */
  164101. METHODDEF(void)
  164102. start_output_pass (j_decompress_ptr cinfo)
  164103. {
  164104. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164105. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164106. /* If multipass, check to see whether to use block smoothing on this pass */
  164107. if (coef->pub.coef_arrays != NULL) {
  164108. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  164109. coef->pub.decompress_data = decompress_smooth_data;
  164110. else
  164111. coef->pub.decompress_data = decompress_data;
  164112. }
  164113. #endif
  164114. cinfo->output_iMCU_row = 0;
  164115. }
  164116. /*
  164117. * Decompress and return some data in the single-pass case.
  164118. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164119. * Input and output must run in lockstep since we have only a one-MCU buffer.
  164120. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164121. *
  164122. * NB: output_buf contains a plane for each component in image,
  164123. * which we index according to the component's SOF position.
  164124. */
  164125. METHODDEF(int)
  164126. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164127. {
  164128. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164129. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164130. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  164131. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164132. int blkn, ci, xindex, yindex, yoffset, useful_width;
  164133. JSAMPARRAY output_ptr;
  164134. JDIMENSION start_col, output_col;
  164135. jpeg_component_info *compptr;
  164136. inverse_DCT_method_ptr inverse_DCT;
  164137. /* Loop to process as much as one whole iMCU row */
  164138. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164139. yoffset++) {
  164140. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  164141. MCU_col_num++) {
  164142. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  164143. jzero_far((void FAR *) coef->MCU_buffer[0],
  164144. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  164145. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164146. /* Suspension forced; update state counters and exit */
  164147. coef->MCU_vert_offset = yoffset;
  164148. coef->MCU_ctr = MCU_col_num;
  164149. return JPEG_SUSPENDED;
  164150. }
  164151. /* Determine where data should go in output_buf and do the IDCT thing.
  164152. * We skip dummy blocks at the right and bottom edges (but blkn gets
  164153. * incremented past them!). Note the inner loop relies on having
  164154. * allocated the MCU_buffer[] blocks sequentially.
  164155. */
  164156. blkn = 0; /* index of current DCT block within MCU */
  164157. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164158. compptr = cinfo->cur_comp_info[ci];
  164159. /* Don't bother to IDCT an uninteresting component. */
  164160. if (! compptr->component_needed) {
  164161. blkn += compptr->MCU_blocks;
  164162. continue;
  164163. }
  164164. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  164165. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  164166. : compptr->last_col_width;
  164167. output_ptr = output_buf[compptr->component_index] +
  164168. yoffset * compptr->DCT_scaled_size;
  164169. start_col = MCU_col_num * compptr->MCU_sample_width;
  164170. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164171. if (cinfo->input_iMCU_row < last_iMCU_row ||
  164172. yoffset+yindex < compptr->last_row_height) {
  164173. output_col = start_col;
  164174. for (xindex = 0; xindex < useful_width; xindex++) {
  164175. (*inverse_DCT) (cinfo, compptr,
  164176. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  164177. output_ptr, output_col);
  164178. output_col += compptr->DCT_scaled_size;
  164179. }
  164180. }
  164181. blkn += compptr->MCU_width;
  164182. output_ptr += compptr->DCT_scaled_size;
  164183. }
  164184. }
  164185. }
  164186. /* Completed an MCU row, but perhaps not an iMCU row */
  164187. coef->MCU_ctr = 0;
  164188. }
  164189. /* Completed the iMCU row, advance counters for next one */
  164190. cinfo->output_iMCU_row++;
  164191. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164192. start_iMCU_row3(cinfo);
  164193. return JPEG_ROW_COMPLETED;
  164194. }
  164195. /* Completed the scan */
  164196. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164197. return JPEG_SCAN_COMPLETED;
  164198. }
  164199. /*
  164200. * Dummy consume-input routine for single-pass operation.
  164201. */
  164202. METHODDEF(int)
  164203. dummy_consume_data (j_decompress_ptr cinfo)
  164204. {
  164205. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  164206. }
  164207. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164208. /*
  164209. * Consume input data and store it in the full-image coefficient buffer.
  164210. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  164211. * ie, v_samp_factor block rows for each component in the scan.
  164212. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164213. */
  164214. METHODDEF(int)
  164215. consume_data (j_decompress_ptr cinfo)
  164216. {
  164217. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164218. JDIMENSION MCU_col_num; /* index of current MCU within row */
  164219. int blkn, ci, xindex, yindex, yoffset;
  164220. JDIMENSION start_col;
  164221. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  164222. JBLOCKROW buffer_ptr;
  164223. jpeg_component_info *compptr;
  164224. /* Align the virtual buffers for the components used in this scan. */
  164225. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164226. compptr = cinfo->cur_comp_info[ci];
  164227. buffer[ci] = (*cinfo->mem->access_virt_barray)
  164228. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  164229. cinfo->input_iMCU_row * compptr->v_samp_factor,
  164230. (JDIMENSION) compptr->v_samp_factor, TRUE);
  164231. /* Note: entropy decoder expects buffer to be zeroed,
  164232. * but this is handled automatically by the memory manager
  164233. * because we requested a pre-zeroed array.
  164234. */
  164235. }
  164236. /* Loop to process one whole iMCU row */
  164237. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  164238. yoffset++) {
  164239. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  164240. MCU_col_num++) {
  164241. /* Construct list of pointers to DCT blocks belonging to this MCU */
  164242. blkn = 0; /* index of current DCT block within MCU */
  164243. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164244. compptr = cinfo->cur_comp_info[ci];
  164245. start_col = MCU_col_num * compptr->MCU_width;
  164246. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  164247. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  164248. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  164249. coef->MCU_buffer[blkn++] = buffer_ptr++;
  164250. }
  164251. }
  164252. }
  164253. /* Try to fetch the MCU. */
  164254. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  164255. /* Suspension forced; update state counters and exit */
  164256. coef->MCU_vert_offset = yoffset;
  164257. coef->MCU_ctr = MCU_col_num;
  164258. return JPEG_SUSPENDED;
  164259. }
  164260. }
  164261. /* Completed an MCU row, but perhaps not an iMCU row */
  164262. coef->MCU_ctr = 0;
  164263. }
  164264. /* Completed the iMCU row, advance counters for next one */
  164265. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  164266. start_iMCU_row3(cinfo);
  164267. return JPEG_ROW_COMPLETED;
  164268. }
  164269. /* Completed the scan */
  164270. (*cinfo->inputctl->finish_input_pass) (cinfo);
  164271. return JPEG_SCAN_COMPLETED;
  164272. }
  164273. /*
  164274. * Decompress and return some data in the multi-pass case.
  164275. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  164276. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  164277. *
  164278. * NB: output_buf contains a plane for each component in image.
  164279. */
  164280. METHODDEF(int)
  164281. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164282. {
  164283. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164284. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164285. JDIMENSION block_num;
  164286. int ci, block_row, block_rows;
  164287. JBLOCKARRAY buffer;
  164288. JBLOCKROW buffer_ptr;
  164289. JSAMPARRAY output_ptr;
  164290. JDIMENSION output_col;
  164291. jpeg_component_info *compptr;
  164292. inverse_DCT_method_ptr inverse_DCT;
  164293. /* Force some input to be done if we are getting ahead of the input. */
  164294. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  164295. (cinfo->input_scan_number == cinfo->output_scan_number &&
  164296. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  164297. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164298. return JPEG_SUSPENDED;
  164299. }
  164300. /* OK, output from the virtual arrays. */
  164301. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164302. ci++, compptr++) {
  164303. /* Don't bother to IDCT an uninteresting component. */
  164304. if (! compptr->component_needed)
  164305. continue;
  164306. /* Align the virtual buffer for this component. */
  164307. buffer = (*cinfo->mem->access_virt_barray)
  164308. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164309. cinfo->output_iMCU_row * compptr->v_samp_factor,
  164310. (JDIMENSION) compptr->v_samp_factor, FALSE);
  164311. /* Count non-dummy DCT block rows in this iMCU row. */
  164312. if (cinfo->output_iMCU_row < last_iMCU_row)
  164313. block_rows = compptr->v_samp_factor;
  164314. else {
  164315. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164316. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164317. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164318. }
  164319. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164320. output_ptr = output_buf[ci];
  164321. /* Loop over all DCT blocks to be processed. */
  164322. for (block_row = 0; block_row < block_rows; block_row++) {
  164323. buffer_ptr = buffer[block_row];
  164324. output_col = 0;
  164325. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  164326. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  164327. output_ptr, output_col);
  164328. buffer_ptr++;
  164329. output_col += compptr->DCT_scaled_size;
  164330. }
  164331. output_ptr += compptr->DCT_scaled_size;
  164332. }
  164333. }
  164334. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164335. return JPEG_ROW_COMPLETED;
  164336. return JPEG_SCAN_COMPLETED;
  164337. }
  164338. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  164339. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164340. /*
  164341. * This code applies interblock smoothing as described by section K.8
  164342. * of the JPEG standard: the first 5 AC coefficients are estimated from
  164343. * the DC values of a DCT block and its 8 neighboring blocks.
  164344. * We apply smoothing only for progressive JPEG decoding, and only if
  164345. * the coefficients it can estimate are not yet known to full precision.
  164346. */
  164347. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  164348. #define Q01_POS 1
  164349. #define Q10_POS 8
  164350. #define Q20_POS 16
  164351. #define Q11_POS 9
  164352. #define Q02_POS 2
  164353. /*
  164354. * Determine whether block smoothing is applicable and safe.
  164355. * We also latch the current states of the coef_bits[] entries for the
  164356. * AC coefficients; otherwise, if the input side of the decompressor
  164357. * advances into a new scan, we might think the coefficients are known
  164358. * more accurately than they really are.
  164359. */
  164360. LOCAL(boolean)
  164361. smoothing_ok (j_decompress_ptr cinfo)
  164362. {
  164363. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164364. boolean smoothing_useful = FALSE;
  164365. int ci, coefi;
  164366. jpeg_component_info *compptr;
  164367. JQUANT_TBL * qtable;
  164368. int * coef_bits;
  164369. int * coef_bits_latch;
  164370. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  164371. return FALSE;
  164372. /* Allocate latch area if not already done */
  164373. if (coef->coef_bits_latch == NULL)
  164374. coef->coef_bits_latch = (int *)
  164375. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164376. cinfo->num_components *
  164377. (SAVED_COEFS * SIZEOF(int)));
  164378. coef_bits_latch = coef->coef_bits_latch;
  164379. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164380. ci++, compptr++) {
  164381. /* All components' quantization values must already be latched. */
  164382. if ((qtable = compptr->quant_table) == NULL)
  164383. return FALSE;
  164384. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  164385. if (qtable->quantval[0] == 0 ||
  164386. qtable->quantval[Q01_POS] == 0 ||
  164387. qtable->quantval[Q10_POS] == 0 ||
  164388. qtable->quantval[Q20_POS] == 0 ||
  164389. qtable->quantval[Q11_POS] == 0 ||
  164390. qtable->quantval[Q02_POS] == 0)
  164391. return FALSE;
  164392. /* DC values must be at least partly known for all components. */
  164393. coef_bits = cinfo->coef_bits[ci];
  164394. if (coef_bits[0] < 0)
  164395. return FALSE;
  164396. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  164397. for (coefi = 1; coefi <= 5; coefi++) {
  164398. coef_bits_latch[coefi] = coef_bits[coefi];
  164399. if (coef_bits[coefi] != 0)
  164400. smoothing_useful = TRUE;
  164401. }
  164402. coef_bits_latch += SAVED_COEFS;
  164403. }
  164404. return smoothing_useful;
  164405. }
  164406. /*
  164407. * Variant of decompress_data for use when doing block smoothing.
  164408. */
  164409. METHODDEF(int)
  164410. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  164411. {
  164412. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  164413. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  164414. JDIMENSION block_num, last_block_column;
  164415. int ci, block_row, block_rows, access_rows;
  164416. JBLOCKARRAY buffer;
  164417. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  164418. JSAMPARRAY output_ptr;
  164419. JDIMENSION output_col;
  164420. jpeg_component_info *compptr;
  164421. inverse_DCT_method_ptr inverse_DCT;
  164422. boolean first_row, last_row;
  164423. JBLOCK workspace;
  164424. int *coef_bits;
  164425. JQUANT_TBL *quanttbl;
  164426. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  164427. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  164428. int Al, pred;
  164429. /* Force some input to be done if we are getting ahead of the input. */
  164430. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  164431. ! cinfo->inputctl->eoi_reached) {
  164432. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  164433. /* If input is working on current scan, we ordinarily want it to
  164434. * have completed the current row. But if input scan is DC,
  164435. * we want it to keep one row ahead so that next block row's DC
  164436. * values are up to date.
  164437. */
  164438. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  164439. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  164440. break;
  164441. }
  164442. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  164443. return JPEG_SUSPENDED;
  164444. }
  164445. /* OK, output from the virtual arrays. */
  164446. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164447. ci++, compptr++) {
  164448. /* Don't bother to IDCT an uninteresting component. */
  164449. if (! compptr->component_needed)
  164450. continue;
  164451. /* Count non-dummy DCT block rows in this iMCU row. */
  164452. if (cinfo->output_iMCU_row < last_iMCU_row) {
  164453. block_rows = compptr->v_samp_factor;
  164454. access_rows = block_rows * 2; /* this and next iMCU row */
  164455. last_row = FALSE;
  164456. } else {
  164457. /* NB: can't use last_row_height here; it is input-side-dependent! */
  164458. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164459. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  164460. access_rows = block_rows; /* this iMCU row only */
  164461. last_row = TRUE;
  164462. }
  164463. /* Align the virtual buffer for this component. */
  164464. if (cinfo->output_iMCU_row > 0) {
  164465. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  164466. buffer = (*cinfo->mem->access_virt_barray)
  164467. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164468. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  164469. (JDIMENSION) access_rows, FALSE);
  164470. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  164471. first_row = FALSE;
  164472. } else {
  164473. buffer = (*cinfo->mem->access_virt_barray)
  164474. ((j_common_ptr) cinfo, coef->whole_image[ci],
  164475. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  164476. first_row = TRUE;
  164477. }
  164478. /* Fetch component-dependent info */
  164479. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  164480. quanttbl = compptr->quant_table;
  164481. Q00 = quanttbl->quantval[0];
  164482. Q01 = quanttbl->quantval[Q01_POS];
  164483. Q10 = quanttbl->quantval[Q10_POS];
  164484. Q20 = quanttbl->quantval[Q20_POS];
  164485. Q11 = quanttbl->quantval[Q11_POS];
  164486. Q02 = quanttbl->quantval[Q02_POS];
  164487. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  164488. output_ptr = output_buf[ci];
  164489. /* Loop over all DCT blocks to be processed. */
  164490. for (block_row = 0; block_row < block_rows; block_row++) {
  164491. buffer_ptr = buffer[block_row];
  164492. if (first_row && block_row == 0)
  164493. prev_block_row = buffer_ptr;
  164494. else
  164495. prev_block_row = buffer[block_row-1];
  164496. if (last_row && block_row == block_rows-1)
  164497. next_block_row = buffer_ptr;
  164498. else
  164499. next_block_row = buffer[block_row+1];
  164500. /* We fetch the surrounding DC values using a sliding-register approach.
  164501. * Initialize all nine here so as to do the right thing on narrow pics.
  164502. */
  164503. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  164504. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  164505. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  164506. output_col = 0;
  164507. last_block_column = compptr->width_in_blocks - 1;
  164508. for (block_num = 0; block_num <= last_block_column; block_num++) {
  164509. /* Fetch current DCT block into workspace so we can modify it. */
  164510. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  164511. /* Update DC values */
  164512. if (block_num < last_block_column) {
  164513. DC3 = (int) prev_block_row[1][0];
  164514. DC6 = (int) buffer_ptr[1][0];
  164515. DC9 = (int) next_block_row[1][0];
  164516. }
  164517. /* Compute coefficient estimates per K.8.
  164518. * An estimate is applied only if coefficient is still zero,
  164519. * and is not known to be fully accurate.
  164520. */
  164521. /* AC01 */
  164522. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  164523. num = 36 * Q00 * (DC4 - DC6);
  164524. if (num >= 0) {
  164525. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  164526. if (Al > 0 && pred >= (1<<Al))
  164527. pred = (1<<Al)-1;
  164528. } else {
  164529. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  164530. if (Al > 0 && pred >= (1<<Al))
  164531. pred = (1<<Al)-1;
  164532. pred = -pred;
  164533. }
  164534. workspace[1] = (JCOEF) pred;
  164535. }
  164536. /* AC10 */
  164537. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  164538. num = 36 * Q00 * (DC2 - DC8);
  164539. if (num >= 0) {
  164540. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  164541. if (Al > 0 && pred >= (1<<Al))
  164542. pred = (1<<Al)-1;
  164543. } else {
  164544. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  164545. if (Al > 0 && pred >= (1<<Al))
  164546. pred = (1<<Al)-1;
  164547. pred = -pred;
  164548. }
  164549. workspace[8] = (JCOEF) pred;
  164550. }
  164551. /* AC20 */
  164552. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  164553. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  164554. if (num >= 0) {
  164555. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  164556. if (Al > 0 && pred >= (1<<Al))
  164557. pred = (1<<Al)-1;
  164558. } else {
  164559. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  164560. if (Al > 0 && pred >= (1<<Al))
  164561. pred = (1<<Al)-1;
  164562. pred = -pred;
  164563. }
  164564. workspace[16] = (JCOEF) pred;
  164565. }
  164566. /* AC11 */
  164567. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  164568. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  164569. if (num >= 0) {
  164570. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  164571. if (Al > 0 && pred >= (1<<Al))
  164572. pred = (1<<Al)-1;
  164573. } else {
  164574. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  164575. if (Al > 0 && pred >= (1<<Al))
  164576. pred = (1<<Al)-1;
  164577. pred = -pred;
  164578. }
  164579. workspace[9] = (JCOEF) pred;
  164580. }
  164581. /* AC02 */
  164582. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  164583. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  164584. if (num >= 0) {
  164585. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  164586. if (Al > 0 && pred >= (1<<Al))
  164587. pred = (1<<Al)-1;
  164588. } else {
  164589. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  164590. if (Al > 0 && pred >= (1<<Al))
  164591. pred = (1<<Al)-1;
  164592. pred = -pred;
  164593. }
  164594. workspace[2] = (JCOEF) pred;
  164595. }
  164596. /* OK, do the IDCT */
  164597. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  164598. output_ptr, output_col);
  164599. /* Advance for next column */
  164600. DC1 = DC2; DC2 = DC3;
  164601. DC4 = DC5; DC5 = DC6;
  164602. DC7 = DC8; DC8 = DC9;
  164603. buffer_ptr++, prev_block_row++, next_block_row++;
  164604. output_col += compptr->DCT_scaled_size;
  164605. }
  164606. output_ptr += compptr->DCT_scaled_size;
  164607. }
  164608. }
  164609. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  164610. return JPEG_ROW_COMPLETED;
  164611. return JPEG_SCAN_COMPLETED;
  164612. }
  164613. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  164614. /*
  164615. * Initialize coefficient buffer controller.
  164616. */
  164617. GLOBAL(void)
  164618. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164619. {
  164620. my_coef_ptr3 coef;
  164621. coef = (my_coef_ptr3)
  164622. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164623. SIZEOF(my_coef_controller3));
  164624. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  164625. coef->pub.start_input_pass = start_input_pass;
  164626. coef->pub.start_output_pass = start_output_pass;
  164627. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164628. coef->coef_bits_latch = NULL;
  164629. #endif
  164630. /* Create the coefficient buffer. */
  164631. if (need_full_buffer) {
  164632. #ifdef D_MULTISCAN_FILES_SUPPORTED
  164633. /* Allocate a full-image virtual array for each component, */
  164634. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  164635. /* Note we ask for a pre-zeroed array. */
  164636. int ci, access_rows;
  164637. jpeg_component_info *compptr;
  164638. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164639. ci++, compptr++) {
  164640. access_rows = compptr->v_samp_factor;
  164641. #ifdef BLOCK_SMOOTHING_SUPPORTED
  164642. /* If block smoothing could be used, need a bigger window */
  164643. if (cinfo->progressive_mode)
  164644. access_rows *= 3;
  164645. #endif
  164646. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  164647. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  164648. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  164649. (long) compptr->h_samp_factor),
  164650. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164651. (long) compptr->v_samp_factor),
  164652. (JDIMENSION) access_rows);
  164653. }
  164654. coef->pub.consume_data = consume_data;
  164655. coef->pub.decompress_data = decompress_data;
  164656. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  164657. #else
  164658. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164659. #endif
  164660. } else {
  164661. /* We only need a single-MCU buffer. */
  164662. JBLOCKROW buffer;
  164663. int i;
  164664. buffer = (JBLOCKROW)
  164665. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164666. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  164667. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  164668. coef->MCU_buffer[i] = buffer + i;
  164669. }
  164670. coef->pub.consume_data = dummy_consume_data;
  164671. coef->pub.decompress_data = decompress_onepass;
  164672. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  164673. }
  164674. }
  164675. /********* End of inlined file: jdcoefct.c *********/
  164676. #undef FIX
  164677. /********* Start of inlined file: jdcolor.c *********/
  164678. #define JPEG_INTERNALS
  164679. /* Private subobject */
  164680. typedef struct {
  164681. struct jpeg_color_deconverter pub; /* public fields */
  164682. /* Private state for YCC->RGB conversion */
  164683. int * Cr_r_tab; /* => table for Cr to R conversion */
  164684. int * Cb_b_tab; /* => table for Cb to B conversion */
  164685. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  164686. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  164687. } my_color_deconverter2;
  164688. typedef my_color_deconverter2 * my_cconvert_ptr2;
  164689. /**************** YCbCr -> RGB conversion: most common case **************/
  164690. /*
  164691. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  164692. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  164693. * The conversion equations to be implemented are therefore
  164694. * R = Y + 1.40200 * Cr
  164695. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  164696. * B = Y + 1.77200 * Cb
  164697. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  164698. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  164699. *
  164700. * To avoid floating-point arithmetic, we represent the fractional constants
  164701. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  164702. * the products by 2^16, with appropriate rounding, to get the correct answer.
  164703. * Notice that Y, being an integral input, does not contribute any fraction
  164704. * so it need not participate in the rounding.
  164705. *
  164706. * For even more speed, we avoid doing any multiplications in the inner loop
  164707. * by precalculating the constants times Cb and Cr for all possible values.
  164708. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  164709. * for 12-bit samples it is still acceptable. It's not very reasonable for
  164710. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  164711. * colorspace anyway.
  164712. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  164713. * values for the G calculation are left scaled up, since we must add them
  164714. * together before rounding.
  164715. */
  164716. #define SCALEBITS 16 /* speediest right-shift on some machines */
  164717. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  164718. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  164719. /*
  164720. * Initialize tables for YCC->RGB colorspace conversion.
  164721. */
  164722. LOCAL(void)
  164723. build_ycc_rgb_table (j_decompress_ptr cinfo)
  164724. {
  164725. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164726. int i;
  164727. INT32 x;
  164728. SHIFT_TEMPS
  164729. cconvert->Cr_r_tab = (int *)
  164730. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164731. (MAXJSAMPLE+1) * SIZEOF(int));
  164732. cconvert->Cb_b_tab = (int *)
  164733. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164734. (MAXJSAMPLE+1) * SIZEOF(int));
  164735. cconvert->Cr_g_tab = (INT32 *)
  164736. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164737. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164738. cconvert->Cb_g_tab = (INT32 *)
  164739. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164740. (MAXJSAMPLE+1) * SIZEOF(INT32));
  164741. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  164742. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  164743. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  164744. /* Cr=>R value is nearest int to 1.40200 * x */
  164745. cconvert->Cr_r_tab[i] = (int)
  164746. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  164747. /* Cb=>B value is nearest int to 1.77200 * x */
  164748. cconvert->Cb_b_tab[i] = (int)
  164749. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  164750. /* Cr=>G value is scaled-up -0.71414 * x */
  164751. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  164752. /* Cb=>G value is scaled-up -0.34414 * x */
  164753. /* We also add in ONE_HALF so that need not do it in inner loop */
  164754. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  164755. }
  164756. }
  164757. /*
  164758. * Convert some rows of samples to the output colorspace.
  164759. *
  164760. * Note that we change from noninterleaved, one-plane-per-component format
  164761. * to interleaved-pixel format. The output buffer is therefore three times
  164762. * as wide as the input buffer.
  164763. * A starting row offset is provided only for the input buffer. The caller
  164764. * can easily adjust the passed output_buf value to accommodate any row
  164765. * offset required on that side.
  164766. */
  164767. METHODDEF(void)
  164768. ycc_rgb_convert (j_decompress_ptr cinfo,
  164769. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164770. JSAMPARRAY output_buf, int num_rows)
  164771. {
  164772. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164773. register int y, cb, cr;
  164774. register JSAMPROW outptr;
  164775. register JSAMPROW inptr0, inptr1, inptr2;
  164776. register JDIMENSION col;
  164777. JDIMENSION num_cols = cinfo->output_width;
  164778. /* copy these pointers into registers if possible */
  164779. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164780. register int * Crrtab = cconvert->Cr_r_tab;
  164781. register int * Cbbtab = cconvert->Cb_b_tab;
  164782. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164783. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164784. SHIFT_TEMPS
  164785. while (--num_rows >= 0) {
  164786. inptr0 = input_buf[0][input_row];
  164787. inptr1 = input_buf[1][input_row];
  164788. inptr2 = input_buf[2][input_row];
  164789. input_row++;
  164790. outptr = *output_buf++;
  164791. for (col = 0; col < num_cols; col++) {
  164792. y = GETJSAMPLE(inptr0[col]);
  164793. cb = GETJSAMPLE(inptr1[col]);
  164794. cr = GETJSAMPLE(inptr2[col]);
  164795. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164796. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  164797. outptr[RGB_GREEN] = range_limit[y +
  164798. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164799. SCALEBITS))];
  164800. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  164801. outptr += RGB_PIXELSIZE;
  164802. }
  164803. }
  164804. }
  164805. /**************** Cases other than YCbCr -> RGB **************/
  164806. /*
  164807. * Color conversion for no colorspace change: just copy the data,
  164808. * converting from separate-planes to interleaved representation.
  164809. */
  164810. METHODDEF(void)
  164811. null_convert2 (j_decompress_ptr cinfo,
  164812. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164813. JSAMPARRAY output_buf, int num_rows)
  164814. {
  164815. register JSAMPROW inptr, outptr;
  164816. register JDIMENSION count;
  164817. register int num_components = cinfo->num_components;
  164818. JDIMENSION num_cols = cinfo->output_width;
  164819. int ci;
  164820. while (--num_rows >= 0) {
  164821. for (ci = 0; ci < num_components; ci++) {
  164822. inptr = input_buf[ci][input_row];
  164823. outptr = output_buf[0] + ci;
  164824. for (count = num_cols; count > 0; count--) {
  164825. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  164826. outptr += num_components;
  164827. }
  164828. }
  164829. input_row++;
  164830. output_buf++;
  164831. }
  164832. }
  164833. /*
  164834. * Color conversion for grayscale: just copy the data.
  164835. * This also works for YCbCr -> grayscale conversion, in which
  164836. * we just copy the Y (luminance) component and ignore chrominance.
  164837. */
  164838. METHODDEF(void)
  164839. grayscale_convert2 (j_decompress_ptr cinfo,
  164840. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164841. JSAMPARRAY output_buf, int num_rows)
  164842. {
  164843. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  164844. num_rows, cinfo->output_width);
  164845. }
  164846. /*
  164847. * Convert grayscale to RGB: just duplicate the graylevel three times.
  164848. * This is provided to support applications that don't want to cope
  164849. * with grayscale as a separate case.
  164850. */
  164851. METHODDEF(void)
  164852. gray_rgb_convert (j_decompress_ptr cinfo,
  164853. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164854. JSAMPARRAY output_buf, int num_rows)
  164855. {
  164856. register JSAMPROW inptr, outptr;
  164857. register JDIMENSION col;
  164858. JDIMENSION num_cols = cinfo->output_width;
  164859. while (--num_rows >= 0) {
  164860. inptr = input_buf[0][input_row++];
  164861. outptr = *output_buf++;
  164862. for (col = 0; col < num_cols; col++) {
  164863. /* We can dispense with GETJSAMPLE() here */
  164864. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  164865. outptr += RGB_PIXELSIZE;
  164866. }
  164867. }
  164868. }
  164869. /*
  164870. * Adobe-style YCCK->CMYK conversion.
  164871. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  164872. * conversion as above, while passing K (black) unchanged.
  164873. * We assume build_ycc_rgb_table has been called.
  164874. */
  164875. METHODDEF(void)
  164876. ycck_cmyk_convert (j_decompress_ptr cinfo,
  164877. JSAMPIMAGE input_buf, JDIMENSION input_row,
  164878. JSAMPARRAY output_buf, int num_rows)
  164879. {
  164880. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  164881. register int y, cb, cr;
  164882. register JSAMPROW outptr;
  164883. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  164884. register JDIMENSION col;
  164885. JDIMENSION num_cols = cinfo->output_width;
  164886. /* copy these pointers into registers if possible */
  164887. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  164888. register int * Crrtab = cconvert->Cr_r_tab;
  164889. register int * Cbbtab = cconvert->Cb_b_tab;
  164890. register INT32 * Crgtab = cconvert->Cr_g_tab;
  164891. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  164892. SHIFT_TEMPS
  164893. while (--num_rows >= 0) {
  164894. inptr0 = input_buf[0][input_row];
  164895. inptr1 = input_buf[1][input_row];
  164896. inptr2 = input_buf[2][input_row];
  164897. inptr3 = input_buf[3][input_row];
  164898. input_row++;
  164899. outptr = *output_buf++;
  164900. for (col = 0; col < num_cols; col++) {
  164901. y = GETJSAMPLE(inptr0[col]);
  164902. cb = GETJSAMPLE(inptr1[col]);
  164903. cr = GETJSAMPLE(inptr2[col]);
  164904. /* Range-limiting is essential due to noise introduced by DCT losses. */
  164905. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  164906. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  164907. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  164908. SCALEBITS)))];
  164909. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  164910. /* K passes through unchanged */
  164911. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  164912. outptr += 4;
  164913. }
  164914. }
  164915. }
  164916. /*
  164917. * Empty method for start_pass.
  164918. */
  164919. METHODDEF(void)
  164920. start_pass_dcolor (j_decompress_ptr cinfo)
  164921. {
  164922. /* no work needed */
  164923. }
  164924. /*
  164925. * Module initialization routine for output colorspace conversion.
  164926. */
  164927. GLOBAL(void)
  164928. jinit_color_deconverter (j_decompress_ptr cinfo)
  164929. {
  164930. my_cconvert_ptr2 cconvert;
  164931. int ci;
  164932. cconvert = (my_cconvert_ptr2)
  164933. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164934. SIZEOF(my_color_deconverter2));
  164935. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  164936. cconvert->pub.start_pass = start_pass_dcolor;
  164937. /* Make sure num_components agrees with jpeg_color_space */
  164938. switch (cinfo->jpeg_color_space) {
  164939. case JCS_GRAYSCALE:
  164940. if (cinfo->num_components != 1)
  164941. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164942. break;
  164943. case JCS_RGB:
  164944. case JCS_YCbCr:
  164945. if (cinfo->num_components != 3)
  164946. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164947. break;
  164948. case JCS_CMYK:
  164949. case JCS_YCCK:
  164950. if (cinfo->num_components != 4)
  164951. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164952. break;
  164953. default: /* JCS_UNKNOWN can be anything */
  164954. if (cinfo->num_components < 1)
  164955. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  164956. break;
  164957. }
  164958. /* Set out_color_components and conversion method based on requested space.
  164959. * Also clear the component_needed flags for any unused components,
  164960. * so that earlier pipeline stages can avoid useless computation.
  164961. */
  164962. switch (cinfo->out_color_space) {
  164963. case JCS_GRAYSCALE:
  164964. cinfo->out_color_components = 1;
  164965. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  164966. cinfo->jpeg_color_space == JCS_YCbCr) {
  164967. cconvert->pub.color_convert = grayscale_convert2;
  164968. /* For color->grayscale conversion, only the Y (0) component is needed */
  164969. for (ci = 1; ci < cinfo->num_components; ci++)
  164970. cinfo->comp_info[ci].component_needed = FALSE;
  164971. } else
  164972. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164973. break;
  164974. case JCS_RGB:
  164975. cinfo->out_color_components = RGB_PIXELSIZE;
  164976. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  164977. cconvert->pub.color_convert = ycc_rgb_convert;
  164978. build_ycc_rgb_table(cinfo);
  164979. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  164980. cconvert->pub.color_convert = gray_rgb_convert;
  164981. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  164982. cconvert->pub.color_convert = null_convert2;
  164983. } else
  164984. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164985. break;
  164986. case JCS_CMYK:
  164987. cinfo->out_color_components = 4;
  164988. if (cinfo->jpeg_color_space == JCS_YCCK) {
  164989. cconvert->pub.color_convert = ycck_cmyk_convert;
  164990. build_ycc_rgb_table(cinfo);
  164991. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  164992. cconvert->pub.color_convert = null_convert2;
  164993. } else
  164994. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  164995. break;
  164996. default:
  164997. /* Permit null conversion to same output space */
  164998. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  164999. cinfo->out_color_components = cinfo->num_components;
  165000. cconvert->pub.color_convert = null_convert2;
  165001. } else /* unsupported non-null conversion */
  165002. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  165003. break;
  165004. }
  165005. if (cinfo->quantize_colors)
  165006. cinfo->output_components = 1; /* single colormapped output component */
  165007. else
  165008. cinfo->output_components = cinfo->out_color_components;
  165009. }
  165010. /********* End of inlined file: jdcolor.c *********/
  165011. #undef FIX
  165012. /********* Start of inlined file: jddctmgr.c *********/
  165013. #define JPEG_INTERNALS
  165014. /*
  165015. * The decompressor input side (jdinput.c) saves away the appropriate
  165016. * quantization table for each component at the start of the first scan
  165017. * involving that component. (This is necessary in order to correctly
  165018. * decode files that reuse Q-table slots.)
  165019. * When we are ready to make an output pass, the saved Q-table is converted
  165020. * to a multiplier table that will actually be used by the IDCT routine.
  165021. * The multiplier table contents are IDCT-method-dependent. To support
  165022. * application changes in IDCT method between scans, we can remake the
  165023. * multiplier tables if necessary.
  165024. * In buffered-image mode, the first output pass may occur before any data
  165025. * has been seen for some components, and thus before their Q-tables have
  165026. * been saved away. To handle this case, multiplier tables are preset
  165027. * to zeroes; the result of the IDCT will be a neutral gray level.
  165028. */
  165029. /* Private subobject for this module */
  165030. typedef struct {
  165031. struct jpeg_inverse_dct pub; /* public fields */
  165032. /* This array contains the IDCT method code that each multiplier table
  165033. * is currently set up for, or -1 if it's not yet set up.
  165034. * The actual multiplier tables are pointed to by dct_table in the
  165035. * per-component comp_info structures.
  165036. */
  165037. int cur_method[MAX_COMPONENTS];
  165038. } my_idct_controller;
  165039. typedef my_idct_controller * my_idct_ptr;
  165040. /* Allocated multiplier tables: big enough for any supported variant */
  165041. typedef union {
  165042. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  165043. #ifdef DCT_IFAST_SUPPORTED
  165044. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  165045. #endif
  165046. #ifdef DCT_FLOAT_SUPPORTED
  165047. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  165048. #endif
  165049. } multiplier_table;
  165050. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  165051. * so be sure to compile that code if either ISLOW or SCALING is requested.
  165052. */
  165053. #ifdef DCT_ISLOW_SUPPORTED
  165054. #define PROVIDE_ISLOW_TABLES
  165055. #else
  165056. #ifdef IDCT_SCALING_SUPPORTED
  165057. #define PROVIDE_ISLOW_TABLES
  165058. #endif
  165059. #endif
  165060. /*
  165061. * Prepare for an output pass.
  165062. * Here we select the proper IDCT routine for each component and build
  165063. * a matching multiplier table.
  165064. */
  165065. METHODDEF(void)
  165066. start_pass (j_decompress_ptr cinfo)
  165067. {
  165068. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  165069. int ci, i;
  165070. jpeg_component_info *compptr;
  165071. int method = 0;
  165072. inverse_DCT_method_ptr method_ptr = NULL;
  165073. JQUANT_TBL * qtbl;
  165074. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165075. ci++, compptr++) {
  165076. /* Select the proper IDCT routine for this component's scaling */
  165077. switch (compptr->DCT_scaled_size) {
  165078. #ifdef IDCT_SCALING_SUPPORTED
  165079. case 1:
  165080. method_ptr = jpeg_idct_1x1;
  165081. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165082. break;
  165083. case 2:
  165084. method_ptr = jpeg_idct_2x2;
  165085. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165086. break;
  165087. case 4:
  165088. method_ptr = jpeg_idct_4x4;
  165089. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  165090. break;
  165091. #endif
  165092. case DCTSIZE:
  165093. switch (cinfo->dct_method) {
  165094. #ifdef DCT_ISLOW_SUPPORTED
  165095. case JDCT_ISLOW:
  165096. method_ptr = jpeg_idct_islow;
  165097. method = JDCT_ISLOW;
  165098. break;
  165099. #endif
  165100. #ifdef DCT_IFAST_SUPPORTED
  165101. case JDCT_IFAST:
  165102. method_ptr = jpeg_idct_ifast;
  165103. method = JDCT_IFAST;
  165104. break;
  165105. #endif
  165106. #ifdef DCT_FLOAT_SUPPORTED
  165107. case JDCT_FLOAT:
  165108. method_ptr = jpeg_idct_float;
  165109. method = JDCT_FLOAT;
  165110. break;
  165111. #endif
  165112. default:
  165113. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165114. break;
  165115. }
  165116. break;
  165117. default:
  165118. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  165119. break;
  165120. }
  165121. idct->pub.inverse_DCT[ci] = method_ptr;
  165122. /* Create multiplier table from quant table.
  165123. * However, we can skip this if the component is uninteresting
  165124. * or if we already built the table. Also, if no quant table
  165125. * has yet been saved for the component, we leave the
  165126. * multiplier table all-zero; we'll be reading zeroes from the
  165127. * coefficient controller's buffer anyway.
  165128. */
  165129. if (! compptr->component_needed || idct->cur_method[ci] == method)
  165130. continue;
  165131. qtbl = compptr->quant_table;
  165132. if (qtbl == NULL) /* happens if no data yet for component */
  165133. continue;
  165134. idct->cur_method[ci] = method;
  165135. switch (method) {
  165136. #ifdef PROVIDE_ISLOW_TABLES
  165137. case JDCT_ISLOW:
  165138. {
  165139. /* For LL&M IDCT method, multipliers are equal to raw quantization
  165140. * coefficients, but are stored as ints to ensure access efficiency.
  165141. */
  165142. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  165143. for (i = 0; i < DCTSIZE2; i++) {
  165144. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  165145. }
  165146. }
  165147. break;
  165148. #endif
  165149. #ifdef DCT_IFAST_SUPPORTED
  165150. case JDCT_IFAST:
  165151. {
  165152. /* For AA&N IDCT method, multipliers are equal to quantization
  165153. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165154. * scalefactor[0] = 1
  165155. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165156. * For integer operation, the multiplier table is to be scaled by
  165157. * IFAST_SCALE_BITS.
  165158. */
  165159. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  165160. #define CONST_BITS 14
  165161. static const INT16 aanscales[DCTSIZE2] = {
  165162. /* precomputed values scaled up by 14 bits */
  165163. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165164. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  165165. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  165166. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  165167. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  165168. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  165169. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  165170. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  165171. };
  165172. SHIFT_TEMPS
  165173. for (i = 0; i < DCTSIZE2; i++) {
  165174. ifmtbl[i] = (IFAST_MULT_TYPE)
  165175. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  165176. (INT32) aanscales[i]),
  165177. CONST_BITS-IFAST_SCALE_BITS);
  165178. }
  165179. }
  165180. break;
  165181. #endif
  165182. #ifdef DCT_FLOAT_SUPPORTED
  165183. case JDCT_FLOAT:
  165184. {
  165185. /* For float AA&N IDCT method, multipliers are equal to quantization
  165186. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  165187. * scalefactor[0] = 1
  165188. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  165189. */
  165190. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  165191. int row, col;
  165192. static const double aanscalefactor[DCTSIZE] = {
  165193. 1.0, 1.387039845, 1.306562965, 1.175875602,
  165194. 1.0, 0.785694958, 0.541196100, 0.275899379
  165195. };
  165196. i = 0;
  165197. for (row = 0; row < DCTSIZE; row++) {
  165198. for (col = 0; col < DCTSIZE; col++) {
  165199. fmtbl[i] = (FLOAT_MULT_TYPE)
  165200. ((double) qtbl->quantval[i] *
  165201. aanscalefactor[row] * aanscalefactor[col]);
  165202. i++;
  165203. }
  165204. }
  165205. }
  165206. break;
  165207. #endif
  165208. default:
  165209. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165210. break;
  165211. }
  165212. }
  165213. }
  165214. /*
  165215. * Initialize IDCT manager.
  165216. */
  165217. GLOBAL(void)
  165218. jinit_inverse_dct (j_decompress_ptr cinfo)
  165219. {
  165220. my_idct_ptr idct;
  165221. int ci;
  165222. jpeg_component_info *compptr;
  165223. idct = (my_idct_ptr)
  165224. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165225. SIZEOF(my_idct_controller));
  165226. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  165227. idct->pub.start_pass = start_pass;
  165228. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165229. ci++, compptr++) {
  165230. /* Allocate and pre-zero a multiplier table for each component */
  165231. compptr->dct_table =
  165232. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165233. SIZEOF(multiplier_table));
  165234. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  165235. /* Mark multiplier table not yet set up for any method */
  165236. idct->cur_method[ci] = -1;
  165237. }
  165238. }
  165239. /********* End of inlined file: jddctmgr.c *********/
  165240. #undef CONST_BITS
  165241. #undef ASSIGN_STATE
  165242. /********* Start of inlined file: jdhuff.c *********/
  165243. #define JPEG_INTERNALS
  165244. /********* Start of inlined file: jdhuff.h *********/
  165245. /* Short forms of external names for systems with brain-damaged linkers. */
  165246. #ifndef __jdhuff_h__
  165247. #define __jdhuff_h__
  165248. #ifdef NEED_SHORT_EXTERNAL_NAMES
  165249. #define jpeg_make_d_derived_tbl jMkDDerived
  165250. #define jpeg_fill_bit_buffer jFilBitBuf
  165251. #define jpeg_huff_decode jHufDecode
  165252. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  165253. /* Derived data constructed for each Huffman table */
  165254. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  165255. typedef struct {
  165256. /* Basic tables: (element [0] of each array is unused) */
  165257. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  165258. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  165259. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  165260. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  165261. * the smallest code of length k; so given a code of length k, the
  165262. * corresponding symbol is huffval[code + valoffset[k]]
  165263. */
  165264. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  165265. JHUFF_TBL *pub;
  165266. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  165267. * the input data stream. If the next Huffman code is no more
  165268. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  165269. * the corresponding symbol directly from these tables.
  165270. */
  165271. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  165272. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  165273. } d_derived_tbl;
  165274. /* Expand a Huffman table definition into the derived format */
  165275. EXTERN(void) jpeg_make_d_derived_tbl
  165276. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  165277. d_derived_tbl ** pdtbl));
  165278. /*
  165279. * Fetching the next N bits from the input stream is a time-critical operation
  165280. * for the Huffman decoders. We implement it with a combination of inline
  165281. * macros and out-of-line subroutines. Note that N (the number of bits
  165282. * demanded at one time) never exceeds 15 for JPEG use.
  165283. *
  165284. * We read source bytes into get_buffer and dole out bits as needed.
  165285. * If get_buffer already contains enough bits, they are fetched in-line
  165286. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  165287. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  165288. * as full as possible (not just to the number of bits needed; this
  165289. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  165290. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  165291. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  165292. * at least the requested number of bits --- dummy zeroes are inserted if
  165293. * necessary.
  165294. */
  165295. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  165296. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  165297. /* If long is > 32 bits on your machine, and shifting/masking longs is
  165298. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  165299. * appropriately should be a win. Unfortunately we can't define the size
  165300. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  165301. * because not all machines measure sizeof in 8-bit bytes.
  165302. */
  165303. typedef struct { /* Bitreading state saved across MCUs */
  165304. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165305. int bits_left; /* # of unused bits in it */
  165306. } bitread_perm_state;
  165307. typedef struct { /* Bitreading working state within an MCU */
  165308. /* Current data source location */
  165309. /* We need a copy, rather than munging the original, in case of suspension */
  165310. const JOCTET * next_input_byte; /* => next byte to read from source */
  165311. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  165312. /* Bit input buffer --- note these values are kept in register variables,
  165313. * not in this struct, inside the inner loops.
  165314. */
  165315. bit_buf_type get_buffer; /* current bit-extraction buffer */
  165316. int bits_left; /* # of unused bits in it */
  165317. /* Pointer needed by jpeg_fill_bit_buffer. */
  165318. j_decompress_ptr cinfo; /* back link to decompress master record */
  165319. } bitread_working_state;
  165320. /* Macros to declare and load/save bitread local variables. */
  165321. #define BITREAD_STATE_VARS \
  165322. register bit_buf_type get_buffer; \
  165323. register int bits_left; \
  165324. bitread_working_state br_state
  165325. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  165326. br_state.cinfo = cinfop; \
  165327. br_state.next_input_byte = cinfop->src->next_input_byte; \
  165328. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  165329. get_buffer = permstate.get_buffer; \
  165330. bits_left = permstate.bits_left;
  165331. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  165332. cinfop->src->next_input_byte = br_state.next_input_byte; \
  165333. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  165334. permstate.get_buffer = get_buffer; \
  165335. permstate.bits_left = bits_left
  165336. /*
  165337. * These macros provide the in-line portion of bit fetching.
  165338. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  165339. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  165340. * The variables get_buffer and bits_left are assumed to be locals,
  165341. * but the state struct might not be (jpeg_huff_decode needs this).
  165342. * CHECK_BIT_BUFFER(state,n,action);
  165343. * Ensure there are N bits in get_buffer; if suspend, take action.
  165344. * val = GET_BITS(n);
  165345. * Fetch next N bits.
  165346. * val = PEEK_BITS(n);
  165347. * Fetch next N bits without removing them from the buffer.
  165348. * DROP_BITS(n);
  165349. * Discard next N bits.
  165350. * The value N should be a simple variable, not an expression, because it
  165351. * is evaluated multiple times.
  165352. */
  165353. #define CHECK_BIT_BUFFER(state,nbits,action) \
  165354. { if (bits_left < (nbits)) { \
  165355. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  165356. { action; } \
  165357. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  165358. #define GET_BITS(nbits) \
  165359. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  165360. #define PEEK_BITS(nbits) \
  165361. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  165362. #define DROP_BITS(nbits) \
  165363. (bits_left -= (nbits))
  165364. /* Load up the bit buffer to a depth of at least nbits */
  165365. EXTERN(boolean) jpeg_fill_bit_buffer
  165366. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165367. register int bits_left, int nbits));
  165368. /*
  165369. * Code for extracting next Huffman-coded symbol from input bit stream.
  165370. * Again, this is time-critical and we make the main paths be macros.
  165371. *
  165372. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  165373. * without looping. Usually, more than 95% of the Huffman codes will be 8
  165374. * or fewer bits long. The few overlength codes are handled with a loop,
  165375. * which need not be inline code.
  165376. *
  165377. * Notes about the HUFF_DECODE macro:
  165378. * 1. Near the end of the data segment, we may fail to get enough bits
  165379. * for a lookahead. In that case, we do it the hard way.
  165380. * 2. If the lookahead table contains no entry, the next code must be
  165381. * more than HUFF_LOOKAHEAD bits long.
  165382. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  165383. */
  165384. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  165385. { register int nb, look; \
  165386. if (bits_left < HUFF_LOOKAHEAD) { \
  165387. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  165388. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165389. if (bits_left < HUFF_LOOKAHEAD) { \
  165390. nb = 1; goto slowlabel; \
  165391. } \
  165392. } \
  165393. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  165394. if ((nb = htbl->look_nbits[look]) != 0) { \
  165395. DROP_BITS(nb); \
  165396. result = htbl->look_sym[look]; \
  165397. } else { \
  165398. nb = HUFF_LOOKAHEAD+1; \
  165399. slowlabel: \
  165400. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  165401. { failaction; } \
  165402. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  165403. } \
  165404. }
  165405. /* Out-of-line case for Huffman code fetching */
  165406. EXTERN(int) jpeg_huff_decode
  165407. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  165408. register int bits_left, d_derived_tbl * htbl, int min_bits));
  165409. #endif
  165410. /********* End of inlined file: jdhuff.h *********/
  165411. /* Declarations shared with jdphuff.c */
  165412. /*
  165413. * Expanded entropy decoder object for Huffman decoding.
  165414. *
  165415. * The savable_state subrecord contains fields that change within an MCU,
  165416. * but must not be updated permanently until we complete the MCU.
  165417. */
  165418. typedef struct {
  165419. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165420. } savable_state2;
  165421. /* This macro is to work around compilers with missing or broken
  165422. * structure assignment. You'll need to fix this code if you have
  165423. * such a compiler and you change MAX_COMPS_IN_SCAN.
  165424. */
  165425. #ifndef NO_STRUCT_ASSIGN
  165426. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  165427. #else
  165428. #if MAX_COMPS_IN_SCAN == 4
  165429. #define ASSIGN_STATE(dest,src) \
  165430. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  165431. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  165432. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  165433. (dest).last_dc_val[3] = (src).last_dc_val[3])
  165434. #endif
  165435. #endif
  165436. typedef struct {
  165437. struct jpeg_entropy_decoder pub; /* public fields */
  165438. /* These fields are loaded into local variables at start of each MCU.
  165439. * In case of suspension, we exit WITHOUT updating them.
  165440. */
  165441. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  165442. savable_state2 saved; /* Other state at start of MCU */
  165443. /* These fields are NOT loaded into local working state. */
  165444. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165445. /* Pointers to derived tables (these workspaces have image lifespan) */
  165446. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  165447. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  165448. /* Precalculated info set up by start_pass for use in decode_mcu: */
  165449. /* Pointers to derived tables to be used for each block within an MCU */
  165450. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165451. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  165452. /* Whether we care about the DC and AC coefficient values for each block */
  165453. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  165454. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  165455. } huff_entropy_decoder2;
  165456. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  165457. /*
  165458. * Initialize for a Huffman-compressed scan.
  165459. */
  165460. METHODDEF(void)
  165461. start_pass_huff_decoder (j_decompress_ptr cinfo)
  165462. {
  165463. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165464. int ci, blkn, dctbl, actbl;
  165465. jpeg_component_info * compptr;
  165466. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  165467. * This ought to be an error condition, but we make it a warning because
  165468. * there are some baseline files out there with all zeroes in these bytes.
  165469. */
  165470. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  165471. cinfo->Ah != 0 || cinfo->Al != 0)
  165472. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  165473. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165474. compptr = cinfo->cur_comp_info[ci];
  165475. dctbl = compptr->dc_tbl_no;
  165476. actbl = compptr->ac_tbl_no;
  165477. /* Compute derived values for Huffman tables */
  165478. /* We may do this more than once for a table, but it's not expensive */
  165479. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  165480. & entropy->dc_derived_tbls[dctbl]);
  165481. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  165482. & entropy->ac_derived_tbls[actbl]);
  165483. /* Initialize DC predictions to 0 */
  165484. entropy->saved.last_dc_val[ci] = 0;
  165485. }
  165486. /* Precalculate decoding info for each block in an MCU of this scan */
  165487. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165488. ci = cinfo->MCU_membership[blkn];
  165489. compptr = cinfo->cur_comp_info[ci];
  165490. /* Precalculate which table to use for each block */
  165491. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  165492. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  165493. /* Decide whether we really care about the coefficient values */
  165494. if (compptr->component_needed) {
  165495. entropy->dc_needed[blkn] = TRUE;
  165496. /* we don't need the ACs if producing a 1/8th-size image */
  165497. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  165498. } else {
  165499. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  165500. }
  165501. }
  165502. /* Initialize bitread state variables */
  165503. entropy->bitstate.bits_left = 0;
  165504. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  165505. entropy->pub.insufficient_data = FALSE;
  165506. /* Initialize restart counter */
  165507. entropy->restarts_to_go = cinfo->restart_interval;
  165508. }
  165509. /*
  165510. * Compute the derived values for a Huffman table.
  165511. * This routine also performs some validation checks on the table.
  165512. *
  165513. * Note this is also used by jdphuff.c.
  165514. */
  165515. GLOBAL(void)
  165516. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  165517. d_derived_tbl ** pdtbl)
  165518. {
  165519. JHUFF_TBL *htbl;
  165520. d_derived_tbl *dtbl;
  165521. int p, i, l, si, numsymbols;
  165522. int lookbits, ctr;
  165523. char huffsize[257];
  165524. unsigned int huffcode[257];
  165525. unsigned int code;
  165526. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  165527. * paralleling the order of the symbols themselves in htbl->huffval[].
  165528. */
  165529. /* Find the input Huffman table */
  165530. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  165531. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165532. htbl =
  165533. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  165534. if (htbl == NULL)
  165535. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  165536. /* Allocate a workspace if we haven't already done so. */
  165537. if (*pdtbl == NULL)
  165538. *pdtbl = (d_derived_tbl *)
  165539. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165540. SIZEOF(d_derived_tbl));
  165541. dtbl = *pdtbl;
  165542. dtbl->pub = htbl; /* fill in back link */
  165543. /* Figure C.1: make table of Huffman code length for each symbol */
  165544. p = 0;
  165545. for (l = 1; l <= 16; l++) {
  165546. i = (int) htbl->bits[l];
  165547. if (i < 0 || p + i > 256) /* protect against table overrun */
  165548. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165549. while (i--)
  165550. huffsize[p++] = (char) l;
  165551. }
  165552. huffsize[p] = 0;
  165553. numsymbols = p;
  165554. /* Figure C.2: generate the codes themselves */
  165555. /* We also validate that the counts represent a legal Huffman code tree. */
  165556. code = 0;
  165557. si = huffsize[0];
  165558. p = 0;
  165559. while (huffsize[p]) {
  165560. while (((int) huffsize[p]) == si) {
  165561. huffcode[p++] = code;
  165562. code++;
  165563. }
  165564. /* code is now 1 more than the last code used for codelength si; but
  165565. * it must still fit in si bits, since no code is allowed to be all ones.
  165566. */
  165567. if (((INT32) code) >= (((INT32) 1) << si))
  165568. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165569. code <<= 1;
  165570. si++;
  165571. }
  165572. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  165573. p = 0;
  165574. for (l = 1; l <= 16; l++) {
  165575. if (htbl->bits[l]) {
  165576. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  165577. * minus the minimum code of length l
  165578. */
  165579. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  165580. p += htbl->bits[l];
  165581. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  165582. } else {
  165583. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  165584. }
  165585. }
  165586. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  165587. /* Compute lookahead tables to speed up decoding.
  165588. * First we set all the table entries to 0, indicating "too long";
  165589. * then we iterate through the Huffman codes that are short enough and
  165590. * fill in all the entries that correspond to bit sequences starting
  165591. * with that code.
  165592. */
  165593. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  165594. p = 0;
  165595. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  165596. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  165597. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  165598. /* Generate left-justified code followed by all possible bit sequences */
  165599. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  165600. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  165601. dtbl->look_nbits[lookbits] = l;
  165602. dtbl->look_sym[lookbits] = htbl->huffval[p];
  165603. lookbits++;
  165604. }
  165605. }
  165606. }
  165607. /* Validate symbols as being reasonable.
  165608. * For AC tables, we make no check, but accept all byte values 0..255.
  165609. * For DC tables, we require the symbols to be in range 0..15.
  165610. * (Tighter bounds could be applied depending on the data depth and mode,
  165611. * but this is sufficient to ensure safe decoding.)
  165612. */
  165613. if (isDC) {
  165614. for (i = 0; i < numsymbols; i++) {
  165615. int sym = htbl->huffval[i];
  165616. if (sym < 0 || sym > 15)
  165617. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165618. }
  165619. }
  165620. }
  165621. /*
  165622. * Out-of-line code for bit fetching (shared with jdphuff.c).
  165623. * See jdhuff.h for info about usage.
  165624. * Note: current values of get_buffer and bits_left are passed as parameters,
  165625. * but are returned in the corresponding fields of the state struct.
  165626. *
  165627. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  165628. * of get_buffer to be used. (On machines with wider words, an even larger
  165629. * buffer could be used.) However, on some machines 32-bit shifts are
  165630. * quite slow and take time proportional to the number of places shifted.
  165631. * (This is true with most PC compilers, for instance.) In this case it may
  165632. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  165633. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  165634. */
  165635. #ifdef SLOW_SHIFT_32
  165636. #define MIN_GET_BITS 15 /* minimum allowable value */
  165637. #else
  165638. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  165639. #endif
  165640. GLOBAL(boolean)
  165641. jpeg_fill_bit_buffer (bitread_working_state * state,
  165642. register bit_buf_type get_buffer, register int bits_left,
  165643. int nbits)
  165644. /* Load up the bit buffer to a depth of at least nbits */
  165645. {
  165646. /* Copy heavily used state fields into locals (hopefully registers) */
  165647. register const JOCTET * next_input_byte = state->next_input_byte;
  165648. register size_t bytes_in_buffer = state->bytes_in_buffer;
  165649. j_decompress_ptr cinfo = state->cinfo;
  165650. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  165651. /* (It is assumed that no request will be for more than that many bits.) */
  165652. /* We fail to do so only if we hit a marker or are forced to suspend. */
  165653. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  165654. while (bits_left < MIN_GET_BITS) {
  165655. register int c;
  165656. /* Attempt to read a byte */
  165657. if (bytes_in_buffer == 0) {
  165658. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165659. return FALSE;
  165660. next_input_byte = cinfo->src->next_input_byte;
  165661. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165662. }
  165663. bytes_in_buffer--;
  165664. c = GETJOCTET(*next_input_byte++);
  165665. /* If it's 0xFF, check and discard stuffed zero byte */
  165666. if (c == 0xFF) {
  165667. /* Loop here to discard any padding FF's on terminating marker,
  165668. * so that we can save a valid unread_marker value. NOTE: we will
  165669. * accept multiple FF's followed by a 0 as meaning a single FF data
  165670. * byte. This data pattern is not valid according to the standard.
  165671. */
  165672. do {
  165673. if (bytes_in_buffer == 0) {
  165674. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  165675. return FALSE;
  165676. next_input_byte = cinfo->src->next_input_byte;
  165677. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  165678. }
  165679. bytes_in_buffer--;
  165680. c = GETJOCTET(*next_input_byte++);
  165681. } while (c == 0xFF);
  165682. if (c == 0) {
  165683. /* Found FF/00, which represents an FF data byte */
  165684. c = 0xFF;
  165685. } else {
  165686. /* Oops, it's actually a marker indicating end of compressed data.
  165687. * Save the marker code for later use.
  165688. * Fine point: it might appear that we should save the marker into
  165689. * bitread working state, not straight into permanent state. But
  165690. * once we have hit a marker, we cannot need to suspend within the
  165691. * current MCU, because we will read no more bytes from the data
  165692. * source. So it is OK to update permanent state right away.
  165693. */
  165694. cinfo->unread_marker = c;
  165695. /* See if we need to insert some fake zero bits. */
  165696. goto no_more_bytes;
  165697. }
  165698. }
  165699. /* OK, load c into get_buffer */
  165700. get_buffer = (get_buffer << 8) | c;
  165701. bits_left += 8;
  165702. } /* end while */
  165703. } else {
  165704. no_more_bytes:
  165705. /* We get here if we've read the marker that terminates the compressed
  165706. * data segment. There should be enough bits in the buffer register
  165707. * to satisfy the request; if so, no problem.
  165708. */
  165709. if (nbits > bits_left) {
  165710. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  165711. * the data stream, so that we can produce some kind of image.
  165712. * We use a nonvolatile flag to ensure that only one warning message
  165713. * appears per data segment.
  165714. */
  165715. if (! cinfo->entropy->insufficient_data) {
  165716. WARNMS(cinfo, JWRN_HIT_MARKER);
  165717. cinfo->entropy->insufficient_data = TRUE;
  165718. }
  165719. /* Fill the buffer with zero bits */
  165720. get_buffer <<= MIN_GET_BITS - bits_left;
  165721. bits_left = MIN_GET_BITS;
  165722. }
  165723. }
  165724. /* Unload the local registers */
  165725. state->next_input_byte = next_input_byte;
  165726. state->bytes_in_buffer = bytes_in_buffer;
  165727. state->get_buffer = get_buffer;
  165728. state->bits_left = bits_left;
  165729. return TRUE;
  165730. }
  165731. /*
  165732. * Out-of-line code for Huffman code decoding.
  165733. * See jdhuff.h for info about usage.
  165734. */
  165735. GLOBAL(int)
  165736. jpeg_huff_decode (bitread_working_state * state,
  165737. register bit_buf_type get_buffer, register int bits_left,
  165738. d_derived_tbl * htbl, int min_bits)
  165739. {
  165740. register int l = min_bits;
  165741. register INT32 code;
  165742. /* HUFF_DECODE has determined that the code is at least min_bits */
  165743. /* bits long, so fetch that many bits in one swoop. */
  165744. CHECK_BIT_BUFFER(*state, l, return -1);
  165745. code = GET_BITS(l);
  165746. /* Collect the rest of the Huffman code one bit at a time. */
  165747. /* This is per Figure F.16 in the JPEG spec. */
  165748. while (code > htbl->maxcode[l]) {
  165749. code <<= 1;
  165750. CHECK_BIT_BUFFER(*state, 1, return -1);
  165751. code |= GET_BITS(1);
  165752. l++;
  165753. }
  165754. /* Unload the local registers */
  165755. state->get_buffer = get_buffer;
  165756. state->bits_left = bits_left;
  165757. /* With garbage input we may reach the sentinel value l = 17. */
  165758. if (l > 16) {
  165759. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  165760. return 0; /* fake a zero as the safest result */
  165761. }
  165762. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  165763. }
  165764. /*
  165765. * Check for a restart marker & resynchronize decoder.
  165766. * Returns FALSE if must suspend.
  165767. */
  165768. LOCAL(boolean)
  165769. process_restart (j_decompress_ptr cinfo)
  165770. {
  165771. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165772. int ci;
  165773. /* Throw away any unused bits remaining in bit buffer; */
  165774. /* include any full bytes in next_marker's count of discarded bytes */
  165775. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  165776. entropy->bitstate.bits_left = 0;
  165777. /* Advance past the RSTn marker */
  165778. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  165779. return FALSE;
  165780. /* Re-initialize DC predictions to 0 */
  165781. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  165782. entropy->saved.last_dc_val[ci] = 0;
  165783. /* Reset restart counter */
  165784. entropy->restarts_to_go = cinfo->restart_interval;
  165785. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  165786. * against a marker. In that case we will end up treating the next data
  165787. * segment as empty, and we can avoid producing bogus output pixels by
  165788. * leaving the flag set.
  165789. */
  165790. if (cinfo->unread_marker == 0)
  165791. entropy->pub.insufficient_data = FALSE;
  165792. return TRUE;
  165793. }
  165794. /*
  165795. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  165796. * The coefficients are reordered from zigzag order into natural array order,
  165797. * but are not dequantized.
  165798. *
  165799. * The i'th block of the MCU is stored into the block pointed to by
  165800. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  165801. * (Wholesale zeroing is usually a little faster than retail...)
  165802. *
  165803. * Returns FALSE if data source requested suspension. In that case no
  165804. * changes have been made to permanent state. (Exception: some output
  165805. * coefficients may already have been assigned. This is harmless for
  165806. * this module, since we'll just re-assign them on the next call.)
  165807. */
  165808. METHODDEF(boolean)
  165809. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  165810. {
  165811. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  165812. int blkn;
  165813. BITREAD_STATE_VARS;
  165814. savable_state2 state;
  165815. /* Process restart marker if needed; may have to suspend */
  165816. if (cinfo->restart_interval) {
  165817. if (entropy->restarts_to_go == 0)
  165818. if (! process_restart(cinfo))
  165819. return FALSE;
  165820. }
  165821. /* If we've run out of data, just leave the MCU set to zeroes.
  165822. * This way, we return uniform gray for the remainder of the segment.
  165823. */
  165824. if (! entropy->pub.insufficient_data) {
  165825. /* Load up working state */
  165826. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  165827. ASSIGN_STATE(state, entropy->saved);
  165828. /* Outer loop handles each block in the MCU */
  165829. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  165830. JBLOCKROW block = MCU_data[blkn];
  165831. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  165832. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  165833. register int s, k, r;
  165834. /* Decode a single block's worth of coefficients */
  165835. /* Section F.2.2.1: decode the DC coefficient difference */
  165836. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  165837. if (s) {
  165838. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165839. r = GET_BITS(s);
  165840. s = HUFF_EXTEND(r, s);
  165841. }
  165842. if (entropy->dc_needed[blkn]) {
  165843. /* Convert DC difference to actual value, update last_dc_val */
  165844. int ci = cinfo->MCU_membership[blkn];
  165845. s += state.last_dc_val[ci];
  165846. state.last_dc_val[ci] = s;
  165847. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  165848. (*block)[0] = (JCOEF) s;
  165849. }
  165850. if (entropy->ac_needed[blkn]) {
  165851. /* Section F.2.2.2: decode the AC coefficients */
  165852. /* Since zeroes are skipped, output area must be cleared beforehand */
  165853. for (k = 1; k < DCTSIZE2; k++) {
  165854. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  165855. r = s >> 4;
  165856. s &= 15;
  165857. if (s) {
  165858. k += r;
  165859. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165860. r = GET_BITS(s);
  165861. s = HUFF_EXTEND(r, s);
  165862. /* Output coefficient in natural (dezigzagged) order.
  165863. * Note: the extra entries in jpeg_natural_order[] will save us
  165864. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  165865. */
  165866. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  165867. } else {
  165868. if (r != 15)
  165869. break;
  165870. k += 15;
  165871. }
  165872. }
  165873. } else {
  165874. /* Section F.2.2.2: decode the AC coefficients */
  165875. /* In this path we just discard the values */
  165876. for (k = 1; k < DCTSIZE2; k++) {
  165877. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  165878. r = s >> 4;
  165879. s &= 15;
  165880. if (s) {
  165881. k += r;
  165882. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  165883. DROP_BITS(s);
  165884. } else {
  165885. if (r != 15)
  165886. break;
  165887. k += 15;
  165888. }
  165889. }
  165890. }
  165891. }
  165892. /* Completed MCU, so update state */
  165893. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  165894. ASSIGN_STATE(entropy->saved, state);
  165895. }
  165896. /* Account for restart interval (no-op if not using restarts) */
  165897. entropy->restarts_to_go--;
  165898. return TRUE;
  165899. }
  165900. /*
  165901. * Module initialization routine for Huffman entropy decoding.
  165902. */
  165903. GLOBAL(void)
  165904. jinit_huff_decoder (j_decompress_ptr cinfo)
  165905. {
  165906. huff_entropy_ptr2 entropy;
  165907. int i;
  165908. entropy = (huff_entropy_ptr2)
  165909. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165910. SIZEOF(huff_entropy_decoder2));
  165911. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  165912. entropy->pub.start_pass = start_pass_huff_decoder;
  165913. entropy->pub.decode_mcu = decode_mcu;
  165914. /* Mark tables unallocated */
  165915. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165916. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  165917. }
  165918. }
  165919. /********* End of inlined file: jdhuff.c *********/
  165920. /********* Start of inlined file: jdinput.c *********/
  165921. #define JPEG_INTERNALS
  165922. /* Private state */
  165923. typedef struct {
  165924. struct jpeg_input_controller pub; /* public fields */
  165925. boolean inheaders; /* TRUE until first SOS is reached */
  165926. } my_input_controller;
  165927. typedef my_input_controller * my_inputctl_ptr;
  165928. /* Forward declarations */
  165929. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  165930. /*
  165931. * Routines to calculate various quantities related to the size of the image.
  165932. */
  165933. LOCAL(void)
  165934. initial_setup2 (j_decompress_ptr cinfo)
  165935. /* Called once, when first SOS marker is reached */
  165936. {
  165937. int ci;
  165938. jpeg_component_info *compptr;
  165939. /* Make sure image isn't bigger than I can handle */
  165940. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  165941. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  165942. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  165943. /* For now, precision must match compiled-in value... */
  165944. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165945. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165946. /* Check that number of components won't exceed internal array sizes */
  165947. if (cinfo->num_components > MAX_COMPONENTS)
  165948. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165949. MAX_COMPONENTS);
  165950. /* Compute maximum sampling factors; check factor validity */
  165951. cinfo->max_h_samp_factor = 1;
  165952. cinfo->max_v_samp_factor = 1;
  165953. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165954. ci++, compptr++) {
  165955. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165956. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165957. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165958. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165959. compptr->h_samp_factor);
  165960. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165961. compptr->v_samp_factor);
  165962. }
  165963. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  165964. * In the full decompressor, this will be overridden by jdmaster.c;
  165965. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  165966. */
  165967. cinfo->min_DCT_scaled_size = DCTSIZE;
  165968. /* Compute dimensions of components */
  165969. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165970. ci++, compptr++) {
  165971. compptr->DCT_scaled_size = DCTSIZE;
  165972. /* Size in DCT blocks */
  165973. compptr->width_in_blocks = (JDIMENSION)
  165974. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165975. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165976. compptr->height_in_blocks = (JDIMENSION)
  165977. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165978. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165979. /* downsampled_width and downsampled_height will also be overridden by
  165980. * jdmaster.c if we are doing full decompression. The transcoder library
  165981. * doesn't use these values, but the calling application might.
  165982. */
  165983. /* Size in samples */
  165984. compptr->downsampled_width = (JDIMENSION)
  165985. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165986. (long) cinfo->max_h_samp_factor);
  165987. compptr->downsampled_height = (JDIMENSION)
  165988. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165989. (long) cinfo->max_v_samp_factor);
  165990. /* Mark component needed, until color conversion says otherwise */
  165991. compptr->component_needed = TRUE;
  165992. /* Mark no quantization table yet saved for component */
  165993. compptr->quant_table = NULL;
  165994. }
  165995. /* Compute number of fully interleaved MCU rows. */
  165996. cinfo->total_iMCU_rows = (JDIMENSION)
  165997. jdiv_round_up((long) cinfo->image_height,
  165998. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165999. /* Decide whether file contains multiple scans */
  166000. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  166001. cinfo->inputctl->has_multiple_scans = TRUE;
  166002. else
  166003. cinfo->inputctl->has_multiple_scans = FALSE;
  166004. }
  166005. LOCAL(void)
  166006. per_scan_setup2 (j_decompress_ptr cinfo)
  166007. /* Do computations that are needed before processing a JPEG scan */
  166008. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  166009. {
  166010. int ci, mcublks, tmp;
  166011. jpeg_component_info *compptr;
  166012. if (cinfo->comps_in_scan == 1) {
  166013. /* Noninterleaved (single-component) scan */
  166014. compptr = cinfo->cur_comp_info[0];
  166015. /* Overall image size in MCUs */
  166016. cinfo->MCUs_per_row = compptr->width_in_blocks;
  166017. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  166018. /* For noninterleaved scan, always one block per MCU */
  166019. compptr->MCU_width = 1;
  166020. compptr->MCU_height = 1;
  166021. compptr->MCU_blocks = 1;
  166022. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  166023. compptr->last_col_width = 1;
  166024. /* For noninterleaved scans, it is convenient to define last_row_height
  166025. * as the number of block rows present in the last iMCU row.
  166026. */
  166027. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  166028. if (tmp == 0) tmp = compptr->v_samp_factor;
  166029. compptr->last_row_height = tmp;
  166030. /* Prepare array describing MCU composition */
  166031. cinfo->blocks_in_MCU = 1;
  166032. cinfo->MCU_membership[0] = 0;
  166033. } else {
  166034. /* Interleaved (multi-component) scan */
  166035. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  166036. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  166037. MAX_COMPS_IN_SCAN);
  166038. /* Overall image size in MCUs */
  166039. cinfo->MCUs_per_row = (JDIMENSION)
  166040. jdiv_round_up((long) cinfo->image_width,
  166041. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  166042. cinfo->MCU_rows_in_scan = (JDIMENSION)
  166043. jdiv_round_up((long) cinfo->image_height,
  166044. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  166045. cinfo->blocks_in_MCU = 0;
  166046. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166047. compptr = cinfo->cur_comp_info[ci];
  166048. /* Sampling factors give # of blocks of component in each MCU */
  166049. compptr->MCU_width = compptr->h_samp_factor;
  166050. compptr->MCU_height = compptr->v_samp_factor;
  166051. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  166052. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  166053. /* Figure number of non-dummy blocks in last MCU column & row */
  166054. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  166055. if (tmp == 0) tmp = compptr->MCU_width;
  166056. compptr->last_col_width = tmp;
  166057. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  166058. if (tmp == 0) tmp = compptr->MCU_height;
  166059. compptr->last_row_height = tmp;
  166060. /* Prepare array describing MCU composition */
  166061. mcublks = compptr->MCU_blocks;
  166062. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  166063. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166064. while (mcublks-- > 0) {
  166065. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166066. }
  166067. }
  166068. }
  166069. }
  166070. /*
  166071. * Save away a copy of the Q-table referenced by each component present
  166072. * in the current scan, unless already saved during a prior scan.
  166073. *
  166074. * In a multiple-scan JPEG file, the encoder could assign different components
  166075. * the same Q-table slot number, but change table definitions between scans
  166076. * so that each component uses a different Q-table. (The IJG encoder is not
  166077. * currently capable of doing this, but other encoders might.) Since we want
  166078. * to be able to dequantize all the components at the end of the file, this
  166079. * means that we have to save away the table actually used for each component.
  166080. * We do this by copying the table at the start of the first scan containing
  166081. * the component.
  166082. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  166083. * slot between scans of a component using that slot. If the encoder does so
  166084. * anyway, this decoder will simply use the Q-table values that were current
  166085. * at the start of the first scan for the component.
  166086. *
  166087. * The decompressor output side looks only at the saved quant tables,
  166088. * not at the current Q-table slots.
  166089. */
  166090. LOCAL(void)
  166091. latch_quant_tables (j_decompress_ptr cinfo)
  166092. {
  166093. int ci, qtblno;
  166094. jpeg_component_info *compptr;
  166095. JQUANT_TBL * qtbl;
  166096. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166097. compptr = cinfo->cur_comp_info[ci];
  166098. /* No work if we already saved Q-table for this component */
  166099. if (compptr->quant_table != NULL)
  166100. continue;
  166101. /* Make sure specified quantization table is present */
  166102. qtblno = compptr->quant_tbl_no;
  166103. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  166104. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  166105. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  166106. /* OK, save away the quantization table */
  166107. qtbl = (JQUANT_TBL *)
  166108. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166109. SIZEOF(JQUANT_TBL));
  166110. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  166111. compptr->quant_table = qtbl;
  166112. }
  166113. }
  166114. /*
  166115. * Initialize the input modules to read a scan of compressed data.
  166116. * The first call to this is done by jdmaster.c after initializing
  166117. * the entire decompressor (during jpeg_start_decompress).
  166118. * Subsequent calls come from consume_markers, below.
  166119. */
  166120. METHODDEF(void)
  166121. start_input_pass2 (j_decompress_ptr cinfo)
  166122. {
  166123. per_scan_setup2(cinfo);
  166124. latch_quant_tables(cinfo);
  166125. (*cinfo->entropy->start_pass) (cinfo);
  166126. (*cinfo->coef->start_input_pass) (cinfo);
  166127. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  166128. }
  166129. /*
  166130. * Finish up after inputting a compressed-data scan.
  166131. * This is called by the coefficient controller after it's read all
  166132. * the expected data of the scan.
  166133. */
  166134. METHODDEF(void)
  166135. finish_input_pass (j_decompress_ptr cinfo)
  166136. {
  166137. cinfo->inputctl->consume_input = consume_markers;
  166138. }
  166139. /*
  166140. * Read JPEG markers before, between, or after compressed-data scans.
  166141. * Change state as necessary when a new scan is reached.
  166142. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  166143. *
  166144. * The consume_input method pointer points either here or to the
  166145. * coefficient controller's consume_data routine, depending on whether
  166146. * we are reading a compressed data segment or inter-segment markers.
  166147. */
  166148. METHODDEF(int)
  166149. consume_markers (j_decompress_ptr cinfo)
  166150. {
  166151. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166152. int val;
  166153. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  166154. return JPEG_REACHED_EOI;
  166155. val = (*cinfo->marker->read_markers) (cinfo);
  166156. switch (val) {
  166157. case JPEG_REACHED_SOS: /* Found SOS */
  166158. if (inputctl->inheaders) { /* 1st SOS */
  166159. initial_setup2(cinfo);
  166160. inputctl->inheaders = FALSE;
  166161. /* Note: start_input_pass must be called by jdmaster.c
  166162. * before any more input can be consumed. jdapimin.c is
  166163. * responsible for enforcing this sequencing.
  166164. */
  166165. } else { /* 2nd or later SOS marker */
  166166. if (! inputctl->pub.has_multiple_scans)
  166167. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  166168. start_input_pass2(cinfo);
  166169. }
  166170. break;
  166171. case JPEG_REACHED_EOI: /* Found EOI */
  166172. inputctl->pub.eoi_reached = TRUE;
  166173. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  166174. if (cinfo->marker->saw_SOF)
  166175. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  166176. } else {
  166177. /* Prevent infinite loop in coef ctlr's decompress_data routine
  166178. * if user set output_scan_number larger than number of scans.
  166179. */
  166180. if (cinfo->output_scan_number > cinfo->input_scan_number)
  166181. cinfo->output_scan_number = cinfo->input_scan_number;
  166182. }
  166183. break;
  166184. case JPEG_SUSPENDED:
  166185. break;
  166186. }
  166187. return val;
  166188. }
  166189. /*
  166190. * Reset state to begin a fresh datastream.
  166191. */
  166192. METHODDEF(void)
  166193. reset_input_controller (j_decompress_ptr cinfo)
  166194. {
  166195. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  166196. inputctl->pub.consume_input = consume_markers;
  166197. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166198. inputctl->pub.eoi_reached = FALSE;
  166199. inputctl->inheaders = TRUE;
  166200. /* Reset other modules */
  166201. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  166202. (*cinfo->marker->reset_marker_reader) (cinfo);
  166203. /* Reset progression state -- would be cleaner if entropy decoder did this */
  166204. cinfo->coef_bits = NULL;
  166205. }
  166206. /*
  166207. * Initialize the input controller module.
  166208. * This is called only once, when the decompression object is created.
  166209. */
  166210. GLOBAL(void)
  166211. jinit_input_controller (j_decompress_ptr cinfo)
  166212. {
  166213. my_inputctl_ptr inputctl;
  166214. /* Create subobject in permanent pool */
  166215. inputctl = (my_inputctl_ptr)
  166216. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166217. SIZEOF(my_input_controller));
  166218. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  166219. /* Initialize method pointers */
  166220. inputctl->pub.consume_input = consume_markers;
  166221. inputctl->pub.reset_input_controller = reset_input_controller;
  166222. inputctl->pub.start_input_pass = start_input_pass2;
  166223. inputctl->pub.finish_input_pass = finish_input_pass;
  166224. /* Initialize state: can't use reset_input_controller since we don't
  166225. * want to try to reset other modules yet.
  166226. */
  166227. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  166228. inputctl->pub.eoi_reached = FALSE;
  166229. inputctl->inheaders = TRUE;
  166230. }
  166231. /********* End of inlined file: jdinput.c *********/
  166232. /********* Start of inlined file: jdmainct.c *********/
  166233. #define JPEG_INTERNALS
  166234. /*
  166235. * In the current system design, the main buffer need never be a full-image
  166236. * buffer; any full-height buffers will be found inside the coefficient or
  166237. * postprocessing controllers. Nonetheless, the main controller is not
  166238. * trivial. Its responsibility is to provide context rows for upsampling/
  166239. * rescaling, and doing this in an efficient fashion is a bit tricky.
  166240. *
  166241. * Postprocessor input data is counted in "row groups". A row group
  166242. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  166243. * sample rows of each component. (We require DCT_scaled_size values to be
  166244. * chosen such that these numbers are integers. In practice DCT_scaled_size
  166245. * values will likely be powers of two, so we actually have the stronger
  166246. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  166247. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  166248. * row group (times any additional scale factor that the upsampler is
  166249. * applying).
  166250. *
  166251. * The coefficient controller will deliver data to us one iMCU row at a time;
  166252. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  166253. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  166254. * to one row of MCUs when the image is fully interleaved.) Note that the
  166255. * number of sample rows varies across components, but the number of row
  166256. * groups does not. Some garbage sample rows may be included in the last iMCU
  166257. * row at the bottom of the image.
  166258. *
  166259. * Depending on the vertical scaling algorithm used, the upsampler may need
  166260. * access to the sample row(s) above and below its current input row group.
  166261. * The upsampler is required to set need_context_rows TRUE at global selection
  166262. * time if so. When need_context_rows is FALSE, this controller can simply
  166263. * obtain one iMCU row at a time from the coefficient controller and dole it
  166264. * out as row groups to the postprocessor.
  166265. *
  166266. * When need_context_rows is TRUE, this controller guarantees that the buffer
  166267. * passed to postprocessing contains at least one row group's worth of samples
  166268. * above and below the row group(s) being processed. Note that the context
  166269. * rows "above" the first passed row group appear at negative row offsets in
  166270. * the passed buffer. At the top and bottom of the image, the required
  166271. * context rows are manufactured by duplicating the first or last real sample
  166272. * row; this avoids having special cases in the upsampling inner loops.
  166273. *
  166274. * The amount of context is fixed at one row group just because that's a
  166275. * convenient number for this controller to work with. The existing
  166276. * upsamplers really only need one sample row of context. An upsampler
  166277. * supporting arbitrary output rescaling might wish for more than one row
  166278. * group of context when shrinking the image; tough, we don't handle that.
  166279. * (This is justified by the assumption that downsizing will be handled mostly
  166280. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  166281. * the upsample step needn't be much less than one.)
  166282. *
  166283. * To provide the desired context, we have to retain the last two row groups
  166284. * of one iMCU row while reading in the next iMCU row. (The last row group
  166285. * can't be processed until we have another row group for its below-context,
  166286. * and so we have to save the next-to-last group too for its above-context.)
  166287. * We could do this most simply by copying data around in our buffer, but
  166288. * that'd be very slow. We can avoid copying any data by creating a rather
  166289. * strange pointer structure. Here's how it works. We allocate a workspace
  166290. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  166291. * of row groups per iMCU row). We create two sets of redundant pointers to
  166292. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  166293. * pointer lists look like this:
  166294. * M+1 M-1
  166295. * master pointer --> 0 master pointer --> 0
  166296. * 1 1
  166297. * ... ...
  166298. * M-3 M-3
  166299. * M-2 M
  166300. * M-1 M+1
  166301. * M M-2
  166302. * M+1 M-1
  166303. * 0 0
  166304. * We read alternate iMCU rows using each master pointer; thus the last two
  166305. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  166306. * The pointer lists are set up so that the required context rows appear to
  166307. * be adjacent to the proper places when we pass the pointer lists to the
  166308. * upsampler.
  166309. *
  166310. * The above pictures describe the normal state of the pointer lists.
  166311. * At top and bottom of the image, we diddle the pointer lists to duplicate
  166312. * the first or last sample row as necessary (this is cheaper than copying
  166313. * sample rows around).
  166314. *
  166315. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  166316. * situation each iMCU row provides only one row group so the buffering logic
  166317. * must be different (eg, we must read two iMCU rows before we can emit the
  166318. * first row group). For now, we simply do not support providing context
  166319. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  166320. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  166321. * want it quick and dirty, so a context-free upsampler is sufficient.
  166322. */
  166323. /* Private buffer controller object */
  166324. typedef struct {
  166325. struct jpeg_d_main_controller pub; /* public fields */
  166326. /* Pointer to allocated workspace (M or M+2 row groups). */
  166327. JSAMPARRAY buffer[MAX_COMPONENTS];
  166328. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  166329. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  166330. /* Remaining fields are only used in the context case. */
  166331. /* These are the master pointers to the funny-order pointer lists. */
  166332. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  166333. int whichptr; /* indicates which pointer set is now in use */
  166334. int context_state; /* process_data state machine status */
  166335. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  166336. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  166337. } my_main_controller4;
  166338. typedef my_main_controller4 * my_main_ptr4;
  166339. /* context_state values: */
  166340. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  166341. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  166342. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  166343. /* Forward declarations */
  166344. METHODDEF(void) process_data_simple_main2
  166345. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166346. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166347. METHODDEF(void) process_data_context_main
  166348. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166349. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166350. #ifdef QUANT_2PASS_SUPPORTED
  166351. METHODDEF(void) process_data_crank_post
  166352. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  166353. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  166354. #endif
  166355. LOCAL(void)
  166356. alloc_funny_pointers (j_decompress_ptr cinfo)
  166357. /* Allocate space for the funny pointer lists.
  166358. * This is done only once, not once per pass.
  166359. */
  166360. {
  166361. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166362. int ci, rgroup;
  166363. int M = cinfo->min_DCT_scaled_size;
  166364. jpeg_component_info *compptr;
  166365. JSAMPARRAY xbuf;
  166366. /* Get top-level space for component array pointers.
  166367. * We alloc both arrays with one call to save a few cycles.
  166368. */
  166369. main_->xbuffer[0] = (JSAMPIMAGE)
  166370. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166371. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  166372. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  166373. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166374. ci++, compptr++) {
  166375. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166376. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166377. /* Get space for pointer lists --- M+4 row groups in each list.
  166378. * We alloc both pointer lists with one call to save a few cycles.
  166379. */
  166380. xbuf = (JSAMPARRAY)
  166381. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166382. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  166383. xbuf += rgroup; /* want one row group at negative offsets */
  166384. main_->xbuffer[0][ci] = xbuf;
  166385. xbuf += rgroup * (M + 4);
  166386. main_->xbuffer[1][ci] = xbuf;
  166387. }
  166388. }
  166389. LOCAL(void)
  166390. make_funny_pointers (j_decompress_ptr cinfo)
  166391. /* Create the funny pointer lists discussed in the comments above.
  166392. * The actual workspace is already allocated (in main->buffer),
  166393. * and the space for the pointer lists is allocated too.
  166394. * This routine just fills in the curiously ordered lists.
  166395. * This will be repeated at the beginning of each pass.
  166396. */
  166397. {
  166398. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166399. int ci, i, rgroup;
  166400. int M = cinfo->min_DCT_scaled_size;
  166401. jpeg_component_info *compptr;
  166402. JSAMPARRAY buf, xbuf0, xbuf1;
  166403. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166404. ci++, compptr++) {
  166405. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166406. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166407. xbuf0 = main_->xbuffer[0][ci];
  166408. xbuf1 = main_->xbuffer[1][ci];
  166409. /* First copy the workspace pointers as-is */
  166410. buf = main_->buffer[ci];
  166411. for (i = 0; i < rgroup * (M + 2); i++) {
  166412. xbuf0[i] = xbuf1[i] = buf[i];
  166413. }
  166414. /* In the second list, put the last four row groups in swapped order */
  166415. for (i = 0; i < rgroup * 2; i++) {
  166416. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  166417. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  166418. }
  166419. /* The wraparound pointers at top and bottom will be filled later
  166420. * (see set_wraparound_pointers, below). Initially we want the "above"
  166421. * pointers to duplicate the first actual data line. This only needs
  166422. * to happen in xbuffer[0].
  166423. */
  166424. for (i = 0; i < rgroup; i++) {
  166425. xbuf0[i - rgroup] = xbuf0[0];
  166426. }
  166427. }
  166428. }
  166429. LOCAL(void)
  166430. set_wraparound_pointers (j_decompress_ptr cinfo)
  166431. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  166432. * This changes the pointer list state from top-of-image to the normal state.
  166433. */
  166434. {
  166435. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166436. int ci, i, rgroup;
  166437. int M = cinfo->min_DCT_scaled_size;
  166438. jpeg_component_info *compptr;
  166439. JSAMPARRAY xbuf0, xbuf1;
  166440. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166441. ci++, compptr++) {
  166442. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166443. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166444. xbuf0 = main_->xbuffer[0][ci];
  166445. xbuf1 = main_->xbuffer[1][ci];
  166446. for (i = 0; i < rgroup; i++) {
  166447. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  166448. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  166449. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  166450. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  166451. }
  166452. }
  166453. }
  166454. LOCAL(void)
  166455. set_bottom_pointers (j_decompress_ptr cinfo)
  166456. /* Change the pointer lists to duplicate the last sample row at the bottom
  166457. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  166458. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  166459. */
  166460. {
  166461. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166462. int ci, i, rgroup, iMCUheight, rows_left;
  166463. jpeg_component_info *compptr;
  166464. JSAMPARRAY xbuf;
  166465. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166466. ci++, compptr++) {
  166467. /* Count sample rows in one iMCU row and in one row group */
  166468. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  166469. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  166470. /* Count nondummy sample rows remaining for this component */
  166471. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  166472. if (rows_left == 0) rows_left = iMCUheight;
  166473. /* Count nondummy row groups. Should get same answer for each component,
  166474. * so we need only do it once.
  166475. */
  166476. if (ci == 0) {
  166477. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  166478. }
  166479. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  166480. * last partial rowgroup and ensures at least one full rowgroup of context.
  166481. */
  166482. xbuf = main_->xbuffer[main_->whichptr][ci];
  166483. for (i = 0; i < rgroup * 2; i++) {
  166484. xbuf[rows_left + i] = xbuf[rows_left-1];
  166485. }
  166486. }
  166487. }
  166488. /*
  166489. * Initialize for a processing pass.
  166490. */
  166491. METHODDEF(void)
  166492. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166493. {
  166494. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166495. switch (pass_mode) {
  166496. case JBUF_PASS_THRU:
  166497. if (cinfo->upsample->need_context_rows) {
  166498. main_->pub.process_data = process_data_context_main;
  166499. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  166500. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  166501. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166502. main_->iMCU_row_ctr = 0;
  166503. } else {
  166504. /* Simple case with no context needed */
  166505. main_->pub.process_data = process_data_simple_main2;
  166506. }
  166507. main_->buffer_full = FALSE; /* Mark buffer empty */
  166508. main_->rowgroup_ctr = 0;
  166509. break;
  166510. #ifdef QUANT_2PASS_SUPPORTED
  166511. case JBUF_CRANK_DEST:
  166512. /* For last pass of 2-pass quantization, just crank the postprocessor */
  166513. main_->pub.process_data = process_data_crank_post;
  166514. break;
  166515. #endif
  166516. default:
  166517. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166518. break;
  166519. }
  166520. }
  166521. /*
  166522. * Process some data.
  166523. * This handles the simple case where no context is required.
  166524. */
  166525. METHODDEF(void)
  166526. process_data_simple_main2 (j_decompress_ptr cinfo,
  166527. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166528. JDIMENSION out_rows_avail)
  166529. {
  166530. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166531. JDIMENSION rowgroups_avail;
  166532. /* Read input data if we haven't filled the main buffer yet */
  166533. if (! main_->buffer_full) {
  166534. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  166535. return; /* suspension forced, can do nothing more */
  166536. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166537. }
  166538. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  166539. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  166540. /* Note: at the bottom of the image, we may pass extra garbage row groups
  166541. * to the postprocessor. The postprocessor has to check for bottom
  166542. * of image anyway (at row resolution), so no point in us doing it too.
  166543. */
  166544. /* Feed the postprocessor */
  166545. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  166546. &main_->rowgroup_ctr, rowgroups_avail,
  166547. output_buf, out_row_ctr, out_rows_avail);
  166548. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  166549. if (main_->rowgroup_ctr >= rowgroups_avail) {
  166550. main_->buffer_full = FALSE;
  166551. main_->rowgroup_ctr = 0;
  166552. }
  166553. }
  166554. /*
  166555. * Process some data.
  166556. * This handles the case where context rows must be provided.
  166557. */
  166558. METHODDEF(void)
  166559. process_data_context_main (j_decompress_ptr cinfo,
  166560. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166561. JDIMENSION out_rows_avail)
  166562. {
  166563. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  166564. /* Read input data if we haven't filled the main buffer yet */
  166565. if (! main_->buffer_full) {
  166566. if (! (*cinfo->coef->decompress_data) (cinfo,
  166567. main_->xbuffer[main_->whichptr]))
  166568. return; /* suspension forced, can do nothing more */
  166569. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  166570. main_->iMCU_row_ctr++; /* count rows received */
  166571. }
  166572. /* Postprocessor typically will not swallow all the input data it is handed
  166573. * in one call (due to filling the output buffer first). Must be prepared
  166574. * to exit and restart. This switch lets us keep track of how far we got.
  166575. * Note that each case falls through to the next on successful completion.
  166576. */
  166577. switch (main_->context_state) {
  166578. case CTX_POSTPONED_ROW:
  166579. /* Call postprocessor using previously set pointers for postponed row */
  166580. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  166581. &main_->rowgroup_ctr, main_->rowgroups_avail,
  166582. output_buf, out_row_ctr, out_rows_avail);
  166583. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  166584. return; /* Need to suspend */
  166585. main_->context_state = CTX_PREPARE_FOR_IMCU;
  166586. if (*out_row_ctr >= out_rows_avail)
  166587. return; /* Postprocessor exactly filled output buf */
  166588. /*FALLTHROUGH*/
  166589. case CTX_PREPARE_FOR_IMCU:
  166590. /* Prepare to process first M-1 row groups of this iMCU row */
  166591. main_->rowgroup_ctr = 0;
  166592. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  166593. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  166594. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  166595. */
  166596. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  166597. set_bottom_pointers(cinfo);
  166598. main_->context_state = CTX_PROCESS_IMCU;
  166599. /*FALLTHROUGH*/
  166600. case CTX_PROCESS_IMCU:
  166601. /* Call postprocessor using previously set pointers */
  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. /* After the first iMCU, change wraparound pointers to normal state */
  166608. if (main_->iMCU_row_ctr == 1)
  166609. set_wraparound_pointers(cinfo);
  166610. /* Prepare to load new iMCU row using other xbuffer list */
  166611. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  166612. main_->buffer_full = FALSE;
  166613. /* Still need to process last row group of this iMCU row, */
  166614. /* which is saved at index M+1 of the other xbuffer */
  166615. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  166616. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  166617. main_->context_state = CTX_POSTPONED_ROW;
  166618. }
  166619. }
  166620. /*
  166621. * Process some data.
  166622. * Final pass of two-pass quantization: just call the postprocessor.
  166623. * Source data will be the postprocessor controller's internal buffer.
  166624. */
  166625. #ifdef QUANT_2PASS_SUPPORTED
  166626. METHODDEF(void)
  166627. process_data_crank_post (j_decompress_ptr cinfo,
  166628. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166629. JDIMENSION out_rows_avail)
  166630. {
  166631. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  166632. (JDIMENSION *) NULL, (JDIMENSION) 0,
  166633. output_buf, out_row_ctr, out_rows_avail);
  166634. }
  166635. #endif /* QUANT_2PASS_SUPPORTED */
  166636. /*
  166637. * Initialize main buffer controller.
  166638. */
  166639. GLOBAL(void)
  166640. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  166641. {
  166642. my_main_ptr4 main_;
  166643. int ci, rgroup, ngroups;
  166644. jpeg_component_info *compptr;
  166645. main_ = (my_main_ptr4)
  166646. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166647. SIZEOF(my_main_controller4));
  166648. cinfo->main = (struct jpeg_d_main_controller *) main_;
  166649. main_->pub.start_pass = start_pass_main2;
  166650. if (need_full_buffer) /* shouldn't happen */
  166651. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166652. /* Allocate the workspace.
  166653. * ngroups is the number of row groups we need.
  166654. */
  166655. if (cinfo->upsample->need_context_rows) {
  166656. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  166657. ERREXIT(cinfo, JERR_NOTIMPL);
  166658. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  166659. ngroups = cinfo->min_DCT_scaled_size + 2;
  166660. } else {
  166661. ngroups = cinfo->min_DCT_scaled_size;
  166662. }
  166663. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166664. ci++, compptr++) {
  166665. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  166666. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  166667. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  166668. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166669. compptr->width_in_blocks * compptr->DCT_scaled_size,
  166670. (JDIMENSION) (rgroup * ngroups));
  166671. }
  166672. }
  166673. /********* End of inlined file: jdmainct.c *********/
  166674. /********* Start of inlined file: jdmarker.c *********/
  166675. #define JPEG_INTERNALS
  166676. /* Private state */
  166677. typedef struct {
  166678. struct jpeg_marker_reader pub; /* public fields */
  166679. /* Application-overridable marker processing methods */
  166680. jpeg_marker_parser_method process_COM;
  166681. jpeg_marker_parser_method process_APPn[16];
  166682. /* Limit on marker data length to save for each marker type */
  166683. unsigned int length_limit_COM;
  166684. unsigned int length_limit_APPn[16];
  166685. /* Status of COM/APPn marker saving */
  166686. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  166687. unsigned int bytes_read; /* data bytes read so far in marker */
  166688. /* Note: cur_marker is not linked into marker_list until it's all read. */
  166689. } my_marker_reader;
  166690. typedef my_marker_reader * my_marker_ptr2;
  166691. /*
  166692. * Macros for fetching data from the data source module.
  166693. *
  166694. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  166695. * the current restart point; we update them only when we have reached a
  166696. * suitable place to restart if a suspension occurs.
  166697. */
  166698. /* Declare and initialize local copies of input pointer/count */
  166699. #define INPUT_VARS(cinfo) \
  166700. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  166701. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  166702. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  166703. /* Unload the local copies --- do this only at a restart boundary */
  166704. #define INPUT_SYNC(cinfo) \
  166705. ( datasrc->next_input_byte = next_input_byte, \
  166706. datasrc->bytes_in_buffer = bytes_in_buffer )
  166707. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  166708. #define INPUT_RELOAD(cinfo) \
  166709. ( next_input_byte = datasrc->next_input_byte, \
  166710. bytes_in_buffer = datasrc->bytes_in_buffer )
  166711. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  166712. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  166713. * but we must reload the local copies after a successful fill.
  166714. */
  166715. #define MAKE_BYTE_AVAIL(cinfo,action) \
  166716. if (bytes_in_buffer == 0) { \
  166717. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  166718. { action; } \
  166719. INPUT_RELOAD(cinfo); \
  166720. }
  166721. /* Read a byte into variable V.
  166722. * If must suspend, take the specified action (typically "return FALSE").
  166723. */
  166724. #define INPUT_BYTE(cinfo,V,action) \
  166725. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166726. bytes_in_buffer--; \
  166727. V = GETJOCTET(*next_input_byte++); )
  166728. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  166729. * V should be declared unsigned int or perhaps INT32.
  166730. */
  166731. #define INPUT_2BYTES(cinfo,V,action) \
  166732. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  166733. bytes_in_buffer--; \
  166734. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  166735. MAKE_BYTE_AVAIL(cinfo,action); \
  166736. bytes_in_buffer--; \
  166737. V += GETJOCTET(*next_input_byte++); )
  166738. /*
  166739. * Routines to process JPEG markers.
  166740. *
  166741. * Entry condition: JPEG marker itself has been read and its code saved
  166742. * in cinfo->unread_marker; input restart point is just after the marker.
  166743. *
  166744. * Exit: if return TRUE, have read and processed any parameters, and have
  166745. * updated the restart point to point after the parameters.
  166746. * If return FALSE, was forced to suspend before reaching end of
  166747. * marker parameters; restart point has not been moved. Same routine
  166748. * will be called again after application supplies more input data.
  166749. *
  166750. * This approach to suspension assumes that all of a marker's parameters
  166751. * can fit into a single input bufferload. This should hold for "normal"
  166752. * markers. Some COM/APPn markers might have large parameter segments
  166753. * that might not fit. If we are simply dropping such a marker, we use
  166754. * skip_input_data to get past it, and thereby put the problem on the
  166755. * source manager's shoulders. If we are saving the marker's contents
  166756. * into memory, we use a slightly different convention: when forced to
  166757. * suspend, the marker processor updates the restart point to the end of
  166758. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  166759. * On resumption, cinfo->unread_marker still contains the marker code,
  166760. * but the data source will point to the next chunk of marker data.
  166761. * The marker processor must retain internal state to deal with this.
  166762. *
  166763. * Note that we don't bother to avoid duplicate trace messages if a
  166764. * suspension occurs within marker parameters. Other side effects
  166765. * require more care.
  166766. */
  166767. LOCAL(boolean)
  166768. get_soi (j_decompress_ptr cinfo)
  166769. /* Process an SOI marker */
  166770. {
  166771. int i;
  166772. TRACEMS(cinfo, 1, JTRC_SOI);
  166773. if (cinfo->marker->saw_SOI)
  166774. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  166775. /* Reset all parameters that are defined to be reset by SOI */
  166776. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166777. cinfo->arith_dc_L[i] = 0;
  166778. cinfo->arith_dc_U[i] = 1;
  166779. cinfo->arith_ac_K[i] = 5;
  166780. }
  166781. cinfo->restart_interval = 0;
  166782. /* Set initial assumptions for colorspace etc */
  166783. cinfo->jpeg_color_space = JCS_UNKNOWN;
  166784. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  166785. cinfo->saw_JFIF_marker = FALSE;
  166786. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  166787. cinfo->JFIF_minor_version = 1;
  166788. cinfo->density_unit = 0;
  166789. cinfo->X_density = 1;
  166790. cinfo->Y_density = 1;
  166791. cinfo->saw_Adobe_marker = FALSE;
  166792. cinfo->Adobe_transform = 0;
  166793. cinfo->marker->saw_SOI = TRUE;
  166794. return TRUE;
  166795. }
  166796. LOCAL(boolean)
  166797. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  166798. /* Process a SOFn marker */
  166799. {
  166800. INT32 length;
  166801. int c, ci;
  166802. jpeg_component_info * compptr;
  166803. INPUT_VARS(cinfo);
  166804. cinfo->progressive_mode = is_prog;
  166805. cinfo->arith_code = is_arith;
  166806. INPUT_2BYTES(cinfo, length, return FALSE);
  166807. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  166808. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  166809. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  166810. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  166811. length -= 8;
  166812. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  166813. (int) cinfo->image_width, (int) cinfo->image_height,
  166814. cinfo->num_components);
  166815. if (cinfo->marker->saw_SOF)
  166816. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  166817. /* We don't support files in which the image height is initially specified */
  166818. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  166819. /* might as well have a general sanity check. */
  166820. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  166821. || cinfo->num_components <= 0)
  166822. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  166823. if (length != (cinfo->num_components * 3))
  166824. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166825. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  166826. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  166827. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166828. cinfo->num_components * SIZEOF(jpeg_component_info));
  166829. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166830. ci++, compptr++) {
  166831. compptr->component_index = ci;
  166832. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  166833. INPUT_BYTE(cinfo, c, return FALSE);
  166834. compptr->h_samp_factor = (c >> 4) & 15;
  166835. compptr->v_samp_factor = (c ) & 15;
  166836. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  166837. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  166838. compptr->component_id, compptr->h_samp_factor,
  166839. compptr->v_samp_factor, compptr->quant_tbl_no);
  166840. }
  166841. cinfo->marker->saw_SOF = TRUE;
  166842. INPUT_SYNC(cinfo);
  166843. return TRUE;
  166844. }
  166845. LOCAL(boolean)
  166846. get_sos (j_decompress_ptr cinfo)
  166847. /* Process a SOS marker */
  166848. {
  166849. INT32 length;
  166850. int i, ci, n, c, cc;
  166851. jpeg_component_info * compptr;
  166852. INPUT_VARS(cinfo);
  166853. if (! cinfo->marker->saw_SOF)
  166854. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  166855. INPUT_2BYTES(cinfo, length, return FALSE);
  166856. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  166857. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  166858. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  166859. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166860. cinfo->comps_in_scan = n;
  166861. /* Collect the component-spec parameters */
  166862. for (i = 0; i < n; i++) {
  166863. INPUT_BYTE(cinfo, cc, return FALSE);
  166864. INPUT_BYTE(cinfo, c, return FALSE);
  166865. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166866. ci++, compptr++) {
  166867. if (cc == compptr->component_id)
  166868. goto id_found;
  166869. }
  166870. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  166871. id_found:
  166872. cinfo->cur_comp_info[i] = compptr;
  166873. compptr->dc_tbl_no = (c >> 4) & 15;
  166874. compptr->ac_tbl_no = (c ) & 15;
  166875. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  166876. compptr->dc_tbl_no, compptr->ac_tbl_no);
  166877. }
  166878. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  166879. INPUT_BYTE(cinfo, c, return FALSE);
  166880. cinfo->Ss = c;
  166881. INPUT_BYTE(cinfo, c, return FALSE);
  166882. cinfo->Se = c;
  166883. INPUT_BYTE(cinfo, c, return FALSE);
  166884. cinfo->Ah = (c >> 4) & 15;
  166885. cinfo->Al = (c ) & 15;
  166886. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  166887. cinfo->Ah, cinfo->Al);
  166888. /* Prepare to scan data & restart markers */
  166889. cinfo->marker->next_restart_num = 0;
  166890. /* Count another SOS marker */
  166891. cinfo->input_scan_number++;
  166892. INPUT_SYNC(cinfo);
  166893. return TRUE;
  166894. }
  166895. #ifdef D_ARITH_CODING_SUPPORTED
  166896. LOCAL(boolean)
  166897. get_dac (j_decompress_ptr cinfo)
  166898. /* Process a DAC marker */
  166899. {
  166900. INT32 length;
  166901. int index, val;
  166902. INPUT_VARS(cinfo);
  166903. INPUT_2BYTES(cinfo, length, return FALSE);
  166904. length -= 2;
  166905. while (length > 0) {
  166906. INPUT_BYTE(cinfo, index, return FALSE);
  166907. INPUT_BYTE(cinfo, val, return FALSE);
  166908. length -= 2;
  166909. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  166910. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  166911. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  166912. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  166913. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  166914. } else { /* define DC table */
  166915. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  166916. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  166917. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  166918. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  166919. }
  166920. }
  166921. if (length != 0)
  166922. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166923. INPUT_SYNC(cinfo);
  166924. return TRUE;
  166925. }
  166926. #else /* ! D_ARITH_CODING_SUPPORTED */
  166927. #define get_dac(cinfo) skip_variable(cinfo)
  166928. #endif /* D_ARITH_CODING_SUPPORTED */
  166929. LOCAL(boolean)
  166930. get_dht (j_decompress_ptr cinfo)
  166931. /* Process a DHT marker */
  166932. {
  166933. INT32 length;
  166934. UINT8 bits[17];
  166935. UINT8 huffval[256];
  166936. int i, index, count;
  166937. JHUFF_TBL **htblptr;
  166938. INPUT_VARS(cinfo);
  166939. INPUT_2BYTES(cinfo, length, return FALSE);
  166940. length -= 2;
  166941. while (length > 16) {
  166942. INPUT_BYTE(cinfo, index, return FALSE);
  166943. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  166944. bits[0] = 0;
  166945. count = 0;
  166946. for (i = 1; i <= 16; i++) {
  166947. INPUT_BYTE(cinfo, bits[i], return FALSE);
  166948. count += bits[i];
  166949. }
  166950. length -= 1 + 16;
  166951. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166952. bits[1], bits[2], bits[3], bits[4],
  166953. bits[5], bits[6], bits[7], bits[8]);
  166954. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  166955. bits[9], bits[10], bits[11], bits[12],
  166956. bits[13], bits[14], bits[15], bits[16]);
  166957. /* Here we just do minimal validation of the counts to avoid walking
  166958. * off the end of our table space. jdhuff.c will check more carefully.
  166959. */
  166960. if (count > 256 || ((INT32) count) > length)
  166961. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166962. for (i = 0; i < count; i++)
  166963. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  166964. length -= count;
  166965. if (index & 0x10) { /* AC table definition */
  166966. index -= 0x10;
  166967. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  166968. } else { /* DC table definition */
  166969. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  166970. }
  166971. if (index < 0 || index >= NUM_HUFF_TBLS)
  166972. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  166973. if (*htblptr == NULL)
  166974. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166975. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  166976. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  166977. }
  166978. if (length != 0)
  166979. ERREXIT(cinfo, JERR_BAD_LENGTH);
  166980. INPUT_SYNC(cinfo);
  166981. return TRUE;
  166982. }
  166983. LOCAL(boolean)
  166984. get_dqt (j_decompress_ptr cinfo)
  166985. /* Process a DQT marker */
  166986. {
  166987. INT32 length;
  166988. int n, i, prec;
  166989. unsigned int tmp;
  166990. JQUANT_TBL *quant_ptr;
  166991. INPUT_VARS(cinfo);
  166992. INPUT_2BYTES(cinfo, length, return FALSE);
  166993. length -= 2;
  166994. while (length > 0) {
  166995. INPUT_BYTE(cinfo, n, return FALSE);
  166996. prec = n >> 4;
  166997. n &= 0x0F;
  166998. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  166999. if (n >= NUM_QUANT_TBLS)
  167000. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  167001. if (cinfo->quant_tbl_ptrs[n] == NULL)
  167002. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  167003. quant_ptr = cinfo->quant_tbl_ptrs[n];
  167004. for (i = 0; i < DCTSIZE2; i++) {
  167005. if (prec)
  167006. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167007. else
  167008. INPUT_BYTE(cinfo, tmp, return FALSE);
  167009. /* We convert the zigzag-order table to natural array order. */
  167010. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  167011. }
  167012. if (cinfo->err->trace_level >= 2) {
  167013. for (i = 0; i < DCTSIZE2; i += 8) {
  167014. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  167015. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  167016. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  167017. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  167018. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  167019. }
  167020. }
  167021. length -= DCTSIZE2+1;
  167022. if (prec) length -= DCTSIZE2;
  167023. }
  167024. if (length != 0)
  167025. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167026. INPUT_SYNC(cinfo);
  167027. return TRUE;
  167028. }
  167029. LOCAL(boolean)
  167030. get_dri (j_decompress_ptr cinfo)
  167031. /* Process a DRI marker */
  167032. {
  167033. INT32 length;
  167034. unsigned int tmp;
  167035. INPUT_VARS(cinfo);
  167036. INPUT_2BYTES(cinfo, length, return FALSE);
  167037. if (length != 4)
  167038. ERREXIT(cinfo, JERR_BAD_LENGTH);
  167039. INPUT_2BYTES(cinfo, tmp, return FALSE);
  167040. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  167041. cinfo->restart_interval = tmp;
  167042. INPUT_SYNC(cinfo);
  167043. return TRUE;
  167044. }
  167045. /*
  167046. * Routines for processing APPn and COM markers.
  167047. * These are either saved in memory or discarded, per application request.
  167048. * APP0 and APP14 are specially checked to see if they are
  167049. * JFIF and Adobe markers, respectively.
  167050. */
  167051. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  167052. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  167053. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  167054. LOCAL(void)
  167055. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167056. unsigned int datalen, INT32 remaining)
  167057. /* Examine first few bytes from an APP0.
  167058. * Take appropriate action if it is a JFIF marker.
  167059. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167060. */
  167061. {
  167062. INT32 totallen = (INT32) datalen + remaining;
  167063. if (datalen >= APP0_DATA_LEN &&
  167064. GETJOCTET(data[0]) == 0x4A &&
  167065. GETJOCTET(data[1]) == 0x46 &&
  167066. GETJOCTET(data[2]) == 0x49 &&
  167067. GETJOCTET(data[3]) == 0x46 &&
  167068. GETJOCTET(data[4]) == 0) {
  167069. /* Found JFIF APP0 marker: save info */
  167070. cinfo->saw_JFIF_marker = TRUE;
  167071. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  167072. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  167073. cinfo->density_unit = GETJOCTET(data[7]);
  167074. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  167075. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  167076. /* Check version.
  167077. * Major version must be 1, anything else signals an incompatible change.
  167078. * (We used to treat this as an error, but now it's a nonfatal warning,
  167079. * because some bozo at Hijaak couldn't read the spec.)
  167080. * Minor version should be 0..2, but process anyway if newer.
  167081. */
  167082. if (cinfo->JFIF_major_version != 1)
  167083. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  167084. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  167085. /* Generate trace messages */
  167086. TRACEMS5(cinfo, 1, JTRC_JFIF,
  167087. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  167088. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  167089. /* Validate thumbnail dimensions and issue appropriate messages */
  167090. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  167091. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  167092. GETJOCTET(data[12]), GETJOCTET(data[13]));
  167093. totallen -= APP0_DATA_LEN;
  167094. if (totallen !=
  167095. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  167096. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  167097. } else if (datalen >= 6 &&
  167098. GETJOCTET(data[0]) == 0x4A &&
  167099. GETJOCTET(data[1]) == 0x46 &&
  167100. GETJOCTET(data[2]) == 0x58 &&
  167101. GETJOCTET(data[3]) == 0x58 &&
  167102. GETJOCTET(data[4]) == 0) {
  167103. /* Found JFIF "JFXX" extension APP0 marker */
  167104. /* The library doesn't actually do anything with these,
  167105. * but we try to produce a helpful trace message.
  167106. */
  167107. switch (GETJOCTET(data[5])) {
  167108. case 0x10:
  167109. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  167110. break;
  167111. case 0x11:
  167112. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  167113. break;
  167114. case 0x13:
  167115. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  167116. break;
  167117. default:
  167118. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  167119. GETJOCTET(data[5]), (int) totallen);
  167120. break;
  167121. }
  167122. } else {
  167123. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  167124. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  167125. }
  167126. }
  167127. LOCAL(void)
  167128. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  167129. unsigned int datalen, INT32 remaining)
  167130. /* Examine first few bytes from an APP14.
  167131. * Take appropriate action if it is an Adobe marker.
  167132. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  167133. */
  167134. {
  167135. unsigned int version, flags0, flags1, transform;
  167136. if (datalen >= APP14_DATA_LEN &&
  167137. GETJOCTET(data[0]) == 0x41 &&
  167138. GETJOCTET(data[1]) == 0x64 &&
  167139. GETJOCTET(data[2]) == 0x6F &&
  167140. GETJOCTET(data[3]) == 0x62 &&
  167141. GETJOCTET(data[4]) == 0x65) {
  167142. /* Found Adobe APP14 marker */
  167143. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  167144. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  167145. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  167146. transform = GETJOCTET(data[11]);
  167147. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  167148. cinfo->saw_Adobe_marker = TRUE;
  167149. cinfo->Adobe_transform = (UINT8) transform;
  167150. } else {
  167151. /* Start of APP14 does not match "Adobe", or too short */
  167152. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  167153. }
  167154. }
  167155. METHODDEF(boolean)
  167156. get_interesting_appn (j_decompress_ptr cinfo)
  167157. /* Process an APP0 or APP14 marker without saving it */
  167158. {
  167159. INT32 length;
  167160. JOCTET b[APPN_DATA_LEN];
  167161. unsigned int i, numtoread;
  167162. INPUT_VARS(cinfo);
  167163. INPUT_2BYTES(cinfo, length, return FALSE);
  167164. length -= 2;
  167165. /* get the interesting part of the marker data */
  167166. if (length >= APPN_DATA_LEN)
  167167. numtoread = APPN_DATA_LEN;
  167168. else if (length > 0)
  167169. numtoread = (unsigned int) length;
  167170. else
  167171. numtoread = 0;
  167172. for (i = 0; i < numtoread; i++)
  167173. INPUT_BYTE(cinfo, b[i], return FALSE);
  167174. length -= numtoread;
  167175. /* process it */
  167176. switch (cinfo->unread_marker) {
  167177. case M_APP0:
  167178. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  167179. break;
  167180. case M_APP14:
  167181. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  167182. break;
  167183. default:
  167184. /* can't get here unless jpeg_save_markers chooses wrong processor */
  167185. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167186. break;
  167187. }
  167188. /* skip any remaining data -- could be lots */
  167189. INPUT_SYNC(cinfo);
  167190. if (length > 0)
  167191. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167192. return TRUE;
  167193. }
  167194. #ifdef SAVE_MARKERS_SUPPORTED
  167195. METHODDEF(boolean)
  167196. save_marker (j_decompress_ptr cinfo)
  167197. /* Save an APPn or COM marker into the marker list */
  167198. {
  167199. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167200. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  167201. unsigned int bytes_read, data_length;
  167202. JOCTET FAR * data;
  167203. INT32 length = 0;
  167204. INPUT_VARS(cinfo);
  167205. if (cur_marker == NULL) {
  167206. /* begin reading a marker */
  167207. INPUT_2BYTES(cinfo, length, return FALSE);
  167208. length -= 2;
  167209. if (length >= 0) { /* watch out for bogus length word */
  167210. /* figure out how much we want to save */
  167211. unsigned int limit;
  167212. if (cinfo->unread_marker == (int) M_COM)
  167213. limit = marker->length_limit_COM;
  167214. else
  167215. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  167216. if ((unsigned int) length < limit)
  167217. limit = (unsigned int) length;
  167218. /* allocate and initialize the marker item */
  167219. cur_marker = (jpeg_saved_marker_ptr)
  167220. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167221. SIZEOF(struct jpeg_marker_struct) + limit);
  167222. cur_marker->next = NULL;
  167223. cur_marker->marker = (UINT8) cinfo->unread_marker;
  167224. cur_marker->original_length = (unsigned int) length;
  167225. cur_marker->data_length = limit;
  167226. /* data area is just beyond the jpeg_marker_struct */
  167227. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  167228. marker->cur_marker = cur_marker;
  167229. marker->bytes_read = 0;
  167230. bytes_read = 0;
  167231. data_length = limit;
  167232. } else {
  167233. /* deal with bogus length word */
  167234. bytes_read = data_length = 0;
  167235. data = NULL;
  167236. }
  167237. } else {
  167238. /* resume reading a marker */
  167239. bytes_read = marker->bytes_read;
  167240. data_length = cur_marker->data_length;
  167241. data = cur_marker->data + bytes_read;
  167242. }
  167243. while (bytes_read < data_length) {
  167244. INPUT_SYNC(cinfo); /* move the restart point to here */
  167245. marker->bytes_read = bytes_read;
  167246. /* If there's not at least one byte in buffer, suspend */
  167247. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  167248. /* Copy bytes with reasonable rapidity */
  167249. while (bytes_read < data_length && bytes_in_buffer > 0) {
  167250. *data++ = *next_input_byte++;
  167251. bytes_in_buffer--;
  167252. bytes_read++;
  167253. }
  167254. }
  167255. /* Done reading what we want to read */
  167256. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  167257. /* Add new marker to end of list */
  167258. if (cinfo->marker_list == NULL) {
  167259. cinfo->marker_list = cur_marker;
  167260. } else {
  167261. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  167262. while (prev->next != NULL)
  167263. prev = prev->next;
  167264. prev->next = cur_marker;
  167265. }
  167266. /* Reset pointer & calc remaining data length */
  167267. data = cur_marker->data;
  167268. length = cur_marker->original_length - data_length;
  167269. }
  167270. /* Reset to initial state for next marker */
  167271. marker->cur_marker = NULL;
  167272. /* Process the marker if interesting; else just make a generic trace msg */
  167273. switch (cinfo->unread_marker) {
  167274. case M_APP0:
  167275. examine_app0(cinfo, data, data_length, length);
  167276. break;
  167277. case M_APP14:
  167278. examine_app14(cinfo, data, data_length, length);
  167279. break;
  167280. default:
  167281. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  167282. (int) (data_length + length));
  167283. break;
  167284. }
  167285. /* skip any remaining data -- could be lots */
  167286. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167287. if (length > 0)
  167288. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167289. return TRUE;
  167290. }
  167291. #endif /* SAVE_MARKERS_SUPPORTED */
  167292. METHODDEF(boolean)
  167293. skip_variable (j_decompress_ptr cinfo)
  167294. /* Skip over an unknown or uninteresting variable-length marker */
  167295. {
  167296. INT32 length;
  167297. INPUT_VARS(cinfo);
  167298. INPUT_2BYTES(cinfo, length, return FALSE);
  167299. length -= 2;
  167300. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  167301. INPUT_SYNC(cinfo); /* do before skip_input_data */
  167302. if (length > 0)
  167303. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  167304. return TRUE;
  167305. }
  167306. /*
  167307. * Find the next JPEG marker, save it in cinfo->unread_marker.
  167308. * Returns FALSE if had to suspend before reaching a marker;
  167309. * in that case cinfo->unread_marker is unchanged.
  167310. *
  167311. * Note that the result might not be a valid marker code,
  167312. * but it will never be 0 or FF.
  167313. */
  167314. LOCAL(boolean)
  167315. next_marker (j_decompress_ptr cinfo)
  167316. {
  167317. int c;
  167318. INPUT_VARS(cinfo);
  167319. for (;;) {
  167320. INPUT_BYTE(cinfo, c, return FALSE);
  167321. /* Skip any non-FF bytes.
  167322. * This may look a bit inefficient, but it will not occur in a valid file.
  167323. * We sync after each discarded byte so that a suspending data source
  167324. * can discard the byte from its buffer.
  167325. */
  167326. while (c != 0xFF) {
  167327. cinfo->marker->discarded_bytes++;
  167328. INPUT_SYNC(cinfo);
  167329. INPUT_BYTE(cinfo, c, return FALSE);
  167330. }
  167331. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  167332. * pad bytes, so don't count them in discarded_bytes. We assume there
  167333. * will not be so many consecutive FF bytes as to overflow a suspending
  167334. * data source's input buffer.
  167335. */
  167336. do {
  167337. INPUT_BYTE(cinfo, c, return FALSE);
  167338. } while (c == 0xFF);
  167339. if (c != 0)
  167340. break; /* found a valid marker, exit loop */
  167341. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  167342. * Discard it and loop back to try again.
  167343. */
  167344. cinfo->marker->discarded_bytes += 2;
  167345. INPUT_SYNC(cinfo);
  167346. }
  167347. if (cinfo->marker->discarded_bytes != 0) {
  167348. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  167349. cinfo->marker->discarded_bytes = 0;
  167350. }
  167351. cinfo->unread_marker = c;
  167352. INPUT_SYNC(cinfo);
  167353. return TRUE;
  167354. }
  167355. LOCAL(boolean)
  167356. first_marker (j_decompress_ptr cinfo)
  167357. /* Like next_marker, but used to obtain the initial SOI marker. */
  167358. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  167359. * we might well scan an entire input file before realizing it ain't JPEG.
  167360. * If an application wants to process non-JFIF files, it must seek to the
  167361. * SOI before calling the JPEG library.
  167362. */
  167363. {
  167364. int c, c2;
  167365. INPUT_VARS(cinfo);
  167366. INPUT_BYTE(cinfo, c, return FALSE);
  167367. INPUT_BYTE(cinfo, c2, return FALSE);
  167368. if (c != 0xFF || c2 != (int) M_SOI)
  167369. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  167370. cinfo->unread_marker = c2;
  167371. INPUT_SYNC(cinfo);
  167372. return TRUE;
  167373. }
  167374. /*
  167375. * Read markers until SOS or EOI.
  167376. *
  167377. * Returns same codes as are defined for jpeg_consume_input:
  167378. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  167379. */
  167380. METHODDEF(int)
  167381. read_markers (j_decompress_ptr cinfo)
  167382. {
  167383. /* Outer loop repeats once for each marker. */
  167384. for (;;) {
  167385. /* Collect the marker proper, unless we already did. */
  167386. /* NB: first_marker() enforces the requirement that SOI appear first. */
  167387. if (cinfo->unread_marker == 0) {
  167388. if (! cinfo->marker->saw_SOI) {
  167389. if (! first_marker(cinfo))
  167390. return JPEG_SUSPENDED;
  167391. } else {
  167392. if (! next_marker(cinfo))
  167393. return JPEG_SUSPENDED;
  167394. }
  167395. }
  167396. /* At this point cinfo->unread_marker contains the marker code and the
  167397. * input point is just past the marker proper, but before any parameters.
  167398. * A suspension will cause us to return with this state still true.
  167399. */
  167400. switch (cinfo->unread_marker) {
  167401. case M_SOI:
  167402. if (! get_soi(cinfo))
  167403. return JPEG_SUSPENDED;
  167404. break;
  167405. case M_SOF0: /* Baseline */
  167406. case M_SOF1: /* Extended sequential, Huffman */
  167407. if (! get_sof(cinfo, FALSE, FALSE))
  167408. return JPEG_SUSPENDED;
  167409. break;
  167410. case M_SOF2: /* Progressive, Huffman */
  167411. if (! get_sof(cinfo, TRUE, FALSE))
  167412. return JPEG_SUSPENDED;
  167413. break;
  167414. case M_SOF9: /* Extended sequential, arithmetic */
  167415. if (! get_sof(cinfo, FALSE, TRUE))
  167416. return JPEG_SUSPENDED;
  167417. break;
  167418. case M_SOF10: /* Progressive, arithmetic */
  167419. if (! get_sof(cinfo, TRUE, TRUE))
  167420. return JPEG_SUSPENDED;
  167421. break;
  167422. /* Currently unsupported SOFn types */
  167423. case M_SOF3: /* Lossless, Huffman */
  167424. case M_SOF5: /* Differential sequential, Huffman */
  167425. case M_SOF6: /* Differential progressive, Huffman */
  167426. case M_SOF7: /* Differential lossless, Huffman */
  167427. case M_JPG: /* Reserved for JPEG extensions */
  167428. case M_SOF11: /* Lossless, arithmetic */
  167429. case M_SOF13: /* Differential sequential, arithmetic */
  167430. case M_SOF14: /* Differential progressive, arithmetic */
  167431. case M_SOF15: /* Differential lossless, arithmetic */
  167432. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  167433. break;
  167434. case M_SOS:
  167435. if (! get_sos(cinfo))
  167436. return JPEG_SUSPENDED;
  167437. cinfo->unread_marker = 0; /* processed the marker */
  167438. return JPEG_REACHED_SOS;
  167439. case M_EOI:
  167440. TRACEMS(cinfo, 1, JTRC_EOI);
  167441. cinfo->unread_marker = 0; /* processed the marker */
  167442. return JPEG_REACHED_EOI;
  167443. case M_DAC:
  167444. if (! get_dac(cinfo))
  167445. return JPEG_SUSPENDED;
  167446. break;
  167447. case M_DHT:
  167448. if (! get_dht(cinfo))
  167449. return JPEG_SUSPENDED;
  167450. break;
  167451. case M_DQT:
  167452. if (! get_dqt(cinfo))
  167453. return JPEG_SUSPENDED;
  167454. break;
  167455. case M_DRI:
  167456. if (! get_dri(cinfo))
  167457. return JPEG_SUSPENDED;
  167458. break;
  167459. case M_APP0:
  167460. case M_APP1:
  167461. case M_APP2:
  167462. case M_APP3:
  167463. case M_APP4:
  167464. case M_APP5:
  167465. case M_APP6:
  167466. case M_APP7:
  167467. case M_APP8:
  167468. case M_APP9:
  167469. case M_APP10:
  167470. case M_APP11:
  167471. case M_APP12:
  167472. case M_APP13:
  167473. case M_APP14:
  167474. case M_APP15:
  167475. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  167476. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  167477. return JPEG_SUSPENDED;
  167478. break;
  167479. case M_COM:
  167480. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  167481. return JPEG_SUSPENDED;
  167482. break;
  167483. case M_RST0: /* these are all parameterless */
  167484. case M_RST1:
  167485. case M_RST2:
  167486. case M_RST3:
  167487. case M_RST4:
  167488. case M_RST5:
  167489. case M_RST6:
  167490. case M_RST7:
  167491. case M_TEM:
  167492. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  167493. break;
  167494. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  167495. if (! skip_variable(cinfo))
  167496. return JPEG_SUSPENDED;
  167497. break;
  167498. default: /* must be DHP, EXP, JPGn, or RESn */
  167499. /* For now, we treat the reserved markers as fatal errors since they are
  167500. * likely to be used to signal incompatible JPEG Part 3 extensions.
  167501. * Once the JPEG 3 version-number marker is well defined, this code
  167502. * ought to change!
  167503. */
  167504. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  167505. break;
  167506. }
  167507. /* Successfully processed marker, so reset state variable */
  167508. cinfo->unread_marker = 0;
  167509. } /* end loop */
  167510. }
  167511. /*
  167512. * Read a restart marker, which is expected to appear next in the datastream;
  167513. * if the marker is not there, take appropriate recovery action.
  167514. * Returns FALSE if suspension is required.
  167515. *
  167516. * This is called by the entropy decoder after it has read an appropriate
  167517. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  167518. * has already read a marker from the data source. Under normal conditions
  167519. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  167520. * it holds a marker which the decoder will be unable to read past.
  167521. */
  167522. METHODDEF(boolean)
  167523. read_restart_marker (j_decompress_ptr cinfo)
  167524. {
  167525. /* Obtain a marker unless we already did. */
  167526. /* Note that next_marker will complain if it skips any data. */
  167527. if (cinfo->unread_marker == 0) {
  167528. if (! next_marker(cinfo))
  167529. return FALSE;
  167530. }
  167531. if (cinfo->unread_marker ==
  167532. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  167533. /* Normal case --- swallow the marker and let entropy decoder continue */
  167534. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  167535. cinfo->unread_marker = 0;
  167536. } else {
  167537. /* Uh-oh, the restart markers have been messed up. */
  167538. /* Let the data source manager determine how to resync. */
  167539. if (! (*cinfo->src->resync_to_restart) (cinfo,
  167540. cinfo->marker->next_restart_num))
  167541. return FALSE;
  167542. }
  167543. /* Update next-restart state */
  167544. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  167545. return TRUE;
  167546. }
  167547. /*
  167548. * This is the default resync_to_restart method for data source managers
  167549. * to use if they don't have any better approach. Some data source managers
  167550. * may be able to back up, or may have additional knowledge about the data
  167551. * which permits a more intelligent recovery strategy; such managers would
  167552. * presumably supply their own resync method.
  167553. *
  167554. * read_restart_marker calls resync_to_restart if it finds a marker other than
  167555. * the restart marker it was expecting. (This code is *not* used unless
  167556. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  167557. * the marker code actually found (might be anything, except 0 or FF).
  167558. * The desired restart marker number (0..7) is passed as a parameter.
  167559. * This routine is supposed to apply whatever error recovery strategy seems
  167560. * appropriate in order to position the input stream to the next data segment.
  167561. * Note that cinfo->unread_marker is treated as a marker appearing before
  167562. * the current data-source input point; usually it should be reset to zero
  167563. * before returning.
  167564. * Returns FALSE if suspension is required.
  167565. *
  167566. * This implementation is substantially constrained by wanting to treat the
  167567. * input as a data stream; this means we can't back up. Therefore, we have
  167568. * only the following actions to work with:
  167569. * 1. Simply discard the marker and let the entropy decoder resume at next
  167570. * byte of file.
  167571. * 2. Read forward until we find another marker, discarding intervening
  167572. * data. (In theory we could look ahead within the current bufferload,
  167573. * without having to discard data if we don't find the desired marker.
  167574. * This idea is not implemented here, in part because it makes behavior
  167575. * dependent on buffer size and chance buffer-boundary positions.)
  167576. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  167577. * This will cause the entropy decoder to process an empty data segment,
  167578. * inserting dummy zeroes, and then we will reprocess the marker.
  167579. *
  167580. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  167581. * appropriate if the found marker is a future restart marker (indicating
  167582. * that we have missed the desired restart marker, probably because it got
  167583. * corrupted).
  167584. * We apply #2 or #3 if the found marker is a restart marker no more than
  167585. * two counts behind or ahead of the expected one. We also apply #2 if the
  167586. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  167587. * If the found marker is a restart marker more than 2 counts away, we do #1
  167588. * (too much risk that the marker is erroneous; with luck we will be able to
  167589. * resync at some future point).
  167590. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  167591. * overrunning the end of a scan. An implementation limited to single-scan
  167592. * files might find it better to apply #2 for markers other than EOI, since
  167593. * any other marker would have to be bogus data in that case.
  167594. */
  167595. GLOBAL(boolean)
  167596. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  167597. {
  167598. int marker = cinfo->unread_marker;
  167599. int action = 1;
  167600. /* Always put up a warning. */
  167601. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  167602. /* Outer loop handles repeated decision after scanning forward. */
  167603. for (;;) {
  167604. if (marker < (int) M_SOF0)
  167605. action = 2; /* invalid marker */
  167606. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  167607. action = 3; /* valid non-restart marker */
  167608. else {
  167609. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  167610. marker == ((int) M_RST0 + ((desired+2) & 7)))
  167611. action = 3; /* one of the next two expected restarts */
  167612. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  167613. marker == ((int) M_RST0 + ((desired-2) & 7)))
  167614. action = 2; /* a prior restart, so advance */
  167615. else
  167616. action = 1; /* desired restart or too far away */
  167617. }
  167618. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  167619. switch (action) {
  167620. case 1:
  167621. /* Discard marker and let entropy decoder resume processing. */
  167622. cinfo->unread_marker = 0;
  167623. return TRUE;
  167624. case 2:
  167625. /* Scan to the next marker, and repeat the decision loop. */
  167626. if (! next_marker(cinfo))
  167627. return FALSE;
  167628. marker = cinfo->unread_marker;
  167629. break;
  167630. case 3:
  167631. /* Return without advancing past this marker. */
  167632. /* Entropy decoder will be forced to process an empty segment. */
  167633. return TRUE;
  167634. }
  167635. } /* end loop */
  167636. }
  167637. /*
  167638. * Reset marker processing state to begin a fresh datastream.
  167639. */
  167640. METHODDEF(void)
  167641. reset_marker_reader (j_decompress_ptr cinfo)
  167642. {
  167643. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167644. cinfo->comp_info = NULL; /* until allocated by get_sof */
  167645. cinfo->input_scan_number = 0; /* no SOS seen yet */
  167646. cinfo->unread_marker = 0; /* no pending marker */
  167647. marker->pub.saw_SOI = FALSE; /* set internal state too */
  167648. marker->pub.saw_SOF = FALSE;
  167649. marker->pub.discarded_bytes = 0;
  167650. marker->cur_marker = NULL;
  167651. }
  167652. /*
  167653. * Initialize the marker reader module.
  167654. * This is called only once, when the decompression object is created.
  167655. */
  167656. GLOBAL(void)
  167657. jinit_marker_reader (j_decompress_ptr cinfo)
  167658. {
  167659. my_marker_ptr2 marker;
  167660. int i;
  167661. /* Create subobject in permanent pool */
  167662. marker = (my_marker_ptr2)
  167663. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  167664. SIZEOF(my_marker_reader));
  167665. cinfo->marker = (struct jpeg_marker_reader *) marker;
  167666. /* Initialize public method pointers */
  167667. marker->pub.reset_marker_reader = reset_marker_reader;
  167668. marker->pub.read_markers = read_markers;
  167669. marker->pub.read_restart_marker = read_restart_marker;
  167670. /* Initialize COM/APPn processing.
  167671. * By default, we examine and then discard APP0 and APP14,
  167672. * but simply discard COM and all other APPn.
  167673. */
  167674. marker->process_COM = skip_variable;
  167675. marker->length_limit_COM = 0;
  167676. for (i = 0; i < 16; i++) {
  167677. marker->process_APPn[i] = skip_variable;
  167678. marker->length_limit_APPn[i] = 0;
  167679. }
  167680. marker->process_APPn[0] = get_interesting_appn;
  167681. marker->process_APPn[14] = get_interesting_appn;
  167682. /* Reset marker processing state */
  167683. reset_marker_reader(cinfo);
  167684. }
  167685. /*
  167686. * Control saving of COM and APPn markers into marker_list.
  167687. */
  167688. #ifdef SAVE_MARKERS_SUPPORTED
  167689. GLOBAL(void)
  167690. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  167691. unsigned int length_limit)
  167692. {
  167693. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167694. long maxlength;
  167695. jpeg_marker_parser_method processor;
  167696. /* Length limit mustn't be larger than what we can allocate
  167697. * (should only be a concern in a 16-bit environment).
  167698. */
  167699. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  167700. if (((long) length_limit) > maxlength)
  167701. length_limit = (unsigned int) maxlength;
  167702. /* Choose processor routine to use.
  167703. * APP0/APP14 have special requirements.
  167704. */
  167705. if (length_limit) {
  167706. processor = save_marker;
  167707. /* If saving APP0/APP14, save at least enough for our internal use. */
  167708. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  167709. length_limit = APP0_DATA_LEN;
  167710. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  167711. length_limit = APP14_DATA_LEN;
  167712. } else {
  167713. processor = skip_variable;
  167714. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  167715. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  167716. processor = get_interesting_appn;
  167717. }
  167718. if (marker_code == (int) M_COM) {
  167719. marker->process_COM = processor;
  167720. marker->length_limit_COM = length_limit;
  167721. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  167722. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  167723. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  167724. } else
  167725. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167726. }
  167727. #endif /* SAVE_MARKERS_SUPPORTED */
  167728. /*
  167729. * Install a special processing method for COM or APPn markers.
  167730. */
  167731. GLOBAL(void)
  167732. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  167733. jpeg_marker_parser_method routine)
  167734. {
  167735. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  167736. if (marker_code == (int) M_COM)
  167737. marker->process_COM = routine;
  167738. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  167739. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  167740. else
  167741. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  167742. }
  167743. /********* End of inlined file: jdmarker.c *********/
  167744. /********* Start of inlined file: jdmaster.c *********/
  167745. #define JPEG_INTERNALS
  167746. /* Private state */
  167747. typedef struct {
  167748. struct jpeg_decomp_master pub; /* public fields */
  167749. int pass_number; /* # of passes completed */
  167750. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  167751. /* Saved references to initialized quantizer modules,
  167752. * in case we need to switch modes.
  167753. */
  167754. struct jpeg_color_quantizer * quantizer_1pass;
  167755. struct jpeg_color_quantizer * quantizer_2pass;
  167756. } my_decomp_master;
  167757. typedef my_decomp_master * my_master_ptr6;
  167758. /*
  167759. * Determine whether merged upsample/color conversion should be used.
  167760. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  167761. */
  167762. LOCAL(boolean)
  167763. use_merged_upsample (j_decompress_ptr cinfo)
  167764. {
  167765. #ifdef UPSAMPLE_MERGING_SUPPORTED
  167766. /* Merging is the equivalent of plain box-filter upsampling */
  167767. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  167768. return FALSE;
  167769. /* jdmerge.c only supports YCC=>RGB color conversion */
  167770. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  167771. cinfo->out_color_space != JCS_RGB ||
  167772. cinfo->out_color_components != RGB_PIXELSIZE)
  167773. return FALSE;
  167774. /* and it only handles 2h1v or 2h2v sampling ratios */
  167775. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  167776. cinfo->comp_info[1].h_samp_factor != 1 ||
  167777. cinfo->comp_info[2].h_samp_factor != 1 ||
  167778. cinfo->comp_info[0].v_samp_factor > 2 ||
  167779. cinfo->comp_info[1].v_samp_factor != 1 ||
  167780. cinfo->comp_info[2].v_samp_factor != 1)
  167781. return FALSE;
  167782. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  167783. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167784. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  167785. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  167786. return FALSE;
  167787. /* ??? also need to test for upsample-time rescaling, when & if supported */
  167788. return TRUE; /* by golly, it'll work... */
  167789. #else
  167790. return FALSE;
  167791. #endif
  167792. }
  167793. /*
  167794. * Compute output image dimensions and related values.
  167795. * NOTE: this is exported for possible use by application.
  167796. * Hence it mustn't do anything that can't be done twice.
  167797. * Also note that it may be called before the master module is initialized!
  167798. */
  167799. GLOBAL(void)
  167800. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  167801. /* Do computations that are needed before master selection phase */
  167802. {
  167803. #ifdef IDCT_SCALING_SUPPORTED
  167804. int ci;
  167805. jpeg_component_info *compptr;
  167806. #endif
  167807. /* Prevent application from calling me at wrong times */
  167808. if (cinfo->global_state != DSTATE_READY)
  167809. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167810. #ifdef IDCT_SCALING_SUPPORTED
  167811. /* Compute actual output image dimensions and DCT scaling choices. */
  167812. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  167813. /* Provide 1/8 scaling */
  167814. cinfo->output_width = (JDIMENSION)
  167815. jdiv_round_up((long) cinfo->image_width, 8L);
  167816. cinfo->output_height = (JDIMENSION)
  167817. jdiv_round_up((long) cinfo->image_height, 8L);
  167818. cinfo->min_DCT_scaled_size = 1;
  167819. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  167820. /* Provide 1/4 scaling */
  167821. cinfo->output_width = (JDIMENSION)
  167822. jdiv_round_up((long) cinfo->image_width, 4L);
  167823. cinfo->output_height = (JDIMENSION)
  167824. jdiv_round_up((long) cinfo->image_height, 4L);
  167825. cinfo->min_DCT_scaled_size = 2;
  167826. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  167827. /* Provide 1/2 scaling */
  167828. cinfo->output_width = (JDIMENSION)
  167829. jdiv_round_up((long) cinfo->image_width, 2L);
  167830. cinfo->output_height = (JDIMENSION)
  167831. jdiv_round_up((long) cinfo->image_height, 2L);
  167832. cinfo->min_DCT_scaled_size = 4;
  167833. } else {
  167834. /* Provide 1/1 scaling */
  167835. cinfo->output_width = cinfo->image_width;
  167836. cinfo->output_height = cinfo->image_height;
  167837. cinfo->min_DCT_scaled_size = DCTSIZE;
  167838. }
  167839. /* In selecting the actual DCT scaling for each component, we try to
  167840. * scale up the chroma components via IDCT scaling rather than upsampling.
  167841. * This saves time if the upsampler gets to use 1:1 scaling.
  167842. * Note this code assumes that the supported DCT scalings are powers of 2.
  167843. */
  167844. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167845. ci++, compptr++) {
  167846. int ssize = cinfo->min_DCT_scaled_size;
  167847. while (ssize < DCTSIZE &&
  167848. (compptr->h_samp_factor * ssize * 2 <=
  167849. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  167850. (compptr->v_samp_factor * ssize * 2 <=
  167851. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  167852. ssize = ssize * 2;
  167853. }
  167854. compptr->DCT_scaled_size = ssize;
  167855. }
  167856. /* Recompute downsampled dimensions of components;
  167857. * application needs to know these if using raw downsampled data.
  167858. */
  167859. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167860. ci++, compptr++) {
  167861. /* Size in samples, after IDCT scaling */
  167862. compptr->downsampled_width = (JDIMENSION)
  167863. jdiv_round_up((long) cinfo->image_width *
  167864. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  167865. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  167866. compptr->downsampled_height = (JDIMENSION)
  167867. jdiv_round_up((long) cinfo->image_height *
  167868. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  167869. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  167870. }
  167871. #else /* !IDCT_SCALING_SUPPORTED */
  167872. /* Hardwire it to "no scaling" */
  167873. cinfo->output_width = cinfo->image_width;
  167874. cinfo->output_height = cinfo->image_height;
  167875. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  167876. * and has computed unscaled downsampled_width and downsampled_height.
  167877. */
  167878. #endif /* IDCT_SCALING_SUPPORTED */
  167879. /* Report number of components in selected colorspace. */
  167880. /* Probably this should be in the color conversion module... */
  167881. switch (cinfo->out_color_space) {
  167882. case JCS_GRAYSCALE:
  167883. cinfo->out_color_components = 1;
  167884. break;
  167885. case JCS_RGB:
  167886. #if RGB_PIXELSIZE != 3
  167887. cinfo->out_color_components = RGB_PIXELSIZE;
  167888. break;
  167889. #endif /* else share code with YCbCr */
  167890. case JCS_YCbCr:
  167891. cinfo->out_color_components = 3;
  167892. break;
  167893. case JCS_CMYK:
  167894. case JCS_YCCK:
  167895. cinfo->out_color_components = 4;
  167896. break;
  167897. default: /* else must be same colorspace as in file */
  167898. cinfo->out_color_components = cinfo->num_components;
  167899. break;
  167900. }
  167901. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  167902. cinfo->out_color_components);
  167903. /* See if upsampler will want to emit more than one row at a time */
  167904. if (use_merged_upsample(cinfo))
  167905. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  167906. else
  167907. cinfo->rec_outbuf_height = 1;
  167908. }
  167909. /*
  167910. * Several decompression processes need to range-limit values to the range
  167911. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  167912. * due to noise introduced by quantization, roundoff error, etc. These
  167913. * processes are inner loops and need to be as fast as possible. On most
  167914. * machines, particularly CPUs with pipelines or instruction prefetch,
  167915. * a (subscript-check-less) C table lookup
  167916. * x = sample_range_limit[x];
  167917. * is faster than explicit tests
  167918. * if (x < 0) x = 0;
  167919. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  167920. * These processes all use a common table prepared by the routine below.
  167921. *
  167922. * For most steps we can mathematically guarantee that the initial value
  167923. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  167924. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  167925. * limiting step (just after the IDCT), a wildly out-of-range value is
  167926. * possible if the input data is corrupt. To avoid any chance of indexing
  167927. * off the end of memory and getting a bad-pointer trap, we perform the
  167928. * post-IDCT limiting thus:
  167929. * x = range_limit[x & MASK];
  167930. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  167931. * samples. Under normal circumstances this is more than enough range and
  167932. * a correct output will be generated; with bogus input data the mask will
  167933. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  167934. * For the post-IDCT step, we want to convert the data from signed to unsigned
  167935. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  167936. * So the post-IDCT limiting table ends up looking like this:
  167937. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  167938. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167939. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  167940. * 0,1,...,CENTERJSAMPLE-1
  167941. * Negative inputs select values from the upper half of the table after
  167942. * masking.
  167943. *
  167944. * We can save some space by overlapping the start of the post-IDCT table
  167945. * with the simpler range limiting table. The post-IDCT table begins at
  167946. * sample_range_limit + CENTERJSAMPLE.
  167947. *
  167948. * Note that the table is allocated in near data space on PCs; it's small
  167949. * enough and used often enough to justify this.
  167950. */
  167951. LOCAL(void)
  167952. prepare_range_limit_table (j_decompress_ptr cinfo)
  167953. /* Allocate and fill in the sample_range_limit table */
  167954. {
  167955. JSAMPLE * table;
  167956. int i;
  167957. table = (JSAMPLE *)
  167958. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167959. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167960. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  167961. cinfo->sample_range_limit = table;
  167962. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  167963. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  167964. /* Main part of "simple" table: limit[x] = x */
  167965. for (i = 0; i <= MAXJSAMPLE; i++)
  167966. table[i] = (JSAMPLE) i;
  167967. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  167968. /* End of simple table, rest of first half of post-IDCT table */
  167969. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  167970. table[i] = MAXJSAMPLE;
  167971. /* Second half of post-IDCT table */
  167972. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  167973. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  167974. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  167975. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  167976. }
  167977. /*
  167978. * Master selection of decompression modules.
  167979. * This is done once at jpeg_start_decompress time. We determine
  167980. * which modules will be used and give them appropriate initialization calls.
  167981. * We also initialize the decompressor input side to begin consuming data.
  167982. *
  167983. * Since jpeg_read_header has finished, we know what is in the SOF
  167984. * and (first) SOS markers. We also have all the application parameter
  167985. * settings.
  167986. */
  167987. LOCAL(void)
  167988. master_selection (j_decompress_ptr cinfo)
  167989. {
  167990. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  167991. boolean use_c_buffer;
  167992. long samplesperrow;
  167993. JDIMENSION jd_samplesperrow;
  167994. /* Initialize dimensions and other stuff */
  167995. jpeg_calc_output_dimensions(cinfo);
  167996. prepare_range_limit_table(cinfo);
  167997. /* Width of an output scanline must be representable as JDIMENSION. */
  167998. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  167999. jd_samplesperrow = (JDIMENSION) samplesperrow;
  168000. if ((long) jd_samplesperrow != samplesperrow)
  168001. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  168002. /* Initialize my private state */
  168003. master->pass_number = 0;
  168004. master->using_merged_upsample = use_merged_upsample(cinfo);
  168005. /* Color quantizer selection */
  168006. master->quantizer_1pass = NULL;
  168007. master->quantizer_2pass = NULL;
  168008. /* No mode changes if not using buffered-image mode. */
  168009. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  168010. cinfo->enable_1pass_quant = FALSE;
  168011. cinfo->enable_external_quant = FALSE;
  168012. cinfo->enable_2pass_quant = FALSE;
  168013. }
  168014. if (cinfo->quantize_colors) {
  168015. if (cinfo->raw_data_out)
  168016. ERREXIT(cinfo, JERR_NOTIMPL);
  168017. /* 2-pass quantizer only works in 3-component color space. */
  168018. if (cinfo->out_color_components != 3) {
  168019. cinfo->enable_1pass_quant = TRUE;
  168020. cinfo->enable_external_quant = FALSE;
  168021. cinfo->enable_2pass_quant = FALSE;
  168022. cinfo->colormap = NULL;
  168023. } else if (cinfo->colormap != NULL) {
  168024. cinfo->enable_external_quant = TRUE;
  168025. } else if (cinfo->two_pass_quantize) {
  168026. cinfo->enable_2pass_quant = TRUE;
  168027. } else {
  168028. cinfo->enable_1pass_quant = TRUE;
  168029. }
  168030. if (cinfo->enable_1pass_quant) {
  168031. #ifdef QUANT_1PASS_SUPPORTED
  168032. jinit_1pass_quantizer(cinfo);
  168033. master->quantizer_1pass = cinfo->cquantize;
  168034. #else
  168035. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168036. #endif
  168037. }
  168038. /* We use the 2-pass code to map to external colormaps. */
  168039. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  168040. #ifdef QUANT_2PASS_SUPPORTED
  168041. jinit_2pass_quantizer(cinfo);
  168042. master->quantizer_2pass = cinfo->cquantize;
  168043. #else
  168044. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168045. #endif
  168046. }
  168047. /* If both quantizers are initialized, the 2-pass one is left active;
  168048. * this is necessary for starting with quantization to an external map.
  168049. */
  168050. }
  168051. /* Post-processing: in particular, color conversion first */
  168052. if (! cinfo->raw_data_out) {
  168053. if (master->using_merged_upsample) {
  168054. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168055. jinit_merged_upsampler(cinfo); /* does color conversion too */
  168056. #else
  168057. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168058. #endif
  168059. } else {
  168060. jinit_color_deconverter(cinfo);
  168061. jinit_upsampler(cinfo);
  168062. }
  168063. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  168064. }
  168065. /* Inverse DCT */
  168066. jinit_inverse_dct(cinfo);
  168067. /* Entropy decoding: either Huffman or arithmetic coding. */
  168068. if (cinfo->arith_code) {
  168069. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168070. } else {
  168071. if (cinfo->progressive_mode) {
  168072. #ifdef D_PROGRESSIVE_SUPPORTED
  168073. jinit_phuff_decoder(cinfo);
  168074. #else
  168075. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168076. #endif
  168077. } else
  168078. jinit_huff_decoder(cinfo);
  168079. }
  168080. /* Initialize principal buffer controllers. */
  168081. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  168082. jinit_d_coef_controller(cinfo, use_c_buffer);
  168083. if (! cinfo->raw_data_out)
  168084. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  168085. /* We can now tell the memory manager to allocate virtual arrays. */
  168086. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168087. /* Initialize input side of decompressor to consume first scan. */
  168088. (*cinfo->inputctl->start_input_pass) (cinfo);
  168089. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168090. /* If jpeg_start_decompress will read the whole file, initialize
  168091. * progress monitoring appropriately. The input step is counted
  168092. * as one pass.
  168093. */
  168094. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  168095. cinfo->inputctl->has_multiple_scans) {
  168096. int nscans;
  168097. /* Estimate number of scans to set pass_limit. */
  168098. if (cinfo->progressive_mode) {
  168099. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  168100. nscans = 2 + 3 * cinfo->num_components;
  168101. } else {
  168102. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  168103. nscans = cinfo->num_components;
  168104. }
  168105. cinfo->progress->pass_counter = 0L;
  168106. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  168107. cinfo->progress->completed_passes = 0;
  168108. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  168109. /* Count the input pass as done */
  168110. master->pass_number++;
  168111. }
  168112. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168113. }
  168114. /*
  168115. * Per-pass setup.
  168116. * This is called at the beginning of each output pass. We determine which
  168117. * modules will be active during this pass and give them appropriate
  168118. * start_pass calls. We also set is_dummy_pass to indicate whether this
  168119. * is a "real" output pass or a dummy pass for color quantization.
  168120. * (In the latter case, jdapistd.c will crank the pass to completion.)
  168121. */
  168122. METHODDEF(void)
  168123. prepare_for_output_pass (j_decompress_ptr cinfo)
  168124. {
  168125. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168126. if (master->pub.is_dummy_pass) {
  168127. #ifdef QUANT_2PASS_SUPPORTED
  168128. /* Final pass of 2-pass quantization */
  168129. master->pub.is_dummy_pass = FALSE;
  168130. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  168131. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  168132. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  168133. #else
  168134. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168135. #endif /* QUANT_2PASS_SUPPORTED */
  168136. } else {
  168137. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  168138. /* Select new quantization method */
  168139. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  168140. cinfo->cquantize = master->quantizer_2pass;
  168141. master->pub.is_dummy_pass = TRUE;
  168142. } else if (cinfo->enable_1pass_quant) {
  168143. cinfo->cquantize = master->quantizer_1pass;
  168144. } else {
  168145. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168146. }
  168147. }
  168148. (*cinfo->idct->start_pass) (cinfo);
  168149. (*cinfo->coef->start_output_pass) (cinfo);
  168150. if (! cinfo->raw_data_out) {
  168151. if (! master->using_merged_upsample)
  168152. (*cinfo->cconvert->start_pass) (cinfo);
  168153. (*cinfo->upsample->start_pass) (cinfo);
  168154. if (cinfo->quantize_colors)
  168155. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  168156. (*cinfo->post->start_pass) (cinfo,
  168157. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  168158. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  168159. }
  168160. }
  168161. /* Set up progress monitor's pass info if present */
  168162. if (cinfo->progress != NULL) {
  168163. cinfo->progress->completed_passes = master->pass_number;
  168164. cinfo->progress->total_passes = master->pass_number +
  168165. (master->pub.is_dummy_pass ? 2 : 1);
  168166. /* In buffered-image mode, we assume one more output pass if EOI not
  168167. * yet reached, but no more passes if EOI has been reached.
  168168. */
  168169. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  168170. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  168171. }
  168172. }
  168173. }
  168174. /*
  168175. * Finish up at end of an output pass.
  168176. */
  168177. METHODDEF(void)
  168178. finish_output_pass (j_decompress_ptr cinfo)
  168179. {
  168180. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168181. if (cinfo->quantize_colors)
  168182. (*cinfo->cquantize->finish_pass) (cinfo);
  168183. master->pass_number++;
  168184. }
  168185. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168186. /*
  168187. * Switch to a new external colormap between output passes.
  168188. */
  168189. GLOBAL(void)
  168190. jpeg_new_colormap (j_decompress_ptr cinfo)
  168191. {
  168192. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  168193. /* Prevent application from calling me at wrong times */
  168194. if (cinfo->global_state != DSTATE_BUFIMAGE)
  168195. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168196. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  168197. cinfo->colormap != NULL) {
  168198. /* Select 2-pass quantizer for external colormap use */
  168199. cinfo->cquantize = master->quantizer_2pass;
  168200. /* Notify quantizer of colormap change */
  168201. (*cinfo->cquantize->new_color_map) (cinfo);
  168202. master->pub.is_dummy_pass = FALSE; /* just in case */
  168203. } else
  168204. ERREXIT(cinfo, JERR_MODE_CHANGE);
  168205. }
  168206. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168207. /*
  168208. * Initialize master decompression control and select active modules.
  168209. * This is performed at the start of jpeg_start_decompress.
  168210. */
  168211. GLOBAL(void)
  168212. jinit_master_decompress (j_decompress_ptr cinfo)
  168213. {
  168214. my_master_ptr6 master;
  168215. master = (my_master_ptr6)
  168216. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168217. SIZEOF(my_decomp_master));
  168218. cinfo->master = (struct jpeg_decomp_master *) master;
  168219. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  168220. master->pub.finish_output_pass = finish_output_pass;
  168221. master->pub.is_dummy_pass = FALSE;
  168222. master_selection(cinfo);
  168223. }
  168224. /********* End of inlined file: jdmaster.c *********/
  168225. #undef FIX
  168226. /********* Start of inlined file: jdmerge.c *********/
  168227. #define JPEG_INTERNALS
  168228. #ifdef UPSAMPLE_MERGING_SUPPORTED
  168229. /* Private subobject */
  168230. typedef struct {
  168231. struct jpeg_upsampler pub; /* public fields */
  168232. /* Pointer to routine to do actual upsampling/conversion of one row group */
  168233. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  168234. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168235. JSAMPARRAY output_buf));
  168236. /* Private state for YCC->RGB conversion */
  168237. int * Cr_r_tab; /* => table for Cr to R conversion */
  168238. int * Cb_b_tab; /* => table for Cb to B conversion */
  168239. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  168240. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  168241. /* For 2:1 vertical sampling, we produce two output rows at a time.
  168242. * We need a "spare" row buffer to hold the second output row if the
  168243. * application provides just a one-row buffer; we also use the spare
  168244. * to discard the dummy last row if the image height is odd.
  168245. */
  168246. JSAMPROW spare_row;
  168247. boolean spare_full; /* T if spare buffer is occupied */
  168248. JDIMENSION out_row_width; /* samples per output row */
  168249. JDIMENSION rows_to_go; /* counts rows remaining in image */
  168250. } my_upsampler;
  168251. typedef my_upsampler * my_upsample_ptr;
  168252. #define SCALEBITS 16 /* speediest right-shift on some machines */
  168253. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  168254. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  168255. /*
  168256. * Initialize tables for YCC->RGB colorspace conversion.
  168257. * This is taken directly from jdcolor.c; see that file for more info.
  168258. */
  168259. LOCAL(void)
  168260. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  168261. {
  168262. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168263. int i;
  168264. INT32 x;
  168265. SHIFT_TEMPS
  168266. upsample->Cr_r_tab = (int *)
  168267. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168268. (MAXJSAMPLE+1) * SIZEOF(int));
  168269. upsample->Cb_b_tab = (int *)
  168270. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168271. (MAXJSAMPLE+1) * SIZEOF(int));
  168272. upsample->Cr_g_tab = (INT32 *)
  168273. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168274. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168275. upsample->Cb_g_tab = (INT32 *)
  168276. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168277. (MAXJSAMPLE+1) * SIZEOF(INT32));
  168278. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  168279. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  168280. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  168281. /* Cr=>R value is nearest int to 1.40200 * x */
  168282. upsample->Cr_r_tab[i] = (int)
  168283. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  168284. /* Cb=>B value is nearest int to 1.77200 * x */
  168285. upsample->Cb_b_tab[i] = (int)
  168286. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  168287. /* Cr=>G value is scaled-up -0.71414 * x */
  168288. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  168289. /* Cb=>G value is scaled-up -0.34414 * x */
  168290. /* We also add in ONE_HALF so that need not do it in inner loop */
  168291. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  168292. }
  168293. }
  168294. /*
  168295. * Initialize for an upsampling pass.
  168296. */
  168297. METHODDEF(void)
  168298. start_pass_merged_upsample (j_decompress_ptr cinfo)
  168299. {
  168300. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168301. /* Mark the spare buffer empty */
  168302. upsample->spare_full = FALSE;
  168303. /* Initialize total-height counter for detecting bottom of image */
  168304. upsample->rows_to_go = cinfo->output_height;
  168305. }
  168306. /*
  168307. * Control routine to do upsampling (and color conversion).
  168308. *
  168309. * The control routine just handles the row buffering considerations.
  168310. */
  168311. METHODDEF(void)
  168312. merged_2v_upsample (j_decompress_ptr cinfo,
  168313. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168314. JDIMENSION in_row_groups_avail,
  168315. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168316. JDIMENSION out_rows_avail)
  168317. /* 2:1 vertical sampling case: may need a spare row. */
  168318. {
  168319. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168320. JSAMPROW work_ptrs[2];
  168321. JDIMENSION num_rows; /* number of rows returned to caller */
  168322. if (upsample->spare_full) {
  168323. /* If we have a spare row saved from a previous cycle, just return it. */
  168324. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  168325. 1, upsample->out_row_width);
  168326. num_rows = 1;
  168327. upsample->spare_full = FALSE;
  168328. } else {
  168329. /* Figure number of rows to return to caller. */
  168330. num_rows = 2;
  168331. /* Not more than the distance to the end of the image. */
  168332. if (num_rows > upsample->rows_to_go)
  168333. num_rows = upsample->rows_to_go;
  168334. /* And not more than what the client can accept: */
  168335. out_rows_avail -= *out_row_ctr;
  168336. if (num_rows > out_rows_avail)
  168337. num_rows = out_rows_avail;
  168338. /* Create output pointer array for upsampler. */
  168339. work_ptrs[0] = output_buf[*out_row_ctr];
  168340. if (num_rows > 1) {
  168341. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  168342. } else {
  168343. work_ptrs[1] = upsample->spare_row;
  168344. upsample->spare_full = TRUE;
  168345. }
  168346. /* Now do the upsampling. */
  168347. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  168348. }
  168349. /* Adjust counts */
  168350. *out_row_ctr += num_rows;
  168351. upsample->rows_to_go -= num_rows;
  168352. /* When the buffer is emptied, declare this input row group consumed */
  168353. if (! upsample->spare_full)
  168354. (*in_row_group_ctr)++;
  168355. }
  168356. METHODDEF(void)
  168357. merged_1v_upsample (j_decompress_ptr cinfo,
  168358. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  168359. JDIMENSION in_row_groups_avail,
  168360. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  168361. JDIMENSION out_rows_avail)
  168362. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  168363. {
  168364. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168365. /* Just do the upsampling. */
  168366. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  168367. output_buf + *out_row_ctr);
  168368. /* Adjust counts */
  168369. (*out_row_ctr)++;
  168370. (*in_row_group_ctr)++;
  168371. }
  168372. /*
  168373. * These are the routines invoked by the control routines to do
  168374. * the actual upsampling/conversion. One row group is processed per call.
  168375. *
  168376. * Note: since we may be writing directly into application-supplied buffers,
  168377. * we have to be honest about the output width; we can't assume the buffer
  168378. * has been rounded up to an even width.
  168379. */
  168380. /*
  168381. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  168382. */
  168383. METHODDEF(void)
  168384. h2v1_merged_upsample (j_decompress_ptr cinfo,
  168385. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168386. JSAMPARRAY output_buf)
  168387. {
  168388. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168389. register int y, cred, cgreen, cblue;
  168390. int cb, cr;
  168391. register JSAMPROW outptr;
  168392. JSAMPROW inptr0, inptr1, inptr2;
  168393. JDIMENSION col;
  168394. /* copy these pointers into registers if possible */
  168395. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168396. int * Crrtab = upsample->Cr_r_tab;
  168397. int * Cbbtab = upsample->Cb_b_tab;
  168398. INT32 * Crgtab = upsample->Cr_g_tab;
  168399. INT32 * Cbgtab = upsample->Cb_g_tab;
  168400. SHIFT_TEMPS
  168401. inptr0 = input_buf[0][in_row_group_ctr];
  168402. inptr1 = input_buf[1][in_row_group_ctr];
  168403. inptr2 = input_buf[2][in_row_group_ctr];
  168404. outptr = output_buf[0];
  168405. /* Loop for each pair of output pixels */
  168406. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168407. /* Do the chroma part of the calculation */
  168408. cb = GETJSAMPLE(*inptr1++);
  168409. cr = GETJSAMPLE(*inptr2++);
  168410. cred = Crrtab[cr];
  168411. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168412. cblue = Cbbtab[cb];
  168413. /* Fetch 2 Y values and emit 2 pixels */
  168414. y = GETJSAMPLE(*inptr0++);
  168415. outptr[RGB_RED] = range_limit[y + cred];
  168416. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168417. outptr[RGB_BLUE] = range_limit[y + cblue];
  168418. outptr += RGB_PIXELSIZE;
  168419. y = GETJSAMPLE(*inptr0++);
  168420. outptr[RGB_RED] = range_limit[y + cred];
  168421. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168422. outptr[RGB_BLUE] = range_limit[y + cblue];
  168423. outptr += RGB_PIXELSIZE;
  168424. }
  168425. /* If image width is odd, do the last output column separately */
  168426. if (cinfo->output_width & 1) {
  168427. cb = GETJSAMPLE(*inptr1);
  168428. cr = GETJSAMPLE(*inptr2);
  168429. cred = Crrtab[cr];
  168430. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168431. cblue = Cbbtab[cb];
  168432. y = GETJSAMPLE(*inptr0);
  168433. outptr[RGB_RED] = range_limit[y + cred];
  168434. outptr[RGB_GREEN] = range_limit[y + cgreen];
  168435. outptr[RGB_BLUE] = range_limit[y + cblue];
  168436. }
  168437. }
  168438. /*
  168439. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  168440. */
  168441. METHODDEF(void)
  168442. h2v2_merged_upsample (j_decompress_ptr cinfo,
  168443. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  168444. JSAMPARRAY output_buf)
  168445. {
  168446. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  168447. register int y, cred, cgreen, cblue;
  168448. int cb, cr;
  168449. register JSAMPROW outptr0, outptr1;
  168450. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  168451. JDIMENSION col;
  168452. /* copy these pointers into registers if possible */
  168453. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  168454. int * Crrtab = upsample->Cr_r_tab;
  168455. int * Cbbtab = upsample->Cb_b_tab;
  168456. INT32 * Crgtab = upsample->Cr_g_tab;
  168457. INT32 * Cbgtab = upsample->Cb_g_tab;
  168458. SHIFT_TEMPS
  168459. inptr00 = input_buf[0][in_row_group_ctr*2];
  168460. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  168461. inptr1 = input_buf[1][in_row_group_ctr];
  168462. inptr2 = input_buf[2][in_row_group_ctr];
  168463. outptr0 = output_buf[0];
  168464. outptr1 = output_buf[1];
  168465. /* Loop for each group of output pixels */
  168466. for (col = cinfo->output_width >> 1; col > 0; col--) {
  168467. /* Do the chroma part of the calculation */
  168468. cb = GETJSAMPLE(*inptr1++);
  168469. cr = GETJSAMPLE(*inptr2++);
  168470. cred = Crrtab[cr];
  168471. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168472. cblue = Cbbtab[cb];
  168473. /* Fetch 4 Y values and emit 4 pixels */
  168474. y = GETJSAMPLE(*inptr00++);
  168475. outptr0[RGB_RED] = range_limit[y + cred];
  168476. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168477. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168478. outptr0 += RGB_PIXELSIZE;
  168479. y = GETJSAMPLE(*inptr00++);
  168480. outptr0[RGB_RED] = range_limit[y + cred];
  168481. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168482. outptr0[RGB_BLUE] = range_limit[y + cblue];
  168483. outptr0 += RGB_PIXELSIZE;
  168484. y = GETJSAMPLE(*inptr01++);
  168485. outptr1[RGB_RED] = range_limit[y + cred];
  168486. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168487. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168488. outptr1 += RGB_PIXELSIZE;
  168489. y = GETJSAMPLE(*inptr01++);
  168490. outptr1[RGB_RED] = range_limit[y + cred];
  168491. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  168492. outptr1[RGB_BLUE] = range_limit[y + cblue];
  168493. outptr1 += RGB_PIXELSIZE;
  168494. }
  168495. /* If image width is odd, do the last output column separately */
  168496. if (cinfo->output_width & 1) {
  168497. cb = GETJSAMPLE(*inptr1);
  168498. cr = GETJSAMPLE(*inptr2);
  168499. cred = Crrtab[cr];
  168500. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  168501. cblue = Cbbtab[cb];
  168502. y = GETJSAMPLE(*inptr00);
  168503. outptr0[RGB_RED] = range_limit[y + cred];
  168504. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  168505. outptr0[RGB_BLUE] = range_limit[y + cblue];
  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. }
  168511. }
  168512. /*
  168513. * Module initialization routine for merged upsampling/color conversion.
  168514. *
  168515. * NB: this is called under the conditions determined by use_merged_upsample()
  168516. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  168517. * of this module; no safety checks are made here.
  168518. */
  168519. GLOBAL(void)
  168520. jinit_merged_upsampler (j_decompress_ptr cinfo)
  168521. {
  168522. my_upsample_ptr upsample;
  168523. upsample = (my_upsample_ptr)
  168524. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168525. SIZEOF(my_upsampler));
  168526. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  168527. upsample->pub.start_pass = start_pass_merged_upsample;
  168528. upsample->pub.need_context_rows = FALSE;
  168529. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  168530. if (cinfo->max_v_samp_factor == 2) {
  168531. upsample->pub.upsample = merged_2v_upsample;
  168532. upsample->upmethod = h2v2_merged_upsample;
  168533. /* Allocate a spare row buffer */
  168534. upsample->spare_row = (JSAMPROW)
  168535. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168536. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  168537. } else {
  168538. upsample->pub.upsample = merged_1v_upsample;
  168539. upsample->upmethod = h2v1_merged_upsample;
  168540. /* No spare row needed */
  168541. upsample->spare_row = NULL;
  168542. }
  168543. build_ycc_rgb_table2(cinfo);
  168544. }
  168545. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  168546. /********* End of inlined file: jdmerge.c *********/
  168547. #undef ASSIGN_STATE
  168548. /********* Start of inlined file: jdphuff.c *********/
  168549. #define JPEG_INTERNALS
  168550. #ifdef D_PROGRESSIVE_SUPPORTED
  168551. /*
  168552. * Expanded entropy decoder object for progressive Huffman decoding.
  168553. *
  168554. * The savable_state subrecord contains fields that change within an MCU,
  168555. * but must not be updated permanently until we complete the MCU.
  168556. */
  168557. typedef struct {
  168558. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  168559. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  168560. } savable_state3;
  168561. /* This macro is to work around compilers with missing or broken
  168562. * structure assignment. You'll need to fix this code if you have
  168563. * such a compiler and you change MAX_COMPS_IN_SCAN.
  168564. */
  168565. #ifndef NO_STRUCT_ASSIGN
  168566. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  168567. #else
  168568. #if MAX_COMPS_IN_SCAN == 4
  168569. #define ASSIGN_STATE(dest,src) \
  168570. ((dest).EOBRUN = (src).EOBRUN, \
  168571. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  168572. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  168573. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  168574. (dest).last_dc_val[3] = (src).last_dc_val[3])
  168575. #endif
  168576. #endif
  168577. typedef struct {
  168578. struct jpeg_entropy_decoder pub; /* public fields */
  168579. /* These fields are loaded into local variables at start of each MCU.
  168580. * In case of suspension, we exit WITHOUT updating them.
  168581. */
  168582. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  168583. savable_state3 saved; /* Other state at start of MCU */
  168584. /* These fields are NOT loaded into local working state. */
  168585. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  168586. /* Pointers to derived tables (these workspaces have image lifespan) */
  168587. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  168588. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  168589. } phuff_entropy_decoder;
  168590. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  168591. /* Forward declarations */
  168592. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  168593. JBLOCKROW *MCU_data));
  168594. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  168595. JBLOCKROW *MCU_data));
  168596. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  168597. JBLOCKROW *MCU_data));
  168598. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  168599. JBLOCKROW *MCU_data));
  168600. /*
  168601. * Initialize for a Huffman-compressed scan.
  168602. */
  168603. METHODDEF(void)
  168604. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  168605. {
  168606. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168607. boolean is_DC_band, bad;
  168608. int ci, coefi, tbl;
  168609. int *coef_bit_ptr;
  168610. jpeg_component_info * compptr;
  168611. is_DC_band = (cinfo->Ss == 0);
  168612. /* Validate scan parameters */
  168613. bad = FALSE;
  168614. if (is_DC_band) {
  168615. if (cinfo->Se != 0)
  168616. bad = TRUE;
  168617. } else {
  168618. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  168619. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  168620. bad = TRUE;
  168621. /* AC scans may have only one component */
  168622. if (cinfo->comps_in_scan != 1)
  168623. bad = TRUE;
  168624. }
  168625. if (cinfo->Ah != 0) {
  168626. /* Successive approximation refinement scan: must have Al = Ah-1. */
  168627. if (cinfo->Al != cinfo->Ah-1)
  168628. bad = TRUE;
  168629. }
  168630. if (cinfo->Al > 13) /* need not check for < 0 */
  168631. bad = TRUE;
  168632. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  168633. * but the spec doesn't say so, and we try to be liberal about what we
  168634. * accept. Note: large Al values could result in out-of-range DC
  168635. * coefficients during early scans, leading to bizarre displays due to
  168636. * overflows in the IDCT math. But we won't crash.
  168637. */
  168638. if (bad)
  168639. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  168640. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  168641. /* Update progression status, and verify that scan order is legal.
  168642. * Note that inter-scan inconsistencies are treated as warnings
  168643. * not fatal errors ... not clear if this is right way to behave.
  168644. */
  168645. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168646. int cindex = cinfo->cur_comp_info[ci]->component_index;
  168647. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  168648. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  168649. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  168650. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  168651. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  168652. if (cinfo->Ah != expected)
  168653. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  168654. coef_bit_ptr[coefi] = cinfo->Al;
  168655. }
  168656. }
  168657. /* Select MCU decoding routine */
  168658. if (cinfo->Ah == 0) {
  168659. if (is_DC_band)
  168660. entropy->pub.decode_mcu = decode_mcu_DC_first;
  168661. else
  168662. entropy->pub.decode_mcu = decode_mcu_AC_first;
  168663. } else {
  168664. if (is_DC_band)
  168665. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  168666. else
  168667. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  168668. }
  168669. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168670. compptr = cinfo->cur_comp_info[ci];
  168671. /* Make sure requested tables are present, and compute derived tables.
  168672. * We may build same derived table more than once, but it's not expensive.
  168673. */
  168674. if (is_DC_band) {
  168675. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  168676. tbl = compptr->dc_tbl_no;
  168677. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  168678. & entropy->derived_tbls[tbl]);
  168679. }
  168680. } else {
  168681. tbl = compptr->ac_tbl_no;
  168682. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  168683. & entropy->derived_tbls[tbl]);
  168684. /* remember the single active table */
  168685. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  168686. }
  168687. /* Initialize DC predictions to 0 */
  168688. entropy->saved.last_dc_val[ci] = 0;
  168689. }
  168690. /* Initialize bitread state variables */
  168691. entropy->bitstate.bits_left = 0;
  168692. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  168693. entropy->pub.insufficient_data = FALSE;
  168694. /* Initialize private state variables */
  168695. entropy->saved.EOBRUN = 0;
  168696. /* Initialize restart counter */
  168697. entropy->restarts_to_go = cinfo->restart_interval;
  168698. }
  168699. /*
  168700. * Check for a restart marker & resynchronize decoder.
  168701. * Returns FALSE if must suspend.
  168702. */
  168703. LOCAL(boolean)
  168704. process_restartp (j_decompress_ptr cinfo)
  168705. {
  168706. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168707. int ci;
  168708. /* Throw away any unused bits remaining in bit buffer; */
  168709. /* include any full bytes in next_marker's count of discarded bytes */
  168710. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  168711. entropy->bitstate.bits_left = 0;
  168712. /* Advance past the RSTn marker */
  168713. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  168714. return FALSE;
  168715. /* Re-initialize DC predictions to 0 */
  168716. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  168717. entropy->saved.last_dc_val[ci] = 0;
  168718. /* Re-init EOB run count, too */
  168719. entropy->saved.EOBRUN = 0;
  168720. /* Reset restart counter */
  168721. entropy->restarts_to_go = cinfo->restart_interval;
  168722. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  168723. * against a marker. In that case we will end up treating the next data
  168724. * segment as empty, and we can avoid producing bogus output pixels by
  168725. * leaving the flag set.
  168726. */
  168727. if (cinfo->unread_marker == 0)
  168728. entropy->pub.insufficient_data = FALSE;
  168729. return TRUE;
  168730. }
  168731. /*
  168732. * Huffman MCU decoding.
  168733. * Each of these routines decodes and returns one MCU's worth of
  168734. * Huffman-compressed coefficients.
  168735. * The coefficients are reordered from zigzag order into natural array order,
  168736. * but are not dequantized.
  168737. *
  168738. * The i'th block of the MCU is stored into the block pointed to by
  168739. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  168740. *
  168741. * We return FALSE if data source requested suspension. In that case no
  168742. * changes have been made to permanent state. (Exception: some output
  168743. * coefficients may already have been assigned. This is harmless for
  168744. * spectral selection, since we'll just re-assign them on the next call.
  168745. * Successive approximation AC refinement has to be more careful, however.)
  168746. */
  168747. /*
  168748. * MCU decoding for DC initial scan (either spectral selection,
  168749. * or first pass of successive approximation).
  168750. */
  168751. METHODDEF(boolean)
  168752. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168753. {
  168754. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168755. int Al = cinfo->Al;
  168756. register int s, r;
  168757. int blkn, ci;
  168758. JBLOCKROW block;
  168759. BITREAD_STATE_VARS;
  168760. savable_state3 state;
  168761. d_derived_tbl * tbl;
  168762. jpeg_component_info * compptr;
  168763. /* Process restart marker if needed; may have to suspend */
  168764. if (cinfo->restart_interval) {
  168765. if (entropy->restarts_to_go == 0)
  168766. if (! process_restartp(cinfo))
  168767. return FALSE;
  168768. }
  168769. /* If we've run out of data, just leave the MCU set to zeroes.
  168770. * This way, we return uniform gray for the remainder of the segment.
  168771. */
  168772. if (! entropy->pub.insufficient_data) {
  168773. /* Load up working state */
  168774. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168775. ASSIGN_STATE(state, entropy->saved);
  168776. /* Outer loop handles each block in the MCU */
  168777. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168778. block = MCU_data[blkn];
  168779. ci = cinfo->MCU_membership[blkn];
  168780. compptr = cinfo->cur_comp_info[ci];
  168781. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  168782. /* Decode a single block's worth of coefficients */
  168783. /* Section F.2.2.1: decode the DC coefficient difference */
  168784. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  168785. if (s) {
  168786. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168787. r = GET_BITS(s);
  168788. s = HUFF_EXTEND(r, s);
  168789. }
  168790. /* Convert DC difference to actual value, update last_dc_val */
  168791. s += state.last_dc_val[ci];
  168792. state.last_dc_val[ci] = s;
  168793. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  168794. (*block)[0] = (JCOEF) (s << Al);
  168795. }
  168796. /* Completed MCU, so update state */
  168797. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168798. ASSIGN_STATE(entropy->saved, state);
  168799. }
  168800. /* Account for restart interval (no-op if not using restarts) */
  168801. entropy->restarts_to_go--;
  168802. return TRUE;
  168803. }
  168804. /*
  168805. * MCU decoding for AC initial scan (either spectral selection,
  168806. * or first pass of successive approximation).
  168807. */
  168808. METHODDEF(boolean)
  168809. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168810. {
  168811. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168812. int Se = cinfo->Se;
  168813. int Al = cinfo->Al;
  168814. register int s, k, r;
  168815. unsigned int EOBRUN;
  168816. JBLOCKROW block;
  168817. BITREAD_STATE_VARS;
  168818. d_derived_tbl * tbl;
  168819. /* Process restart marker if needed; may have to suspend */
  168820. if (cinfo->restart_interval) {
  168821. if (entropy->restarts_to_go == 0)
  168822. if (! process_restartp(cinfo))
  168823. return FALSE;
  168824. }
  168825. /* If we've run out of data, just leave the MCU set to zeroes.
  168826. * This way, we return uniform gray for the remainder of the segment.
  168827. */
  168828. if (! entropy->pub.insufficient_data) {
  168829. /* Load up working state.
  168830. * We can avoid loading/saving bitread state if in an EOB run.
  168831. */
  168832. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168833. /* There is always only one block per MCU */
  168834. if (EOBRUN > 0) /* if it's a band of zeroes... */
  168835. EOBRUN--; /* ...process it now (we do nothing) */
  168836. else {
  168837. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168838. block = MCU_data[0];
  168839. tbl = entropy->ac_derived_tbl;
  168840. for (k = cinfo->Ss; k <= Se; k++) {
  168841. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  168842. r = s >> 4;
  168843. s &= 15;
  168844. if (s) {
  168845. k += r;
  168846. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  168847. r = GET_BITS(s);
  168848. s = HUFF_EXTEND(r, s);
  168849. /* Scale and output coefficient in natural (dezigzagged) order */
  168850. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  168851. } else {
  168852. if (r == 15) { /* ZRL */
  168853. k += 15; /* skip 15 zeroes in band */
  168854. } else { /* EOBr, run length is 2^r + appended bits */
  168855. EOBRUN = 1 << r;
  168856. if (r) { /* EOBr, r > 0 */
  168857. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  168858. r = GET_BITS(r);
  168859. EOBRUN += r;
  168860. }
  168861. EOBRUN--; /* this band is processed at this moment */
  168862. break; /* force end-of-band */
  168863. }
  168864. }
  168865. }
  168866. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168867. }
  168868. /* Completed MCU, so update state */
  168869. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  168870. }
  168871. /* Account for restart interval (no-op if not using restarts) */
  168872. entropy->restarts_to_go--;
  168873. return TRUE;
  168874. }
  168875. /*
  168876. * MCU decoding for DC successive approximation refinement scan.
  168877. * Note: we assume such scans can be multi-component, although the spec
  168878. * is not very clear on the point.
  168879. */
  168880. METHODDEF(boolean)
  168881. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168882. {
  168883. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168884. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168885. int blkn;
  168886. JBLOCKROW block;
  168887. BITREAD_STATE_VARS;
  168888. /* Process restart marker if needed; may have to suspend */
  168889. if (cinfo->restart_interval) {
  168890. if (entropy->restarts_to_go == 0)
  168891. if (! process_restartp(cinfo))
  168892. return FALSE;
  168893. }
  168894. /* Not worth the cycles to check insufficient_data here,
  168895. * since we will not change the data anyway if we read zeroes.
  168896. */
  168897. /* Load up working state */
  168898. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168899. /* Outer loop handles each block in the MCU */
  168900. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  168901. block = MCU_data[blkn];
  168902. /* Encoded data is simply the next bit of the two's-complement DC value */
  168903. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  168904. if (GET_BITS(1))
  168905. (*block)[0] |= p1;
  168906. /* Note: since we use |=, repeating the assignment later is safe */
  168907. }
  168908. /* Completed MCU, so update state */
  168909. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  168910. /* Account for restart interval (no-op if not using restarts) */
  168911. entropy->restarts_to_go--;
  168912. return TRUE;
  168913. }
  168914. /*
  168915. * MCU decoding for AC successive approximation refinement scan.
  168916. */
  168917. METHODDEF(boolean)
  168918. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  168919. {
  168920. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  168921. int Se = cinfo->Se;
  168922. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  168923. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  168924. register int s, k, r;
  168925. unsigned int EOBRUN;
  168926. JBLOCKROW block;
  168927. JCOEFPTR thiscoef;
  168928. BITREAD_STATE_VARS;
  168929. d_derived_tbl * tbl;
  168930. int num_newnz;
  168931. int newnz_pos[DCTSIZE2];
  168932. /* Process restart marker if needed; may have to suspend */
  168933. if (cinfo->restart_interval) {
  168934. if (entropy->restarts_to_go == 0)
  168935. if (! process_restartp(cinfo))
  168936. return FALSE;
  168937. }
  168938. /* If we've run out of data, don't modify the MCU.
  168939. */
  168940. if (! entropy->pub.insufficient_data) {
  168941. /* Load up working state */
  168942. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  168943. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  168944. /* There is always only one block per MCU */
  168945. block = MCU_data[0];
  168946. tbl = entropy->ac_derived_tbl;
  168947. /* If we are forced to suspend, we must undo the assignments to any newly
  168948. * nonzero coefficients in the block, because otherwise we'd get confused
  168949. * next time about which coefficients were already nonzero.
  168950. * But we need not undo addition of bits to already-nonzero coefficients;
  168951. * instead, we can test the current bit to see if we already did it.
  168952. */
  168953. num_newnz = 0;
  168954. /* initialize coefficient loop counter to start of band */
  168955. k = cinfo->Ss;
  168956. if (EOBRUN == 0) {
  168957. for (; k <= Se; k++) {
  168958. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  168959. r = s >> 4;
  168960. s &= 15;
  168961. if (s) {
  168962. if (s != 1) /* size of new coef should always be 1 */
  168963. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  168964. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168965. if (GET_BITS(1))
  168966. s = p1; /* newly nonzero coef is positive */
  168967. else
  168968. s = m1; /* newly nonzero coef is negative */
  168969. } else {
  168970. if (r != 15) {
  168971. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  168972. if (r) {
  168973. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  168974. r = GET_BITS(r);
  168975. EOBRUN += r;
  168976. }
  168977. break; /* rest of block is handled by EOB logic */
  168978. }
  168979. /* note s = 0 for processing ZRL */
  168980. }
  168981. /* Advance over already-nonzero coefs and r still-zero coefs,
  168982. * appending correction bits to the nonzeroes. A correction bit is 1
  168983. * if the absolute value of the coefficient must be increased.
  168984. */
  168985. do {
  168986. thiscoef = *block + jpeg_natural_order[k];
  168987. if (*thiscoef != 0) {
  168988. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  168989. if (GET_BITS(1)) {
  168990. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  168991. if (*thiscoef >= 0)
  168992. *thiscoef += p1;
  168993. else
  168994. *thiscoef += m1;
  168995. }
  168996. }
  168997. } else {
  168998. if (--r < 0)
  168999. break; /* reached target zero coefficient */
  169000. }
  169001. k++;
  169002. } while (k <= Se);
  169003. if (s) {
  169004. int pos = jpeg_natural_order[k];
  169005. /* Output newly nonzero coefficient */
  169006. (*block)[pos] = (JCOEF) s;
  169007. /* Remember its position in case we have to suspend */
  169008. newnz_pos[num_newnz++] = pos;
  169009. }
  169010. }
  169011. }
  169012. if (EOBRUN > 0) {
  169013. /* Scan any remaining coefficient positions after the end-of-band
  169014. * (the last newly nonzero coefficient, if any). Append a correction
  169015. * bit to each already-nonzero coefficient. A correction bit is 1
  169016. * if the absolute value of the coefficient must be increased.
  169017. */
  169018. for (; k <= Se; k++) {
  169019. thiscoef = *block + jpeg_natural_order[k];
  169020. if (*thiscoef != 0) {
  169021. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  169022. if (GET_BITS(1)) {
  169023. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  169024. if (*thiscoef >= 0)
  169025. *thiscoef += p1;
  169026. else
  169027. *thiscoef += m1;
  169028. }
  169029. }
  169030. }
  169031. }
  169032. /* Count one block completed in EOB run */
  169033. EOBRUN--;
  169034. }
  169035. /* Completed MCU, so update state */
  169036. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  169037. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  169038. }
  169039. /* Account for restart interval (no-op if not using restarts) */
  169040. entropy->restarts_to_go--;
  169041. return TRUE;
  169042. undoit:
  169043. /* Re-zero any output coefficients that we made newly nonzero */
  169044. while (num_newnz > 0)
  169045. (*block)[newnz_pos[--num_newnz]] = 0;
  169046. return FALSE;
  169047. }
  169048. /*
  169049. * Module initialization routine for progressive Huffman entropy decoding.
  169050. */
  169051. GLOBAL(void)
  169052. jinit_phuff_decoder (j_decompress_ptr cinfo)
  169053. {
  169054. phuff_entropy_ptr2 entropy;
  169055. int *coef_bit_ptr;
  169056. int ci, i;
  169057. entropy = (phuff_entropy_ptr2)
  169058. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169059. SIZEOF(phuff_entropy_decoder));
  169060. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  169061. entropy->pub.start_pass = start_pass_phuff_decoder;
  169062. /* Mark derived tables unallocated */
  169063. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  169064. entropy->derived_tbls[i] = NULL;
  169065. }
  169066. /* Create progression status table */
  169067. cinfo->coef_bits = (int (*)[DCTSIZE2])
  169068. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169069. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  169070. coef_bit_ptr = & cinfo->coef_bits[0][0];
  169071. for (ci = 0; ci < cinfo->num_components; ci++)
  169072. for (i = 0; i < DCTSIZE2; i++)
  169073. *coef_bit_ptr++ = -1;
  169074. }
  169075. #endif /* D_PROGRESSIVE_SUPPORTED */
  169076. /********* End of inlined file: jdphuff.c *********/
  169077. /********* Start of inlined file: jdpostct.c *********/
  169078. #define JPEG_INTERNALS
  169079. /* Private buffer controller object */
  169080. typedef struct {
  169081. struct jpeg_d_post_controller pub; /* public fields */
  169082. /* Color quantization source buffer: this holds output data from
  169083. * the upsample/color conversion step to be passed to the quantizer.
  169084. * For two-pass color quantization, we need a full-image buffer;
  169085. * for one-pass operation, a strip buffer is sufficient.
  169086. */
  169087. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  169088. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  169089. JDIMENSION strip_height; /* buffer size in rows */
  169090. /* for two-pass mode only: */
  169091. JDIMENSION starting_row; /* row # of first row in current strip */
  169092. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  169093. } my_post_controller;
  169094. typedef my_post_controller * my_post_ptr;
  169095. /* Forward declarations */
  169096. METHODDEF(void) post_process_1pass
  169097. JPP((j_decompress_ptr cinfo,
  169098. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169099. JDIMENSION in_row_groups_avail,
  169100. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169101. JDIMENSION out_rows_avail));
  169102. #ifdef QUANT_2PASS_SUPPORTED
  169103. METHODDEF(void) post_process_prepass
  169104. JPP((j_decompress_ptr cinfo,
  169105. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169106. JDIMENSION in_row_groups_avail,
  169107. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169108. JDIMENSION out_rows_avail));
  169109. METHODDEF(void) post_process_2pass
  169110. JPP((j_decompress_ptr cinfo,
  169111. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169112. JDIMENSION in_row_groups_avail,
  169113. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169114. JDIMENSION out_rows_avail));
  169115. #endif
  169116. /*
  169117. * Initialize for a processing pass.
  169118. */
  169119. METHODDEF(void)
  169120. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  169121. {
  169122. my_post_ptr post = (my_post_ptr) cinfo->post;
  169123. switch (pass_mode) {
  169124. case JBUF_PASS_THRU:
  169125. if (cinfo->quantize_colors) {
  169126. /* Single-pass processing with color quantization. */
  169127. post->pub.post_process_data = post_process_1pass;
  169128. /* We could be doing buffered-image output before starting a 2-pass
  169129. * color quantization; in that case, jinit_d_post_controller did not
  169130. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  169131. */
  169132. if (post->buffer == NULL) {
  169133. post->buffer = (*cinfo->mem->access_virt_sarray)
  169134. ((j_common_ptr) cinfo, post->whole_image,
  169135. (JDIMENSION) 0, post->strip_height, TRUE);
  169136. }
  169137. } else {
  169138. /* For single-pass processing without color quantization,
  169139. * I have no work to do; just call the upsampler directly.
  169140. */
  169141. post->pub.post_process_data = cinfo->upsample->upsample;
  169142. }
  169143. break;
  169144. #ifdef QUANT_2PASS_SUPPORTED
  169145. case JBUF_SAVE_AND_PASS:
  169146. /* First pass of 2-pass quantization */
  169147. if (post->whole_image == NULL)
  169148. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169149. post->pub.post_process_data = post_process_prepass;
  169150. break;
  169151. case JBUF_CRANK_DEST:
  169152. /* Second pass of 2-pass quantization */
  169153. if (post->whole_image == NULL)
  169154. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169155. post->pub.post_process_data = post_process_2pass;
  169156. break;
  169157. #endif /* QUANT_2PASS_SUPPORTED */
  169158. default:
  169159. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169160. break;
  169161. }
  169162. post->starting_row = post->next_row = 0;
  169163. }
  169164. /*
  169165. * Process some data in the one-pass (strip buffer) case.
  169166. * This is used for color precision reduction as well as one-pass quantization.
  169167. */
  169168. METHODDEF(void)
  169169. post_process_1pass (j_decompress_ptr cinfo,
  169170. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169171. JDIMENSION in_row_groups_avail,
  169172. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169173. JDIMENSION out_rows_avail)
  169174. {
  169175. my_post_ptr post = (my_post_ptr) cinfo->post;
  169176. JDIMENSION num_rows, max_rows;
  169177. /* Fill the buffer, but not more than what we can dump out in one go. */
  169178. /* Note we rely on the upsampler to detect bottom of image. */
  169179. max_rows = out_rows_avail - *out_row_ctr;
  169180. if (max_rows > post->strip_height)
  169181. max_rows = post->strip_height;
  169182. num_rows = 0;
  169183. (*cinfo->upsample->upsample) (cinfo,
  169184. input_buf, in_row_group_ctr, in_row_groups_avail,
  169185. post->buffer, &num_rows, max_rows);
  169186. /* Quantize and emit data. */
  169187. (*cinfo->cquantize->color_quantize) (cinfo,
  169188. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  169189. *out_row_ctr += num_rows;
  169190. }
  169191. #ifdef QUANT_2PASS_SUPPORTED
  169192. /*
  169193. * Process some data in the first pass of 2-pass quantization.
  169194. */
  169195. METHODDEF(void)
  169196. post_process_prepass (j_decompress_ptr cinfo,
  169197. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169198. JDIMENSION in_row_groups_avail,
  169199. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169200. JDIMENSION out_rows_avail)
  169201. {
  169202. my_post_ptr post = (my_post_ptr) cinfo->post;
  169203. JDIMENSION old_next_row, num_rows;
  169204. /* Reposition virtual buffer if at start of strip. */
  169205. if (post->next_row == 0) {
  169206. post->buffer = (*cinfo->mem->access_virt_sarray)
  169207. ((j_common_ptr) cinfo, post->whole_image,
  169208. post->starting_row, post->strip_height, TRUE);
  169209. }
  169210. /* Upsample some data (up to a strip height's worth). */
  169211. old_next_row = post->next_row;
  169212. (*cinfo->upsample->upsample) (cinfo,
  169213. input_buf, in_row_group_ctr, in_row_groups_avail,
  169214. post->buffer, &post->next_row, post->strip_height);
  169215. /* Allow quantizer to scan new data. No data is emitted, */
  169216. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  169217. if (post->next_row > old_next_row) {
  169218. num_rows = post->next_row - old_next_row;
  169219. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  169220. (JSAMPARRAY) NULL, (int) num_rows);
  169221. *out_row_ctr += num_rows;
  169222. }
  169223. /* Advance if we filled the strip. */
  169224. if (post->next_row >= post->strip_height) {
  169225. post->starting_row += post->strip_height;
  169226. post->next_row = 0;
  169227. }
  169228. }
  169229. /*
  169230. * Process some data in the second pass of 2-pass quantization.
  169231. */
  169232. METHODDEF(void)
  169233. post_process_2pass (j_decompress_ptr cinfo,
  169234. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169235. JDIMENSION in_row_groups_avail,
  169236. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169237. JDIMENSION out_rows_avail)
  169238. {
  169239. my_post_ptr post = (my_post_ptr) cinfo->post;
  169240. JDIMENSION num_rows, max_rows;
  169241. /* Reposition virtual buffer if at start of strip. */
  169242. if (post->next_row == 0) {
  169243. post->buffer = (*cinfo->mem->access_virt_sarray)
  169244. ((j_common_ptr) cinfo, post->whole_image,
  169245. post->starting_row, post->strip_height, FALSE);
  169246. }
  169247. /* Determine number of rows to emit. */
  169248. num_rows = post->strip_height - post->next_row; /* available in strip */
  169249. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  169250. if (num_rows > max_rows)
  169251. num_rows = max_rows;
  169252. /* We have to check bottom of image here, can't depend on upsampler. */
  169253. max_rows = cinfo->output_height - post->starting_row;
  169254. if (num_rows > max_rows)
  169255. num_rows = max_rows;
  169256. /* Quantize and emit data. */
  169257. (*cinfo->cquantize->color_quantize) (cinfo,
  169258. post->buffer + post->next_row, output_buf + *out_row_ctr,
  169259. (int) num_rows);
  169260. *out_row_ctr += num_rows;
  169261. /* Advance if we filled the strip. */
  169262. post->next_row += num_rows;
  169263. if (post->next_row >= post->strip_height) {
  169264. post->starting_row += post->strip_height;
  169265. post->next_row = 0;
  169266. }
  169267. }
  169268. #endif /* QUANT_2PASS_SUPPORTED */
  169269. /*
  169270. * Initialize postprocessing controller.
  169271. */
  169272. GLOBAL(void)
  169273. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169274. {
  169275. my_post_ptr post;
  169276. post = (my_post_ptr)
  169277. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169278. SIZEOF(my_post_controller));
  169279. cinfo->post = (struct jpeg_d_post_controller *) post;
  169280. post->pub.start_pass = start_pass_dpost;
  169281. post->whole_image = NULL; /* flag for no virtual arrays */
  169282. post->buffer = NULL; /* flag for no strip buffer */
  169283. /* Create the quantization buffer, if needed */
  169284. if (cinfo->quantize_colors) {
  169285. /* The buffer strip height is max_v_samp_factor, which is typically
  169286. * an efficient number of rows for upsampling to return.
  169287. * (In the presence of output rescaling, we might want to be smarter?)
  169288. */
  169289. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  169290. if (need_full_buffer) {
  169291. /* Two-pass color quantization: need full-image storage. */
  169292. /* We round up the number of rows to a multiple of the strip height. */
  169293. #ifdef QUANT_2PASS_SUPPORTED
  169294. post->whole_image = (*cinfo->mem->request_virt_sarray)
  169295. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  169296. cinfo->output_width * cinfo->out_color_components,
  169297. (JDIMENSION) jround_up((long) cinfo->output_height,
  169298. (long) post->strip_height),
  169299. post->strip_height);
  169300. #else
  169301. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  169302. #endif /* QUANT_2PASS_SUPPORTED */
  169303. } else {
  169304. /* One-pass color quantization: just make a strip buffer. */
  169305. post->buffer = (*cinfo->mem->alloc_sarray)
  169306. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169307. cinfo->output_width * cinfo->out_color_components,
  169308. post->strip_height);
  169309. }
  169310. }
  169311. }
  169312. /********* End of inlined file: jdpostct.c *********/
  169313. #undef FIX
  169314. /********* Start of inlined file: jdsample.c *********/
  169315. #define JPEG_INTERNALS
  169316. /* Pointer to routine to upsample a single component */
  169317. typedef JMETHOD(void, upsample1_ptr,
  169318. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169319. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  169320. /* Private subobject */
  169321. typedef struct {
  169322. struct jpeg_upsampler pub; /* public fields */
  169323. /* Color conversion buffer. When using separate upsampling and color
  169324. * conversion steps, this buffer holds one upsampled row group until it
  169325. * has been color converted and output.
  169326. * Note: we do not allocate any storage for component(s) which are full-size,
  169327. * ie do not need rescaling. The corresponding entry of color_buf[] is
  169328. * simply set to point to the input data array, thereby avoiding copying.
  169329. */
  169330. JSAMPARRAY color_buf[MAX_COMPONENTS];
  169331. /* Per-component upsampling method pointers */
  169332. upsample1_ptr methods[MAX_COMPONENTS];
  169333. int next_row_out; /* counts rows emitted from color_buf */
  169334. JDIMENSION rows_to_go; /* counts rows remaining in image */
  169335. /* Height of an input row group for each component. */
  169336. int rowgroup_height[MAX_COMPONENTS];
  169337. /* These arrays save pixel expansion factors so that int_expand need not
  169338. * recompute them each time. They are unused for other upsampling methods.
  169339. */
  169340. UINT8 h_expand[MAX_COMPONENTS];
  169341. UINT8 v_expand[MAX_COMPONENTS];
  169342. } my_upsampler2;
  169343. typedef my_upsampler2 * my_upsample_ptr2;
  169344. /*
  169345. * Initialize for an upsampling pass.
  169346. */
  169347. METHODDEF(void)
  169348. start_pass_upsample (j_decompress_ptr cinfo)
  169349. {
  169350. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169351. /* Mark the conversion buffer empty */
  169352. upsample->next_row_out = cinfo->max_v_samp_factor;
  169353. /* Initialize total-height counter for detecting bottom of image */
  169354. upsample->rows_to_go = cinfo->output_height;
  169355. }
  169356. /*
  169357. * Control routine to do upsampling (and color conversion).
  169358. *
  169359. * In this version we upsample each component independently.
  169360. * We upsample one row group into the conversion buffer, then apply
  169361. * color conversion a row at a time.
  169362. */
  169363. METHODDEF(void)
  169364. sep_upsample (j_decompress_ptr cinfo,
  169365. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  169366. JDIMENSION in_row_groups_avail,
  169367. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  169368. JDIMENSION out_rows_avail)
  169369. {
  169370. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169371. int ci;
  169372. jpeg_component_info * compptr;
  169373. JDIMENSION num_rows;
  169374. /* Fill the conversion buffer, if it's empty */
  169375. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  169376. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169377. ci++, compptr++) {
  169378. /* Invoke per-component upsample method. Notice we pass a POINTER
  169379. * to color_buf[ci], so that fullsize_upsample can change it.
  169380. */
  169381. (*upsample->methods[ci]) (cinfo, compptr,
  169382. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  169383. upsample->color_buf + ci);
  169384. }
  169385. upsample->next_row_out = 0;
  169386. }
  169387. /* Color-convert and emit rows */
  169388. /* How many we have in the buffer: */
  169389. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  169390. /* Not more than the distance to the end of the image. Need this test
  169391. * in case the image height is not a multiple of max_v_samp_factor:
  169392. */
  169393. if (num_rows > upsample->rows_to_go)
  169394. num_rows = upsample->rows_to_go;
  169395. /* And not more than what the client can accept: */
  169396. out_rows_avail -= *out_row_ctr;
  169397. if (num_rows > out_rows_avail)
  169398. num_rows = out_rows_avail;
  169399. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  169400. (JDIMENSION) upsample->next_row_out,
  169401. output_buf + *out_row_ctr,
  169402. (int) num_rows);
  169403. /* Adjust counts */
  169404. *out_row_ctr += num_rows;
  169405. upsample->rows_to_go -= num_rows;
  169406. upsample->next_row_out += num_rows;
  169407. /* When the buffer is emptied, declare this input row group consumed */
  169408. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  169409. (*in_row_group_ctr)++;
  169410. }
  169411. /*
  169412. * These are the routines invoked by sep_upsample to upsample pixel values
  169413. * of a single component. One row group is processed per call.
  169414. */
  169415. /*
  169416. * For full-size components, we just make color_buf[ci] point at the
  169417. * input buffer, and thus avoid copying any data. Note that this is
  169418. * safe only because sep_upsample doesn't declare the input row group
  169419. * "consumed" until we are done color converting and emitting it.
  169420. */
  169421. METHODDEF(void)
  169422. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169423. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169424. {
  169425. *output_data_ptr = input_data;
  169426. }
  169427. /*
  169428. * This is a no-op version used for "uninteresting" components.
  169429. * These components will not be referenced by color conversion.
  169430. */
  169431. METHODDEF(void)
  169432. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169433. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169434. {
  169435. *output_data_ptr = NULL; /* safety check */
  169436. }
  169437. /*
  169438. * This version handles any integral sampling ratios.
  169439. * This is not used for typical JPEG files, so it need not be fast.
  169440. * Nor, for that matter, is it particularly accurate: the algorithm is
  169441. * simple replication of the input pixel onto the corresponding output
  169442. * pixels. The hi-falutin sampling literature refers to this as a
  169443. * "box filter". A box filter tends to introduce visible artifacts,
  169444. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  169445. * you would be well advised to improve this code.
  169446. */
  169447. METHODDEF(void)
  169448. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169449. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169450. {
  169451. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  169452. JSAMPARRAY output_data = *output_data_ptr;
  169453. register JSAMPROW inptr, outptr;
  169454. register JSAMPLE invalue;
  169455. register int h;
  169456. JSAMPROW outend;
  169457. int h_expand, v_expand;
  169458. int inrow, outrow;
  169459. h_expand = upsample->h_expand[compptr->component_index];
  169460. v_expand = upsample->v_expand[compptr->component_index];
  169461. inrow = outrow = 0;
  169462. while (outrow < cinfo->max_v_samp_factor) {
  169463. /* Generate one output row with proper horizontal expansion */
  169464. inptr = input_data[inrow];
  169465. outptr = output_data[outrow];
  169466. outend = outptr + cinfo->output_width;
  169467. while (outptr < outend) {
  169468. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169469. for (h = h_expand; h > 0; h--) {
  169470. *outptr++ = invalue;
  169471. }
  169472. }
  169473. /* Generate any additional output rows by duplicating the first one */
  169474. if (v_expand > 1) {
  169475. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169476. v_expand-1, cinfo->output_width);
  169477. }
  169478. inrow++;
  169479. outrow += v_expand;
  169480. }
  169481. }
  169482. /*
  169483. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  169484. * It's still a box filter.
  169485. */
  169486. METHODDEF(void)
  169487. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169488. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169489. {
  169490. JSAMPARRAY output_data = *output_data_ptr;
  169491. register JSAMPROW inptr, outptr;
  169492. register JSAMPLE invalue;
  169493. JSAMPROW outend;
  169494. int inrow;
  169495. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169496. inptr = input_data[inrow];
  169497. outptr = output_data[inrow];
  169498. outend = outptr + cinfo->output_width;
  169499. while (outptr < outend) {
  169500. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169501. *outptr++ = invalue;
  169502. *outptr++ = invalue;
  169503. }
  169504. }
  169505. }
  169506. /*
  169507. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  169508. * It's still a box filter.
  169509. */
  169510. METHODDEF(void)
  169511. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169512. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169513. {
  169514. JSAMPARRAY output_data = *output_data_ptr;
  169515. register JSAMPROW inptr, outptr;
  169516. register JSAMPLE invalue;
  169517. JSAMPROW outend;
  169518. int inrow, outrow;
  169519. inrow = outrow = 0;
  169520. while (outrow < cinfo->max_v_samp_factor) {
  169521. inptr = input_data[inrow];
  169522. outptr = output_data[outrow];
  169523. outend = outptr + cinfo->output_width;
  169524. while (outptr < outend) {
  169525. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  169526. *outptr++ = invalue;
  169527. *outptr++ = invalue;
  169528. }
  169529. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  169530. 1, cinfo->output_width);
  169531. inrow++;
  169532. outrow += 2;
  169533. }
  169534. }
  169535. /*
  169536. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  169537. *
  169538. * The upsampling algorithm is linear interpolation between pixel centers,
  169539. * also known as a "triangle filter". This is a good compromise between
  169540. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  169541. * of the way between input pixel centers.
  169542. *
  169543. * A note about the "bias" calculations: when rounding fractional values to
  169544. * integer, we do not want to always round 0.5 up to the next integer.
  169545. * If we did that, we'd introduce a noticeable bias towards larger values.
  169546. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  169547. * alternate pixel locations (a simple ordered dither pattern).
  169548. */
  169549. METHODDEF(void)
  169550. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169551. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169552. {
  169553. JSAMPARRAY output_data = *output_data_ptr;
  169554. register JSAMPROW inptr, outptr;
  169555. register int invalue;
  169556. register JDIMENSION colctr;
  169557. int inrow;
  169558. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  169559. inptr = input_data[inrow];
  169560. outptr = output_data[inrow];
  169561. /* Special case for first column */
  169562. invalue = GETJSAMPLE(*inptr++);
  169563. *outptr++ = (JSAMPLE) invalue;
  169564. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  169565. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169566. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  169567. invalue = GETJSAMPLE(*inptr++) * 3;
  169568. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  169569. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  169570. }
  169571. /* Special case for last column */
  169572. invalue = GETJSAMPLE(*inptr);
  169573. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  169574. *outptr++ = (JSAMPLE) invalue;
  169575. }
  169576. }
  169577. /*
  169578. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  169579. * Again a triangle filter; see comments for h2v1 case, above.
  169580. *
  169581. * It is OK for us to reference the adjacent input rows because we demanded
  169582. * context from the main buffer controller (see initialization code).
  169583. */
  169584. METHODDEF(void)
  169585. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169586. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  169587. {
  169588. JSAMPARRAY output_data = *output_data_ptr;
  169589. register JSAMPROW inptr0, inptr1, outptr;
  169590. #if BITS_IN_JSAMPLE == 8
  169591. register int thiscolsum, lastcolsum, nextcolsum;
  169592. #else
  169593. register INT32 thiscolsum, lastcolsum, nextcolsum;
  169594. #endif
  169595. register JDIMENSION colctr;
  169596. int inrow, outrow, v;
  169597. inrow = outrow = 0;
  169598. while (outrow < cinfo->max_v_samp_factor) {
  169599. for (v = 0; v < 2; v++) {
  169600. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  169601. inptr0 = input_data[inrow];
  169602. if (v == 0) /* next nearest is row above */
  169603. inptr1 = input_data[inrow-1];
  169604. else /* next nearest is row below */
  169605. inptr1 = input_data[inrow+1];
  169606. outptr = output_data[outrow++];
  169607. /* Special case for first column */
  169608. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169609. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169610. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  169611. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169612. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169613. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  169614. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  169615. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  169616. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  169617. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169618. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  169619. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  169620. }
  169621. /* Special case for last column */
  169622. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  169623. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  169624. }
  169625. inrow++;
  169626. }
  169627. }
  169628. /*
  169629. * Module initialization routine for upsampling.
  169630. */
  169631. GLOBAL(void)
  169632. jinit_upsampler (j_decompress_ptr cinfo)
  169633. {
  169634. my_upsample_ptr2 upsample;
  169635. int ci;
  169636. jpeg_component_info * compptr;
  169637. boolean need_buffer, do_fancy;
  169638. int h_in_group, v_in_group, h_out_group, v_out_group;
  169639. upsample = (my_upsample_ptr2)
  169640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169641. SIZEOF(my_upsampler2));
  169642. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  169643. upsample->pub.start_pass = start_pass_upsample;
  169644. upsample->pub.upsample = sep_upsample;
  169645. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  169646. if (cinfo->CCIR601_sampling) /* this isn't supported */
  169647. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  169648. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  169649. * so don't ask for it.
  169650. */
  169651. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  169652. /* Verify we can handle the sampling factors, select per-component methods,
  169653. * and create storage as needed.
  169654. */
  169655. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169656. ci++, compptr++) {
  169657. /* Compute size of an "input group" after IDCT scaling. This many samples
  169658. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  169659. */
  169660. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  169661. cinfo->min_DCT_scaled_size;
  169662. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  169663. cinfo->min_DCT_scaled_size;
  169664. h_out_group = cinfo->max_h_samp_factor;
  169665. v_out_group = cinfo->max_v_samp_factor;
  169666. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  169667. need_buffer = TRUE;
  169668. if (! compptr->component_needed) {
  169669. /* Don't bother to upsample an uninteresting component. */
  169670. upsample->methods[ci] = noop_upsample;
  169671. need_buffer = FALSE;
  169672. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  169673. /* Fullsize components can be processed without any work. */
  169674. upsample->methods[ci] = fullsize_upsample;
  169675. need_buffer = FALSE;
  169676. } else if (h_in_group * 2 == h_out_group &&
  169677. v_in_group == v_out_group) {
  169678. /* Special cases for 2h1v upsampling */
  169679. if (do_fancy && compptr->downsampled_width > 2)
  169680. upsample->methods[ci] = h2v1_fancy_upsample;
  169681. else
  169682. upsample->methods[ci] = h2v1_upsample;
  169683. } else if (h_in_group * 2 == h_out_group &&
  169684. v_in_group * 2 == v_out_group) {
  169685. /* Special cases for 2h2v upsampling */
  169686. if (do_fancy && compptr->downsampled_width > 2) {
  169687. upsample->methods[ci] = h2v2_fancy_upsample;
  169688. upsample->pub.need_context_rows = TRUE;
  169689. } else
  169690. upsample->methods[ci] = h2v2_upsample;
  169691. } else if ((h_out_group % h_in_group) == 0 &&
  169692. (v_out_group % v_in_group) == 0) {
  169693. /* Generic integral-factors upsampling method */
  169694. upsample->methods[ci] = int_upsample;
  169695. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  169696. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  169697. } else
  169698. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  169699. if (need_buffer) {
  169700. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  169701. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169702. (JDIMENSION) jround_up((long) cinfo->output_width,
  169703. (long) cinfo->max_h_samp_factor),
  169704. (JDIMENSION) cinfo->max_v_samp_factor);
  169705. }
  169706. }
  169707. }
  169708. /********* End of inlined file: jdsample.c *********/
  169709. /********* Start of inlined file: jdtrans.c *********/
  169710. #define JPEG_INTERNALS
  169711. /* Forward declarations */
  169712. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  169713. /*
  169714. * Read the coefficient arrays from a JPEG file.
  169715. * jpeg_read_header must be completed before calling this.
  169716. *
  169717. * The entire image is read into a set of virtual coefficient-block arrays,
  169718. * one per component. The return value is a pointer to the array of
  169719. * virtual-array descriptors. These can be manipulated directly via the
  169720. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  169721. * To release the memory occupied by the virtual arrays, call
  169722. * jpeg_finish_decompress() when done with the data.
  169723. *
  169724. * An alternative usage is to simply obtain access to the coefficient arrays
  169725. * during a buffered-image-mode decompression operation. This is allowed
  169726. * after any jpeg_finish_output() call. The arrays can be accessed until
  169727. * jpeg_finish_decompress() is called. (Note that any call to the library
  169728. * may reposition the arrays, so don't rely on access_virt_barray() results
  169729. * to stay valid across library calls.)
  169730. *
  169731. * Returns NULL if suspended. This case need be checked only if
  169732. * a suspending data source is used.
  169733. */
  169734. GLOBAL(jvirt_barray_ptr *)
  169735. jpeg_read_coefficients (j_decompress_ptr cinfo)
  169736. {
  169737. if (cinfo->global_state == DSTATE_READY) {
  169738. /* First call: initialize active modules */
  169739. transdecode_master_selection(cinfo);
  169740. cinfo->global_state = DSTATE_RDCOEFS;
  169741. }
  169742. if (cinfo->global_state == DSTATE_RDCOEFS) {
  169743. /* Absorb whole file into the coef buffer */
  169744. for (;;) {
  169745. int retcode;
  169746. /* Call progress monitor hook if present */
  169747. if (cinfo->progress != NULL)
  169748. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  169749. /* Absorb some more input */
  169750. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  169751. if (retcode == JPEG_SUSPENDED)
  169752. return NULL;
  169753. if (retcode == JPEG_REACHED_EOI)
  169754. break;
  169755. /* Advance progress counter if appropriate */
  169756. if (cinfo->progress != NULL &&
  169757. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  169758. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  169759. /* startup underestimated number of scans; ratchet up one scan */
  169760. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  169761. }
  169762. }
  169763. }
  169764. /* Set state so that jpeg_finish_decompress does the right thing */
  169765. cinfo->global_state = DSTATE_STOPPING;
  169766. }
  169767. /* At this point we should be in state DSTATE_STOPPING if being used
  169768. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  169769. * to the coefficients during a full buffered-image-mode decompression.
  169770. */
  169771. if ((cinfo->global_state == DSTATE_STOPPING ||
  169772. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  169773. return cinfo->coef->coef_arrays;
  169774. }
  169775. /* Oops, improper usage */
  169776. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169777. return NULL; /* keep compiler happy */
  169778. }
  169779. /*
  169780. * Master selection of decompression modules for transcoding.
  169781. * This substitutes for jdmaster.c's initialization of the full decompressor.
  169782. */
  169783. LOCAL(void)
  169784. transdecode_master_selection (j_decompress_ptr cinfo)
  169785. {
  169786. /* This is effectively a buffered-image operation. */
  169787. cinfo->buffered_image = TRUE;
  169788. /* Entropy decoding: either Huffman or arithmetic coding. */
  169789. if (cinfo->arith_code) {
  169790. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  169791. } else {
  169792. if (cinfo->progressive_mode) {
  169793. #ifdef D_PROGRESSIVE_SUPPORTED
  169794. jinit_phuff_decoder(cinfo);
  169795. #else
  169796. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169797. #endif
  169798. } else
  169799. jinit_huff_decoder(cinfo);
  169800. }
  169801. /* Always get a full-image coefficient buffer. */
  169802. jinit_d_coef_controller(cinfo, TRUE);
  169803. /* We can now tell the memory manager to allocate virtual arrays. */
  169804. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  169805. /* Initialize input side of decompressor to consume first scan. */
  169806. (*cinfo->inputctl->start_input_pass) (cinfo);
  169807. /* Initialize progress monitoring. */
  169808. if (cinfo->progress != NULL) {
  169809. int nscans;
  169810. /* Estimate number of scans to set pass_limit. */
  169811. if (cinfo->progressive_mode) {
  169812. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  169813. nscans = 2 + 3 * cinfo->num_components;
  169814. } else if (cinfo->inputctl->has_multiple_scans) {
  169815. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  169816. nscans = cinfo->num_components;
  169817. } else {
  169818. nscans = 1;
  169819. }
  169820. cinfo->progress->pass_counter = 0L;
  169821. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  169822. cinfo->progress->completed_passes = 0;
  169823. cinfo->progress->total_passes = 1;
  169824. }
  169825. }
  169826. /********* End of inlined file: jdtrans.c *********/
  169827. /********* Start of inlined file: jfdctflt.c *********/
  169828. #define JPEG_INTERNALS
  169829. #ifdef DCT_FLOAT_SUPPORTED
  169830. /*
  169831. * This module is specialized to the case DCTSIZE = 8.
  169832. */
  169833. #if DCTSIZE != 8
  169834. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169835. #endif
  169836. /*
  169837. * Perform the forward DCT on one block of samples.
  169838. */
  169839. GLOBAL(void)
  169840. jpeg_fdct_float (FAST_FLOAT * data)
  169841. {
  169842. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  169843. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  169844. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  169845. FAST_FLOAT *dataptr;
  169846. int ctr;
  169847. /* Pass 1: process rows. */
  169848. dataptr = data;
  169849. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169850. tmp0 = dataptr[0] + dataptr[7];
  169851. tmp7 = dataptr[0] - dataptr[7];
  169852. tmp1 = dataptr[1] + dataptr[6];
  169853. tmp6 = dataptr[1] - dataptr[6];
  169854. tmp2 = dataptr[2] + dataptr[5];
  169855. tmp5 = dataptr[2] - dataptr[5];
  169856. tmp3 = dataptr[3] + dataptr[4];
  169857. tmp4 = dataptr[3] - dataptr[4];
  169858. /* Even part */
  169859. tmp10 = tmp0 + tmp3; /* phase 2 */
  169860. tmp13 = tmp0 - tmp3;
  169861. tmp11 = tmp1 + tmp2;
  169862. tmp12 = tmp1 - tmp2;
  169863. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  169864. dataptr[4] = tmp10 - tmp11;
  169865. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169866. dataptr[2] = tmp13 + z1; /* phase 5 */
  169867. dataptr[6] = tmp13 - z1;
  169868. /* Odd part */
  169869. tmp10 = tmp4 + tmp5; /* phase 2 */
  169870. tmp11 = tmp5 + tmp6;
  169871. tmp12 = tmp6 + tmp7;
  169872. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169873. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169874. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169875. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169876. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169877. z11 = tmp7 + z3; /* phase 5 */
  169878. z13 = tmp7 - z3;
  169879. dataptr[5] = z13 + z2; /* phase 6 */
  169880. dataptr[3] = z13 - z2;
  169881. dataptr[1] = z11 + z4;
  169882. dataptr[7] = z11 - z4;
  169883. dataptr += DCTSIZE; /* advance pointer to next row */
  169884. }
  169885. /* Pass 2: process columns. */
  169886. dataptr = data;
  169887. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  169888. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  169889. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  169890. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  169891. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  169892. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  169893. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  169894. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  169895. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  169896. /* Even part */
  169897. tmp10 = tmp0 + tmp3; /* phase 2 */
  169898. tmp13 = tmp0 - tmp3;
  169899. tmp11 = tmp1 + tmp2;
  169900. tmp12 = tmp1 - tmp2;
  169901. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  169902. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  169903. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  169904. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  169905. dataptr[DCTSIZE*6] = tmp13 - z1;
  169906. /* Odd part */
  169907. tmp10 = tmp4 + tmp5; /* phase 2 */
  169908. tmp11 = tmp5 + tmp6;
  169909. tmp12 = tmp6 + tmp7;
  169910. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  169911. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  169912. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  169913. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  169914. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  169915. z11 = tmp7 + z3; /* phase 5 */
  169916. z13 = tmp7 - z3;
  169917. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  169918. dataptr[DCTSIZE*3] = z13 - z2;
  169919. dataptr[DCTSIZE*1] = z11 + z4;
  169920. dataptr[DCTSIZE*7] = z11 - z4;
  169921. dataptr++; /* advance pointer to next column */
  169922. }
  169923. }
  169924. #endif /* DCT_FLOAT_SUPPORTED */
  169925. /********* End of inlined file: jfdctflt.c *********/
  169926. /********* Start of inlined file: jfdctint.c *********/
  169927. #define JPEG_INTERNALS
  169928. #ifdef DCT_ISLOW_SUPPORTED
  169929. /*
  169930. * This module is specialized to the case DCTSIZE = 8.
  169931. */
  169932. #if DCTSIZE != 8
  169933. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  169934. #endif
  169935. /*
  169936. * The poop on this scaling stuff is as follows:
  169937. *
  169938. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  169939. * larger than the true DCT outputs. The final outputs are therefore
  169940. * a factor of N larger than desired; since N=8 this can be cured by
  169941. * a simple right shift at the end of the algorithm. The advantage of
  169942. * this arrangement is that we save two multiplications per 1-D DCT,
  169943. * because the y0 and y4 outputs need not be divided by sqrt(N).
  169944. * In the IJG code, this factor of 8 is removed by the quantization step
  169945. * (in jcdctmgr.c), NOT in this module.
  169946. *
  169947. * We have to do addition and subtraction of the integer inputs, which
  169948. * is no problem, and multiplication by fractional constants, which is
  169949. * a problem to do in integer arithmetic. We multiply all the constants
  169950. * by CONST_SCALE and convert them to integer constants (thus retaining
  169951. * CONST_BITS bits of precision in the constants). After doing a
  169952. * multiplication we have to divide the product by CONST_SCALE, with proper
  169953. * rounding, to produce the correct output. This division can be done
  169954. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  169955. * as long as possible so that partial sums can be added together with
  169956. * full fractional precision.
  169957. *
  169958. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  169959. * they are represented to better-than-integral precision. These outputs
  169960. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  169961. * with the recommended scaling. (For 12-bit sample data, the intermediate
  169962. * array is INT32 anyway.)
  169963. *
  169964. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  169965. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  169966. * shows that the values given below are the most effective.
  169967. */
  169968. #if BITS_IN_JSAMPLE == 8
  169969. #define CONST_BITS 13
  169970. #define PASS1_BITS 2
  169971. #else
  169972. #define CONST_BITS 13
  169973. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  169974. #endif
  169975. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  169976. * causing a lot of useless floating-point operations at run time.
  169977. * To get around this we use the following pre-calculated constants.
  169978. * If you change CONST_BITS you may want to add appropriate values.
  169979. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  169980. */
  169981. #if CONST_BITS == 13
  169982. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  169983. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  169984. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  169985. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  169986. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  169987. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  169988. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  169989. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  169990. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  169991. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  169992. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  169993. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  169994. #else
  169995. #define FIX_0_298631336 FIX(0.298631336)
  169996. #define FIX_0_390180644 FIX(0.390180644)
  169997. #define FIX_0_541196100 FIX(0.541196100)
  169998. #define FIX_0_765366865 FIX(0.765366865)
  169999. #define FIX_0_899976223 FIX(0.899976223)
  170000. #define FIX_1_175875602 FIX(1.175875602)
  170001. #define FIX_1_501321110 FIX(1.501321110)
  170002. #define FIX_1_847759065 FIX(1.847759065)
  170003. #define FIX_1_961570560 FIX(1.961570560)
  170004. #define FIX_2_053119869 FIX(2.053119869)
  170005. #define FIX_2_562915447 FIX(2.562915447)
  170006. #define FIX_3_072711026 FIX(3.072711026)
  170007. #endif
  170008. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170009. * For 8-bit samples with the recommended scaling, all the variable
  170010. * and constant values involved are no more than 16 bits wide, so a
  170011. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170012. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170013. */
  170014. #if BITS_IN_JSAMPLE == 8
  170015. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170016. #else
  170017. #define MULTIPLY(var,const) ((var) * (const))
  170018. #endif
  170019. /*
  170020. * Perform the forward DCT on one block of samples.
  170021. */
  170022. GLOBAL(void)
  170023. jpeg_fdct_islow (DCTELEM * data)
  170024. {
  170025. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170026. INT32 tmp10, tmp11, tmp12, tmp13;
  170027. INT32 z1, z2, z3, z4, z5;
  170028. DCTELEM *dataptr;
  170029. int ctr;
  170030. SHIFT_TEMPS
  170031. /* Pass 1: process rows. */
  170032. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  170033. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170034. dataptr = data;
  170035. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170036. tmp0 = dataptr[0] + dataptr[7];
  170037. tmp7 = dataptr[0] - dataptr[7];
  170038. tmp1 = dataptr[1] + dataptr[6];
  170039. tmp6 = dataptr[1] - dataptr[6];
  170040. tmp2 = dataptr[2] + dataptr[5];
  170041. tmp5 = dataptr[2] - dataptr[5];
  170042. tmp3 = dataptr[3] + dataptr[4];
  170043. tmp4 = dataptr[3] - dataptr[4];
  170044. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170045. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170046. */
  170047. tmp10 = tmp0 + tmp3;
  170048. tmp13 = tmp0 - tmp3;
  170049. tmp11 = tmp1 + tmp2;
  170050. tmp12 = tmp1 - tmp2;
  170051. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  170052. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  170053. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170054. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170055. CONST_BITS-PASS1_BITS);
  170056. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170057. CONST_BITS-PASS1_BITS);
  170058. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170059. * cK represents cos(K*pi/16).
  170060. * i0..i3 in the paper are tmp4..tmp7 here.
  170061. */
  170062. z1 = tmp4 + tmp7;
  170063. z2 = tmp5 + tmp6;
  170064. z3 = tmp4 + tmp6;
  170065. z4 = tmp5 + tmp7;
  170066. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170067. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170068. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170069. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170070. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170071. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170072. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170073. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170074. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170075. z3 += z5;
  170076. z4 += z5;
  170077. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  170078. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  170079. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  170080. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  170081. dataptr += DCTSIZE; /* advance pointer to next row */
  170082. }
  170083. /* Pass 2: process columns.
  170084. * We remove the PASS1_BITS scaling, but leave the results scaled up
  170085. * by an overall factor of 8.
  170086. */
  170087. dataptr = data;
  170088. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170089. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170090. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170091. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170092. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170093. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170094. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170095. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170096. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170097. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  170098. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  170099. */
  170100. tmp10 = tmp0 + tmp3;
  170101. tmp13 = tmp0 - tmp3;
  170102. tmp11 = tmp1 + tmp2;
  170103. tmp12 = tmp1 - tmp2;
  170104. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  170105. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  170106. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  170107. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  170108. CONST_BITS+PASS1_BITS);
  170109. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  170110. CONST_BITS+PASS1_BITS);
  170111. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  170112. * cK represents cos(K*pi/16).
  170113. * i0..i3 in the paper are tmp4..tmp7 here.
  170114. */
  170115. z1 = tmp4 + tmp7;
  170116. z2 = tmp5 + tmp6;
  170117. z3 = tmp4 + tmp6;
  170118. z4 = tmp5 + tmp7;
  170119. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170120. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170121. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170122. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170123. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170124. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170125. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170126. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170127. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170128. z3 += z5;
  170129. z4 += z5;
  170130. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  170131. CONST_BITS+PASS1_BITS);
  170132. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  170133. CONST_BITS+PASS1_BITS);
  170134. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  170135. CONST_BITS+PASS1_BITS);
  170136. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  170137. CONST_BITS+PASS1_BITS);
  170138. dataptr++; /* advance pointer to next column */
  170139. }
  170140. }
  170141. #endif /* DCT_ISLOW_SUPPORTED */
  170142. /********* End of inlined file: jfdctint.c *********/
  170143. #undef CONST_BITS
  170144. #undef MULTIPLY
  170145. #undef FIX_0_541196100
  170146. /********* Start of inlined file: jfdctfst.c *********/
  170147. #define JPEG_INTERNALS
  170148. #ifdef DCT_IFAST_SUPPORTED
  170149. /*
  170150. * This module is specialized to the case DCTSIZE = 8.
  170151. */
  170152. #if DCTSIZE != 8
  170153. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170154. #endif
  170155. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170156. * see jfdctint.c for more details. However, we choose to descale
  170157. * (right shift) multiplication products as soon as they are formed,
  170158. * rather than carrying additional fractional bits into subsequent additions.
  170159. * This compromises accuracy slightly, but it lets us save a few shifts.
  170160. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170161. * everywhere except in the multiplications proper; this saves a good deal
  170162. * of work on 16-bit-int machines.
  170163. *
  170164. * Again to save a few shifts, the intermediate results between pass 1 and
  170165. * pass 2 are not upscaled, but are represented only to integral precision.
  170166. *
  170167. * A final compromise is to represent the multiplicative constants to only
  170168. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170169. * machines, and may also reduce the cost of multiplication (since there
  170170. * are fewer one-bits in the constants).
  170171. */
  170172. #define CONST_BITS 8
  170173. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170174. * causing a lot of useless floating-point operations at run time.
  170175. * To get around this we use the following pre-calculated constants.
  170176. * If you change CONST_BITS you may want to add appropriate values.
  170177. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170178. */
  170179. #if CONST_BITS == 8
  170180. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  170181. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  170182. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  170183. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  170184. #else
  170185. #define FIX_0_382683433 FIX(0.382683433)
  170186. #define FIX_0_541196100 FIX(0.541196100)
  170187. #define FIX_0_707106781 FIX(0.707106781)
  170188. #define FIX_1_306562965 FIX(1.306562965)
  170189. #endif
  170190. /* We can gain a little more speed, with a further compromise in accuracy,
  170191. * by omitting the addition in a descaling shift. This yields an incorrectly
  170192. * rounded result half the time...
  170193. */
  170194. #ifndef USE_ACCURATE_ROUNDING
  170195. #undef DESCALE
  170196. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170197. #endif
  170198. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170199. * descale to yield a DCTELEM result.
  170200. */
  170201. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170202. /*
  170203. * Perform the forward DCT on one block of samples.
  170204. */
  170205. GLOBAL(void)
  170206. jpeg_fdct_ifast (DCTELEM * data)
  170207. {
  170208. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170209. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170210. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  170211. DCTELEM *dataptr;
  170212. int ctr;
  170213. SHIFT_TEMPS
  170214. /* Pass 1: process rows. */
  170215. dataptr = data;
  170216. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170217. tmp0 = dataptr[0] + dataptr[7];
  170218. tmp7 = dataptr[0] - dataptr[7];
  170219. tmp1 = dataptr[1] + dataptr[6];
  170220. tmp6 = dataptr[1] - dataptr[6];
  170221. tmp2 = dataptr[2] + dataptr[5];
  170222. tmp5 = dataptr[2] - dataptr[5];
  170223. tmp3 = dataptr[3] + dataptr[4];
  170224. tmp4 = dataptr[3] - dataptr[4];
  170225. /* Even part */
  170226. tmp10 = tmp0 + tmp3; /* phase 2 */
  170227. tmp13 = tmp0 - tmp3;
  170228. tmp11 = tmp1 + tmp2;
  170229. tmp12 = tmp1 - tmp2;
  170230. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  170231. dataptr[4] = tmp10 - tmp11;
  170232. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170233. dataptr[2] = tmp13 + z1; /* phase 5 */
  170234. dataptr[6] = tmp13 - z1;
  170235. /* Odd part */
  170236. tmp10 = tmp4 + tmp5; /* phase 2 */
  170237. tmp11 = tmp5 + tmp6;
  170238. tmp12 = tmp6 + tmp7;
  170239. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170240. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170241. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170242. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170243. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170244. z11 = tmp7 + z3; /* phase 5 */
  170245. z13 = tmp7 - z3;
  170246. dataptr[5] = z13 + z2; /* phase 6 */
  170247. dataptr[3] = z13 - z2;
  170248. dataptr[1] = z11 + z4;
  170249. dataptr[7] = z11 - z4;
  170250. dataptr += DCTSIZE; /* advance pointer to next row */
  170251. }
  170252. /* Pass 2: process columns. */
  170253. dataptr = data;
  170254. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  170255. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  170256. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  170257. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  170258. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  170259. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  170260. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  170261. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  170262. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  170263. /* Even part */
  170264. tmp10 = tmp0 + tmp3; /* phase 2 */
  170265. tmp13 = tmp0 - tmp3;
  170266. tmp11 = tmp1 + tmp2;
  170267. tmp12 = tmp1 - tmp2;
  170268. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  170269. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  170270. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  170271. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  170272. dataptr[DCTSIZE*6] = tmp13 - z1;
  170273. /* Odd part */
  170274. tmp10 = tmp4 + tmp5; /* phase 2 */
  170275. tmp11 = tmp5 + tmp6;
  170276. tmp12 = tmp6 + tmp7;
  170277. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  170278. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  170279. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  170280. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  170281. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  170282. z11 = tmp7 + z3; /* phase 5 */
  170283. z13 = tmp7 - z3;
  170284. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  170285. dataptr[DCTSIZE*3] = z13 - z2;
  170286. dataptr[DCTSIZE*1] = z11 + z4;
  170287. dataptr[DCTSIZE*7] = z11 - z4;
  170288. dataptr++; /* advance pointer to next column */
  170289. }
  170290. }
  170291. #endif /* DCT_IFAST_SUPPORTED */
  170292. /********* End of inlined file: jfdctfst.c *********/
  170293. #undef FIX_0_541196100
  170294. /********* Start of inlined file: jidctflt.c *********/
  170295. #define JPEG_INTERNALS
  170296. #ifdef DCT_FLOAT_SUPPORTED
  170297. /*
  170298. * This module is specialized to the case DCTSIZE = 8.
  170299. */
  170300. #if DCTSIZE != 8
  170301. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170302. #endif
  170303. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170304. * entry; produce a float result.
  170305. */
  170306. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  170307. /*
  170308. * Perform dequantization and inverse DCT on one block of coefficients.
  170309. */
  170310. GLOBAL(void)
  170311. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170312. JCOEFPTR coef_block,
  170313. JSAMPARRAY output_buf, JDIMENSION output_col)
  170314. {
  170315. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170316. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  170317. FAST_FLOAT z5, z10, z11, z12, z13;
  170318. JCOEFPTR inptr;
  170319. FLOAT_MULT_TYPE * quantptr;
  170320. FAST_FLOAT * wsptr;
  170321. JSAMPROW outptr;
  170322. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170323. int ctr;
  170324. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  170325. SHIFT_TEMPS
  170326. /* Pass 1: process columns from input, store into work array. */
  170327. inptr = coef_block;
  170328. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  170329. wsptr = workspace;
  170330. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170331. /* Due to quantization, we will usually find that many of the input
  170332. * coefficients are zero, especially the AC terms. We can exploit this
  170333. * by short-circuiting the IDCT calculation for any column in which all
  170334. * the AC terms are zero. In that case each output is equal to the
  170335. * DC coefficient (with scale factor as needed).
  170336. * With typical images and quantization tables, half or more of the
  170337. * column DCT calculations can be simplified this way.
  170338. */
  170339. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170340. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170341. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170342. inptr[DCTSIZE*7] == 0) {
  170343. /* AC terms all zero */
  170344. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170345. wsptr[DCTSIZE*0] = dcval;
  170346. wsptr[DCTSIZE*1] = dcval;
  170347. wsptr[DCTSIZE*2] = dcval;
  170348. wsptr[DCTSIZE*3] = dcval;
  170349. wsptr[DCTSIZE*4] = dcval;
  170350. wsptr[DCTSIZE*5] = dcval;
  170351. wsptr[DCTSIZE*6] = dcval;
  170352. wsptr[DCTSIZE*7] = dcval;
  170353. inptr++; /* advance pointers to next column */
  170354. quantptr++;
  170355. wsptr++;
  170356. continue;
  170357. }
  170358. /* Even part */
  170359. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170360. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170361. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170362. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170363. tmp10 = tmp0 + tmp2; /* phase 3 */
  170364. tmp11 = tmp0 - tmp2;
  170365. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170366. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  170367. tmp0 = tmp10 + tmp13; /* phase 2 */
  170368. tmp3 = tmp10 - tmp13;
  170369. tmp1 = tmp11 + tmp12;
  170370. tmp2 = tmp11 - tmp12;
  170371. /* Odd part */
  170372. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170373. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170374. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170375. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170376. z13 = tmp6 + tmp5; /* phase 6 */
  170377. z10 = tmp6 - tmp5;
  170378. z11 = tmp4 + tmp7;
  170379. z12 = tmp4 - tmp7;
  170380. tmp7 = z11 + z13; /* phase 5 */
  170381. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  170382. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170383. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170384. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170385. tmp6 = tmp12 - tmp7; /* phase 2 */
  170386. tmp5 = tmp11 - tmp6;
  170387. tmp4 = tmp10 + tmp5;
  170388. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  170389. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  170390. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  170391. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  170392. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  170393. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  170394. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  170395. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  170396. inptr++; /* advance pointers to next column */
  170397. quantptr++;
  170398. wsptr++;
  170399. }
  170400. /* Pass 2: process rows from work array, store into output array. */
  170401. /* Note that we must descale the results by a factor of 8 == 2**3. */
  170402. wsptr = workspace;
  170403. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170404. outptr = output_buf[ctr] + output_col;
  170405. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170406. * However, the column calculation has created many nonzero AC terms, so
  170407. * the simplification applies less often (typically 5% to 10% of the time).
  170408. * And testing floats for zero is relatively expensive, so we don't bother.
  170409. */
  170410. /* Even part */
  170411. tmp10 = wsptr[0] + wsptr[4];
  170412. tmp11 = wsptr[0] - wsptr[4];
  170413. tmp13 = wsptr[2] + wsptr[6];
  170414. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  170415. tmp0 = tmp10 + tmp13;
  170416. tmp3 = tmp10 - tmp13;
  170417. tmp1 = tmp11 + tmp12;
  170418. tmp2 = tmp11 - tmp12;
  170419. /* Odd part */
  170420. z13 = wsptr[5] + wsptr[3];
  170421. z10 = wsptr[5] - wsptr[3];
  170422. z11 = wsptr[1] + wsptr[7];
  170423. z12 = wsptr[1] - wsptr[7];
  170424. tmp7 = z11 + z13;
  170425. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  170426. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  170427. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  170428. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  170429. tmp6 = tmp12 - tmp7;
  170430. tmp5 = tmp11 - tmp6;
  170431. tmp4 = tmp10 + tmp5;
  170432. /* Final output stage: scale down by a factor of 8 and range-limit */
  170433. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  170434. & RANGE_MASK];
  170435. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  170436. & RANGE_MASK];
  170437. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  170438. & RANGE_MASK];
  170439. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  170440. & RANGE_MASK];
  170441. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  170442. & RANGE_MASK];
  170443. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  170444. & RANGE_MASK];
  170445. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  170446. & RANGE_MASK];
  170447. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  170448. & RANGE_MASK];
  170449. wsptr += DCTSIZE; /* advance pointer to next row */
  170450. }
  170451. }
  170452. #endif /* DCT_FLOAT_SUPPORTED */
  170453. /********* End of inlined file: jidctflt.c *********/
  170454. #undef CONST_BITS
  170455. #undef FIX_1_847759065
  170456. #undef MULTIPLY
  170457. #undef DEQUANTIZE
  170458. #undef DESCALE
  170459. /********* Start of inlined file: jidctfst.c *********/
  170460. #define JPEG_INTERNALS
  170461. #ifdef DCT_IFAST_SUPPORTED
  170462. /*
  170463. * This module is specialized to the case DCTSIZE = 8.
  170464. */
  170465. #if DCTSIZE != 8
  170466. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170467. #endif
  170468. /* Scaling decisions are generally the same as in the LL&M algorithm;
  170469. * see jidctint.c for more details. However, we choose to descale
  170470. * (right shift) multiplication products as soon as they are formed,
  170471. * rather than carrying additional fractional bits into subsequent additions.
  170472. * This compromises accuracy slightly, but it lets us save a few shifts.
  170473. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  170474. * everywhere except in the multiplications proper; this saves a good deal
  170475. * of work on 16-bit-int machines.
  170476. *
  170477. * The dequantized coefficients are not integers because the AA&N scaling
  170478. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  170479. * so that the first and second IDCT rounds have the same input scaling.
  170480. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  170481. * avoid a descaling shift; this compromises accuracy rather drastically
  170482. * for small quantization table entries, but it saves a lot of shifts.
  170483. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  170484. * so we use a much larger scaling factor to preserve accuracy.
  170485. *
  170486. * A final compromise is to represent the multiplicative constants to only
  170487. * 8 fractional bits, rather than 13. This saves some shifting work on some
  170488. * machines, and may also reduce the cost of multiplication (since there
  170489. * are fewer one-bits in the constants).
  170490. */
  170491. #if BITS_IN_JSAMPLE == 8
  170492. #define CONST_BITS 8
  170493. #define PASS1_BITS 2
  170494. #else
  170495. #define CONST_BITS 8
  170496. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170497. #endif
  170498. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170499. * causing a lot of useless floating-point operations at run time.
  170500. * To get around this we use the following pre-calculated constants.
  170501. * If you change CONST_BITS you may want to add appropriate values.
  170502. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170503. */
  170504. #if CONST_BITS == 8
  170505. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  170506. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  170507. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  170508. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  170509. #else
  170510. #define FIX_1_082392200 FIX(1.082392200)
  170511. #define FIX_1_414213562 FIX(1.414213562)
  170512. #define FIX_1_847759065 FIX(1.847759065)
  170513. #define FIX_2_613125930 FIX(2.613125930)
  170514. #endif
  170515. /* We can gain a little more speed, with a further compromise in accuracy,
  170516. * by omitting the addition in a descaling shift. This yields an incorrectly
  170517. * rounded result half the time...
  170518. */
  170519. #ifndef USE_ACCURATE_ROUNDING
  170520. #undef DESCALE
  170521. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  170522. #endif
  170523. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  170524. * descale to yield a DCTELEM result.
  170525. */
  170526. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  170527. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170528. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  170529. * multiplication will do. For 12-bit data, the multiplier table is
  170530. * declared INT32, so a 32-bit multiply will be used.
  170531. */
  170532. #if BITS_IN_JSAMPLE == 8
  170533. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  170534. #else
  170535. #define DEQUANTIZE(coef,quantval) \
  170536. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  170537. #endif
  170538. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  170539. * We assume that int right shift is unsigned if INT32 right shift is.
  170540. */
  170541. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  170542. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  170543. #if BITS_IN_JSAMPLE == 8
  170544. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  170545. #else
  170546. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  170547. #endif
  170548. #define IRIGHT_SHIFT(x,shft) \
  170549. ((ishift_temp = (x)) < 0 ? \
  170550. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  170551. (ishift_temp >> (shft)))
  170552. #else
  170553. #define ISHIFT_TEMPS
  170554. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  170555. #endif
  170556. #ifdef USE_ACCURATE_ROUNDING
  170557. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  170558. #else
  170559. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  170560. #endif
  170561. /*
  170562. * Perform dequantization and inverse DCT on one block of coefficients.
  170563. */
  170564. GLOBAL(void)
  170565. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170566. JCOEFPTR coef_block,
  170567. JSAMPARRAY output_buf, JDIMENSION output_col)
  170568. {
  170569. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  170570. DCTELEM tmp10, tmp11, tmp12, tmp13;
  170571. DCTELEM z5, z10, z11, z12, z13;
  170572. JCOEFPTR inptr;
  170573. IFAST_MULT_TYPE * quantptr;
  170574. int * wsptr;
  170575. JSAMPROW outptr;
  170576. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170577. int ctr;
  170578. int workspace[DCTSIZE2]; /* buffers data between passes */
  170579. SHIFT_TEMPS /* for DESCALE */
  170580. ISHIFT_TEMPS /* for IDESCALE */
  170581. /* Pass 1: process columns from input, store into work array. */
  170582. inptr = coef_block;
  170583. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  170584. wsptr = workspace;
  170585. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170586. /* Due to quantization, we will usually find that many of the input
  170587. * coefficients are zero, especially the AC terms. We can exploit this
  170588. * by short-circuiting the IDCT calculation for any column in which all
  170589. * the AC terms are zero. In that case each output is equal to the
  170590. * DC coefficient (with scale factor as needed).
  170591. * With typical images and quantization tables, half or more of the
  170592. * column DCT calculations can be simplified this way.
  170593. */
  170594. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170595. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170596. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170597. inptr[DCTSIZE*7] == 0) {
  170598. /* AC terms all zero */
  170599. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170600. wsptr[DCTSIZE*0] = dcval;
  170601. wsptr[DCTSIZE*1] = dcval;
  170602. wsptr[DCTSIZE*2] = dcval;
  170603. wsptr[DCTSIZE*3] = dcval;
  170604. wsptr[DCTSIZE*4] = dcval;
  170605. wsptr[DCTSIZE*5] = dcval;
  170606. wsptr[DCTSIZE*6] = dcval;
  170607. wsptr[DCTSIZE*7] = dcval;
  170608. inptr++; /* advance pointers to next column */
  170609. quantptr++;
  170610. wsptr++;
  170611. continue;
  170612. }
  170613. /* Even part */
  170614. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170615. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170616. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170617. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170618. tmp10 = tmp0 + tmp2; /* phase 3 */
  170619. tmp11 = tmp0 - tmp2;
  170620. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  170621. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  170622. tmp0 = tmp10 + tmp13; /* phase 2 */
  170623. tmp3 = tmp10 - tmp13;
  170624. tmp1 = tmp11 + tmp12;
  170625. tmp2 = tmp11 - tmp12;
  170626. /* Odd part */
  170627. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170628. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170629. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170630. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170631. z13 = tmp6 + tmp5; /* phase 6 */
  170632. z10 = tmp6 - tmp5;
  170633. z11 = tmp4 + tmp7;
  170634. z12 = tmp4 - tmp7;
  170635. tmp7 = z11 + z13; /* phase 5 */
  170636. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170637. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170638. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170639. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170640. tmp6 = tmp12 - tmp7; /* phase 2 */
  170641. tmp5 = tmp11 - tmp6;
  170642. tmp4 = tmp10 + tmp5;
  170643. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  170644. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  170645. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  170646. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  170647. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  170648. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  170649. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  170650. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  170651. inptr++; /* advance pointers to next column */
  170652. quantptr++;
  170653. wsptr++;
  170654. }
  170655. /* Pass 2: process rows from work array, store into output array. */
  170656. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170657. /* and also undo the PASS1_BITS scaling. */
  170658. wsptr = workspace;
  170659. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170660. outptr = output_buf[ctr] + output_col;
  170661. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170662. * However, the column calculation has created many nonzero AC terms, so
  170663. * the simplification applies less often (typically 5% to 10% of the time).
  170664. * On machines with very fast multiplication, it's possible that the
  170665. * test takes more time than it's worth. In that case this section
  170666. * may be commented out.
  170667. */
  170668. #ifndef NO_ZERO_ROW_TEST
  170669. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170670. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170671. /* AC terms all zero */
  170672. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  170673. & RANGE_MASK];
  170674. outptr[0] = dcval;
  170675. outptr[1] = dcval;
  170676. outptr[2] = dcval;
  170677. outptr[3] = dcval;
  170678. outptr[4] = dcval;
  170679. outptr[5] = dcval;
  170680. outptr[6] = dcval;
  170681. outptr[7] = dcval;
  170682. wsptr += DCTSIZE; /* advance pointer to next row */
  170683. continue;
  170684. }
  170685. #endif
  170686. /* Even part */
  170687. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  170688. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  170689. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  170690. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  170691. - tmp13;
  170692. tmp0 = tmp10 + tmp13;
  170693. tmp3 = tmp10 - tmp13;
  170694. tmp1 = tmp11 + tmp12;
  170695. tmp2 = tmp11 - tmp12;
  170696. /* Odd part */
  170697. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  170698. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  170699. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  170700. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  170701. tmp7 = z11 + z13; /* phase 5 */
  170702. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  170703. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  170704. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  170705. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  170706. tmp6 = tmp12 - tmp7; /* phase 2 */
  170707. tmp5 = tmp11 - tmp6;
  170708. tmp4 = tmp10 + tmp5;
  170709. /* Final output stage: scale down by a factor of 8 and range-limit */
  170710. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  170711. & RANGE_MASK];
  170712. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  170713. & RANGE_MASK];
  170714. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  170715. & RANGE_MASK];
  170716. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  170717. & RANGE_MASK];
  170718. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  170719. & RANGE_MASK];
  170720. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  170721. & RANGE_MASK];
  170722. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  170723. & RANGE_MASK];
  170724. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  170725. & RANGE_MASK];
  170726. wsptr += DCTSIZE; /* advance pointer to next row */
  170727. }
  170728. }
  170729. #endif /* DCT_IFAST_SUPPORTED */
  170730. /********* End of inlined file: jidctfst.c *********/
  170731. #undef CONST_BITS
  170732. #undef FIX_1_847759065
  170733. #undef MULTIPLY
  170734. #undef DEQUANTIZE
  170735. /********* Start of inlined file: jidctint.c *********/
  170736. #define JPEG_INTERNALS
  170737. #ifdef DCT_ISLOW_SUPPORTED
  170738. /*
  170739. * This module is specialized to the case DCTSIZE = 8.
  170740. */
  170741. #if DCTSIZE != 8
  170742. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  170743. #endif
  170744. /*
  170745. * The poop on this scaling stuff is as follows:
  170746. *
  170747. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  170748. * larger than the true IDCT outputs. The final outputs are therefore
  170749. * a factor of N larger than desired; since N=8 this can be cured by
  170750. * a simple right shift at the end of the algorithm. The advantage of
  170751. * this arrangement is that we save two multiplications per 1-D IDCT,
  170752. * because the y0 and y4 inputs need not be divided by sqrt(N).
  170753. *
  170754. * We have to do addition and subtraction of the integer inputs, which
  170755. * is no problem, and multiplication by fractional constants, which is
  170756. * a problem to do in integer arithmetic. We multiply all the constants
  170757. * by CONST_SCALE and convert them to integer constants (thus retaining
  170758. * CONST_BITS bits of precision in the constants). After doing a
  170759. * multiplication we have to divide the product by CONST_SCALE, with proper
  170760. * rounding, to produce the correct output. This division can be done
  170761. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  170762. * as long as possible so that partial sums can be added together with
  170763. * full fractional precision.
  170764. *
  170765. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  170766. * they are represented to better-than-integral precision. These outputs
  170767. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  170768. * with the recommended scaling. (To scale up 12-bit sample data further, an
  170769. * intermediate INT32 array would be needed.)
  170770. *
  170771. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  170772. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  170773. * shows that the values given below are the most effective.
  170774. */
  170775. #if BITS_IN_JSAMPLE == 8
  170776. #define CONST_BITS 13
  170777. #define PASS1_BITS 2
  170778. #else
  170779. #define CONST_BITS 13
  170780. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  170781. #endif
  170782. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  170783. * causing a lot of useless floating-point operations at run time.
  170784. * To get around this we use the following pre-calculated constants.
  170785. * If you change CONST_BITS you may want to add appropriate values.
  170786. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  170787. */
  170788. #if CONST_BITS == 13
  170789. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  170790. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  170791. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  170792. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  170793. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  170794. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  170795. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  170796. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  170797. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  170798. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  170799. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  170800. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  170801. #else
  170802. #define FIX_0_298631336 FIX(0.298631336)
  170803. #define FIX_0_390180644 FIX(0.390180644)
  170804. #define FIX_0_541196100 FIX(0.541196100)
  170805. #define FIX_0_765366865 FIX(0.765366865)
  170806. #define FIX_0_899976223 FIX(0.899976223)
  170807. #define FIX_1_175875602 FIX(1.175875602)
  170808. #define FIX_1_501321110 FIX(1.501321110)
  170809. #define FIX_1_847759065 FIX(1.847759065)
  170810. #define FIX_1_961570560 FIX(1.961570560)
  170811. #define FIX_2_053119869 FIX(2.053119869)
  170812. #define FIX_2_562915447 FIX(2.562915447)
  170813. #define FIX_3_072711026 FIX(3.072711026)
  170814. #endif
  170815. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  170816. * For 8-bit samples with the recommended scaling, all the variable
  170817. * and constant values involved are no more than 16 bits wide, so a
  170818. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  170819. * For 12-bit samples, a full 32-bit multiplication will be needed.
  170820. */
  170821. #if BITS_IN_JSAMPLE == 8
  170822. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  170823. #else
  170824. #define MULTIPLY(var,const) ((var) * (const))
  170825. #endif
  170826. /* Dequantize a coefficient by multiplying it by the multiplier-table
  170827. * entry; produce an int result. In this module, both inputs and result
  170828. * are 16 bits or less, so either int or short multiply will work.
  170829. */
  170830. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  170831. /*
  170832. * Perform dequantization and inverse DCT on one block of coefficients.
  170833. */
  170834. GLOBAL(void)
  170835. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  170836. JCOEFPTR coef_block,
  170837. JSAMPARRAY output_buf, JDIMENSION output_col)
  170838. {
  170839. INT32 tmp0, tmp1, tmp2, tmp3;
  170840. INT32 tmp10, tmp11, tmp12, tmp13;
  170841. INT32 z1, z2, z3, z4, z5;
  170842. JCOEFPTR inptr;
  170843. ISLOW_MULT_TYPE * quantptr;
  170844. int * wsptr;
  170845. JSAMPROW outptr;
  170846. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  170847. int ctr;
  170848. int workspace[DCTSIZE2]; /* buffers data between passes */
  170849. SHIFT_TEMPS
  170850. /* Pass 1: process columns from input, store into work array. */
  170851. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  170852. /* furthermore, we scale the results by 2**PASS1_BITS. */
  170853. inptr = coef_block;
  170854. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170855. wsptr = workspace;
  170856. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  170857. /* Due to quantization, we will usually find that many of the input
  170858. * coefficients are zero, especially the AC terms. We can exploit this
  170859. * by short-circuiting the IDCT calculation for any column in which all
  170860. * the AC terms are zero. In that case each output is equal to the
  170861. * DC coefficient (with scale factor as needed).
  170862. * With typical images and quantization tables, half or more of the
  170863. * column DCT calculations can be simplified this way.
  170864. */
  170865. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  170866. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  170867. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  170868. inptr[DCTSIZE*7] == 0) {
  170869. /* AC terms all zero */
  170870. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  170871. wsptr[DCTSIZE*0] = dcval;
  170872. wsptr[DCTSIZE*1] = dcval;
  170873. wsptr[DCTSIZE*2] = dcval;
  170874. wsptr[DCTSIZE*3] = dcval;
  170875. wsptr[DCTSIZE*4] = dcval;
  170876. wsptr[DCTSIZE*5] = dcval;
  170877. wsptr[DCTSIZE*6] = dcval;
  170878. wsptr[DCTSIZE*7] = dcval;
  170879. inptr++; /* advance pointers to next column */
  170880. quantptr++;
  170881. wsptr++;
  170882. continue;
  170883. }
  170884. /* Even part: reverse the even part of the forward DCT. */
  170885. /* The rotator is sqrt(2)*c(-6). */
  170886. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  170887. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  170888. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170889. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170890. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170891. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  170892. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  170893. tmp0 = (z2 + z3) << CONST_BITS;
  170894. tmp1 = (z2 - z3) << CONST_BITS;
  170895. tmp10 = tmp0 + tmp3;
  170896. tmp13 = tmp0 - tmp3;
  170897. tmp11 = tmp1 + tmp2;
  170898. tmp12 = tmp1 - tmp2;
  170899. /* Odd part per figure 8; the matrix is unitary and hence its
  170900. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170901. */
  170902. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  170903. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  170904. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  170905. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  170906. z1 = tmp0 + tmp3;
  170907. z2 = tmp1 + tmp2;
  170908. z3 = tmp0 + tmp2;
  170909. z4 = tmp1 + tmp3;
  170910. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170911. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170912. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170913. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170914. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170915. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170916. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  170917. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  170918. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  170919. z3 += z5;
  170920. z4 += z5;
  170921. tmp0 += z1 + z3;
  170922. tmp1 += z2 + z4;
  170923. tmp2 += z2 + z3;
  170924. tmp3 += z1 + z4;
  170925. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  170926. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  170927. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  170928. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  170929. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  170930. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  170931. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  170932. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  170933. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  170934. inptr++; /* advance pointers to next column */
  170935. quantptr++;
  170936. wsptr++;
  170937. }
  170938. /* Pass 2: process rows from work array, store into output array. */
  170939. /* Note that we must descale the results by a factor of 8 == 2**3, */
  170940. /* and also undo the PASS1_BITS scaling. */
  170941. wsptr = workspace;
  170942. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  170943. outptr = output_buf[ctr] + output_col;
  170944. /* Rows of zeroes can be exploited in the same way as we did with columns.
  170945. * However, the column calculation has created many nonzero AC terms, so
  170946. * the simplification applies less often (typically 5% to 10% of the time).
  170947. * On machines with very fast multiplication, it's possible that the
  170948. * test takes more time than it's worth. In that case this section
  170949. * may be commented out.
  170950. */
  170951. #ifndef NO_ZERO_ROW_TEST
  170952. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  170953. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  170954. /* AC terms all zero */
  170955. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  170956. & RANGE_MASK];
  170957. outptr[0] = dcval;
  170958. outptr[1] = dcval;
  170959. outptr[2] = dcval;
  170960. outptr[3] = dcval;
  170961. outptr[4] = dcval;
  170962. outptr[5] = dcval;
  170963. outptr[6] = dcval;
  170964. outptr[7] = dcval;
  170965. wsptr += DCTSIZE; /* advance pointer to next row */
  170966. continue;
  170967. }
  170968. #endif
  170969. /* Even part: reverse the even part of the forward DCT. */
  170970. /* The rotator is sqrt(2)*c(-6). */
  170971. z2 = (INT32) wsptr[2];
  170972. z3 = (INT32) wsptr[6];
  170973. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  170974. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  170975. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  170976. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  170977. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  170978. tmp10 = tmp0 + tmp3;
  170979. tmp13 = tmp0 - tmp3;
  170980. tmp11 = tmp1 + tmp2;
  170981. tmp12 = tmp1 - tmp2;
  170982. /* Odd part per figure 8; the matrix is unitary and hence its
  170983. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  170984. */
  170985. tmp0 = (INT32) wsptr[7];
  170986. tmp1 = (INT32) wsptr[5];
  170987. tmp2 = (INT32) wsptr[3];
  170988. tmp3 = (INT32) wsptr[1];
  170989. z1 = tmp0 + tmp3;
  170990. z2 = tmp1 + tmp2;
  170991. z3 = tmp0 + tmp2;
  170992. z4 = tmp1 + tmp3;
  170993. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  170994. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  170995. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  170996. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  170997. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  170998. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  170999. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  171000. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  171001. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  171002. z3 += z5;
  171003. z4 += z5;
  171004. tmp0 += z1 + z3;
  171005. tmp1 += z2 + z4;
  171006. tmp2 += z2 + z3;
  171007. tmp3 += z1 + z4;
  171008. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  171009. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  171010. CONST_BITS+PASS1_BITS+3)
  171011. & RANGE_MASK];
  171012. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  171013. CONST_BITS+PASS1_BITS+3)
  171014. & RANGE_MASK];
  171015. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  171016. CONST_BITS+PASS1_BITS+3)
  171017. & RANGE_MASK];
  171018. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  171019. CONST_BITS+PASS1_BITS+3)
  171020. & RANGE_MASK];
  171021. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  171022. CONST_BITS+PASS1_BITS+3)
  171023. & RANGE_MASK];
  171024. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  171025. CONST_BITS+PASS1_BITS+3)
  171026. & RANGE_MASK];
  171027. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  171028. CONST_BITS+PASS1_BITS+3)
  171029. & RANGE_MASK];
  171030. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  171031. CONST_BITS+PASS1_BITS+3)
  171032. & RANGE_MASK];
  171033. wsptr += DCTSIZE; /* advance pointer to next row */
  171034. }
  171035. }
  171036. #endif /* DCT_ISLOW_SUPPORTED */
  171037. /********* End of inlined file: jidctint.c *********/
  171038. /********* Start of inlined file: jidctred.c *********/
  171039. #define JPEG_INTERNALS
  171040. #ifdef IDCT_SCALING_SUPPORTED
  171041. /*
  171042. * This module is specialized to the case DCTSIZE = 8.
  171043. */
  171044. #if DCTSIZE != 8
  171045. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  171046. #endif
  171047. /* Scaling is the same as in jidctint.c. */
  171048. #if BITS_IN_JSAMPLE == 8
  171049. #define CONST_BITS 13
  171050. #define PASS1_BITS 2
  171051. #else
  171052. #define CONST_BITS 13
  171053. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  171054. #endif
  171055. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  171056. * causing a lot of useless floating-point operations at run time.
  171057. * To get around this we use the following pre-calculated constants.
  171058. * If you change CONST_BITS you may want to add appropriate values.
  171059. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  171060. */
  171061. #if CONST_BITS == 13
  171062. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  171063. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  171064. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  171065. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  171066. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  171067. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  171068. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  171069. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  171070. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  171071. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  171072. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  171073. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  171074. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  171075. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  171076. #else
  171077. #define FIX_0_211164243 FIX(0.211164243)
  171078. #define FIX_0_509795579 FIX(0.509795579)
  171079. #define FIX_0_601344887 FIX(0.601344887)
  171080. #define FIX_0_720959822 FIX(0.720959822)
  171081. #define FIX_0_765366865 FIX(0.765366865)
  171082. #define FIX_0_850430095 FIX(0.850430095)
  171083. #define FIX_0_899976223 FIX(0.899976223)
  171084. #define FIX_1_061594337 FIX(1.061594337)
  171085. #define FIX_1_272758580 FIX(1.272758580)
  171086. #define FIX_1_451774981 FIX(1.451774981)
  171087. #define FIX_1_847759065 FIX(1.847759065)
  171088. #define FIX_2_172734803 FIX(2.172734803)
  171089. #define FIX_2_562915447 FIX(2.562915447)
  171090. #define FIX_3_624509785 FIX(3.624509785)
  171091. #endif
  171092. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  171093. * For 8-bit samples with the recommended scaling, all the variable
  171094. * and constant values involved are no more than 16 bits wide, so a
  171095. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  171096. * For 12-bit samples, a full 32-bit multiplication will be needed.
  171097. */
  171098. #if BITS_IN_JSAMPLE == 8
  171099. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  171100. #else
  171101. #define MULTIPLY(var,const) ((var) * (const))
  171102. #endif
  171103. /* Dequantize a coefficient by multiplying it by the multiplier-table
  171104. * entry; produce an int result. In this module, both inputs and result
  171105. * are 16 bits or less, so either int or short multiply will work.
  171106. */
  171107. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  171108. /*
  171109. * Perform dequantization and inverse DCT on one block of coefficients,
  171110. * producing a reduced-size 4x4 output block.
  171111. */
  171112. GLOBAL(void)
  171113. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171114. JCOEFPTR coef_block,
  171115. JSAMPARRAY output_buf, JDIMENSION output_col)
  171116. {
  171117. INT32 tmp0, tmp2, tmp10, tmp12;
  171118. INT32 z1, z2, z3, z4;
  171119. JCOEFPTR inptr;
  171120. ISLOW_MULT_TYPE * quantptr;
  171121. int * wsptr;
  171122. JSAMPROW outptr;
  171123. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171124. int ctr;
  171125. int workspace[DCTSIZE*4]; /* buffers data between passes */
  171126. SHIFT_TEMPS
  171127. /* Pass 1: process columns from input, store into work array. */
  171128. inptr = coef_block;
  171129. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171130. wsptr = workspace;
  171131. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171132. /* Don't bother to process column 4, because second pass won't use it */
  171133. if (ctr == DCTSIZE-4)
  171134. continue;
  171135. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  171136. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  171137. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  171138. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  171139. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171140. wsptr[DCTSIZE*0] = dcval;
  171141. wsptr[DCTSIZE*1] = dcval;
  171142. wsptr[DCTSIZE*2] = dcval;
  171143. wsptr[DCTSIZE*3] = dcval;
  171144. continue;
  171145. }
  171146. /* Even part */
  171147. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171148. tmp0 <<= (CONST_BITS+1);
  171149. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  171150. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  171151. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  171152. tmp10 = tmp0 + tmp2;
  171153. tmp12 = tmp0 - tmp2;
  171154. /* Odd part */
  171155. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171156. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171157. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171158. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171159. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171160. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171161. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171162. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171163. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171164. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171165. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171166. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171167. /* Final output stage */
  171168. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  171169. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  171170. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  171171. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  171172. }
  171173. /* Pass 2: process 4 rows from work array, store into output array. */
  171174. wsptr = workspace;
  171175. for (ctr = 0; ctr < 4; ctr++) {
  171176. outptr = output_buf[ctr] + output_col;
  171177. /* It's not clear whether a zero row test is worthwhile here ... */
  171178. #ifndef NO_ZERO_ROW_TEST
  171179. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  171180. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  171181. /* AC terms all zero */
  171182. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171183. & RANGE_MASK];
  171184. outptr[0] = dcval;
  171185. outptr[1] = dcval;
  171186. outptr[2] = dcval;
  171187. outptr[3] = dcval;
  171188. wsptr += DCTSIZE; /* advance pointer to next row */
  171189. continue;
  171190. }
  171191. #endif
  171192. /* Even part */
  171193. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  171194. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  171195. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  171196. tmp10 = tmp0 + tmp2;
  171197. tmp12 = tmp0 - tmp2;
  171198. /* Odd part */
  171199. z1 = (INT32) wsptr[7];
  171200. z2 = (INT32) wsptr[5];
  171201. z3 = (INT32) wsptr[3];
  171202. z4 = (INT32) wsptr[1];
  171203. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  171204. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  171205. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  171206. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  171207. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  171208. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  171209. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  171210. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  171211. /* Final output stage */
  171212. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  171213. CONST_BITS+PASS1_BITS+3+1)
  171214. & RANGE_MASK];
  171215. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  171216. CONST_BITS+PASS1_BITS+3+1)
  171217. & RANGE_MASK];
  171218. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  171219. CONST_BITS+PASS1_BITS+3+1)
  171220. & RANGE_MASK];
  171221. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  171222. CONST_BITS+PASS1_BITS+3+1)
  171223. & RANGE_MASK];
  171224. wsptr += DCTSIZE; /* advance pointer to next row */
  171225. }
  171226. }
  171227. /*
  171228. * Perform dequantization and inverse DCT on one block of coefficients,
  171229. * producing a reduced-size 2x2 output block.
  171230. */
  171231. GLOBAL(void)
  171232. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171233. JCOEFPTR coef_block,
  171234. JSAMPARRAY output_buf, JDIMENSION output_col)
  171235. {
  171236. INT32 tmp0, tmp10, z1;
  171237. JCOEFPTR inptr;
  171238. ISLOW_MULT_TYPE * quantptr;
  171239. int * wsptr;
  171240. JSAMPROW outptr;
  171241. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171242. int ctr;
  171243. int workspace[DCTSIZE*2]; /* buffers data between passes */
  171244. SHIFT_TEMPS
  171245. /* Pass 1: process columns from input, store into work array. */
  171246. inptr = coef_block;
  171247. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171248. wsptr = workspace;
  171249. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  171250. /* Don't bother to process columns 2,4,6 */
  171251. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  171252. continue;
  171253. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  171254. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  171255. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  171256. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  171257. wsptr[DCTSIZE*0] = dcval;
  171258. wsptr[DCTSIZE*1] = dcval;
  171259. continue;
  171260. }
  171261. /* Even part */
  171262. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  171263. tmp10 = z1 << (CONST_BITS+2);
  171264. /* Odd part */
  171265. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  171266. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  171267. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  171268. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  171269. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  171270. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  171271. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  171272. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171273. /* Final output stage */
  171274. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  171275. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  171276. }
  171277. /* Pass 2: process 2 rows from work array, store into output array. */
  171278. wsptr = workspace;
  171279. for (ctr = 0; ctr < 2; ctr++) {
  171280. outptr = output_buf[ctr] + output_col;
  171281. /* It's not clear whether a zero row test is worthwhile here ... */
  171282. #ifndef NO_ZERO_ROW_TEST
  171283. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  171284. /* AC terms all zero */
  171285. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  171286. & RANGE_MASK];
  171287. outptr[0] = dcval;
  171288. outptr[1] = dcval;
  171289. wsptr += DCTSIZE; /* advance pointer to next row */
  171290. continue;
  171291. }
  171292. #endif
  171293. /* Even part */
  171294. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  171295. /* Odd part */
  171296. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  171297. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  171298. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  171299. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  171300. /* Final output stage */
  171301. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  171302. CONST_BITS+PASS1_BITS+3+2)
  171303. & RANGE_MASK];
  171304. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  171305. CONST_BITS+PASS1_BITS+3+2)
  171306. & RANGE_MASK];
  171307. wsptr += DCTSIZE; /* advance pointer to next row */
  171308. }
  171309. }
  171310. /*
  171311. * Perform dequantization and inverse DCT on one block of coefficients,
  171312. * producing a reduced-size 1x1 output block.
  171313. */
  171314. GLOBAL(void)
  171315. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  171316. JCOEFPTR coef_block,
  171317. JSAMPARRAY output_buf, JDIMENSION output_col)
  171318. {
  171319. int dcval;
  171320. ISLOW_MULT_TYPE * quantptr;
  171321. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  171322. SHIFT_TEMPS
  171323. /* We hardly need an inverse DCT routine for this: just take the
  171324. * average pixel value, which is one-eighth of the DC coefficient.
  171325. */
  171326. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  171327. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  171328. dcval = (int) DESCALE((INT32) dcval, 3);
  171329. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  171330. }
  171331. #endif /* IDCT_SCALING_SUPPORTED */
  171332. /********* End of inlined file: jidctred.c *********/
  171333. /********* Start of inlined file: jmemmgr.c *********/
  171334. #define JPEG_INTERNALS
  171335. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  171336. /********* Start of inlined file: jmemsys.h *********/
  171337. #ifndef __jmemsys_h__
  171338. #define __jmemsys_h__
  171339. /* Short forms of external names for systems with brain-damaged linkers. */
  171340. #ifdef NEED_SHORT_EXTERNAL_NAMES
  171341. #define jpeg_get_small jGetSmall
  171342. #define jpeg_free_small jFreeSmall
  171343. #define jpeg_get_large jGetLarge
  171344. #define jpeg_free_large jFreeLarge
  171345. #define jpeg_mem_available jMemAvail
  171346. #define jpeg_open_backing_store jOpenBackStore
  171347. #define jpeg_mem_init jMemInit
  171348. #define jpeg_mem_term jMemTerm
  171349. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  171350. /*
  171351. * These two functions are used to allocate and release small chunks of
  171352. * memory. (Typically the total amount requested through jpeg_get_small is
  171353. * no more than 20K or so; this will be requested in chunks of a few K each.)
  171354. * Behavior should be the same as for the standard library functions malloc
  171355. * and free; in particular, jpeg_get_small must return NULL on failure.
  171356. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  171357. * size of the object being freed, just in case it's needed.
  171358. * On an 80x86 machine using small-data memory model, these manage near heap.
  171359. */
  171360. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  171361. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  171362. size_t sizeofobject));
  171363. /*
  171364. * These two functions are used to allocate and release large chunks of
  171365. * memory (up to the total free space designated by jpeg_mem_available).
  171366. * The interface is the same as above, except that on an 80x86 machine,
  171367. * far pointers are used. On most other machines these are identical to
  171368. * the jpeg_get/free_small routines; but we keep them separate anyway,
  171369. * in case a different allocation strategy is desirable for large chunks.
  171370. */
  171371. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  171372. size_t sizeofobject));
  171373. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  171374. size_t sizeofobject));
  171375. /*
  171376. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  171377. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  171378. * matter, but that case should never come into play). This macro is needed
  171379. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  171380. * On those machines, we expect that jconfig.h will provide a proper value.
  171381. * On machines with 32-bit flat address spaces, any large constant may be used.
  171382. *
  171383. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  171384. * size_t and will be a multiple of sizeof(align_type).
  171385. */
  171386. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  171387. #define MAX_ALLOC_CHUNK 1000000000L
  171388. #endif
  171389. /*
  171390. * This routine computes the total space still available for allocation by
  171391. * jpeg_get_large. If more space than this is needed, backing store will be
  171392. * used. NOTE: any memory already allocated must not be counted.
  171393. *
  171394. * There is a minimum space requirement, corresponding to the minimum
  171395. * feasible buffer sizes; jmemmgr.c will request that much space even if
  171396. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  171397. * all working storage in memory, is also passed in case it is useful.
  171398. * Finally, the total space already allocated is passed. If no better
  171399. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  171400. * is often a suitable calculation.
  171401. *
  171402. * It is OK for jpeg_mem_available to underestimate the space available
  171403. * (that'll just lead to more backing-store access than is really necessary).
  171404. * However, an overestimate will lead to failure. Hence it's wise to subtract
  171405. * a slop factor from the true available space. 5% should be enough.
  171406. *
  171407. * On machines with lots of virtual memory, any large constant may be returned.
  171408. * Conversely, zero may be returned to always use the minimum amount of memory.
  171409. */
  171410. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  171411. long min_bytes_needed,
  171412. long max_bytes_needed,
  171413. long already_allocated));
  171414. /*
  171415. * This structure holds whatever state is needed to access a single
  171416. * backing-store object. The read/write/close method pointers are called
  171417. * by jmemmgr.c to manipulate the backing-store object; all other fields
  171418. * are private to the system-dependent backing store routines.
  171419. */
  171420. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  171421. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  171422. typedef unsigned short XMSH; /* type of extended-memory handles */
  171423. typedef unsigned short EMSH; /* type of expanded-memory handles */
  171424. typedef union {
  171425. short file_handle; /* DOS file handle if it's a temp file */
  171426. XMSH xms_handle; /* handle if it's a chunk of XMS */
  171427. EMSH ems_handle; /* handle if it's a chunk of EMS */
  171428. } handle_union;
  171429. #endif /* USE_MSDOS_MEMMGR */
  171430. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  171431. #include <Files.h>
  171432. #endif /* USE_MAC_MEMMGR */
  171433. //typedef struct backing_store_struct * backing_store_ptr;
  171434. typedef struct backing_store_struct {
  171435. /* Methods for reading/writing/closing this backing-store object */
  171436. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  171437. struct backing_store_struct *info,
  171438. void FAR * buffer_address,
  171439. long file_offset, long byte_count));
  171440. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  171441. struct backing_store_struct *info,
  171442. void FAR * buffer_address,
  171443. long file_offset, long byte_count));
  171444. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  171445. struct backing_store_struct *info));
  171446. /* Private fields for system-dependent backing-store management */
  171447. #ifdef USE_MSDOS_MEMMGR
  171448. /* For the MS-DOS manager (jmemdos.c), we need: */
  171449. handle_union handle; /* reference to backing-store storage object */
  171450. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171451. #else
  171452. #ifdef USE_MAC_MEMMGR
  171453. /* For the Mac manager (jmemmac.c), we need: */
  171454. short temp_file; /* file reference number to temp file */
  171455. FSSpec tempSpec; /* the FSSpec for the temp file */
  171456. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  171457. #else
  171458. /* For a typical implementation with temp files, we need: */
  171459. FILE * temp_file; /* stdio reference to temp file */
  171460. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  171461. #endif
  171462. #endif
  171463. } backing_store_info;
  171464. /*
  171465. * Initial opening of a backing-store object. This must fill in the
  171466. * read/write/close pointers in the object. The read/write routines
  171467. * may take an error exit if the specified maximum file size is exceeded.
  171468. * (If jpeg_mem_available always returns a large value, this routine can
  171469. * just take an error exit.)
  171470. */
  171471. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  171472. struct backing_store_struct *info,
  171473. long total_bytes_needed));
  171474. /*
  171475. * These routines take care of any system-dependent initialization and
  171476. * cleanup required. jpeg_mem_init will be called before anything is
  171477. * allocated (and, therefore, nothing in cinfo is of use except the error
  171478. * manager pointer). It should return a suitable default value for
  171479. * max_memory_to_use; this may subsequently be overridden by the surrounding
  171480. * application. (Note that max_memory_to_use is only important if
  171481. * jpeg_mem_available chooses to consult it ... no one else will.)
  171482. * jpeg_mem_term may assume that all requested memory has been freed and that
  171483. * all opened backing-store objects have been closed.
  171484. */
  171485. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  171486. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  171487. #endif
  171488. /********* End of inlined file: jmemsys.h *********/
  171489. /* import the system-dependent declarations */
  171490. #ifndef NO_GETENV
  171491. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  171492. extern char * getenv JPP((const char * name));
  171493. #endif
  171494. #endif
  171495. /*
  171496. * Some important notes:
  171497. * The allocation routines provided here must never return NULL.
  171498. * They should exit to error_exit if unsuccessful.
  171499. *
  171500. * It's not a good idea to try to merge the sarray and barray routines,
  171501. * even though they are textually almost the same, because samples are
  171502. * usually stored as bytes while coefficients are shorts or ints. Thus,
  171503. * in machines where byte pointers have a different representation from
  171504. * word pointers, the resulting machine code could not be the same.
  171505. */
  171506. /*
  171507. * Many machines require storage alignment: longs must start on 4-byte
  171508. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  171509. * always returns pointers that are multiples of the worst-case alignment
  171510. * requirement, and we had better do so too.
  171511. * There isn't any really portable way to determine the worst-case alignment
  171512. * requirement. This module assumes that the alignment requirement is
  171513. * multiples of sizeof(ALIGN_TYPE).
  171514. * By default, we define ALIGN_TYPE as double. This is necessary on some
  171515. * workstations (where doubles really do need 8-byte alignment) and will work
  171516. * fine on nearly everything. If your machine has lesser alignment needs,
  171517. * you can save a few bytes by making ALIGN_TYPE smaller.
  171518. * The only place I know of where this will NOT work is certain Macintosh
  171519. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  171520. * Doing 10-byte alignment is counterproductive because longwords won't be
  171521. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  171522. * such a compiler.
  171523. */
  171524. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  171525. #define ALIGN_TYPE double
  171526. #endif
  171527. /*
  171528. * We allocate objects from "pools", where each pool is gotten with a single
  171529. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  171530. * overhead within a pool, except for alignment padding. Each pool has a
  171531. * header with a link to the next pool of the same class.
  171532. * Small and large pool headers are identical except that the latter's
  171533. * link pointer must be FAR on 80x86 machines.
  171534. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  171535. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  171536. * of the alignment requirement of ALIGN_TYPE.
  171537. */
  171538. typedef union small_pool_struct * small_pool_ptr;
  171539. typedef union small_pool_struct {
  171540. struct {
  171541. small_pool_ptr next; /* next in list of pools */
  171542. size_t bytes_used; /* how many bytes already used within pool */
  171543. size_t bytes_left; /* bytes still available in this pool */
  171544. } hdr;
  171545. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171546. } small_pool_hdr;
  171547. typedef union large_pool_struct FAR * large_pool_ptr;
  171548. typedef union large_pool_struct {
  171549. struct {
  171550. large_pool_ptr next; /* next in list of pools */
  171551. size_t bytes_used; /* how many bytes already used within pool */
  171552. size_t bytes_left; /* bytes still available in this pool */
  171553. } hdr;
  171554. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  171555. } large_pool_hdr;
  171556. /*
  171557. * Here is the full definition of a memory manager object.
  171558. */
  171559. typedef struct {
  171560. struct jpeg_memory_mgr pub; /* public fields */
  171561. /* Each pool identifier (lifetime class) names a linked list of pools. */
  171562. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  171563. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  171564. /* Since we only have one lifetime class of virtual arrays, only one
  171565. * linked list is necessary (for each datatype). Note that the virtual
  171566. * array control blocks being linked together are actually stored somewhere
  171567. * in the small-pool list.
  171568. */
  171569. jvirt_sarray_ptr virt_sarray_list;
  171570. jvirt_barray_ptr virt_barray_list;
  171571. /* This counts total space obtained from jpeg_get_small/large */
  171572. long total_space_allocated;
  171573. /* alloc_sarray and alloc_barray set this value for use by virtual
  171574. * array routines.
  171575. */
  171576. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  171577. } my_memory_mgr;
  171578. typedef my_memory_mgr * my_mem_ptr;
  171579. /*
  171580. * The control blocks for virtual arrays.
  171581. * Note that these blocks are allocated in the "small" pool area.
  171582. * System-dependent info for the associated backing store (if any) is hidden
  171583. * inside the backing_store_info struct.
  171584. */
  171585. struct jvirt_sarray_control {
  171586. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  171587. JDIMENSION rows_in_array; /* total virtual array height */
  171588. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  171589. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  171590. JDIMENSION rows_in_mem; /* height of memory buffer */
  171591. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171592. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171593. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171594. boolean pre_zero; /* pre-zero mode requested? */
  171595. boolean dirty; /* do current buffer contents need written? */
  171596. boolean b_s_open; /* is backing-store data valid? */
  171597. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  171598. backing_store_info b_s_info; /* System-dependent control info */
  171599. };
  171600. struct jvirt_barray_control {
  171601. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  171602. JDIMENSION rows_in_array; /* total virtual array height */
  171603. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  171604. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  171605. JDIMENSION rows_in_mem; /* height of memory buffer */
  171606. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  171607. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  171608. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  171609. boolean pre_zero; /* pre-zero mode requested? */
  171610. boolean dirty; /* do current buffer contents need written? */
  171611. boolean b_s_open; /* is backing-store data valid? */
  171612. jvirt_barray_ptr next; /* link to next virtual barray control block */
  171613. backing_store_info b_s_info; /* System-dependent control info */
  171614. };
  171615. #ifdef MEM_STATS /* optional extra stuff for statistics */
  171616. LOCAL(void)
  171617. print_mem_stats (j_common_ptr cinfo, int pool_id)
  171618. {
  171619. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171620. small_pool_ptr shdr_ptr;
  171621. large_pool_ptr lhdr_ptr;
  171622. /* Since this is only a debugging stub, we can cheat a little by using
  171623. * fprintf directly rather than going through the trace message code.
  171624. * This is helpful because message parm array can't handle longs.
  171625. */
  171626. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  171627. pool_id, mem->total_space_allocated);
  171628. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  171629. lhdr_ptr = lhdr_ptr->hdr.next) {
  171630. fprintf(stderr, " Large chunk used %ld\n",
  171631. (long) lhdr_ptr->hdr.bytes_used);
  171632. }
  171633. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  171634. shdr_ptr = shdr_ptr->hdr.next) {
  171635. fprintf(stderr, " Small chunk used %ld free %ld\n",
  171636. (long) shdr_ptr->hdr.bytes_used,
  171637. (long) shdr_ptr->hdr.bytes_left);
  171638. }
  171639. }
  171640. #endif /* MEM_STATS */
  171641. LOCAL(void)
  171642. out_of_memory (j_common_ptr cinfo, int which)
  171643. /* Report an out-of-memory error and stop execution */
  171644. /* If we compiled MEM_STATS support, report alloc requests before dying */
  171645. {
  171646. #ifdef MEM_STATS
  171647. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  171648. #endif
  171649. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  171650. }
  171651. /*
  171652. * Allocation of "small" objects.
  171653. *
  171654. * For these, we use pooled storage. When a new pool must be created,
  171655. * we try to get enough space for the current request plus a "slop" factor,
  171656. * where the slop will be the amount of leftover space in the new pool.
  171657. * The speed vs. space tradeoff is largely determined by the slop values.
  171658. * A different slop value is provided for each pool class (lifetime),
  171659. * and we also distinguish the first pool of a class from later ones.
  171660. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  171661. * machines, but may be too small if longs are 64 bits or more.
  171662. */
  171663. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  171664. {
  171665. 1600, /* first PERMANENT pool */
  171666. 16000 /* first IMAGE pool */
  171667. };
  171668. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  171669. {
  171670. 0, /* additional PERMANENT pools */
  171671. 5000 /* additional IMAGE pools */
  171672. };
  171673. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  171674. METHODDEF(void *)
  171675. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171676. /* Allocate a "small" object */
  171677. {
  171678. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171679. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  171680. char * data_ptr;
  171681. size_t odd_bytes, min_request, slop;
  171682. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171683. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  171684. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  171685. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171686. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171687. if (odd_bytes > 0)
  171688. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171689. /* See if space is available in any existing pool */
  171690. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171691. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171692. prev_hdr_ptr = NULL;
  171693. hdr_ptr = mem->small_list[pool_id];
  171694. while (hdr_ptr != NULL) {
  171695. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  171696. break; /* found pool with enough space */
  171697. prev_hdr_ptr = hdr_ptr;
  171698. hdr_ptr = hdr_ptr->hdr.next;
  171699. }
  171700. /* Time to make a new pool? */
  171701. if (hdr_ptr == NULL) {
  171702. /* min_request is what we need now, slop is what will be leftover */
  171703. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  171704. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171705. slop = first_pool_slop[pool_id];
  171706. else
  171707. slop = extra_pool_slop[pool_id];
  171708. /* Don't ask for more than MAX_ALLOC_CHUNK */
  171709. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  171710. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  171711. /* Try to get space, if fail reduce slop and try again */
  171712. for (;;) {
  171713. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  171714. if (hdr_ptr != NULL)
  171715. break;
  171716. slop /= 2;
  171717. if (slop < MIN_SLOP) /* give up when it gets real small */
  171718. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  171719. }
  171720. mem->total_space_allocated += min_request + slop;
  171721. /* Success, initialize the new pool header and add to end of list */
  171722. hdr_ptr->hdr.next = NULL;
  171723. hdr_ptr->hdr.bytes_used = 0;
  171724. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  171725. if (prev_hdr_ptr == NULL) /* first pool in class? */
  171726. mem->small_list[pool_id] = hdr_ptr;
  171727. else
  171728. prev_hdr_ptr->hdr.next = hdr_ptr;
  171729. }
  171730. /* OK, allocate the object from the current pool */
  171731. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  171732. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  171733. hdr_ptr->hdr.bytes_used += sizeofobject;
  171734. hdr_ptr->hdr.bytes_left -= sizeofobject;
  171735. return (void *) data_ptr;
  171736. }
  171737. /*
  171738. * Allocation of "large" objects.
  171739. *
  171740. * The external semantics of these are the same as "small" objects,
  171741. * except that FAR pointers are used on 80x86. However the pool
  171742. * management heuristics are quite different. We assume that each
  171743. * request is large enough that it may as well be passed directly to
  171744. * jpeg_get_large; the pool management just links everything together
  171745. * so that we can free it all on demand.
  171746. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  171747. * structures. The routines that create these structures (see below)
  171748. * deliberately bunch rows together to ensure a large request size.
  171749. */
  171750. METHODDEF(void FAR *)
  171751. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  171752. /* Allocate a "large" object */
  171753. {
  171754. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171755. large_pool_ptr hdr_ptr;
  171756. size_t odd_bytes;
  171757. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  171758. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  171759. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  171760. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  171761. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  171762. if (odd_bytes > 0)
  171763. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  171764. /* Always make a new pool */
  171765. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  171766. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171767. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  171768. SIZEOF(large_pool_hdr));
  171769. if (hdr_ptr == NULL)
  171770. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  171771. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  171772. /* Success, initialize the new pool header and add to list */
  171773. hdr_ptr->hdr.next = mem->large_list[pool_id];
  171774. /* We maintain space counts in each pool header for statistical purposes,
  171775. * even though they are not needed for allocation.
  171776. */
  171777. hdr_ptr->hdr.bytes_used = sizeofobject;
  171778. hdr_ptr->hdr.bytes_left = 0;
  171779. mem->large_list[pool_id] = hdr_ptr;
  171780. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  171781. }
  171782. /*
  171783. * Creation of 2-D sample arrays.
  171784. * The pointers are in near heap, the samples themselves in FAR heap.
  171785. *
  171786. * To minimize allocation overhead and to allow I/O of large contiguous
  171787. * blocks, we allocate the sample rows in groups of as many rows as possible
  171788. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  171789. * NB: the virtual array control routines, later in this file, know about
  171790. * this chunking of rows. The rowsperchunk value is left in the mem manager
  171791. * object so that it can be saved away if this sarray is the workspace for
  171792. * a virtual array.
  171793. */
  171794. METHODDEF(JSAMPARRAY)
  171795. alloc_sarray (j_common_ptr cinfo, int pool_id,
  171796. JDIMENSION samplesperrow, JDIMENSION numrows)
  171797. /* Allocate a 2-D sample array */
  171798. {
  171799. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171800. JSAMPARRAY result;
  171801. JSAMPROW workspace;
  171802. JDIMENSION rowsperchunk, currow, i;
  171803. long ltemp;
  171804. /* Calculate max # of rows allowed in one allocation chunk */
  171805. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171806. ((long) samplesperrow * SIZEOF(JSAMPLE));
  171807. if (ltemp <= 0)
  171808. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171809. if (ltemp < (long) numrows)
  171810. rowsperchunk = (JDIMENSION) ltemp;
  171811. else
  171812. rowsperchunk = numrows;
  171813. mem->last_rowsperchunk = rowsperchunk;
  171814. /* Get space for row pointers (small object) */
  171815. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  171816. (size_t) (numrows * SIZEOF(JSAMPROW)));
  171817. /* Get the rows themselves (large objects) */
  171818. currow = 0;
  171819. while (currow < numrows) {
  171820. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171821. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  171822. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  171823. * SIZEOF(JSAMPLE)));
  171824. for (i = rowsperchunk; i > 0; i--) {
  171825. result[currow++] = workspace;
  171826. workspace += samplesperrow;
  171827. }
  171828. }
  171829. return result;
  171830. }
  171831. /*
  171832. * Creation of 2-D coefficient-block arrays.
  171833. * This is essentially the same as the code for sample arrays, above.
  171834. */
  171835. METHODDEF(JBLOCKARRAY)
  171836. alloc_barray (j_common_ptr cinfo, int pool_id,
  171837. JDIMENSION blocksperrow, JDIMENSION numrows)
  171838. /* Allocate a 2-D coefficient-block array */
  171839. {
  171840. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171841. JBLOCKARRAY result;
  171842. JBLOCKROW workspace;
  171843. JDIMENSION rowsperchunk, currow, i;
  171844. long ltemp;
  171845. /* Calculate max # of rows allowed in one allocation chunk */
  171846. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  171847. ((long) blocksperrow * SIZEOF(JBLOCK));
  171848. if (ltemp <= 0)
  171849. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  171850. if (ltemp < (long) numrows)
  171851. rowsperchunk = (JDIMENSION) ltemp;
  171852. else
  171853. rowsperchunk = numrows;
  171854. mem->last_rowsperchunk = rowsperchunk;
  171855. /* Get space for row pointers (small object) */
  171856. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  171857. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  171858. /* Get the rows themselves (large objects) */
  171859. currow = 0;
  171860. while (currow < numrows) {
  171861. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  171862. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  171863. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  171864. * SIZEOF(JBLOCK)));
  171865. for (i = rowsperchunk; i > 0; i--) {
  171866. result[currow++] = workspace;
  171867. workspace += blocksperrow;
  171868. }
  171869. }
  171870. return result;
  171871. }
  171872. /*
  171873. * About virtual array management:
  171874. *
  171875. * The above "normal" array routines are only used to allocate strip buffers
  171876. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  171877. * are handled as "virtual" arrays. The array is still accessed a strip at a
  171878. * time, but the memory manager must save the whole array for repeated
  171879. * accesses. The intended implementation is that there is a strip buffer in
  171880. * memory (as high as is possible given the desired memory limit), plus a
  171881. * backing file that holds the rest of the array.
  171882. *
  171883. * The request_virt_array routines are told the total size of the image and
  171884. * the maximum number of rows that will be accessed at once. The in-memory
  171885. * buffer must be at least as large as the maxaccess value.
  171886. *
  171887. * The request routines create control blocks but not the in-memory buffers.
  171888. * That is postponed until realize_virt_arrays is called. At that time the
  171889. * total amount of space needed is known (approximately, anyway), so free
  171890. * memory can be divided up fairly.
  171891. *
  171892. * The access_virt_array routines are responsible for making a specific strip
  171893. * area accessible (after reading or writing the backing file, if necessary).
  171894. * Note that the access routines are told whether the caller intends to modify
  171895. * the accessed strip; during a read-only pass this saves having to rewrite
  171896. * data to disk. The access routines are also responsible for pre-zeroing
  171897. * any newly accessed rows, if pre-zeroing was requested.
  171898. *
  171899. * In current usage, the access requests are usually for nonoverlapping
  171900. * strips; that is, successive access start_row numbers differ by exactly
  171901. * num_rows = maxaccess. This means we can get good performance with simple
  171902. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  171903. * of the access height; then there will never be accesses across bufferload
  171904. * boundaries. The code will still work with overlapping access requests,
  171905. * but it doesn't handle bufferload overlaps very efficiently.
  171906. */
  171907. METHODDEF(jvirt_sarray_ptr)
  171908. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171909. JDIMENSION samplesperrow, JDIMENSION numrows,
  171910. JDIMENSION maxaccess)
  171911. /* Request a virtual 2-D sample array */
  171912. {
  171913. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171914. jvirt_sarray_ptr result;
  171915. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171916. if (pool_id != JPOOL_IMAGE)
  171917. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171918. /* get control block */
  171919. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  171920. SIZEOF(struct jvirt_sarray_control));
  171921. result->mem_buffer = NULL; /* marks array not yet realized */
  171922. result->rows_in_array = numrows;
  171923. result->samplesperrow = samplesperrow;
  171924. result->maxaccess = maxaccess;
  171925. result->pre_zero = pre_zero;
  171926. result->b_s_open = FALSE; /* no associated backing-store object */
  171927. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  171928. mem->virt_sarray_list = result;
  171929. return result;
  171930. }
  171931. METHODDEF(jvirt_barray_ptr)
  171932. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  171933. JDIMENSION blocksperrow, JDIMENSION numrows,
  171934. JDIMENSION maxaccess)
  171935. /* Request a virtual 2-D coefficient-block array */
  171936. {
  171937. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171938. jvirt_barray_ptr result;
  171939. /* Only IMAGE-lifetime virtual arrays are currently supported */
  171940. if (pool_id != JPOOL_IMAGE)
  171941. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  171942. /* get control block */
  171943. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  171944. SIZEOF(struct jvirt_barray_control));
  171945. result->mem_buffer = NULL; /* marks array not yet realized */
  171946. result->rows_in_array = numrows;
  171947. result->blocksperrow = blocksperrow;
  171948. result->maxaccess = maxaccess;
  171949. result->pre_zero = pre_zero;
  171950. result->b_s_open = FALSE; /* no associated backing-store object */
  171951. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  171952. mem->virt_barray_list = result;
  171953. return result;
  171954. }
  171955. METHODDEF(void)
  171956. realize_virt_arrays (j_common_ptr cinfo)
  171957. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  171958. {
  171959. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  171960. long space_per_minheight, maximum_space, avail_mem;
  171961. long minheights, max_minheights;
  171962. jvirt_sarray_ptr sptr;
  171963. jvirt_barray_ptr bptr;
  171964. /* Compute the minimum space needed (maxaccess rows in each buffer)
  171965. * and the maximum space needed (full image height in each buffer).
  171966. * These may be of use to the system-dependent jpeg_mem_available routine.
  171967. */
  171968. space_per_minheight = 0;
  171969. maximum_space = 0;
  171970. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  171971. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  171972. space_per_minheight += (long) sptr->maxaccess *
  171973. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171974. maximum_space += (long) sptr->rows_in_array *
  171975. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  171976. }
  171977. }
  171978. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  171979. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  171980. space_per_minheight += (long) bptr->maxaccess *
  171981. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171982. maximum_space += (long) bptr->rows_in_array *
  171983. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  171984. }
  171985. }
  171986. if (space_per_minheight <= 0)
  171987. return; /* no unrealized arrays, no work */
  171988. /* Determine amount of memory to actually use; this is system-dependent. */
  171989. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  171990. mem->total_space_allocated);
  171991. /* If the maximum space needed is available, make all the buffers full
  171992. * height; otherwise parcel it out with the same number of minheights
  171993. * in each buffer.
  171994. */
  171995. if (avail_mem >= maximum_space)
  171996. max_minheights = 1000000000L;
  171997. else {
  171998. max_minheights = avail_mem / space_per_minheight;
  171999. /* If there doesn't seem to be enough space, try to get the minimum
  172000. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  172001. */
  172002. if (max_minheights <= 0)
  172003. max_minheights = 1;
  172004. }
  172005. /* Allocate the in-memory buffers and initialize backing store as needed. */
  172006. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172007. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  172008. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  172009. if (minheights <= max_minheights) {
  172010. /* This buffer fits in memory */
  172011. sptr->rows_in_mem = sptr->rows_in_array;
  172012. } else {
  172013. /* It doesn't fit in memory, create backing store. */
  172014. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  172015. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  172016. (long) sptr->rows_in_array *
  172017. (long) sptr->samplesperrow *
  172018. (long) SIZEOF(JSAMPLE));
  172019. sptr->b_s_open = TRUE;
  172020. }
  172021. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  172022. sptr->samplesperrow, sptr->rows_in_mem);
  172023. sptr->rowsperchunk = mem->last_rowsperchunk;
  172024. sptr->cur_start_row = 0;
  172025. sptr->first_undef_row = 0;
  172026. sptr->dirty = FALSE;
  172027. }
  172028. }
  172029. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172030. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  172031. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  172032. if (minheights <= max_minheights) {
  172033. /* This buffer fits in memory */
  172034. bptr->rows_in_mem = bptr->rows_in_array;
  172035. } else {
  172036. /* It doesn't fit in memory, create backing store. */
  172037. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  172038. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  172039. (long) bptr->rows_in_array *
  172040. (long) bptr->blocksperrow *
  172041. (long) SIZEOF(JBLOCK));
  172042. bptr->b_s_open = TRUE;
  172043. }
  172044. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  172045. bptr->blocksperrow, bptr->rows_in_mem);
  172046. bptr->rowsperchunk = mem->last_rowsperchunk;
  172047. bptr->cur_start_row = 0;
  172048. bptr->first_undef_row = 0;
  172049. bptr->dirty = FALSE;
  172050. }
  172051. }
  172052. }
  172053. LOCAL(void)
  172054. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  172055. /* Do backing store read or write of a virtual sample array */
  172056. {
  172057. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172058. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172059. file_offset = ptr->cur_start_row * bytesperrow;
  172060. /* Loop to read or write each allocation chunk in mem_buffer */
  172061. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172062. /* One chunk, but check for short chunk at end of buffer */
  172063. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172064. /* Transfer no more than is currently defined */
  172065. thisrow = (long) ptr->cur_start_row + i;
  172066. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172067. /* Transfer no more than fits in file */
  172068. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172069. if (rows <= 0) /* this chunk might be past end of file! */
  172070. break;
  172071. byte_count = rows * bytesperrow;
  172072. if (writing)
  172073. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172074. (void FAR *) ptr->mem_buffer[i],
  172075. file_offset, byte_count);
  172076. else
  172077. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172078. (void FAR *) ptr->mem_buffer[i],
  172079. file_offset, byte_count);
  172080. file_offset += byte_count;
  172081. }
  172082. }
  172083. LOCAL(void)
  172084. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  172085. /* Do backing store read or write of a virtual coefficient-block array */
  172086. {
  172087. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  172088. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  172089. file_offset = ptr->cur_start_row * bytesperrow;
  172090. /* Loop to read or write each allocation chunk in mem_buffer */
  172091. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  172092. /* One chunk, but check for short chunk at end of buffer */
  172093. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  172094. /* Transfer no more than is currently defined */
  172095. thisrow = (long) ptr->cur_start_row + i;
  172096. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  172097. /* Transfer no more than fits in file */
  172098. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  172099. if (rows <= 0) /* this chunk might be past end of file! */
  172100. break;
  172101. byte_count = rows * bytesperrow;
  172102. if (writing)
  172103. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  172104. (void FAR *) ptr->mem_buffer[i],
  172105. file_offset, byte_count);
  172106. else
  172107. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  172108. (void FAR *) ptr->mem_buffer[i],
  172109. file_offset, byte_count);
  172110. file_offset += byte_count;
  172111. }
  172112. }
  172113. METHODDEF(JSAMPARRAY)
  172114. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  172115. JDIMENSION start_row, JDIMENSION num_rows,
  172116. boolean writable)
  172117. /* Access the part of a virtual sample array starting at start_row */
  172118. /* and extending for num_rows rows. writable is true if */
  172119. /* caller intends to modify the accessed area. */
  172120. {
  172121. JDIMENSION end_row = start_row + num_rows;
  172122. JDIMENSION undef_row;
  172123. /* debugging check */
  172124. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172125. ptr->mem_buffer == NULL)
  172126. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172127. /* Make the desired part of the virtual array accessible */
  172128. if (start_row < ptr->cur_start_row ||
  172129. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172130. if (! ptr->b_s_open)
  172131. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172132. /* Flush old buffer contents if necessary */
  172133. if (ptr->dirty) {
  172134. do_sarray_io(cinfo, ptr, TRUE);
  172135. ptr->dirty = FALSE;
  172136. }
  172137. /* Decide what part of virtual array to access.
  172138. * Algorithm: if target address > current window, assume forward scan,
  172139. * load starting at target address. If target address < current window,
  172140. * assume backward scan, load so that target area is top of window.
  172141. * Note that when switching from forward write to forward read, will have
  172142. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172143. */
  172144. if (start_row > ptr->cur_start_row) {
  172145. ptr->cur_start_row = start_row;
  172146. } else {
  172147. /* use long arithmetic here to avoid overflow & unsigned problems */
  172148. long ltemp;
  172149. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172150. if (ltemp < 0)
  172151. ltemp = 0; /* don't fall off front end of file */
  172152. ptr->cur_start_row = (JDIMENSION) ltemp;
  172153. }
  172154. /* Read in the selected part of the array.
  172155. * During the initial write pass, we will do no actual read
  172156. * because the selected part is all undefined.
  172157. */
  172158. do_sarray_io(cinfo, ptr, FALSE);
  172159. }
  172160. /* Ensure the accessed part of the array is defined; prezero if needed.
  172161. * To improve locality of access, we only prezero the part of the array
  172162. * that the caller is about to access, not the entire in-memory array.
  172163. */
  172164. if (ptr->first_undef_row < end_row) {
  172165. if (ptr->first_undef_row < start_row) {
  172166. if (writable) /* writer skipped over a section of array */
  172167. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172168. undef_row = start_row; /* but reader is allowed to read ahead */
  172169. } else {
  172170. undef_row = ptr->first_undef_row;
  172171. }
  172172. if (writable)
  172173. ptr->first_undef_row = end_row;
  172174. if (ptr->pre_zero) {
  172175. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  172176. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172177. end_row -= ptr->cur_start_row;
  172178. while (undef_row < end_row) {
  172179. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172180. undef_row++;
  172181. }
  172182. } else {
  172183. if (! writable) /* reader looking at undefined data */
  172184. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172185. }
  172186. }
  172187. /* Flag the buffer dirty if caller will write in it */
  172188. if (writable)
  172189. ptr->dirty = TRUE;
  172190. /* Return address of proper part of the buffer */
  172191. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172192. }
  172193. METHODDEF(JBLOCKARRAY)
  172194. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  172195. JDIMENSION start_row, JDIMENSION num_rows,
  172196. boolean writable)
  172197. /* Access the part of a virtual block array starting at start_row */
  172198. /* and extending for num_rows rows. writable is true if */
  172199. /* caller intends to modify the accessed area. */
  172200. {
  172201. JDIMENSION end_row = start_row + num_rows;
  172202. JDIMENSION undef_row;
  172203. /* debugging check */
  172204. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  172205. ptr->mem_buffer == NULL)
  172206. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172207. /* Make the desired part of the virtual array accessible */
  172208. if (start_row < ptr->cur_start_row ||
  172209. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  172210. if (! ptr->b_s_open)
  172211. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  172212. /* Flush old buffer contents if necessary */
  172213. if (ptr->dirty) {
  172214. do_barray_io(cinfo, ptr, TRUE);
  172215. ptr->dirty = FALSE;
  172216. }
  172217. /* Decide what part of virtual array to access.
  172218. * Algorithm: if target address > current window, assume forward scan,
  172219. * load starting at target address. If target address < current window,
  172220. * assume backward scan, load so that target area is top of window.
  172221. * Note that when switching from forward write to forward read, will have
  172222. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  172223. */
  172224. if (start_row > ptr->cur_start_row) {
  172225. ptr->cur_start_row = start_row;
  172226. } else {
  172227. /* use long arithmetic here to avoid overflow & unsigned problems */
  172228. long ltemp;
  172229. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  172230. if (ltemp < 0)
  172231. ltemp = 0; /* don't fall off front end of file */
  172232. ptr->cur_start_row = (JDIMENSION) ltemp;
  172233. }
  172234. /* Read in the selected part of the array.
  172235. * During the initial write pass, we will do no actual read
  172236. * because the selected part is all undefined.
  172237. */
  172238. do_barray_io(cinfo, ptr, FALSE);
  172239. }
  172240. /* Ensure the accessed part of the array is defined; prezero if needed.
  172241. * To improve locality of access, we only prezero the part of the array
  172242. * that the caller is about to access, not the entire in-memory array.
  172243. */
  172244. if (ptr->first_undef_row < end_row) {
  172245. if (ptr->first_undef_row < start_row) {
  172246. if (writable) /* writer skipped over a section of array */
  172247. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172248. undef_row = start_row; /* but reader is allowed to read ahead */
  172249. } else {
  172250. undef_row = ptr->first_undef_row;
  172251. }
  172252. if (writable)
  172253. ptr->first_undef_row = end_row;
  172254. if (ptr->pre_zero) {
  172255. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  172256. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  172257. end_row -= ptr->cur_start_row;
  172258. while (undef_row < end_row) {
  172259. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  172260. undef_row++;
  172261. }
  172262. } else {
  172263. if (! writable) /* reader looking at undefined data */
  172264. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  172265. }
  172266. }
  172267. /* Flag the buffer dirty if caller will write in it */
  172268. if (writable)
  172269. ptr->dirty = TRUE;
  172270. /* Return address of proper part of the buffer */
  172271. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  172272. }
  172273. /*
  172274. * Release all objects belonging to a specified pool.
  172275. */
  172276. METHODDEF(void)
  172277. free_pool (j_common_ptr cinfo, int pool_id)
  172278. {
  172279. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  172280. small_pool_ptr shdr_ptr;
  172281. large_pool_ptr lhdr_ptr;
  172282. size_t space_freed;
  172283. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  172284. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  172285. #ifdef MEM_STATS
  172286. if (cinfo->err->trace_level > 1)
  172287. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  172288. #endif
  172289. /* If freeing IMAGE pool, close any virtual arrays first */
  172290. if (pool_id == JPOOL_IMAGE) {
  172291. jvirt_sarray_ptr sptr;
  172292. jvirt_barray_ptr bptr;
  172293. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  172294. if (sptr->b_s_open) { /* there may be no backing store */
  172295. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  172296. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  172297. }
  172298. }
  172299. mem->virt_sarray_list = NULL;
  172300. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  172301. if (bptr->b_s_open) { /* there may be no backing store */
  172302. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  172303. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  172304. }
  172305. }
  172306. mem->virt_barray_list = NULL;
  172307. }
  172308. /* Release large objects */
  172309. lhdr_ptr = mem->large_list[pool_id];
  172310. mem->large_list[pool_id] = NULL;
  172311. while (lhdr_ptr != NULL) {
  172312. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  172313. space_freed = lhdr_ptr->hdr.bytes_used +
  172314. lhdr_ptr->hdr.bytes_left +
  172315. SIZEOF(large_pool_hdr);
  172316. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  172317. mem->total_space_allocated -= space_freed;
  172318. lhdr_ptr = next_lhdr_ptr;
  172319. }
  172320. /* Release small objects */
  172321. shdr_ptr = mem->small_list[pool_id];
  172322. mem->small_list[pool_id] = NULL;
  172323. while (shdr_ptr != NULL) {
  172324. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  172325. space_freed = shdr_ptr->hdr.bytes_used +
  172326. shdr_ptr->hdr.bytes_left +
  172327. SIZEOF(small_pool_hdr);
  172328. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  172329. mem->total_space_allocated -= space_freed;
  172330. shdr_ptr = next_shdr_ptr;
  172331. }
  172332. }
  172333. /*
  172334. * Close up shop entirely.
  172335. * Note that this cannot be called unless cinfo->mem is non-NULL.
  172336. */
  172337. METHODDEF(void)
  172338. self_destruct (j_common_ptr cinfo)
  172339. {
  172340. int pool;
  172341. /* Close all backing store, release all memory.
  172342. * Releasing pools in reverse order might help avoid fragmentation
  172343. * with some (brain-damaged) malloc libraries.
  172344. */
  172345. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172346. free_pool(cinfo, pool);
  172347. }
  172348. /* Release the memory manager control block too. */
  172349. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  172350. cinfo->mem = NULL; /* ensures I will be called only once */
  172351. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172352. }
  172353. /*
  172354. * Memory manager initialization.
  172355. * When this is called, only the error manager pointer is valid in cinfo!
  172356. */
  172357. GLOBAL(void)
  172358. jinit_memory_mgr (j_common_ptr cinfo)
  172359. {
  172360. my_mem_ptr mem;
  172361. long max_to_use;
  172362. int pool;
  172363. size_t test_mac;
  172364. cinfo->mem = NULL; /* for safety if init fails */
  172365. /* Check for configuration errors.
  172366. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  172367. * doesn't reflect any real hardware alignment requirement.
  172368. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  172369. * in common if and only if X is a power of 2, ie has only one one-bit.
  172370. * Some compilers may give an "unreachable code" warning here; ignore it.
  172371. */
  172372. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  172373. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  172374. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  172375. * a multiple of SIZEOF(ALIGN_TYPE).
  172376. * Again, an "unreachable code" warning may be ignored here.
  172377. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  172378. */
  172379. test_mac = (size_t) MAX_ALLOC_CHUNK;
  172380. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  172381. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  172382. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  172383. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  172384. /* Attempt to allocate memory manager's control block */
  172385. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  172386. if (mem == NULL) {
  172387. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  172388. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  172389. }
  172390. /* OK, fill in the method pointers */
  172391. mem->pub.alloc_small = alloc_small;
  172392. mem->pub.alloc_large = alloc_large;
  172393. mem->pub.alloc_sarray = alloc_sarray;
  172394. mem->pub.alloc_barray = alloc_barray;
  172395. mem->pub.request_virt_sarray = request_virt_sarray;
  172396. mem->pub.request_virt_barray = request_virt_barray;
  172397. mem->pub.realize_virt_arrays = realize_virt_arrays;
  172398. mem->pub.access_virt_sarray = access_virt_sarray;
  172399. mem->pub.access_virt_barray = access_virt_barray;
  172400. mem->pub.free_pool = free_pool;
  172401. mem->pub.self_destruct = self_destruct;
  172402. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  172403. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  172404. /* Initialize working state */
  172405. mem->pub.max_memory_to_use = max_to_use;
  172406. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  172407. mem->small_list[pool] = NULL;
  172408. mem->large_list[pool] = NULL;
  172409. }
  172410. mem->virt_sarray_list = NULL;
  172411. mem->virt_barray_list = NULL;
  172412. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  172413. /* Declare ourselves open for business */
  172414. cinfo->mem = & mem->pub;
  172415. /* Check for an environment variable JPEGMEM; if found, override the
  172416. * default max_memory setting from jpeg_mem_init. Note that the
  172417. * surrounding application may again override this value.
  172418. * If your system doesn't support getenv(), define NO_GETENV to disable
  172419. * this feature.
  172420. */
  172421. #ifndef NO_GETENV
  172422. { char * memenv;
  172423. if ((memenv = getenv("JPEGMEM")) != NULL) {
  172424. char ch = 'x';
  172425. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  172426. if (ch == 'm' || ch == 'M')
  172427. max_to_use *= 1000L;
  172428. mem->pub.max_memory_to_use = max_to_use * 1000L;
  172429. }
  172430. }
  172431. }
  172432. #endif
  172433. }
  172434. /********* End of inlined file: jmemmgr.c *********/
  172435. /********* Start of inlined file: jmemnobs.c *********/
  172436. #define JPEG_INTERNALS
  172437. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  172438. extern void * malloc JPP((size_t size));
  172439. extern void free JPP((void *ptr));
  172440. #endif
  172441. /*
  172442. * Memory allocation and freeing are controlled by the regular library
  172443. * routines malloc() and free().
  172444. */
  172445. GLOBAL(void *)
  172446. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  172447. {
  172448. return (void *) malloc(sizeofobject);
  172449. }
  172450. GLOBAL(void)
  172451. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  172452. {
  172453. free(object);
  172454. }
  172455. /*
  172456. * "Large" objects are treated the same as "small" ones.
  172457. * NB: although we include FAR keywords in the routine declarations,
  172458. * this file won't actually work in 80x86 small/medium model; at least,
  172459. * you probably won't be able to process useful-size images in only 64KB.
  172460. */
  172461. GLOBAL(void FAR *)
  172462. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  172463. {
  172464. return (void FAR *) malloc(sizeofobject);
  172465. }
  172466. GLOBAL(void)
  172467. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  172468. {
  172469. free(object);
  172470. }
  172471. /*
  172472. * This routine computes the total memory space available for allocation.
  172473. * Here we always say, "we got all you want bud!"
  172474. */
  172475. GLOBAL(long)
  172476. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  172477. long max_bytes_needed, long already_allocated)
  172478. {
  172479. return max_bytes_needed;
  172480. }
  172481. /*
  172482. * Backing store (temporary file) management.
  172483. * Since jpeg_mem_available always promised the moon,
  172484. * this should never be called and we can just error out.
  172485. */
  172486. GLOBAL(void)
  172487. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  172488. long total_bytes_needed)
  172489. {
  172490. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  172491. }
  172492. /*
  172493. * These routines take care of any system-dependent initialization and
  172494. * cleanup required. Here, there isn't any.
  172495. */
  172496. GLOBAL(long)
  172497. jpeg_mem_init (j_common_ptr cinfo)
  172498. {
  172499. return 0; /* just set max_memory_to_use to 0 */
  172500. }
  172501. GLOBAL(void)
  172502. jpeg_mem_term (j_common_ptr cinfo)
  172503. {
  172504. /* no work */
  172505. }
  172506. /********* End of inlined file: jmemnobs.c *********/
  172507. /********* Start of inlined file: jquant1.c *********/
  172508. #define JPEG_INTERNALS
  172509. #ifdef QUANT_1PASS_SUPPORTED
  172510. /*
  172511. * The main purpose of 1-pass quantization is to provide a fast, if not very
  172512. * high quality, colormapped output capability. A 2-pass quantizer usually
  172513. * gives better visual quality; however, for quantized grayscale output this
  172514. * quantizer is perfectly adequate. Dithering is highly recommended with this
  172515. * quantizer, though you can turn it off if you really want to.
  172516. *
  172517. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  172518. * image. We use a map consisting of all combinations of Ncolors[i] color
  172519. * values for the i'th component. The Ncolors[] values are chosen so that
  172520. * their product, the total number of colors, is no more than that requested.
  172521. * (In most cases, the product will be somewhat less.)
  172522. *
  172523. * Since the colormap is orthogonal, the representative value for each color
  172524. * component can be determined without considering the other components;
  172525. * then these indexes can be combined into a colormap index by a standard
  172526. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  172527. * can be precalculated and stored in the lookup table colorindex[].
  172528. * colorindex[i][j] maps pixel value j in component i to the nearest
  172529. * representative value (grid plane) for that component; this index is
  172530. * multiplied by the array stride for component i, so that the
  172531. * index of the colormap entry closest to a given pixel value is just
  172532. * sum( colorindex[component-number][pixel-component-value] )
  172533. * Aside from being fast, this scheme allows for variable spacing between
  172534. * representative values with no additional lookup cost.
  172535. *
  172536. * If gamma correction has been applied in color conversion, it might be wise
  172537. * to adjust the color grid spacing so that the representative colors are
  172538. * equidistant in linear space. At this writing, gamma correction is not
  172539. * implemented by jdcolor, so nothing is done here.
  172540. */
  172541. /* Declarations for ordered dithering.
  172542. *
  172543. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  172544. * dithering is described in many references, for instance Dale Schumacher's
  172545. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  172546. * In place of Schumacher's comparisons against a "threshold" value, we add a
  172547. * "dither" value to the input pixel and then round the result to the nearest
  172548. * output value. The dither value is equivalent to (0.5 - threshold) times
  172549. * the distance between output values. For ordered dithering, we assume that
  172550. * the output colors are equally spaced; if not, results will probably be
  172551. * worse, since the dither may be too much or too little at a given point.
  172552. *
  172553. * The normal calculation would be to form pixel value + dither, range-limit
  172554. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  172555. * We can skip the separate range-limiting step by extending the colorindex
  172556. * table in both directions.
  172557. */
  172558. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  172559. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  172560. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  172561. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  172562. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  172563. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  172564. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  172565. /* Bayer's order-4 dither array. Generated by the code given in
  172566. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  172567. * The values in this array must range from 0 to ODITHER_CELLS-1.
  172568. */
  172569. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  172570. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  172571. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  172572. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  172573. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  172574. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  172575. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  172576. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  172577. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  172578. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  172579. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  172580. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  172581. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  172582. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  172583. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  172584. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  172585. };
  172586. /* Declarations for Floyd-Steinberg dithering.
  172587. *
  172588. * Errors are accumulated into the array fserrors[], at a resolution of
  172589. * 1/16th of a pixel count. The error at a given pixel is propagated
  172590. * to its not-yet-processed neighbors using the standard F-S fractions,
  172591. * ... (here) 7/16
  172592. * 3/16 5/16 1/16
  172593. * We work left-to-right on even rows, right-to-left on odd rows.
  172594. *
  172595. * We can get away with a single array (holding one row's worth of errors)
  172596. * by using it to store the current row's errors at pixel columns not yet
  172597. * processed, but the next row's errors at columns already processed. We
  172598. * need only a few extra variables to hold the errors immediately around the
  172599. * current column. (If we are lucky, those variables are in registers, but
  172600. * even if not, they're probably cheaper to access than array elements are.)
  172601. *
  172602. * The fserrors[] array is indexed [component#][position].
  172603. * We provide (#columns + 2) entries per component; the extra entry at each
  172604. * end saves us from special-casing the first and last pixels.
  172605. *
  172606. * Note: on a wide image, we might not have enough room in a PC's near data
  172607. * segment to hold the error array; so it is allocated with alloc_large.
  172608. */
  172609. #if BITS_IN_JSAMPLE == 8
  172610. typedef INT16 FSERROR; /* 16 bits should be enough */
  172611. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  172612. #else
  172613. typedef INT32 FSERROR; /* may need more than 16 bits */
  172614. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  172615. #endif
  172616. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  172617. /* Private subobject */
  172618. #define MAX_Q_COMPS 4 /* max components I can handle */
  172619. typedef struct {
  172620. struct jpeg_color_quantizer pub; /* public fields */
  172621. /* Initially allocated colormap is saved here */
  172622. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  172623. int sv_actual; /* number of entries in use */
  172624. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  172625. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  172626. * premultiplied as described above. Since colormap indexes must fit into
  172627. * JSAMPLEs, the entries of this array will too.
  172628. */
  172629. boolean is_padded; /* is the colorindex padded for odither? */
  172630. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  172631. /* Variables for ordered dithering */
  172632. int row_index; /* cur row's vertical index in dither matrix */
  172633. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  172634. /* Variables for Floyd-Steinberg dithering */
  172635. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  172636. boolean on_odd_row; /* flag to remember which row we are on */
  172637. } my_cquantizer;
  172638. typedef my_cquantizer * my_cquantize_ptr;
  172639. /*
  172640. * Policy-making subroutines for create_colormap and create_colorindex.
  172641. * These routines determine the colormap to be used. The rest of the module
  172642. * only assumes that the colormap is orthogonal.
  172643. *
  172644. * * select_ncolors decides how to divvy up the available colors
  172645. * among the components.
  172646. * * output_value defines the set of representative values for a component.
  172647. * * largest_input_value defines the mapping from input values to
  172648. * representative values for a component.
  172649. * Note that the latter two routines may impose different policies for
  172650. * different components, though this is not currently done.
  172651. */
  172652. LOCAL(int)
  172653. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  172654. /* Determine allocation of desired colors to components, */
  172655. /* and fill in Ncolors[] array to indicate choice. */
  172656. /* Return value is total number of colors (product of Ncolors[] values). */
  172657. {
  172658. int nc = cinfo->out_color_components; /* number of color components */
  172659. int max_colors = cinfo->desired_number_of_colors;
  172660. int total_colors, iroot, i, j;
  172661. boolean changed;
  172662. long temp;
  172663. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  172664. /* We can allocate at least the nc'th root of max_colors per component. */
  172665. /* Compute floor(nc'th root of max_colors). */
  172666. iroot = 1;
  172667. do {
  172668. iroot++;
  172669. temp = iroot; /* set temp = iroot ** nc */
  172670. for (i = 1; i < nc; i++)
  172671. temp *= iroot;
  172672. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  172673. iroot--; /* now iroot = floor(root) */
  172674. /* Must have at least 2 color values per component */
  172675. if (iroot < 2)
  172676. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  172677. /* Initialize to iroot color values for each component */
  172678. total_colors = 1;
  172679. for (i = 0; i < nc; i++) {
  172680. Ncolors[i] = iroot;
  172681. total_colors *= iroot;
  172682. }
  172683. /* We may be able to increment the count for one or more components without
  172684. * exceeding max_colors, though we know not all can be incremented.
  172685. * Sometimes, the first component can be incremented more than once!
  172686. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  172687. * In RGB colorspace, try to increment G first, then R, then B.
  172688. */
  172689. do {
  172690. changed = FALSE;
  172691. for (i = 0; i < nc; i++) {
  172692. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  172693. /* calculate new total_colors if Ncolors[j] is incremented */
  172694. temp = total_colors / Ncolors[j];
  172695. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  172696. if (temp > (long) max_colors)
  172697. break; /* won't fit, done with this pass */
  172698. Ncolors[j]++; /* OK, apply the increment */
  172699. total_colors = (int) temp;
  172700. changed = TRUE;
  172701. }
  172702. } while (changed);
  172703. return total_colors;
  172704. }
  172705. LOCAL(int)
  172706. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172707. /* Return j'th output value, where j will range from 0 to maxj */
  172708. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  172709. {
  172710. /* We always provide values 0 and MAXJSAMPLE for each component;
  172711. * any additional values are equally spaced between these limits.
  172712. * (Forcing the upper and lower values to the limits ensures that
  172713. * dithering can't produce a color outside the selected gamut.)
  172714. */
  172715. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  172716. }
  172717. LOCAL(int)
  172718. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  172719. /* Return largest input value that should map to j'th output value */
  172720. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  172721. {
  172722. /* Breakpoints are halfway between values returned by output_value */
  172723. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  172724. }
  172725. /*
  172726. * Create the colormap.
  172727. */
  172728. LOCAL(void)
  172729. create_colormap (j_decompress_ptr cinfo)
  172730. {
  172731. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172732. JSAMPARRAY colormap; /* Created colormap */
  172733. int total_colors; /* Number of distinct output colors */
  172734. int i,j,k, nci, blksize, blkdist, ptr, val;
  172735. /* Select number of colors for each component */
  172736. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  172737. /* Report selected color counts */
  172738. if (cinfo->out_color_components == 3)
  172739. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  172740. total_colors, cquantize->Ncolors[0],
  172741. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  172742. else
  172743. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  172744. /* Allocate and fill in the colormap. */
  172745. /* The colors are ordered in the map in standard row-major order, */
  172746. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  172747. colormap = (*cinfo->mem->alloc_sarray)
  172748. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172749. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  172750. /* blksize is number of adjacent repeated entries for a component */
  172751. /* blkdist is distance between groups of identical entries for a component */
  172752. blkdist = total_colors;
  172753. for (i = 0; i < cinfo->out_color_components; i++) {
  172754. /* fill in colormap entries for i'th color component */
  172755. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172756. blksize = blkdist / nci;
  172757. for (j = 0; j < nci; j++) {
  172758. /* Compute j'th output value (out of nci) for component */
  172759. val = output_value(cinfo, i, j, nci-1);
  172760. /* Fill in all colormap entries that have this value of this component */
  172761. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  172762. /* fill in blksize entries beginning at ptr */
  172763. for (k = 0; k < blksize; k++)
  172764. colormap[i][ptr+k] = (JSAMPLE) val;
  172765. }
  172766. }
  172767. blkdist = blksize; /* blksize of this color is blkdist of next */
  172768. }
  172769. /* Save the colormap in private storage,
  172770. * where it will survive color quantization mode changes.
  172771. */
  172772. cquantize->sv_colormap = colormap;
  172773. cquantize->sv_actual = total_colors;
  172774. }
  172775. /*
  172776. * Create the color index table.
  172777. */
  172778. LOCAL(void)
  172779. create_colorindex (j_decompress_ptr cinfo)
  172780. {
  172781. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172782. JSAMPROW indexptr;
  172783. int i,j,k, nci, blksize, val, pad;
  172784. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  172785. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  172786. * This is not necessary in the other dithering modes. However, we
  172787. * flag whether it was done in case user changes dithering mode.
  172788. */
  172789. if (cinfo->dither_mode == JDITHER_ORDERED) {
  172790. pad = MAXJSAMPLE*2;
  172791. cquantize->is_padded = TRUE;
  172792. } else {
  172793. pad = 0;
  172794. cquantize->is_padded = FALSE;
  172795. }
  172796. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  172797. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172798. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  172799. (JDIMENSION) cinfo->out_color_components);
  172800. /* blksize is number of adjacent repeated entries for a component */
  172801. blksize = cquantize->sv_actual;
  172802. for (i = 0; i < cinfo->out_color_components; i++) {
  172803. /* fill in colorindex entries for i'th color component */
  172804. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172805. blksize = blksize / nci;
  172806. /* adjust colorindex pointers to provide padding at negative indexes. */
  172807. if (pad)
  172808. cquantize->colorindex[i] += MAXJSAMPLE;
  172809. /* in loop, val = index of current output value, */
  172810. /* and k = largest j that maps to current val */
  172811. indexptr = cquantize->colorindex[i];
  172812. val = 0;
  172813. k = largest_input_value(cinfo, i, 0, nci-1);
  172814. for (j = 0; j <= MAXJSAMPLE; j++) {
  172815. while (j > k) /* advance val if past boundary */
  172816. k = largest_input_value(cinfo, i, ++val, nci-1);
  172817. /* premultiply so that no multiplication needed in main processing */
  172818. indexptr[j] = (JSAMPLE) (val * blksize);
  172819. }
  172820. /* Pad at both ends if necessary */
  172821. if (pad)
  172822. for (j = 1; j <= MAXJSAMPLE; j++) {
  172823. indexptr[-j] = indexptr[0];
  172824. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  172825. }
  172826. }
  172827. }
  172828. /*
  172829. * Create an ordered-dither array for a component having ncolors
  172830. * distinct output values.
  172831. */
  172832. LOCAL(ODITHER_MATRIX_PTR)
  172833. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  172834. {
  172835. ODITHER_MATRIX_PTR odither;
  172836. int j,k;
  172837. INT32 num,den;
  172838. odither = (ODITHER_MATRIX_PTR)
  172839. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172840. SIZEOF(ODITHER_MATRIX));
  172841. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  172842. * Hence the dither value for the matrix cell with fill order f
  172843. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  172844. * On 16-bit-int machine, be careful to avoid overflow.
  172845. */
  172846. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  172847. for (j = 0; j < ODITHER_SIZE; j++) {
  172848. for (k = 0; k < ODITHER_SIZE; k++) {
  172849. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  172850. * MAXJSAMPLE;
  172851. /* Ensure round towards zero despite C's lack of consistency
  172852. * about rounding negative values in integer division...
  172853. */
  172854. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  172855. }
  172856. }
  172857. return odither;
  172858. }
  172859. /*
  172860. * Create the ordered-dither tables.
  172861. * Components having the same number of representative colors may
  172862. * share a dither table.
  172863. */
  172864. LOCAL(void)
  172865. create_odither_tables (j_decompress_ptr cinfo)
  172866. {
  172867. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172868. ODITHER_MATRIX_PTR odither;
  172869. int i, j, nci;
  172870. for (i = 0; i < cinfo->out_color_components; i++) {
  172871. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  172872. odither = NULL; /* search for matching prior component */
  172873. for (j = 0; j < i; j++) {
  172874. if (nci == cquantize->Ncolors[j]) {
  172875. odither = cquantize->odither[j];
  172876. break;
  172877. }
  172878. }
  172879. if (odither == NULL) /* need a new table? */
  172880. odither = make_odither_array(cinfo, nci);
  172881. cquantize->odither[i] = odither;
  172882. }
  172883. }
  172884. /*
  172885. * Map some rows of pixels to the output colormapped representation.
  172886. */
  172887. METHODDEF(void)
  172888. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172889. JSAMPARRAY output_buf, int num_rows)
  172890. /* General case, no dithering */
  172891. {
  172892. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172893. JSAMPARRAY colorindex = cquantize->colorindex;
  172894. register int pixcode, ci;
  172895. register JSAMPROW ptrin, ptrout;
  172896. int row;
  172897. JDIMENSION col;
  172898. JDIMENSION width = cinfo->output_width;
  172899. register int nc = cinfo->out_color_components;
  172900. for (row = 0; row < num_rows; row++) {
  172901. ptrin = input_buf[row];
  172902. ptrout = output_buf[row];
  172903. for (col = width; col > 0; col--) {
  172904. pixcode = 0;
  172905. for (ci = 0; ci < nc; ci++) {
  172906. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  172907. }
  172908. *ptrout++ = (JSAMPLE) pixcode;
  172909. }
  172910. }
  172911. }
  172912. METHODDEF(void)
  172913. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172914. JSAMPARRAY output_buf, int num_rows)
  172915. /* Fast path for out_color_components==3, no dithering */
  172916. {
  172917. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172918. register int pixcode;
  172919. register JSAMPROW ptrin, ptrout;
  172920. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172921. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172922. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172923. int row;
  172924. JDIMENSION col;
  172925. JDIMENSION width = cinfo->output_width;
  172926. for (row = 0; row < num_rows; row++) {
  172927. ptrin = input_buf[row];
  172928. ptrout = output_buf[row];
  172929. for (col = width; col > 0; col--) {
  172930. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  172931. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  172932. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  172933. *ptrout++ = (JSAMPLE) pixcode;
  172934. }
  172935. }
  172936. }
  172937. METHODDEF(void)
  172938. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172939. JSAMPARRAY output_buf, int num_rows)
  172940. /* General case, with ordered dithering */
  172941. {
  172942. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172943. register JSAMPROW input_ptr;
  172944. register JSAMPROW output_ptr;
  172945. JSAMPROW colorindex_ci;
  172946. int * dither; /* points to active row of dither matrix */
  172947. int row_index, col_index; /* current indexes into dither matrix */
  172948. int nc = cinfo->out_color_components;
  172949. int ci;
  172950. int row;
  172951. JDIMENSION col;
  172952. JDIMENSION width = cinfo->output_width;
  172953. for (row = 0; row < num_rows; row++) {
  172954. /* Initialize output values to 0 so can process components separately */
  172955. jzero_far((void FAR *) output_buf[row],
  172956. (size_t) (width * SIZEOF(JSAMPLE)));
  172957. row_index = cquantize->row_index;
  172958. for (ci = 0; ci < nc; ci++) {
  172959. input_ptr = input_buf[row] + ci;
  172960. output_ptr = output_buf[row];
  172961. colorindex_ci = cquantize->colorindex[ci];
  172962. dither = cquantize->odither[ci][row_index];
  172963. col_index = 0;
  172964. for (col = width; col > 0; col--) {
  172965. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  172966. * select output value, accumulate into output code for this pixel.
  172967. * Range-limiting need not be done explicitly, as we have extended
  172968. * the colorindex table to produce the right answers for out-of-range
  172969. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  172970. * required amount of padding.
  172971. */
  172972. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  172973. input_ptr += nc;
  172974. output_ptr++;
  172975. col_index = (col_index + 1) & ODITHER_MASK;
  172976. }
  172977. }
  172978. /* Advance row index for next row */
  172979. row_index = (row_index + 1) & ODITHER_MASK;
  172980. cquantize->row_index = row_index;
  172981. }
  172982. }
  172983. METHODDEF(void)
  172984. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  172985. JSAMPARRAY output_buf, int num_rows)
  172986. /* Fast path for out_color_components==3, with ordered dithering */
  172987. {
  172988. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  172989. register int pixcode;
  172990. register JSAMPROW input_ptr;
  172991. register JSAMPROW output_ptr;
  172992. JSAMPROW colorindex0 = cquantize->colorindex[0];
  172993. JSAMPROW colorindex1 = cquantize->colorindex[1];
  172994. JSAMPROW colorindex2 = cquantize->colorindex[2];
  172995. int * dither0; /* points to active row of dither matrix */
  172996. int * dither1;
  172997. int * dither2;
  172998. int row_index, col_index; /* current indexes into dither matrix */
  172999. int row;
  173000. JDIMENSION col;
  173001. JDIMENSION width = cinfo->output_width;
  173002. for (row = 0; row < num_rows; row++) {
  173003. row_index = cquantize->row_index;
  173004. input_ptr = input_buf[row];
  173005. output_ptr = output_buf[row];
  173006. dither0 = cquantize->odither[0][row_index];
  173007. dither1 = cquantize->odither[1][row_index];
  173008. dither2 = cquantize->odither[2][row_index];
  173009. col_index = 0;
  173010. for (col = width; col > 0; col--) {
  173011. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  173012. dither0[col_index]]);
  173013. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  173014. dither1[col_index]]);
  173015. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  173016. dither2[col_index]]);
  173017. *output_ptr++ = (JSAMPLE) pixcode;
  173018. col_index = (col_index + 1) & ODITHER_MASK;
  173019. }
  173020. row_index = (row_index + 1) & ODITHER_MASK;
  173021. cquantize->row_index = row_index;
  173022. }
  173023. }
  173024. METHODDEF(void)
  173025. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173026. JSAMPARRAY output_buf, int num_rows)
  173027. /* General case, with Floyd-Steinberg dithering */
  173028. {
  173029. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173030. register LOCFSERROR cur; /* current error or pixel value */
  173031. LOCFSERROR belowerr; /* error for pixel below cur */
  173032. LOCFSERROR bpreverr; /* error for below/prev col */
  173033. LOCFSERROR bnexterr; /* error for below/next col */
  173034. LOCFSERROR delta;
  173035. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  173036. register JSAMPROW input_ptr;
  173037. register JSAMPROW output_ptr;
  173038. JSAMPROW colorindex_ci;
  173039. JSAMPROW colormap_ci;
  173040. int pixcode;
  173041. int nc = cinfo->out_color_components;
  173042. int dir; /* 1 for left-to-right, -1 for right-to-left */
  173043. int dirnc; /* dir * nc */
  173044. int ci;
  173045. int row;
  173046. JDIMENSION col;
  173047. JDIMENSION width = cinfo->output_width;
  173048. JSAMPLE *range_limit = cinfo->sample_range_limit;
  173049. SHIFT_TEMPS
  173050. for (row = 0; row < num_rows; row++) {
  173051. /* Initialize output values to 0 so can process components separately */
  173052. jzero_far((void FAR *) output_buf[row],
  173053. (size_t) (width * SIZEOF(JSAMPLE)));
  173054. for (ci = 0; ci < nc; ci++) {
  173055. input_ptr = input_buf[row] + ci;
  173056. output_ptr = output_buf[row];
  173057. if (cquantize->on_odd_row) {
  173058. /* work right to left in this row */
  173059. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  173060. output_ptr += width-1;
  173061. dir = -1;
  173062. dirnc = -nc;
  173063. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  173064. } else {
  173065. /* work left to right in this row */
  173066. dir = 1;
  173067. dirnc = nc;
  173068. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  173069. }
  173070. colorindex_ci = cquantize->colorindex[ci];
  173071. colormap_ci = cquantize->sv_colormap[ci];
  173072. /* Preset error values: no error propagated to first pixel from left */
  173073. cur = 0;
  173074. /* and no error propagated to row below yet */
  173075. belowerr = bpreverr = 0;
  173076. for (col = width; col > 0; col--) {
  173077. /* cur holds the error propagated from the previous pixel on the
  173078. * current line. Add the error propagated from the previous line
  173079. * to form the complete error correction term for this pixel, and
  173080. * round the error term (which is expressed * 16) to an integer.
  173081. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  173082. * for either sign of the error value.
  173083. * Note: errorptr points to *previous* column's array entry.
  173084. */
  173085. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  173086. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  173087. * The maximum error is +- MAXJSAMPLE; this sets the required size
  173088. * of the range_limit array.
  173089. */
  173090. cur += GETJSAMPLE(*input_ptr);
  173091. cur = GETJSAMPLE(range_limit[cur]);
  173092. /* Select output value, accumulate into output code for this pixel */
  173093. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  173094. *output_ptr += (JSAMPLE) pixcode;
  173095. /* Compute actual representation error at this pixel */
  173096. /* Note: we can do this even though we don't have the final */
  173097. /* pixel code, because the colormap is orthogonal. */
  173098. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  173099. /* Compute error fractions to be propagated to adjacent pixels.
  173100. * Add these into the running sums, and simultaneously shift the
  173101. * next-line error sums left by 1 column.
  173102. */
  173103. bnexterr = cur;
  173104. delta = cur * 2;
  173105. cur += delta; /* form error * 3 */
  173106. errorptr[0] = (FSERROR) (bpreverr + cur);
  173107. cur += delta; /* form error * 5 */
  173108. bpreverr = belowerr + cur;
  173109. belowerr = bnexterr;
  173110. cur += delta; /* form error * 7 */
  173111. /* At this point cur contains the 7/16 error value to be propagated
  173112. * to the next pixel on the current line, and all the errors for the
  173113. * next line have been shifted over. We are therefore ready to move on.
  173114. */
  173115. input_ptr += dirnc; /* advance input ptr to next column */
  173116. output_ptr += dir; /* advance output ptr to next column */
  173117. errorptr += dir; /* advance errorptr to current column */
  173118. }
  173119. /* Post-loop cleanup: we must unload the final error value into the
  173120. * final fserrors[] entry. Note we need not unload belowerr because
  173121. * it is for the dummy column before or after the actual array.
  173122. */
  173123. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  173124. }
  173125. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  173126. }
  173127. }
  173128. /*
  173129. * Allocate workspace for Floyd-Steinberg errors.
  173130. */
  173131. LOCAL(void)
  173132. alloc_fs_workspace (j_decompress_ptr cinfo)
  173133. {
  173134. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173135. size_t arraysize;
  173136. int i;
  173137. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173138. for (i = 0; i < cinfo->out_color_components; i++) {
  173139. cquantize->fserrors[i] = (FSERRPTR)
  173140. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  173141. }
  173142. }
  173143. /*
  173144. * Initialize for one-pass color quantization.
  173145. */
  173146. METHODDEF(void)
  173147. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  173148. {
  173149. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  173150. size_t arraysize;
  173151. int i;
  173152. /* Install my colormap. */
  173153. cinfo->colormap = cquantize->sv_colormap;
  173154. cinfo->actual_number_of_colors = cquantize->sv_actual;
  173155. /* Initialize for desired dithering mode. */
  173156. switch (cinfo->dither_mode) {
  173157. case JDITHER_NONE:
  173158. if (cinfo->out_color_components == 3)
  173159. cquantize->pub.color_quantize = color_quantize3;
  173160. else
  173161. cquantize->pub.color_quantize = color_quantize;
  173162. break;
  173163. case JDITHER_ORDERED:
  173164. if (cinfo->out_color_components == 3)
  173165. cquantize->pub.color_quantize = quantize3_ord_dither;
  173166. else
  173167. cquantize->pub.color_quantize = quantize_ord_dither;
  173168. cquantize->row_index = 0; /* initialize state for ordered dither */
  173169. /* If user changed to ordered dither from another mode,
  173170. * we must recreate the color index table with padding.
  173171. * This will cost extra space, but probably isn't very likely.
  173172. */
  173173. if (! cquantize->is_padded)
  173174. create_colorindex(cinfo);
  173175. /* Create ordered-dither tables if we didn't already. */
  173176. if (cquantize->odither[0] == NULL)
  173177. create_odither_tables(cinfo);
  173178. break;
  173179. case JDITHER_FS:
  173180. cquantize->pub.color_quantize = quantize_fs_dither;
  173181. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  173182. /* Allocate Floyd-Steinberg workspace if didn't already. */
  173183. if (cquantize->fserrors[0] == NULL)
  173184. alloc_fs_workspace(cinfo);
  173185. /* Initialize the propagated errors to zero. */
  173186. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  173187. for (i = 0; i < cinfo->out_color_components; i++)
  173188. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  173189. break;
  173190. default:
  173191. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173192. break;
  173193. }
  173194. }
  173195. /*
  173196. * Finish up at the end of the pass.
  173197. */
  173198. METHODDEF(void)
  173199. finish_pass_1_quant (j_decompress_ptr cinfo)
  173200. {
  173201. /* no work in 1-pass case */
  173202. }
  173203. /*
  173204. * Switch to a new external colormap between output passes.
  173205. * Shouldn't get to this module!
  173206. */
  173207. METHODDEF(void)
  173208. new_color_map_1_quant (j_decompress_ptr cinfo)
  173209. {
  173210. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173211. }
  173212. /*
  173213. * Module initialization routine for 1-pass color quantization.
  173214. */
  173215. GLOBAL(void)
  173216. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  173217. {
  173218. my_cquantize_ptr cquantize;
  173219. cquantize = (my_cquantize_ptr)
  173220. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173221. SIZEOF(my_cquantizer));
  173222. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  173223. cquantize->pub.start_pass = start_pass_1_quant;
  173224. cquantize->pub.finish_pass = finish_pass_1_quant;
  173225. cquantize->pub.new_color_map = new_color_map_1_quant;
  173226. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  173227. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  173228. /* Make sure my internal arrays won't overflow */
  173229. if (cinfo->out_color_components > MAX_Q_COMPS)
  173230. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  173231. /* Make sure colormap indexes can be represented by JSAMPLEs */
  173232. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  173233. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  173234. /* Create the colormap and color index table. */
  173235. create_colormap(cinfo);
  173236. create_colorindex(cinfo);
  173237. /* Allocate Floyd-Steinberg workspace now if requested.
  173238. * We do this now since it is FAR storage and may affect the memory
  173239. * manager's space calculations. If the user changes to FS dither
  173240. * mode in a later pass, we will allocate the space then, and will
  173241. * possibly overrun the max_memory_to_use setting.
  173242. */
  173243. if (cinfo->dither_mode == JDITHER_FS)
  173244. alloc_fs_workspace(cinfo);
  173245. }
  173246. #endif /* QUANT_1PASS_SUPPORTED */
  173247. /********* End of inlined file: jquant1.c *********/
  173248. /********* Start of inlined file: jquant2.c *********/
  173249. #define JPEG_INTERNALS
  173250. #ifdef QUANT_2PASS_SUPPORTED
  173251. /*
  173252. * This module implements the well-known Heckbert paradigm for color
  173253. * quantization. Most of the ideas used here can be traced back to
  173254. * Heckbert's seminal paper
  173255. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  173256. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  173257. *
  173258. * In the first pass over the image, we accumulate a histogram showing the
  173259. * usage count of each possible color. To keep the histogram to a reasonable
  173260. * size, we reduce the precision of the input; typical practice is to retain
  173261. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  173262. * in the same histogram cell.
  173263. *
  173264. * Next, the color-selection step begins with a box representing the whole
  173265. * color space, and repeatedly splits the "largest" remaining box until we
  173266. * have as many boxes as desired colors. Then the mean color in each
  173267. * remaining box becomes one of the possible output colors.
  173268. *
  173269. * The second pass over the image maps each input pixel to the closest output
  173270. * color (optionally after applying a Floyd-Steinberg dithering correction).
  173271. * This mapping is logically trivial, but making it go fast enough requires
  173272. * considerable care.
  173273. *
  173274. * Heckbert-style quantizers vary a good deal in their policies for choosing
  173275. * the "largest" box and deciding where to cut it. The particular policies
  173276. * used here have proved out well in experimental comparisons, but better ones
  173277. * may yet be found.
  173278. *
  173279. * In earlier versions of the IJG code, this module quantized in YCbCr color
  173280. * space, processing the raw upsampled data without a color conversion step.
  173281. * This allowed the color conversion math to be done only once per colormap
  173282. * entry, not once per pixel. However, that optimization precluded other
  173283. * useful optimizations (such as merging color conversion with upsampling)
  173284. * and it also interfered with desired capabilities such as quantizing to an
  173285. * externally-supplied colormap. We have therefore abandoned that approach.
  173286. * The present code works in the post-conversion color space, typically RGB.
  173287. *
  173288. * To improve the visual quality of the results, we actually work in scaled
  173289. * RGB space, giving G distances more weight than R, and R in turn more than
  173290. * B. To do everything in integer math, we must use integer scale factors.
  173291. * The 2/3/1 scale factors used here correspond loosely to the relative
  173292. * weights of the colors in the NTSC grayscale equation.
  173293. * If you want to use this code to quantize a non-RGB color space, you'll
  173294. * probably need to change these scale factors.
  173295. */
  173296. #define R_SCALE 2 /* scale R distances by this much */
  173297. #define G_SCALE 3 /* scale G distances by this much */
  173298. #define B_SCALE 1 /* and B by this much */
  173299. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  173300. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  173301. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  173302. * you'll get compile errors until you extend this logic. In that case
  173303. * you'll probably want to tweak the histogram sizes too.
  173304. */
  173305. #if RGB_RED == 0
  173306. #define C0_SCALE R_SCALE
  173307. #endif
  173308. #if RGB_BLUE == 0
  173309. #define C0_SCALE B_SCALE
  173310. #endif
  173311. #if RGB_GREEN == 1
  173312. #define C1_SCALE G_SCALE
  173313. #endif
  173314. #if RGB_RED == 2
  173315. #define C2_SCALE R_SCALE
  173316. #endif
  173317. #if RGB_BLUE == 2
  173318. #define C2_SCALE B_SCALE
  173319. #endif
  173320. /*
  173321. * First we have the histogram data structure and routines for creating it.
  173322. *
  173323. * The number of bits of precision can be adjusted by changing these symbols.
  173324. * We recommend keeping 6 bits for G and 5 each for R and B.
  173325. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  173326. * better results; if you are short of memory, 5 bits all around will save
  173327. * some space but degrade the results.
  173328. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  173329. * (preferably unsigned long) for each cell. In practice this is overkill;
  173330. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  173331. * and clamping those that do overflow to the maximum value will give close-
  173332. * enough results. This reduces the recommended histogram size from 256Kb
  173333. * to 128Kb, which is a useful savings on PC-class machines.
  173334. * (In the second pass the histogram space is re-used for pixel mapping data;
  173335. * in that capacity, each cell must be able to store zero to the number of
  173336. * desired colors. 16 bits/cell is plenty for that too.)
  173337. * Since the JPEG code is intended to run in small memory model on 80x86
  173338. * machines, we can't just allocate the histogram in one chunk. Instead
  173339. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  173340. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  173341. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  173342. * on 80x86 machines, the pointer row is in near memory but the actual
  173343. * arrays are in far memory (same arrangement as we use for image arrays).
  173344. */
  173345. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  173346. /* These will do the right thing for either R,G,B or B,G,R color order,
  173347. * but you may not like the results for other color orders.
  173348. */
  173349. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  173350. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  173351. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  173352. /* Number of elements along histogram axes. */
  173353. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  173354. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  173355. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  173356. /* These are the amounts to shift an input value to get a histogram index. */
  173357. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  173358. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  173359. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  173360. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  173361. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  173362. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  173363. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  173364. typedef hist2d * hist3d; /* type for top-level pointer */
  173365. /* Declarations for Floyd-Steinberg dithering.
  173366. *
  173367. * Errors are accumulated into the array fserrors[], at a resolution of
  173368. * 1/16th of a pixel count. The error at a given pixel is propagated
  173369. * to its not-yet-processed neighbors using the standard F-S fractions,
  173370. * ... (here) 7/16
  173371. * 3/16 5/16 1/16
  173372. * We work left-to-right on even rows, right-to-left on odd rows.
  173373. *
  173374. * We can get away with a single array (holding one row's worth of errors)
  173375. * by using it to store the current row's errors at pixel columns not yet
  173376. * processed, but the next row's errors at columns already processed. We
  173377. * need only a few extra variables to hold the errors immediately around the
  173378. * current column. (If we are lucky, those variables are in registers, but
  173379. * even if not, they're probably cheaper to access than array elements are.)
  173380. *
  173381. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  173382. * each end saves us from special-casing the first and last pixels.
  173383. * Each entry is three values long, one value for each color component.
  173384. *
  173385. * Note: on a wide image, we might not have enough room in a PC's near data
  173386. * segment to hold the error array; so it is allocated with alloc_large.
  173387. */
  173388. #if BITS_IN_JSAMPLE == 8
  173389. typedef INT16 FSERROR; /* 16 bits should be enough */
  173390. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  173391. #else
  173392. typedef INT32 FSERROR; /* may need more than 16 bits */
  173393. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  173394. #endif
  173395. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  173396. /* Private subobject */
  173397. typedef struct {
  173398. struct jpeg_color_quantizer pub; /* public fields */
  173399. /* Space for the eventually created colormap is stashed here */
  173400. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  173401. int desired; /* desired # of colors = size of colormap */
  173402. /* Variables for accumulating image statistics */
  173403. hist3d histogram; /* pointer to the histogram */
  173404. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  173405. /* Variables for Floyd-Steinberg dithering */
  173406. FSERRPTR fserrors; /* accumulated errors */
  173407. boolean on_odd_row; /* flag to remember which row we are on */
  173408. int * error_limiter; /* table for clamping the applied error */
  173409. } my_cquantizer2;
  173410. typedef my_cquantizer2 * my_cquantize_ptr2;
  173411. /*
  173412. * Prescan some rows of pixels.
  173413. * In this module the prescan simply updates the histogram, which has been
  173414. * initialized to zeroes by start_pass.
  173415. * An output_buf parameter is required by the method signature, but no data
  173416. * is actually output (in fact the buffer controller is probably passing a
  173417. * NULL pointer).
  173418. */
  173419. METHODDEF(void)
  173420. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  173421. JSAMPARRAY output_buf, int num_rows)
  173422. {
  173423. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173424. register JSAMPROW ptr;
  173425. register histptr histp;
  173426. register hist3d histogram = cquantize->histogram;
  173427. int row;
  173428. JDIMENSION col;
  173429. JDIMENSION width = cinfo->output_width;
  173430. for (row = 0; row < num_rows; row++) {
  173431. ptr = input_buf[row];
  173432. for (col = width; col > 0; col--) {
  173433. /* get pixel value and index into the histogram */
  173434. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  173435. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  173436. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  173437. /* increment, check for overflow and undo increment if so. */
  173438. if (++(*histp) <= 0)
  173439. (*histp)--;
  173440. ptr += 3;
  173441. }
  173442. }
  173443. }
  173444. /*
  173445. * Next we have the really interesting routines: selection of a colormap
  173446. * given the completed histogram.
  173447. * These routines work with a list of "boxes", each representing a rectangular
  173448. * subset of the input color space (to histogram precision).
  173449. */
  173450. typedef struct {
  173451. /* The bounds of the box (inclusive); expressed as histogram indexes */
  173452. int c0min, c0max;
  173453. int c1min, c1max;
  173454. int c2min, c2max;
  173455. /* The volume (actually 2-norm) of the box */
  173456. INT32 volume;
  173457. /* The number of nonzero histogram cells within this box */
  173458. long colorcount;
  173459. } box;
  173460. typedef box * boxptr;
  173461. LOCAL(boxptr)
  173462. find_biggest_color_pop (boxptr boxlist, int numboxes)
  173463. /* Find the splittable box with the largest color population */
  173464. /* Returns NULL if no splittable boxes remain */
  173465. {
  173466. register boxptr boxp;
  173467. register int i;
  173468. register long maxc = 0;
  173469. boxptr which = NULL;
  173470. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173471. if (boxp->colorcount > maxc && boxp->volume > 0) {
  173472. which = boxp;
  173473. maxc = boxp->colorcount;
  173474. }
  173475. }
  173476. return which;
  173477. }
  173478. LOCAL(boxptr)
  173479. find_biggest_volume (boxptr boxlist, int numboxes)
  173480. /* Find the splittable box with the largest (scaled) volume */
  173481. /* Returns NULL if no splittable boxes remain */
  173482. {
  173483. register boxptr boxp;
  173484. register int i;
  173485. register INT32 maxv = 0;
  173486. boxptr which = NULL;
  173487. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  173488. if (boxp->volume > maxv) {
  173489. which = boxp;
  173490. maxv = boxp->volume;
  173491. }
  173492. }
  173493. return which;
  173494. }
  173495. LOCAL(void)
  173496. update_box (j_decompress_ptr cinfo, boxptr boxp)
  173497. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  173498. /* and recompute its volume and population */
  173499. {
  173500. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173501. hist3d histogram = cquantize->histogram;
  173502. histptr histp;
  173503. int c0,c1,c2;
  173504. int c0min,c0max,c1min,c1max,c2min,c2max;
  173505. INT32 dist0,dist1,dist2;
  173506. long ccount;
  173507. c0min = boxp->c0min; c0max = boxp->c0max;
  173508. c1min = boxp->c1min; c1max = boxp->c1max;
  173509. c2min = boxp->c2min; c2max = boxp->c2max;
  173510. if (c0max > c0min)
  173511. for (c0 = c0min; c0 <= c0max; c0++)
  173512. for (c1 = c1min; c1 <= c1max; c1++) {
  173513. histp = & histogram[c0][c1][c2min];
  173514. for (c2 = c2min; c2 <= c2max; c2++)
  173515. if (*histp++ != 0) {
  173516. boxp->c0min = c0min = c0;
  173517. goto have_c0min;
  173518. }
  173519. }
  173520. have_c0min:
  173521. if (c0max > c0min)
  173522. for (c0 = c0max; c0 >= c0min; c0--)
  173523. for (c1 = c1min; c1 <= c1max; c1++) {
  173524. histp = & histogram[c0][c1][c2min];
  173525. for (c2 = c2min; c2 <= c2max; c2++)
  173526. if (*histp++ != 0) {
  173527. boxp->c0max = c0max = c0;
  173528. goto have_c0max;
  173529. }
  173530. }
  173531. have_c0max:
  173532. if (c1max > c1min)
  173533. for (c1 = c1min; c1 <= c1max; c1++)
  173534. for (c0 = c0min; c0 <= c0max; c0++) {
  173535. histp = & histogram[c0][c1][c2min];
  173536. for (c2 = c2min; c2 <= c2max; c2++)
  173537. if (*histp++ != 0) {
  173538. boxp->c1min = c1min = c1;
  173539. goto have_c1min;
  173540. }
  173541. }
  173542. have_c1min:
  173543. if (c1max > c1min)
  173544. for (c1 = c1max; c1 >= c1min; c1--)
  173545. for (c0 = c0min; c0 <= c0max; c0++) {
  173546. histp = & histogram[c0][c1][c2min];
  173547. for (c2 = c2min; c2 <= c2max; c2++)
  173548. if (*histp++ != 0) {
  173549. boxp->c1max = c1max = c1;
  173550. goto have_c1max;
  173551. }
  173552. }
  173553. have_c1max:
  173554. if (c2max > c2min)
  173555. for (c2 = c2min; c2 <= c2max; c2++)
  173556. for (c0 = c0min; c0 <= c0max; c0++) {
  173557. histp = & histogram[c0][c1min][c2];
  173558. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173559. if (*histp != 0) {
  173560. boxp->c2min = c2min = c2;
  173561. goto have_c2min;
  173562. }
  173563. }
  173564. have_c2min:
  173565. if (c2max > c2min)
  173566. for (c2 = c2max; c2 >= c2min; c2--)
  173567. for (c0 = c0min; c0 <= c0max; c0++) {
  173568. histp = & histogram[c0][c1min][c2];
  173569. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  173570. if (*histp != 0) {
  173571. boxp->c2max = c2max = c2;
  173572. goto have_c2max;
  173573. }
  173574. }
  173575. have_c2max:
  173576. /* Update box volume.
  173577. * We use 2-norm rather than real volume here; this biases the method
  173578. * against making long narrow boxes, and it has the side benefit that
  173579. * a box is splittable iff norm > 0.
  173580. * Since the differences are expressed in histogram-cell units,
  173581. * we have to shift back to JSAMPLE units to get consistent distances;
  173582. * after which, we scale according to the selected distance scale factors.
  173583. */
  173584. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  173585. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  173586. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  173587. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  173588. /* Now scan remaining volume of box and compute population */
  173589. ccount = 0;
  173590. for (c0 = c0min; c0 <= c0max; c0++)
  173591. for (c1 = c1min; c1 <= c1max; c1++) {
  173592. histp = & histogram[c0][c1][c2min];
  173593. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  173594. if (*histp != 0) {
  173595. ccount++;
  173596. }
  173597. }
  173598. boxp->colorcount = ccount;
  173599. }
  173600. LOCAL(int)
  173601. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  173602. int desired_colors)
  173603. /* Repeatedly select and split the largest box until we have enough boxes */
  173604. {
  173605. int n,lb;
  173606. int c0,c1,c2,cmax;
  173607. register boxptr b1,b2;
  173608. while (numboxes < desired_colors) {
  173609. /* Select box to split.
  173610. * Current algorithm: by population for first half, then by volume.
  173611. */
  173612. if (numboxes*2 <= desired_colors) {
  173613. b1 = find_biggest_color_pop(boxlist, numboxes);
  173614. } else {
  173615. b1 = find_biggest_volume(boxlist, numboxes);
  173616. }
  173617. if (b1 == NULL) /* no splittable boxes left! */
  173618. break;
  173619. b2 = &boxlist[numboxes]; /* where new box will go */
  173620. /* Copy the color bounds to the new box. */
  173621. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  173622. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  173623. /* Choose which axis to split the box on.
  173624. * Current algorithm: longest scaled axis.
  173625. * See notes in update_box about scaling distances.
  173626. */
  173627. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  173628. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  173629. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  173630. /* We want to break any ties in favor of green, then red, blue last.
  173631. * This code does the right thing for R,G,B or B,G,R color orders only.
  173632. */
  173633. #if RGB_RED == 0
  173634. cmax = c1; n = 1;
  173635. if (c0 > cmax) { cmax = c0; n = 0; }
  173636. if (c2 > cmax) { n = 2; }
  173637. #else
  173638. cmax = c1; n = 1;
  173639. if (c2 > cmax) { cmax = c2; n = 2; }
  173640. if (c0 > cmax) { n = 0; }
  173641. #endif
  173642. /* Choose split point along selected axis, and update box bounds.
  173643. * Current algorithm: split at halfway point.
  173644. * (Since the box has been shrunk to minimum volume,
  173645. * any split will produce two nonempty subboxes.)
  173646. * Note that lb value is max for lower box, so must be < old max.
  173647. */
  173648. switch (n) {
  173649. case 0:
  173650. lb = (b1->c0max + b1->c0min) / 2;
  173651. b1->c0max = lb;
  173652. b2->c0min = lb+1;
  173653. break;
  173654. case 1:
  173655. lb = (b1->c1max + b1->c1min) / 2;
  173656. b1->c1max = lb;
  173657. b2->c1min = lb+1;
  173658. break;
  173659. case 2:
  173660. lb = (b1->c2max + b1->c2min) / 2;
  173661. b1->c2max = lb;
  173662. b2->c2min = lb+1;
  173663. break;
  173664. }
  173665. /* Update stats for boxes */
  173666. update_box(cinfo, b1);
  173667. update_box(cinfo, b2);
  173668. numboxes++;
  173669. }
  173670. return numboxes;
  173671. }
  173672. LOCAL(void)
  173673. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  173674. /* Compute representative color for a box, put it in colormap[icolor] */
  173675. {
  173676. /* Current algorithm: mean weighted by pixels (not colors) */
  173677. /* Note it is important to get the rounding correct! */
  173678. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  173679. hist3d histogram = cquantize->histogram;
  173680. histptr histp;
  173681. int c0,c1,c2;
  173682. int c0min,c0max,c1min,c1max,c2min,c2max;
  173683. long count;
  173684. long total = 0;
  173685. long c0total = 0;
  173686. long c1total = 0;
  173687. long c2total = 0;
  173688. c0min = boxp->c0min; c0max = boxp->c0max;
  173689. c1min = boxp->c1min; c1max = boxp->c1max;
  173690. c2min = boxp->c2min; c2max = boxp->c2max;
  173691. for (c0 = c0min; c0 <= c0max; c0++)
  173692. for (c1 = c1min; c1 <= c1max; c1++) {
  173693. histp = & histogram[c0][c1][c2min];
  173694. for (c2 = c2min; c2 <= c2max; c2++) {
  173695. if ((count = *histp++) != 0) {
  173696. total += count;
  173697. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  173698. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  173699. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  173700. }
  173701. }
  173702. }
  173703. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  173704. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  173705. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  173706. }
  173707. LOCAL(void)
  173708. select_colors (j_decompress_ptr cinfo, int desired_colors)
  173709. /* Master routine for color selection */
  173710. {
  173711. boxptr boxlist;
  173712. int numboxes;
  173713. int i;
  173714. /* Allocate workspace for box list */
  173715. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  173716. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  173717. /* Initialize one box containing whole space */
  173718. numboxes = 1;
  173719. boxlist[0].c0min = 0;
  173720. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  173721. boxlist[0].c1min = 0;
  173722. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  173723. boxlist[0].c2min = 0;
  173724. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  173725. /* Shrink it to actually-used volume and set its statistics */
  173726. update_box(cinfo, & boxlist[0]);
  173727. /* Perform median-cut to produce final box list */
  173728. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  173729. /* Compute the representative color for each box, fill colormap */
  173730. for (i = 0; i < numboxes; i++)
  173731. compute_color(cinfo, & boxlist[i], i);
  173732. cinfo->actual_number_of_colors = numboxes;
  173733. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  173734. }
  173735. /*
  173736. * These routines are concerned with the time-critical task of mapping input
  173737. * colors to the nearest color in the selected colormap.
  173738. *
  173739. * We re-use the histogram space as an "inverse color map", essentially a
  173740. * cache for the results of nearest-color searches. All colors within a
  173741. * histogram cell will be mapped to the same colormap entry, namely the one
  173742. * closest to the cell's center. This may not be quite the closest entry to
  173743. * the actual input color, but it's almost as good. A zero in the cache
  173744. * indicates we haven't found the nearest color for that cell yet; the array
  173745. * is cleared to zeroes before starting the mapping pass. When we find the
  173746. * nearest color for a cell, its colormap index plus one is recorded in the
  173747. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  173748. * when they need to use an unfilled entry in the cache.
  173749. *
  173750. * Our method of efficiently finding nearest colors is based on the "locally
  173751. * sorted search" idea described by Heckbert and on the incremental distance
  173752. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  173753. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  173754. * the distances from a given colormap entry to each cell of the histogram can
  173755. * be computed quickly using an incremental method: the differences between
  173756. * distances to adjacent cells themselves differ by a constant. This allows a
  173757. * fairly fast implementation of the "brute force" approach of computing the
  173758. * distance from every colormap entry to every histogram cell. Unfortunately,
  173759. * it needs a work array to hold the best-distance-so-far for each histogram
  173760. * cell (because the inner loop has to be over cells, not colormap entries).
  173761. * The work array elements have to be INT32s, so the work array would need
  173762. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  173763. *
  173764. * To get around these problems, we apply Thomas' method to compute the
  173765. * nearest colors for only the cells within a small subbox of the histogram.
  173766. * The work array need be only as big as the subbox, so the memory usage
  173767. * problem is solved. Furthermore, we need not fill subboxes that are never
  173768. * referenced in pass2; many images use only part of the color gamut, so a
  173769. * fair amount of work is saved. An additional advantage of this
  173770. * approach is that we can apply Heckbert's locality criterion to quickly
  173771. * eliminate colormap entries that are far away from the subbox; typically
  173772. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  173773. * and we need not compute their distances to individual cells in the subbox.
  173774. * The speed of this approach is heavily influenced by the subbox size: too
  173775. * small means too much overhead, too big loses because Heckbert's criterion
  173776. * can't eliminate as many colormap entries. Empirically the best subbox
  173777. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  173778. *
  173779. * Thomas' article also describes a refined method which is asymptotically
  173780. * faster than the brute-force method, but it is also far more complex and
  173781. * cannot efficiently be applied to small subboxes. It is therefore not
  173782. * useful for programs intended to be portable to DOS machines. On machines
  173783. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  173784. * refined method might be faster than the present code --- but then again,
  173785. * it might not be any faster, and it's certainly more complicated.
  173786. */
  173787. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  173788. #define BOX_C0_LOG (HIST_C0_BITS-3)
  173789. #define BOX_C1_LOG (HIST_C1_BITS-3)
  173790. #define BOX_C2_LOG (HIST_C2_BITS-3)
  173791. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  173792. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  173793. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  173794. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  173795. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  173796. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  173797. /*
  173798. * The next three routines implement inverse colormap filling. They could
  173799. * all be folded into one big routine, but splitting them up this way saves
  173800. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  173801. * and may allow some compilers to produce better code by registerizing more
  173802. * inner-loop variables.
  173803. */
  173804. LOCAL(int)
  173805. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173806. JSAMPLE colorlist[])
  173807. /* Locate the colormap entries close enough to an update box to be candidates
  173808. * for the nearest entry to some cell(s) in the update box. The update box
  173809. * is specified by the center coordinates of its first cell. The number of
  173810. * candidate colormap entries is returned, and their colormap indexes are
  173811. * placed in colorlist[].
  173812. * This routine uses Heckbert's "locally sorted search" criterion to select
  173813. * the colors that need further consideration.
  173814. */
  173815. {
  173816. int numcolors = cinfo->actual_number_of_colors;
  173817. int maxc0, maxc1, maxc2;
  173818. int centerc0, centerc1, centerc2;
  173819. int i, x, ncolors;
  173820. INT32 minmaxdist, min_dist, max_dist, tdist;
  173821. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  173822. /* Compute true coordinates of update box's upper corner and center.
  173823. * Actually we compute the coordinates of the center of the upper-corner
  173824. * histogram cell, which are the upper bounds of the volume we care about.
  173825. * Note that since ">>" rounds down, the "center" values may be closer to
  173826. * min than to max; hence comparisons to them must be "<=", not "<".
  173827. */
  173828. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  173829. centerc0 = (minc0 + maxc0) >> 1;
  173830. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  173831. centerc1 = (minc1 + maxc1) >> 1;
  173832. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  173833. centerc2 = (minc2 + maxc2) >> 1;
  173834. /* For each color in colormap, find:
  173835. * 1. its minimum squared-distance to any point in the update box
  173836. * (zero if color is within update box);
  173837. * 2. its maximum squared-distance to any point in the update box.
  173838. * Both of these can be found by considering only the corners of the box.
  173839. * We save the minimum distance for each color in mindist[];
  173840. * only the smallest maximum distance is of interest.
  173841. */
  173842. minmaxdist = 0x7FFFFFFFL;
  173843. for (i = 0; i < numcolors; i++) {
  173844. /* We compute the squared-c0-distance term, then add in the other two. */
  173845. x = GETJSAMPLE(cinfo->colormap[0][i]);
  173846. if (x < minc0) {
  173847. tdist = (x - minc0) * C0_SCALE;
  173848. min_dist = tdist*tdist;
  173849. tdist = (x - maxc0) * C0_SCALE;
  173850. max_dist = tdist*tdist;
  173851. } else if (x > maxc0) {
  173852. tdist = (x - maxc0) * C0_SCALE;
  173853. min_dist = tdist*tdist;
  173854. tdist = (x - minc0) * C0_SCALE;
  173855. max_dist = tdist*tdist;
  173856. } else {
  173857. /* within cell range so no contribution to min_dist */
  173858. min_dist = 0;
  173859. if (x <= centerc0) {
  173860. tdist = (x - maxc0) * C0_SCALE;
  173861. max_dist = tdist*tdist;
  173862. } else {
  173863. tdist = (x - minc0) * C0_SCALE;
  173864. max_dist = tdist*tdist;
  173865. }
  173866. }
  173867. x = GETJSAMPLE(cinfo->colormap[1][i]);
  173868. if (x < minc1) {
  173869. tdist = (x - minc1) * C1_SCALE;
  173870. min_dist += tdist*tdist;
  173871. tdist = (x - maxc1) * C1_SCALE;
  173872. max_dist += tdist*tdist;
  173873. } else if (x > maxc1) {
  173874. tdist = (x - maxc1) * C1_SCALE;
  173875. min_dist += tdist*tdist;
  173876. tdist = (x - minc1) * C1_SCALE;
  173877. max_dist += tdist*tdist;
  173878. } else {
  173879. /* within cell range so no contribution to min_dist */
  173880. if (x <= centerc1) {
  173881. tdist = (x - maxc1) * C1_SCALE;
  173882. max_dist += tdist*tdist;
  173883. } else {
  173884. tdist = (x - minc1) * C1_SCALE;
  173885. max_dist += tdist*tdist;
  173886. }
  173887. }
  173888. x = GETJSAMPLE(cinfo->colormap[2][i]);
  173889. if (x < minc2) {
  173890. tdist = (x - minc2) * C2_SCALE;
  173891. min_dist += tdist*tdist;
  173892. tdist = (x - maxc2) * C2_SCALE;
  173893. max_dist += tdist*tdist;
  173894. } else if (x > maxc2) {
  173895. tdist = (x - maxc2) * C2_SCALE;
  173896. min_dist += tdist*tdist;
  173897. tdist = (x - minc2) * C2_SCALE;
  173898. max_dist += tdist*tdist;
  173899. } else {
  173900. /* within cell range so no contribution to min_dist */
  173901. if (x <= centerc2) {
  173902. tdist = (x - maxc2) * C2_SCALE;
  173903. max_dist += tdist*tdist;
  173904. } else {
  173905. tdist = (x - minc2) * C2_SCALE;
  173906. max_dist += tdist*tdist;
  173907. }
  173908. }
  173909. mindist[i] = min_dist; /* save away the results */
  173910. if (max_dist < minmaxdist)
  173911. minmaxdist = max_dist;
  173912. }
  173913. /* Now we know that no cell in the update box is more than minmaxdist
  173914. * away from some colormap entry. Therefore, only colors that are
  173915. * within minmaxdist of some part of the box need be considered.
  173916. */
  173917. ncolors = 0;
  173918. for (i = 0; i < numcolors; i++) {
  173919. if (mindist[i] <= minmaxdist)
  173920. colorlist[ncolors++] = (JSAMPLE) i;
  173921. }
  173922. return ncolors;
  173923. }
  173924. LOCAL(void)
  173925. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  173926. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  173927. /* Find the closest colormap entry for each cell in the update box,
  173928. * given the list of candidate colors prepared by find_nearby_colors.
  173929. * Return the indexes of the closest entries in the bestcolor[] array.
  173930. * This routine uses Thomas' incremental distance calculation method to
  173931. * find the distance from a colormap entry to successive cells in the box.
  173932. */
  173933. {
  173934. int ic0, ic1, ic2;
  173935. int i, icolor;
  173936. register INT32 * bptr; /* pointer into bestdist[] array */
  173937. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  173938. INT32 dist0, dist1; /* initial distance values */
  173939. register INT32 dist2; /* current distance in inner loop */
  173940. INT32 xx0, xx1; /* distance increments */
  173941. register INT32 xx2;
  173942. INT32 inc0, inc1, inc2; /* initial values for increments */
  173943. /* This array holds the distance to the nearest-so-far color for each cell */
  173944. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  173945. /* Initialize best-distance for each cell of the update box */
  173946. bptr = bestdist;
  173947. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  173948. *bptr++ = 0x7FFFFFFFL;
  173949. /* For each color selected by find_nearby_colors,
  173950. * compute its distance to the center of each cell in the box.
  173951. * If that's less than best-so-far, update best distance and color number.
  173952. */
  173953. /* Nominal steps between cell centers ("x" in Thomas article) */
  173954. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  173955. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  173956. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  173957. for (i = 0; i < numcolors; i++) {
  173958. icolor = GETJSAMPLE(colorlist[i]);
  173959. /* Compute (square of) distance from minc0/c1/c2 to this color */
  173960. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  173961. dist0 = inc0*inc0;
  173962. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  173963. dist0 += inc1*inc1;
  173964. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  173965. dist0 += inc2*inc2;
  173966. /* Form the initial difference increments */
  173967. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  173968. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  173969. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  173970. /* Now loop over all cells in box, updating distance per Thomas method */
  173971. bptr = bestdist;
  173972. cptr = bestcolor;
  173973. xx0 = inc0;
  173974. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  173975. dist1 = dist0;
  173976. xx1 = inc1;
  173977. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  173978. dist2 = dist1;
  173979. xx2 = inc2;
  173980. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  173981. if (dist2 < *bptr) {
  173982. *bptr = dist2;
  173983. *cptr = (JSAMPLE) icolor;
  173984. }
  173985. dist2 += xx2;
  173986. xx2 += 2 * STEP_C2 * STEP_C2;
  173987. bptr++;
  173988. cptr++;
  173989. }
  173990. dist1 += xx1;
  173991. xx1 += 2 * STEP_C1 * STEP_C1;
  173992. }
  173993. dist0 += xx0;
  173994. xx0 += 2 * STEP_C0 * STEP_C0;
  173995. }
  173996. }
  173997. }
  173998. LOCAL(void)
  173999. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  174000. /* Fill the inverse-colormap entries in the update box that contains */
  174001. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  174002. /* we can fill as many others as we wish.) */
  174003. {
  174004. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174005. hist3d histogram = cquantize->histogram;
  174006. int minc0, minc1, minc2; /* lower left corner of update box */
  174007. int ic0, ic1, ic2;
  174008. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  174009. register histptr cachep; /* pointer into main cache array */
  174010. /* This array lists the candidate colormap indexes. */
  174011. JSAMPLE colorlist[MAXNUMCOLORS];
  174012. int numcolors; /* number of candidate colors */
  174013. /* This array holds the actually closest colormap index for each cell. */
  174014. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  174015. /* Convert cell coordinates to update box ID */
  174016. c0 >>= BOX_C0_LOG;
  174017. c1 >>= BOX_C1_LOG;
  174018. c2 >>= BOX_C2_LOG;
  174019. /* Compute true coordinates of update box's origin corner.
  174020. * Actually we compute the coordinates of the center of the corner
  174021. * histogram cell, which are the lower bounds of the volume we care about.
  174022. */
  174023. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  174024. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  174025. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  174026. /* Determine which colormap entries are close enough to be candidates
  174027. * for the nearest entry to some cell in the update box.
  174028. */
  174029. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  174030. /* Determine the actually nearest colors. */
  174031. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  174032. bestcolor);
  174033. /* Save the best color numbers (plus 1) in the main cache array */
  174034. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  174035. c1 <<= BOX_C1_LOG;
  174036. c2 <<= BOX_C2_LOG;
  174037. cptr = bestcolor;
  174038. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  174039. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  174040. cachep = & histogram[c0+ic0][c1+ic1][c2];
  174041. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  174042. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  174043. }
  174044. }
  174045. }
  174046. }
  174047. /*
  174048. * Map some rows of pixels to the output colormapped representation.
  174049. */
  174050. METHODDEF(void)
  174051. pass2_no_dither (j_decompress_ptr cinfo,
  174052. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174053. /* This version performs no dithering */
  174054. {
  174055. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174056. hist3d histogram = cquantize->histogram;
  174057. register JSAMPROW inptr, outptr;
  174058. register histptr cachep;
  174059. register int c0, c1, c2;
  174060. int row;
  174061. JDIMENSION col;
  174062. JDIMENSION width = cinfo->output_width;
  174063. for (row = 0; row < num_rows; row++) {
  174064. inptr = input_buf[row];
  174065. outptr = output_buf[row];
  174066. for (col = width; col > 0; col--) {
  174067. /* get pixel value and index into the cache */
  174068. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  174069. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  174070. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  174071. cachep = & histogram[c0][c1][c2];
  174072. /* If we have not seen this color before, find nearest colormap entry */
  174073. /* and update the cache */
  174074. if (*cachep == 0)
  174075. fill_inverse_cmap(cinfo, c0,c1,c2);
  174076. /* Now emit the colormap index for this cell */
  174077. *outptr++ = (JSAMPLE) (*cachep - 1);
  174078. }
  174079. }
  174080. }
  174081. METHODDEF(void)
  174082. pass2_fs_dither (j_decompress_ptr cinfo,
  174083. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  174084. /* This version performs Floyd-Steinberg dithering */
  174085. {
  174086. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174087. hist3d histogram = cquantize->histogram;
  174088. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  174089. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  174090. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  174091. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  174092. JSAMPROW inptr; /* => current input pixel */
  174093. JSAMPROW outptr; /* => current output pixel */
  174094. histptr cachep;
  174095. int dir; /* +1 or -1 depending on direction */
  174096. int dir3; /* 3*dir, for advancing inptr & errorptr */
  174097. int row;
  174098. JDIMENSION col;
  174099. JDIMENSION width = cinfo->output_width;
  174100. JSAMPLE *range_limit = cinfo->sample_range_limit;
  174101. int *error_limit = cquantize->error_limiter;
  174102. JSAMPROW colormap0 = cinfo->colormap[0];
  174103. JSAMPROW colormap1 = cinfo->colormap[1];
  174104. JSAMPROW colormap2 = cinfo->colormap[2];
  174105. SHIFT_TEMPS
  174106. for (row = 0; row < num_rows; row++) {
  174107. inptr = input_buf[row];
  174108. outptr = output_buf[row];
  174109. if (cquantize->on_odd_row) {
  174110. /* work right to left in this row */
  174111. inptr += (width-1) * 3; /* so point to rightmost pixel */
  174112. outptr += width-1;
  174113. dir = -1;
  174114. dir3 = -3;
  174115. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  174116. cquantize->on_odd_row = FALSE; /* flip for next time */
  174117. } else {
  174118. /* work left to right in this row */
  174119. dir = 1;
  174120. dir3 = 3;
  174121. errorptr = cquantize->fserrors; /* => entry before first real column */
  174122. cquantize->on_odd_row = TRUE; /* flip for next time */
  174123. }
  174124. /* Preset error values: no error propagated to first pixel from left */
  174125. cur0 = cur1 = cur2 = 0;
  174126. /* and no error propagated to row below yet */
  174127. belowerr0 = belowerr1 = belowerr2 = 0;
  174128. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  174129. for (col = width; col > 0; col--) {
  174130. /* curN holds the error propagated from the previous pixel on the
  174131. * current line. Add the error propagated from the previous line
  174132. * to form the complete error correction term for this pixel, and
  174133. * round the error term (which is expressed * 16) to an integer.
  174134. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  174135. * for either sign of the error value.
  174136. * Note: errorptr points to *previous* column's array entry.
  174137. */
  174138. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  174139. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  174140. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  174141. /* Limit the error using transfer function set by init_error_limit.
  174142. * See comments with init_error_limit for rationale.
  174143. */
  174144. cur0 = error_limit[cur0];
  174145. cur1 = error_limit[cur1];
  174146. cur2 = error_limit[cur2];
  174147. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  174148. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  174149. * this sets the required size of the range_limit array.
  174150. */
  174151. cur0 += GETJSAMPLE(inptr[0]);
  174152. cur1 += GETJSAMPLE(inptr[1]);
  174153. cur2 += GETJSAMPLE(inptr[2]);
  174154. cur0 = GETJSAMPLE(range_limit[cur0]);
  174155. cur1 = GETJSAMPLE(range_limit[cur1]);
  174156. cur2 = GETJSAMPLE(range_limit[cur2]);
  174157. /* Index into the cache with adjusted pixel value */
  174158. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  174159. /* If we have not seen this color before, find nearest colormap */
  174160. /* entry and update the cache */
  174161. if (*cachep == 0)
  174162. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  174163. /* Now emit the colormap index for this cell */
  174164. { register int pixcode = *cachep - 1;
  174165. *outptr = (JSAMPLE) pixcode;
  174166. /* Compute representation error for this pixel */
  174167. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  174168. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  174169. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  174170. }
  174171. /* Compute error fractions to be propagated to adjacent pixels.
  174172. * Add these into the running sums, and simultaneously shift the
  174173. * next-line error sums left by 1 column.
  174174. */
  174175. { register LOCFSERROR bnexterr, delta;
  174176. bnexterr = cur0; /* Process component 0 */
  174177. delta = cur0 * 2;
  174178. cur0 += delta; /* form error * 3 */
  174179. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  174180. cur0 += delta; /* form error * 5 */
  174181. bpreverr0 = belowerr0 + cur0;
  174182. belowerr0 = bnexterr;
  174183. cur0 += delta; /* form error * 7 */
  174184. bnexterr = cur1; /* Process component 1 */
  174185. delta = cur1 * 2;
  174186. cur1 += delta; /* form error * 3 */
  174187. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  174188. cur1 += delta; /* form error * 5 */
  174189. bpreverr1 = belowerr1 + cur1;
  174190. belowerr1 = bnexterr;
  174191. cur1 += delta; /* form error * 7 */
  174192. bnexterr = cur2; /* Process component 2 */
  174193. delta = cur2 * 2;
  174194. cur2 += delta; /* form error * 3 */
  174195. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  174196. cur2 += delta; /* form error * 5 */
  174197. bpreverr2 = belowerr2 + cur2;
  174198. belowerr2 = bnexterr;
  174199. cur2 += delta; /* form error * 7 */
  174200. }
  174201. /* At this point curN contains the 7/16 error value to be propagated
  174202. * to the next pixel on the current line, and all the errors for the
  174203. * next line have been shifted over. We are therefore ready to move on.
  174204. */
  174205. inptr += dir3; /* Advance pixel pointers to next column */
  174206. outptr += dir;
  174207. errorptr += dir3; /* advance errorptr to current column */
  174208. }
  174209. /* Post-loop cleanup: we must unload the final error values into the
  174210. * final fserrors[] entry. Note we need not unload belowerrN because
  174211. * it is for the dummy column before or after the actual array.
  174212. */
  174213. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  174214. errorptr[1] = (FSERROR) bpreverr1;
  174215. errorptr[2] = (FSERROR) bpreverr2;
  174216. }
  174217. }
  174218. /*
  174219. * Initialize the error-limiting transfer function (lookup table).
  174220. * The raw F-S error computation can potentially compute error values of up to
  174221. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  174222. * much less, otherwise obviously wrong pixels will be created. (Typical
  174223. * effects include weird fringes at color-area boundaries, isolated bright
  174224. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  174225. * is to ensure that the "corners" of the color cube are allocated as output
  174226. * colors; then repeated errors in the same direction cannot cause cascading
  174227. * error buildup. However, that only prevents the error from getting
  174228. * completely out of hand; Aaron Giles reports that error limiting improves
  174229. * the results even with corner colors allocated.
  174230. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  174231. * well, but the smoother transfer function used below is even better. Thanks
  174232. * to Aaron Giles for this idea.
  174233. */
  174234. LOCAL(void)
  174235. init_error_limit (j_decompress_ptr cinfo)
  174236. /* Allocate and fill in the error_limiter table */
  174237. {
  174238. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174239. int * table;
  174240. int in, out;
  174241. table = (int *) (*cinfo->mem->alloc_small)
  174242. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  174243. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  174244. cquantize->error_limiter = table;
  174245. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  174246. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  174247. out = 0;
  174248. for (in = 0; in < STEPSIZE; in++, out++) {
  174249. table[in] = out; table[-in] = -out;
  174250. }
  174251. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  174252. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  174253. table[in] = out; table[-in] = -out;
  174254. }
  174255. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  174256. for (; in <= MAXJSAMPLE; in++) {
  174257. table[in] = out; table[-in] = -out;
  174258. }
  174259. #undef STEPSIZE
  174260. }
  174261. /*
  174262. * Finish up at the end of each pass.
  174263. */
  174264. METHODDEF(void)
  174265. finish_pass1 (j_decompress_ptr cinfo)
  174266. {
  174267. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174268. /* Select the representative colors and fill in cinfo->colormap */
  174269. cinfo->colormap = cquantize->sv_colormap;
  174270. select_colors(cinfo, cquantize->desired);
  174271. /* Force next pass to zero the color index table */
  174272. cquantize->needs_zeroed = TRUE;
  174273. }
  174274. METHODDEF(void)
  174275. finish_pass2 (j_decompress_ptr cinfo)
  174276. {
  174277. /* no work */
  174278. }
  174279. /*
  174280. * Initialize for each processing pass.
  174281. */
  174282. METHODDEF(void)
  174283. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  174284. {
  174285. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174286. hist3d histogram = cquantize->histogram;
  174287. int i;
  174288. /* Only F-S dithering or no dithering is supported. */
  174289. /* If user asks for ordered dither, give him F-S. */
  174290. if (cinfo->dither_mode != JDITHER_NONE)
  174291. cinfo->dither_mode = JDITHER_FS;
  174292. if (is_pre_scan) {
  174293. /* Set up method pointers */
  174294. cquantize->pub.color_quantize = prescan_quantize;
  174295. cquantize->pub.finish_pass = finish_pass1;
  174296. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  174297. } else {
  174298. /* Set up method pointers */
  174299. if (cinfo->dither_mode == JDITHER_FS)
  174300. cquantize->pub.color_quantize = pass2_fs_dither;
  174301. else
  174302. cquantize->pub.color_quantize = pass2_no_dither;
  174303. cquantize->pub.finish_pass = finish_pass2;
  174304. /* Make sure color count is acceptable */
  174305. i = cinfo->actual_number_of_colors;
  174306. if (i < 1)
  174307. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  174308. if (i > MAXNUMCOLORS)
  174309. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174310. if (cinfo->dither_mode == JDITHER_FS) {
  174311. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  174312. (3 * SIZEOF(FSERROR)));
  174313. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  174314. if (cquantize->fserrors == NULL)
  174315. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174316. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  174317. /* Initialize the propagated errors to zero. */
  174318. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  174319. /* Make the error-limit table if we didn't already. */
  174320. if (cquantize->error_limiter == NULL)
  174321. init_error_limit(cinfo);
  174322. cquantize->on_odd_row = FALSE;
  174323. }
  174324. }
  174325. /* Zero the histogram or inverse color map, if necessary */
  174326. if (cquantize->needs_zeroed) {
  174327. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174328. jzero_far((void FAR *) histogram[i],
  174329. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174330. }
  174331. cquantize->needs_zeroed = FALSE;
  174332. }
  174333. }
  174334. /*
  174335. * Switch to a new external colormap between output passes.
  174336. */
  174337. METHODDEF(void)
  174338. new_color_map_2_quant (j_decompress_ptr cinfo)
  174339. {
  174340. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  174341. /* Reset the inverse color map */
  174342. cquantize->needs_zeroed = TRUE;
  174343. }
  174344. /*
  174345. * Module initialization routine for 2-pass color quantization.
  174346. */
  174347. GLOBAL(void)
  174348. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  174349. {
  174350. my_cquantize_ptr2 cquantize;
  174351. int i;
  174352. cquantize = (my_cquantize_ptr2)
  174353. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174354. SIZEOF(my_cquantizer2));
  174355. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  174356. cquantize->pub.start_pass = start_pass_2_quant;
  174357. cquantize->pub.new_color_map = new_color_map_2_quant;
  174358. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  174359. cquantize->error_limiter = NULL;
  174360. /* Make sure jdmaster didn't give me a case I can't handle */
  174361. if (cinfo->out_color_components != 3)
  174362. ERREXIT(cinfo, JERR_NOTIMPL);
  174363. /* Allocate the histogram/inverse colormap storage */
  174364. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  174365. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  174366. for (i = 0; i < HIST_C0_ELEMS; i++) {
  174367. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  174368. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174369. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  174370. }
  174371. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  174372. /* Allocate storage for the completed colormap, if required.
  174373. * We do this now since it is FAR storage and may affect
  174374. * the memory manager's space calculations.
  174375. */
  174376. if (cinfo->enable_2pass_quant) {
  174377. /* Make sure color count is acceptable */
  174378. int desired = cinfo->desired_number_of_colors;
  174379. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  174380. if (desired < 8)
  174381. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  174382. /* Make sure colormap indexes can be represented by JSAMPLEs */
  174383. if (desired > MAXNUMCOLORS)
  174384. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  174385. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  174386. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  174387. cquantize->desired = desired;
  174388. } else
  174389. cquantize->sv_colormap = NULL;
  174390. /* Only F-S dithering or no dithering is supported. */
  174391. /* If user asks for ordered dither, give him F-S. */
  174392. if (cinfo->dither_mode != JDITHER_NONE)
  174393. cinfo->dither_mode = JDITHER_FS;
  174394. /* Allocate Floyd-Steinberg workspace if necessary.
  174395. * This isn't really needed until pass 2, but again it is FAR storage.
  174396. * Although we will cope with a later change in dither_mode,
  174397. * we do not promise to honor max_memory_to_use if dither_mode changes.
  174398. */
  174399. if (cinfo->dither_mode == JDITHER_FS) {
  174400. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  174401. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174402. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  174403. /* Might as well create the error-limiting table too. */
  174404. init_error_limit(cinfo);
  174405. }
  174406. }
  174407. #endif /* QUANT_2PASS_SUPPORTED */
  174408. /********* End of inlined file: jquant2.c *********/
  174409. /********* Start of inlined file: jutils.c *********/
  174410. #define JPEG_INTERNALS
  174411. /*
  174412. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  174413. * of a DCT block read in natural order (left to right, top to bottom).
  174414. */
  174415. #if 0 /* This table is not actually needed in v6a */
  174416. const int jpeg_zigzag_order[DCTSIZE2] = {
  174417. 0, 1, 5, 6, 14, 15, 27, 28,
  174418. 2, 4, 7, 13, 16, 26, 29, 42,
  174419. 3, 8, 12, 17, 25, 30, 41, 43,
  174420. 9, 11, 18, 24, 31, 40, 44, 53,
  174421. 10, 19, 23, 32, 39, 45, 52, 54,
  174422. 20, 22, 33, 38, 46, 51, 55, 60,
  174423. 21, 34, 37, 47, 50, 56, 59, 61,
  174424. 35, 36, 48, 49, 57, 58, 62, 63
  174425. };
  174426. #endif
  174427. /*
  174428. * jpeg_natural_order[i] is the natural-order position of the i'th element
  174429. * of zigzag order.
  174430. *
  174431. * When reading corrupted data, the Huffman decoders could attempt
  174432. * to reference an entry beyond the end of this array (if the decoded
  174433. * zero run length reaches past the end of the block). To prevent
  174434. * wild stores without adding an inner-loop test, we put some extra
  174435. * "63"s after the real entries. This will cause the extra coefficient
  174436. * to be stored in location 63 of the block, not somewhere random.
  174437. * The worst case would be a run-length of 15, which means we need 16
  174438. * fake entries.
  174439. */
  174440. const int jpeg_natural_order[DCTSIZE2+16] = {
  174441. 0, 1, 8, 16, 9, 2, 3, 10,
  174442. 17, 24, 32, 25, 18, 11, 4, 5,
  174443. 12, 19, 26, 33, 40, 48, 41, 34,
  174444. 27, 20, 13, 6, 7, 14, 21, 28,
  174445. 35, 42, 49, 56, 57, 50, 43, 36,
  174446. 29, 22, 15, 23, 30, 37, 44, 51,
  174447. 58, 59, 52, 45, 38, 31, 39, 46,
  174448. 53, 60, 61, 54, 47, 55, 62, 63,
  174449. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  174450. 63, 63, 63, 63, 63, 63, 63, 63
  174451. };
  174452. /*
  174453. * Arithmetic utilities
  174454. */
  174455. GLOBAL(long)
  174456. jdiv_round_up (long a, long b)
  174457. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  174458. /* Assumes a >= 0, b > 0 */
  174459. {
  174460. return (a + b - 1L) / b;
  174461. }
  174462. GLOBAL(long)
  174463. jround_up (long a, long b)
  174464. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  174465. /* Assumes a >= 0, b > 0 */
  174466. {
  174467. a += b - 1L;
  174468. return a - (a % b);
  174469. }
  174470. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  174471. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  174472. * are FAR and we're assuming a small-pointer memory model. However, some
  174473. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  174474. * in the small-model libraries. These will be used if USE_FMEM is defined.
  174475. * Otherwise, the routines below do it the hard way. (The performance cost
  174476. * is not all that great, because these routines aren't very heavily used.)
  174477. */
  174478. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  174479. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  174480. #define FMEMZERO(target,size) MEMZERO(target,size)
  174481. #else /* 80x86 case, define if we can */
  174482. #ifdef USE_FMEM
  174483. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  174484. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  174485. #endif
  174486. #endif
  174487. GLOBAL(void)
  174488. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  174489. JSAMPARRAY output_array, int dest_row,
  174490. int num_rows, JDIMENSION num_cols)
  174491. /* Copy some rows of samples from one place to another.
  174492. * num_rows rows are copied from input_array[source_row++]
  174493. * to output_array[dest_row++]; these areas may overlap for duplication.
  174494. * The source and destination arrays must be at least as wide as num_cols.
  174495. */
  174496. {
  174497. register JSAMPROW inptr, outptr;
  174498. #ifdef FMEMCOPY
  174499. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  174500. #else
  174501. register JDIMENSION count;
  174502. #endif
  174503. register int row;
  174504. input_array += source_row;
  174505. output_array += dest_row;
  174506. for (row = num_rows; row > 0; row--) {
  174507. inptr = *input_array++;
  174508. outptr = *output_array++;
  174509. #ifdef FMEMCOPY
  174510. FMEMCOPY(outptr, inptr, count);
  174511. #else
  174512. for (count = num_cols; count > 0; count--)
  174513. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  174514. #endif
  174515. }
  174516. }
  174517. GLOBAL(void)
  174518. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  174519. JDIMENSION num_blocks)
  174520. /* Copy a row of coefficient blocks from one place to another. */
  174521. {
  174522. #ifdef FMEMCOPY
  174523. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  174524. #else
  174525. register JCOEFPTR inptr, outptr;
  174526. register long count;
  174527. inptr = (JCOEFPTR) input_row;
  174528. outptr = (JCOEFPTR) output_row;
  174529. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  174530. *outptr++ = *inptr++;
  174531. }
  174532. #endif
  174533. }
  174534. GLOBAL(void)
  174535. jzero_far (void FAR * target, size_t bytestozero)
  174536. /* Zero out a chunk of FAR memory. */
  174537. /* This might be sample-array data, block-array data, or alloc_large data. */
  174538. {
  174539. #ifdef FMEMZERO
  174540. FMEMZERO(target, bytestozero);
  174541. #else
  174542. register char FAR * ptr = (char FAR *) target;
  174543. register size_t count;
  174544. for (count = bytestozero; count > 0; count--) {
  174545. *ptr++ = 0;
  174546. }
  174547. #endif
  174548. }
  174549. /********* End of inlined file: jutils.c *********/
  174550. /********* Start of inlined file: transupp.c *********/
  174551. /* Although this file really shouldn't have access to the library internals,
  174552. * it's helpful to let it call jround_up() and jcopy_block_row().
  174553. */
  174554. #define JPEG_INTERNALS
  174555. /********* Start of inlined file: transupp.h *********/
  174556. /* If you happen not to want the image transform support, disable it here */
  174557. #ifndef TRANSFORMS_SUPPORTED
  174558. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  174559. #endif
  174560. /* Short forms of external names for systems with brain-damaged linkers. */
  174561. #ifdef NEED_SHORT_EXTERNAL_NAMES
  174562. #define jtransform_request_workspace jTrRequest
  174563. #define jtransform_adjust_parameters jTrAdjust
  174564. #define jtransform_execute_transformation jTrExec
  174565. #define jcopy_markers_setup jCMrkSetup
  174566. #define jcopy_markers_execute jCMrkExec
  174567. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  174568. /*
  174569. * Codes for supported types of image transformations.
  174570. */
  174571. typedef enum {
  174572. JXFORM_NONE, /* no transformation */
  174573. JXFORM_FLIP_H, /* horizontal flip */
  174574. JXFORM_FLIP_V, /* vertical flip */
  174575. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  174576. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  174577. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  174578. JXFORM_ROT_180, /* 180-degree rotation */
  174579. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  174580. } JXFORM_CODE;
  174581. /*
  174582. * Although rotating and flipping data expressed as DCT coefficients is not
  174583. * hard, there is an asymmetry in the JPEG format specification for images
  174584. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  174585. * image edges are padded out to the next iMCU boundary with junk data; but
  174586. * no padding is possible at the top and left edges. If we were to flip
  174587. * the whole image including the pad data, then pad garbage would become
  174588. * visible at the top and/or left, and real pixels would disappear into the
  174589. * pad margins --- perhaps permanently, since encoders & decoders may not
  174590. * bother to preserve DCT blocks that appear to be completely outside the
  174591. * nominal image area. So, we have to exclude any partial iMCUs from the
  174592. * basic transformation.
  174593. *
  174594. * Transpose is the only transformation that can handle partial iMCUs at the
  174595. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  174596. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  174597. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  174598. * The other transforms are defined as combinations of these basic transforms
  174599. * and process edge blocks in a way that preserves the equivalence.
  174600. *
  174601. * The "trim" option causes untransformable partial iMCUs to be dropped;
  174602. * this is not strictly lossless, but it usually gives the best-looking
  174603. * result for odd-size images. Note that when this option is active,
  174604. * the expected mathematical equivalences between the transforms may not hold.
  174605. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  174606. * followed by -rot 180 -trim trims both edges.)
  174607. *
  174608. * We also offer a "force to grayscale" option, which simply discards the
  174609. * chrominance channels of a YCbCr image. This is lossless in the sense that
  174610. * the luminance channel is preserved exactly. It's not the same kind of
  174611. * thing as the rotate/flip transformations, but it's convenient to handle it
  174612. * as part of this package, mainly because the transformation routines have to
  174613. * be aware of the option to know how many components to work on.
  174614. */
  174615. typedef struct {
  174616. /* Options: set by caller */
  174617. JXFORM_CODE transform; /* image transform operator */
  174618. boolean trim; /* if TRUE, trim partial MCUs as needed */
  174619. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  174620. /* Internal workspace: caller should not touch these */
  174621. int num_components; /* # of components in workspace */
  174622. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  174623. } jpeg_transform_info;
  174624. #if TRANSFORMS_SUPPORTED
  174625. /* Request any required workspace */
  174626. EXTERN(void) jtransform_request_workspace
  174627. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  174628. /* Adjust output image parameters */
  174629. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  174630. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174631. jvirt_barray_ptr *src_coef_arrays,
  174632. jpeg_transform_info *info));
  174633. /* Execute the actual transformation, if any */
  174634. EXTERN(void) jtransform_execute_transformation
  174635. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174636. jvirt_barray_ptr *src_coef_arrays,
  174637. jpeg_transform_info *info));
  174638. #endif /* TRANSFORMS_SUPPORTED */
  174639. /*
  174640. * Support for copying optional markers from source to destination file.
  174641. */
  174642. typedef enum {
  174643. JCOPYOPT_NONE, /* copy no optional markers */
  174644. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  174645. JCOPYOPT_ALL /* copy all optional markers */
  174646. } JCOPY_OPTION;
  174647. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  174648. /* Setup decompression object to save desired markers in memory */
  174649. EXTERN(void) jcopy_markers_setup
  174650. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  174651. /* Copy markers saved in the given source object to the destination object */
  174652. EXTERN(void) jcopy_markers_execute
  174653. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174654. JCOPY_OPTION option));
  174655. /********* End of inlined file: transupp.h *********/
  174656. /* My own external interface */
  174657. #if TRANSFORMS_SUPPORTED
  174658. /*
  174659. * Lossless image transformation routines. These routines work on DCT
  174660. * coefficient arrays and thus do not require any lossy decompression
  174661. * or recompression of the image.
  174662. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  174663. *
  174664. * Horizontal flipping is done in-place, using a single top-to-bottom
  174665. * pass through the virtual source array. It will thus be much the
  174666. * fastest option for images larger than main memory.
  174667. *
  174668. * The other routines require a set of destination virtual arrays, so they
  174669. * need twice as much memory as jpegtran normally does. The destination
  174670. * arrays are always written in normal scan order (top to bottom) because
  174671. * the virtual array manager expects this. The source arrays will be scanned
  174672. * in the corresponding order, which means multiple passes through the source
  174673. * arrays for most of the transforms. That could result in much thrashing
  174674. * if the image is larger than main memory.
  174675. *
  174676. * Some notes about the operating environment of the individual transform
  174677. * routines:
  174678. * 1. Both the source and destination virtual arrays are allocated from the
  174679. * source JPEG object, and therefore should be manipulated by calling the
  174680. * source's memory manager.
  174681. * 2. The destination's component count should be used. It may be smaller
  174682. * than the source's when forcing to grayscale.
  174683. * 3. Likewise the destination's sampling factors should be used. When
  174684. * forcing to grayscale the destination's sampling factors will be all 1,
  174685. * and we may as well take that as the effective iMCU size.
  174686. * 4. When "trim" is in effect, the destination's dimensions will be the
  174687. * trimmed values but the source's will be untrimmed.
  174688. * 5. All the routines assume that the source and destination buffers are
  174689. * padded out to a full iMCU boundary. This is true, although for the
  174690. * source buffer it is an undocumented property of jdcoefct.c.
  174691. * Notes 2,3,4 boil down to this: generally we should use the destination's
  174692. * dimensions and ignore the source's.
  174693. */
  174694. LOCAL(void)
  174695. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174696. jvirt_barray_ptr *src_coef_arrays)
  174697. /* Horizontal flip; done in-place, so no separate dest array is required */
  174698. {
  174699. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  174700. int ci, k, offset_y;
  174701. JBLOCKARRAY buffer;
  174702. JCOEFPTR ptr1, ptr2;
  174703. JCOEF temp1, temp2;
  174704. jpeg_component_info *compptr;
  174705. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  174706. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  174707. * mirroring by changing the signs of odd-numbered columns.
  174708. * Partial iMCUs at the right edge are left untouched.
  174709. */
  174710. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174711. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174712. compptr = dstinfo->comp_info + ci;
  174713. comp_width = MCU_cols * compptr->h_samp_factor;
  174714. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  174715. blk_y += compptr->v_samp_factor) {
  174716. buffer = (*srcinfo->mem->access_virt_barray)
  174717. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  174718. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174719. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174720. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  174721. ptr1 = buffer[offset_y][blk_x];
  174722. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  174723. /* this unrolled loop doesn't need to know which row it's on... */
  174724. for (k = 0; k < DCTSIZE2; k += 2) {
  174725. temp1 = *ptr1; /* swap even column */
  174726. temp2 = *ptr2;
  174727. *ptr1++ = temp2;
  174728. *ptr2++ = temp1;
  174729. temp1 = *ptr1; /* swap odd column with sign change */
  174730. temp2 = *ptr2;
  174731. *ptr1++ = -temp2;
  174732. *ptr2++ = -temp1;
  174733. }
  174734. }
  174735. }
  174736. }
  174737. }
  174738. }
  174739. LOCAL(void)
  174740. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174741. jvirt_barray_ptr *src_coef_arrays,
  174742. jvirt_barray_ptr *dst_coef_arrays)
  174743. /* Vertical flip */
  174744. {
  174745. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174746. int ci, i, j, offset_y;
  174747. JBLOCKARRAY src_buffer, dst_buffer;
  174748. JBLOCKROW src_row_ptr, dst_row_ptr;
  174749. JCOEFPTR src_ptr, dst_ptr;
  174750. jpeg_component_info *compptr;
  174751. /* We output into a separate array because we can't touch different
  174752. * rows of the source virtual array simultaneously. Otherwise, this
  174753. * is a pretty straightforward analog of horizontal flip.
  174754. * Within a DCT block, vertical mirroring is done by changing the signs
  174755. * of odd-numbered rows.
  174756. * Partial iMCUs at the bottom edge are copied verbatim.
  174757. */
  174758. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174759. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174760. compptr = dstinfo->comp_info + ci;
  174761. comp_height = MCU_rows * compptr->v_samp_factor;
  174762. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174763. dst_blk_y += compptr->v_samp_factor) {
  174764. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174765. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174766. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174767. if (dst_blk_y < comp_height) {
  174768. /* Row is within the mirrorable area. */
  174769. src_buffer = (*srcinfo->mem->access_virt_barray)
  174770. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174771. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174772. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174773. } else {
  174774. /* Bottom-edge blocks will be copied verbatim. */
  174775. src_buffer = (*srcinfo->mem->access_virt_barray)
  174776. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  174777. (JDIMENSION) compptr->v_samp_factor, FALSE);
  174778. }
  174779. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174780. if (dst_blk_y < comp_height) {
  174781. /* Row is within the mirrorable area. */
  174782. dst_row_ptr = dst_buffer[offset_y];
  174783. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  174784. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174785. dst_blk_x++) {
  174786. dst_ptr = dst_row_ptr[dst_blk_x];
  174787. src_ptr = src_row_ptr[dst_blk_x];
  174788. for (i = 0; i < DCTSIZE; i += 2) {
  174789. /* copy even row */
  174790. for (j = 0; j < DCTSIZE; j++)
  174791. *dst_ptr++ = *src_ptr++;
  174792. /* copy odd row with sign change */
  174793. for (j = 0; j < DCTSIZE; j++)
  174794. *dst_ptr++ = - *src_ptr++;
  174795. }
  174796. }
  174797. } else {
  174798. /* Just copy row verbatim. */
  174799. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  174800. compptr->width_in_blocks);
  174801. }
  174802. }
  174803. }
  174804. }
  174805. }
  174806. LOCAL(void)
  174807. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174808. jvirt_barray_ptr *src_coef_arrays,
  174809. jvirt_barray_ptr *dst_coef_arrays)
  174810. /* Transpose source into destination */
  174811. {
  174812. JDIMENSION dst_blk_x, dst_blk_y;
  174813. int ci, i, j, offset_x, offset_y;
  174814. JBLOCKARRAY src_buffer, dst_buffer;
  174815. JCOEFPTR src_ptr, dst_ptr;
  174816. jpeg_component_info *compptr;
  174817. /* Transposing pixels within a block just requires transposing the
  174818. * DCT coefficients.
  174819. * Partial iMCUs at the edges require no special treatment; we simply
  174820. * process all the available DCT blocks for every component.
  174821. */
  174822. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174823. compptr = dstinfo->comp_info + ci;
  174824. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174825. dst_blk_y += compptr->v_samp_factor) {
  174826. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174827. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174828. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174829. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174830. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174831. dst_blk_x += compptr->h_samp_factor) {
  174832. src_buffer = (*srcinfo->mem->access_virt_barray)
  174833. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174834. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174835. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174836. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174837. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174838. for (i = 0; i < DCTSIZE; i++)
  174839. for (j = 0; j < DCTSIZE; j++)
  174840. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174841. }
  174842. }
  174843. }
  174844. }
  174845. }
  174846. }
  174847. LOCAL(void)
  174848. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174849. jvirt_barray_ptr *src_coef_arrays,
  174850. jvirt_barray_ptr *dst_coef_arrays)
  174851. /* 90 degree rotation is equivalent to
  174852. * 1. Transposing the image;
  174853. * 2. Horizontal mirroring.
  174854. * These two steps are merged into a single processing routine.
  174855. */
  174856. {
  174857. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  174858. int ci, i, j, offset_x, offset_y;
  174859. JBLOCKARRAY src_buffer, dst_buffer;
  174860. JCOEFPTR src_ptr, dst_ptr;
  174861. jpeg_component_info *compptr;
  174862. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174863. * at the (output) right edge properly. They just get transposed and
  174864. * not mirrored.
  174865. */
  174866. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174867. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174868. compptr = dstinfo->comp_info + ci;
  174869. comp_width = MCU_cols * compptr->h_samp_factor;
  174870. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174871. dst_blk_y += compptr->v_samp_factor) {
  174872. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174873. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174874. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174875. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174876. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174877. dst_blk_x += compptr->h_samp_factor) {
  174878. src_buffer = (*srcinfo->mem->access_virt_barray)
  174879. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174880. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174881. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174882. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174883. if (dst_blk_x < comp_width) {
  174884. /* Block is within the mirrorable area. */
  174885. dst_ptr = dst_buffer[offset_y]
  174886. [comp_width - dst_blk_x - offset_x - 1];
  174887. for (i = 0; i < DCTSIZE; i++) {
  174888. for (j = 0; j < DCTSIZE; j++)
  174889. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174890. i++;
  174891. for (j = 0; j < DCTSIZE; j++)
  174892. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174893. }
  174894. } else {
  174895. /* Edge blocks are transposed but not mirrored. */
  174896. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174897. for (i = 0; i < DCTSIZE; i++)
  174898. for (j = 0; j < DCTSIZE; j++)
  174899. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174900. }
  174901. }
  174902. }
  174903. }
  174904. }
  174905. }
  174906. }
  174907. LOCAL(void)
  174908. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174909. jvirt_barray_ptr *src_coef_arrays,
  174910. jvirt_barray_ptr *dst_coef_arrays)
  174911. /* 270 degree rotation is equivalent to
  174912. * 1. Horizontal mirroring;
  174913. * 2. Transposing the image.
  174914. * These two steps are merged into a single processing routine.
  174915. */
  174916. {
  174917. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  174918. int ci, i, j, offset_x, offset_y;
  174919. JBLOCKARRAY src_buffer, dst_buffer;
  174920. JCOEFPTR src_ptr, dst_ptr;
  174921. jpeg_component_info *compptr;
  174922. /* Because of the horizontal mirror step, we can't process partial iMCUs
  174923. * at the (output) bottom edge properly. They just get transposed and
  174924. * not mirrored.
  174925. */
  174926. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174927. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174928. compptr = dstinfo->comp_info + ci;
  174929. comp_height = MCU_rows * compptr->v_samp_factor;
  174930. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174931. dst_blk_y += compptr->v_samp_factor) {
  174932. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174933. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174934. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174935. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  174936. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  174937. dst_blk_x += compptr->h_samp_factor) {
  174938. src_buffer = (*srcinfo->mem->access_virt_barray)
  174939. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  174940. (JDIMENSION) compptr->h_samp_factor, FALSE);
  174941. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  174942. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  174943. if (dst_blk_y < comp_height) {
  174944. /* Block is within the mirrorable area. */
  174945. src_ptr = src_buffer[offset_x]
  174946. [comp_height - dst_blk_y - offset_y - 1];
  174947. for (i = 0; i < DCTSIZE; i++) {
  174948. for (j = 0; j < DCTSIZE; j++) {
  174949. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174950. j++;
  174951. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  174952. }
  174953. }
  174954. } else {
  174955. /* Edge blocks are transposed but not mirrored. */
  174956. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  174957. for (i = 0; i < DCTSIZE; i++)
  174958. for (j = 0; j < DCTSIZE; j++)
  174959. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  174960. }
  174961. }
  174962. }
  174963. }
  174964. }
  174965. }
  174966. }
  174967. LOCAL(void)
  174968. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  174969. jvirt_barray_ptr *src_coef_arrays,
  174970. jvirt_barray_ptr *dst_coef_arrays)
  174971. /* 180 degree rotation is equivalent to
  174972. * 1. Vertical mirroring;
  174973. * 2. Horizontal mirroring.
  174974. * These two steps are merged into a single processing routine.
  174975. */
  174976. {
  174977. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  174978. int ci, i, j, offset_y;
  174979. JBLOCKARRAY src_buffer, dst_buffer;
  174980. JBLOCKROW src_row_ptr, dst_row_ptr;
  174981. JCOEFPTR src_ptr, dst_ptr;
  174982. jpeg_component_info *compptr;
  174983. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  174984. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  174985. for (ci = 0; ci < dstinfo->num_components; ci++) {
  174986. compptr = dstinfo->comp_info + ci;
  174987. comp_width = MCU_cols * compptr->h_samp_factor;
  174988. comp_height = MCU_rows * compptr->v_samp_factor;
  174989. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  174990. dst_blk_y += compptr->v_samp_factor) {
  174991. dst_buffer = (*srcinfo->mem->access_virt_barray)
  174992. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  174993. (JDIMENSION) compptr->v_samp_factor, TRUE);
  174994. if (dst_blk_y < comp_height) {
  174995. /* Row is within the vertically mirrorable area. */
  174996. src_buffer = (*srcinfo->mem->access_virt_barray)
  174997. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  174998. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  174999. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175000. } else {
  175001. /* Bottom-edge rows are only mirrored horizontally. */
  175002. src_buffer = (*srcinfo->mem->access_virt_barray)
  175003. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  175004. (JDIMENSION) compptr->v_samp_factor, FALSE);
  175005. }
  175006. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175007. if (dst_blk_y < comp_height) {
  175008. /* Row is within the mirrorable area. */
  175009. dst_row_ptr = dst_buffer[offset_y];
  175010. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  175011. /* Process the blocks that can be mirrored both ways. */
  175012. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175013. dst_ptr = dst_row_ptr[dst_blk_x];
  175014. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175015. for (i = 0; i < DCTSIZE; i += 2) {
  175016. /* For even row, negate every odd column. */
  175017. for (j = 0; j < DCTSIZE; j += 2) {
  175018. *dst_ptr++ = *src_ptr++;
  175019. *dst_ptr++ = - *src_ptr++;
  175020. }
  175021. /* For odd row, negate every even column. */
  175022. for (j = 0; j < DCTSIZE; j += 2) {
  175023. *dst_ptr++ = - *src_ptr++;
  175024. *dst_ptr++ = *src_ptr++;
  175025. }
  175026. }
  175027. }
  175028. /* Any remaining right-edge blocks are only mirrored vertically. */
  175029. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175030. dst_ptr = dst_row_ptr[dst_blk_x];
  175031. src_ptr = src_row_ptr[dst_blk_x];
  175032. for (i = 0; i < DCTSIZE; i += 2) {
  175033. for (j = 0; j < DCTSIZE; j++)
  175034. *dst_ptr++ = *src_ptr++;
  175035. for (j = 0; j < DCTSIZE; j++)
  175036. *dst_ptr++ = - *src_ptr++;
  175037. }
  175038. }
  175039. } else {
  175040. /* Remaining rows are just mirrored horizontally. */
  175041. dst_row_ptr = dst_buffer[offset_y];
  175042. src_row_ptr = src_buffer[offset_y];
  175043. /* Process the blocks that can be mirrored. */
  175044. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  175045. dst_ptr = dst_row_ptr[dst_blk_x];
  175046. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  175047. for (i = 0; i < DCTSIZE2; i += 2) {
  175048. *dst_ptr++ = *src_ptr++;
  175049. *dst_ptr++ = - *src_ptr++;
  175050. }
  175051. }
  175052. /* Any remaining right-edge blocks are only copied. */
  175053. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  175054. dst_ptr = dst_row_ptr[dst_blk_x];
  175055. src_ptr = src_row_ptr[dst_blk_x];
  175056. for (i = 0; i < DCTSIZE2; i++)
  175057. *dst_ptr++ = *src_ptr++;
  175058. }
  175059. }
  175060. }
  175061. }
  175062. }
  175063. }
  175064. LOCAL(void)
  175065. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175066. jvirt_barray_ptr *src_coef_arrays,
  175067. jvirt_barray_ptr *dst_coef_arrays)
  175068. /* Transverse transpose is equivalent to
  175069. * 1. 180 degree rotation;
  175070. * 2. Transposition;
  175071. * or
  175072. * 1. Horizontal mirroring;
  175073. * 2. Transposition;
  175074. * 3. Horizontal mirroring.
  175075. * These steps are merged into a single processing routine.
  175076. */
  175077. {
  175078. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  175079. int ci, i, j, offset_x, offset_y;
  175080. JBLOCKARRAY src_buffer, dst_buffer;
  175081. JCOEFPTR src_ptr, dst_ptr;
  175082. jpeg_component_info *compptr;
  175083. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  175084. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  175085. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175086. compptr = dstinfo->comp_info + ci;
  175087. comp_width = MCU_cols * compptr->h_samp_factor;
  175088. comp_height = MCU_rows * compptr->v_samp_factor;
  175089. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  175090. dst_blk_y += compptr->v_samp_factor) {
  175091. dst_buffer = (*srcinfo->mem->access_virt_barray)
  175092. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  175093. (JDIMENSION) compptr->v_samp_factor, TRUE);
  175094. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  175095. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  175096. dst_blk_x += compptr->h_samp_factor) {
  175097. src_buffer = (*srcinfo->mem->access_virt_barray)
  175098. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  175099. (JDIMENSION) compptr->h_samp_factor, FALSE);
  175100. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  175101. if (dst_blk_y < comp_height) {
  175102. src_ptr = src_buffer[offset_x]
  175103. [comp_height - dst_blk_y - offset_y - 1];
  175104. if (dst_blk_x < comp_width) {
  175105. /* Block is within the mirrorable area. */
  175106. dst_ptr = dst_buffer[offset_y]
  175107. [comp_width - dst_blk_x - offset_x - 1];
  175108. for (i = 0; i < DCTSIZE; i++) {
  175109. for (j = 0; j < DCTSIZE; j++) {
  175110. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175111. j++;
  175112. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175113. }
  175114. i++;
  175115. for (j = 0; j < DCTSIZE; j++) {
  175116. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175117. j++;
  175118. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175119. }
  175120. }
  175121. } else {
  175122. /* Right-edge blocks are mirrored in y only */
  175123. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175124. for (i = 0; i < DCTSIZE; i++) {
  175125. for (j = 0; j < DCTSIZE; j++) {
  175126. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175127. j++;
  175128. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175129. }
  175130. }
  175131. }
  175132. } else {
  175133. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  175134. if (dst_blk_x < comp_width) {
  175135. /* Bottom-edge blocks are mirrored in x only */
  175136. dst_ptr = dst_buffer[offset_y]
  175137. [comp_width - dst_blk_x - offset_x - 1];
  175138. for (i = 0; i < DCTSIZE; i++) {
  175139. for (j = 0; j < DCTSIZE; j++)
  175140. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175141. i++;
  175142. for (j = 0; j < DCTSIZE; j++)
  175143. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  175144. }
  175145. } else {
  175146. /* At lower right corner, just transpose, no mirroring */
  175147. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  175148. for (i = 0; i < DCTSIZE; i++)
  175149. for (j = 0; j < DCTSIZE; j++)
  175150. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  175151. }
  175152. }
  175153. }
  175154. }
  175155. }
  175156. }
  175157. }
  175158. }
  175159. /* Request any required workspace.
  175160. *
  175161. * We allocate the workspace virtual arrays from the source decompression
  175162. * object, so that all the arrays (both the original data and the workspace)
  175163. * will be taken into account while making memory management decisions.
  175164. * Hence, this routine must be called after jpeg_read_header (which reads
  175165. * the image dimensions) and before jpeg_read_coefficients (which realizes
  175166. * the source's virtual arrays).
  175167. */
  175168. GLOBAL(void)
  175169. jtransform_request_workspace (j_decompress_ptr srcinfo,
  175170. jpeg_transform_info *info)
  175171. {
  175172. jvirt_barray_ptr *coef_arrays = NULL;
  175173. jpeg_component_info *compptr;
  175174. int ci;
  175175. if (info->force_grayscale &&
  175176. srcinfo->jpeg_color_space == JCS_YCbCr &&
  175177. srcinfo->num_components == 3) {
  175178. /* We'll only process the first component */
  175179. info->num_components = 1;
  175180. } else {
  175181. /* Process all the components */
  175182. info->num_components = srcinfo->num_components;
  175183. }
  175184. switch (info->transform) {
  175185. case JXFORM_NONE:
  175186. case JXFORM_FLIP_H:
  175187. /* Don't need a workspace array */
  175188. break;
  175189. case JXFORM_FLIP_V:
  175190. case JXFORM_ROT_180:
  175191. /* Need workspace arrays having same dimensions as source image.
  175192. * Note that we allocate arrays padded out to the next iMCU boundary,
  175193. * so that transform routines need not worry about missing edge blocks.
  175194. */
  175195. coef_arrays = (jvirt_barray_ptr *)
  175196. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  175197. SIZEOF(jvirt_barray_ptr) * info->num_components);
  175198. for (ci = 0; ci < info->num_components; ci++) {
  175199. compptr = srcinfo->comp_info + ci;
  175200. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  175201. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  175202. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175203. (long) compptr->h_samp_factor),
  175204. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  175205. (long) compptr->v_samp_factor),
  175206. (JDIMENSION) compptr->v_samp_factor);
  175207. }
  175208. break;
  175209. case JXFORM_TRANSPOSE:
  175210. case JXFORM_TRANSVERSE:
  175211. case JXFORM_ROT_90:
  175212. case JXFORM_ROT_270:
  175213. /* Need workspace arrays having transposed dimensions.
  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->height_in_blocks,
  175225. (long) compptr->v_samp_factor),
  175226. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  175227. (long) compptr->h_samp_factor),
  175228. (JDIMENSION) compptr->h_samp_factor);
  175229. }
  175230. break;
  175231. }
  175232. info->workspace_coef_arrays = coef_arrays;
  175233. }
  175234. /* Transpose destination image parameters */
  175235. LOCAL(void)
  175236. transpose_critical_parameters (j_compress_ptr dstinfo)
  175237. {
  175238. int tblno, i, j, ci, itemp;
  175239. jpeg_component_info *compptr;
  175240. JQUANT_TBL *qtblptr;
  175241. JDIMENSION dtemp;
  175242. UINT16 qtemp;
  175243. /* Transpose basic image dimensions */
  175244. dtemp = dstinfo->image_width;
  175245. dstinfo->image_width = dstinfo->image_height;
  175246. dstinfo->image_height = dtemp;
  175247. /* Transpose sampling factors */
  175248. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175249. compptr = dstinfo->comp_info + ci;
  175250. itemp = compptr->h_samp_factor;
  175251. compptr->h_samp_factor = compptr->v_samp_factor;
  175252. compptr->v_samp_factor = itemp;
  175253. }
  175254. /* Transpose quantization tables */
  175255. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  175256. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  175257. if (qtblptr != NULL) {
  175258. for (i = 0; i < DCTSIZE; i++) {
  175259. for (j = 0; j < i; j++) {
  175260. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  175261. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  175262. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  175263. }
  175264. }
  175265. }
  175266. }
  175267. }
  175268. /* Trim off any partial iMCUs on the indicated destination edge */
  175269. LOCAL(void)
  175270. trim_right_edge (j_compress_ptr dstinfo)
  175271. {
  175272. int ci, max_h_samp_factor;
  175273. JDIMENSION MCU_cols;
  175274. /* We have to compute max_h_samp_factor ourselves,
  175275. * because it hasn't been set yet in the destination
  175276. * (and we don't want to use the source's value).
  175277. */
  175278. max_h_samp_factor = 1;
  175279. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175280. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  175281. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  175282. }
  175283. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  175284. if (MCU_cols > 0) /* can't trim to 0 pixels */
  175285. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  175286. }
  175287. LOCAL(void)
  175288. trim_bottom_edge (j_compress_ptr dstinfo)
  175289. {
  175290. int ci, max_v_samp_factor;
  175291. JDIMENSION MCU_rows;
  175292. /* We have to compute max_v_samp_factor ourselves,
  175293. * because it hasn't been set yet in the destination
  175294. * (and we don't want to use the source's value).
  175295. */
  175296. max_v_samp_factor = 1;
  175297. for (ci = 0; ci < dstinfo->num_components; ci++) {
  175298. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  175299. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  175300. }
  175301. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  175302. if (MCU_rows > 0) /* can't trim to 0 pixels */
  175303. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  175304. }
  175305. /* Adjust output image parameters as needed.
  175306. *
  175307. * This must be called after jpeg_copy_critical_parameters()
  175308. * and before jpeg_write_coefficients().
  175309. *
  175310. * The return value is the set of virtual coefficient arrays to be written
  175311. * (either the ones allocated by jtransform_request_workspace, or the
  175312. * original source data arrays). The caller will need to pass this value
  175313. * to jpeg_write_coefficients().
  175314. */
  175315. GLOBAL(jvirt_barray_ptr *)
  175316. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  175317. j_compress_ptr dstinfo,
  175318. jvirt_barray_ptr *src_coef_arrays,
  175319. jpeg_transform_info *info)
  175320. {
  175321. /* If force-to-grayscale is requested, adjust destination parameters */
  175322. if (info->force_grayscale) {
  175323. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  175324. * properly. Among other things, the target h_samp_factor & v_samp_factor
  175325. * will get set to 1, which typically won't match the source.
  175326. * In fact we do this even if the source is already grayscale; that
  175327. * provides an easy way of coercing a grayscale JPEG with funny sampling
  175328. * factors to the customary 1,1. (Some decoders fail on other factors.)
  175329. */
  175330. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  175331. dstinfo->num_components == 3) ||
  175332. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  175333. dstinfo->num_components == 1)) {
  175334. /* We have to preserve the source's quantization table number. */
  175335. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  175336. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  175337. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  175338. } else {
  175339. /* Sorry, can't do it */
  175340. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  175341. }
  175342. }
  175343. /* Correct the destination's image dimensions etc if necessary */
  175344. switch (info->transform) {
  175345. case JXFORM_NONE:
  175346. /* Nothing to do */
  175347. break;
  175348. case JXFORM_FLIP_H:
  175349. if (info->trim)
  175350. trim_right_edge(dstinfo);
  175351. break;
  175352. case JXFORM_FLIP_V:
  175353. if (info->trim)
  175354. trim_bottom_edge(dstinfo);
  175355. break;
  175356. case JXFORM_TRANSPOSE:
  175357. transpose_critical_parameters(dstinfo);
  175358. /* transpose does NOT have to trim anything */
  175359. break;
  175360. case JXFORM_TRANSVERSE:
  175361. transpose_critical_parameters(dstinfo);
  175362. if (info->trim) {
  175363. trim_right_edge(dstinfo);
  175364. trim_bottom_edge(dstinfo);
  175365. }
  175366. break;
  175367. case JXFORM_ROT_90:
  175368. transpose_critical_parameters(dstinfo);
  175369. if (info->trim)
  175370. trim_right_edge(dstinfo);
  175371. break;
  175372. case JXFORM_ROT_180:
  175373. if (info->trim) {
  175374. trim_right_edge(dstinfo);
  175375. trim_bottom_edge(dstinfo);
  175376. }
  175377. break;
  175378. case JXFORM_ROT_270:
  175379. transpose_critical_parameters(dstinfo);
  175380. if (info->trim)
  175381. trim_bottom_edge(dstinfo);
  175382. break;
  175383. }
  175384. /* Return the appropriate output data set */
  175385. if (info->workspace_coef_arrays != NULL)
  175386. return info->workspace_coef_arrays;
  175387. return src_coef_arrays;
  175388. }
  175389. /* Execute the actual transformation, if any.
  175390. *
  175391. * This must be called *after* jpeg_write_coefficients, because it depends
  175392. * on jpeg_write_coefficients to have computed subsidiary values such as
  175393. * the per-component width and height fields in the destination object.
  175394. *
  175395. * Note that some transformations will modify the source data arrays!
  175396. */
  175397. GLOBAL(void)
  175398. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  175399. j_compress_ptr dstinfo,
  175400. jvirt_barray_ptr *src_coef_arrays,
  175401. jpeg_transform_info *info)
  175402. {
  175403. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  175404. switch (info->transform) {
  175405. case JXFORM_NONE:
  175406. break;
  175407. case JXFORM_FLIP_H:
  175408. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  175409. break;
  175410. case JXFORM_FLIP_V:
  175411. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175412. break;
  175413. case JXFORM_TRANSPOSE:
  175414. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175415. break;
  175416. case JXFORM_TRANSVERSE:
  175417. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175418. break;
  175419. case JXFORM_ROT_90:
  175420. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175421. break;
  175422. case JXFORM_ROT_180:
  175423. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175424. break;
  175425. case JXFORM_ROT_270:
  175426. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  175427. break;
  175428. }
  175429. }
  175430. #endif /* TRANSFORMS_SUPPORTED */
  175431. /* Setup decompression object to save desired markers in memory.
  175432. * This must be called before jpeg_read_header() to have the desired effect.
  175433. */
  175434. GLOBAL(void)
  175435. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  175436. {
  175437. #ifdef SAVE_MARKERS_SUPPORTED
  175438. int m;
  175439. /* Save comments except under NONE option */
  175440. if (option != JCOPYOPT_NONE) {
  175441. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  175442. }
  175443. /* Save all types of APPn markers iff ALL option */
  175444. if (option == JCOPYOPT_ALL) {
  175445. for (m = 0; m < 16; m++)
  175446. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  175447. }
  175448. #endif /* SAVE_MARKERS_SUPPORTED */
  175449. }
  175450. /* Copy markers saved in the given source object to the destination object.
  175451. * This should be called just after jpeg_start_compress() or
  175452. * jpeg_write_coefficients().
  175453. * Note that those routines will have written the SOI, and also the
  175454. * JFIF APP0 or Adobe APP14 markers if selected.
  175455. */
  175456. GLOBAL(void)
  175457. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  175458. JCOPY_OPTION option)
  175459. {
  175460. jpeg_saved_marker_ptr marker;
  175461. /* In the current implementation, we don't actually need to examine the
  175462. * option flag here; we just copy everything that got saved.
  175463. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  175464. * if the encoder library already wrote one.
  175465. */
  175466. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  175467. if (dstinfo->write_JFIF_header &&
  175468. marker->marker == JPEG_APP0 &&
  175469. marker->data_length >= 5 &&
  175470. GETJOCTET(marker->data[0]) == 0x4A &&
  175471. GETJOCTET(marker->data[1]) == 0x46 &&
  175472. GETJOCTET(marker->data[2]) == 0x49 &&
  175473. GETJOCTET(marker->data[3]) == 0x46 &&
  175474. GETJOCTET(marker->data[4]) == 0)
  175475. continue; /* reject duplicate JFIF */
  175476. if (dstinfo->write_Adobe_marker &&
  175477. marker->marker == JPEG_APP0+14 &&
  175478. marker->data_length >= 5 &&
  175479. GETJOCTET(marker->data[0]) == 0x41 &&
  175480. GETJOCTET(marker->data[1]) == 0x64 &&
  175481. GETJOCTET(marker->data[2]) == 0x6F &&
  175482. GETJOCTET(marker->data[3]) == 0x62 &&
  175483. GETJOCTET(marker->data[4]) == 0x65)
  175484. continue; /* reject duplicate Adobe */
  175485. #ifdef NEED_FAR_POINTERS
  175486. /* We could use jpeg_write_marker if the data weren't FAR... */
  175487. {
  175488. unsigned int i;
  175489. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  175490. for (i = 0; i < marker->data_length; i++)
  175491. jpeg_write_m_byte(dstinfo, marker->data[i]);
  175492. }
  175493. #else
  175494. jpeg_write_marker(dstinfo, marker->marker,
  175495. marker->data, marker->data_length);
  175496. #endif
  175497. }
  175498. }
  175499. /********* End of inlined file: transupp.c *********/
  175500. }
  175501. #else
  175502. #define JPEG_INTERNALS
  175503. #undef FAR
  175504. #include <jpeglib.h>
  175505. #endif
  175506. }
  175507. #if JUCE_MSVC
  175508. #pragma warning (pop)
  175509. #endif
  175510. BEGIN_JUCE_NAMESPACE
  175511. using namespace jpeglibNamespace;
  175512. #if ! JUCE_WIN32
  175513. using jpeglibNamespace::boolean;
  175514. #endif
  175515. struct JPEGDecodingFailure {};
  175516. static void fatalErrorHandler (j_common_ptr)
  175517. {
  175518. throw JPEGDecodingFailure();
  175519. }
  175520. static void silentErrorCallback1 (j_common_ptr) {}
  175521. static void silentErrorCallback2 (j_common_ptr, int) {}
  175522. static void silentErrorCallback3 (j_common_ptr, char*) {}
  175523. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  175524. {
  175525. zerostruct (err);
  175526. err.error_exit = fatalErrorHandler;
  175527. err.emit_message = silentErrorCallback2;
  175528. err.output_message = silentErrorCallback1;
  175529. err.format_message = silentErrorCallback3;
  175530. err.reset_error_mgr = silentErrorCallback1;
  175531. }
  175532. static void dummyCallback1 (j_decompress_ptr) throw()
  175533. {
  175534. }
  175535. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  175536. {
  175537. decompStruct->src->next_input_byte += num;
  175538. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  175539. decompStruct->src->bytes_in_buffer -= num;
  175540. }
  175541. static boolean jpegFill (j_decompress_ptr) throw()
  175542. {
  175543. return 0;
  175544. }
  175545. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  175546. {
  175547. MemoryBlock mb;
  175548. in.readIntoMemoryBlock (mb);
  175549. Image* image = 0;
  175550. if (mb.getSize() > 16)
  175551. {
  175552. struct jpeg_decompress_struct jpegDecompStruct;
  175553. struct jpeg_error_mgr jerr;
  175554. setupSilentErrorHandler (jerr);
  175555. jpegDecompStruct.err = &jerr;
  175556. jpeg_create_decompress (&jpegDecompStruct);
  175557. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  175558. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  175559. jpegDecompStruct.src->init_source = dummyCallback1;
  175560. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  175561. jpegDecompStruct.src->skip_input_data = jpegSkip;
  175562. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  175563. jpegDecompStruct.src->term_source = dummyCallback1;
  175564. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  175565. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  175566. try
  175567. {
  175568. jpeg_read_header (&jpegDecompStruct, TRUE);
  175569. jpeg_calc_output_dimensions (&jpegDecompStruct);
  175570. const int width = jpegDecompStruct.output_width;
  175571. const int height = jpegDecompStruct.output_height;
  175572. jpegDecompStruct.out_color_space = JCS_RGB;
  175573. JSAMPARRAY buffer
  175574. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  175575. JPOOL_IMAGE,
  175576. width * 3, 1);
  175577. if (jpeg_start_decompress (&jpegDecompStruct))
  175578. {
  175579. image = new Image (Image::RGB, width, height, false);
  175580. for (int y = 0; y < height; ++y)
  175581. {
  175582. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  175583. int stride, pixelStride;
  175584. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  175585. const uint8* src = *buffer;
  175586. uint8* dest = pixels;
  175587. for (int i = width; --i >= 0;)
  175588. {
  175589. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  175590. dest += pixelStride;
  175591. src += 3;
  175592. }
  175593. image->releasePixelDataReadWrite (pixels);
  175594. }
  175595. jpeg_finish_decompress (&jpegDecompStruct);
  175596. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  175597. }
  175598. jpeg_destroy_decompress (&jpegDecompStruct);
  175599. }
  175600. catch (...)
  175601. {}
  175602. }
  175603. return image;
  175604. }
  175605. static const int bufferSize = 512;
  175606. struct JuceJpegDest : public jpeg_destination_mgr
  175607. {
  175608. OutputStream* output;
  175609. char* buffer;
  175610. };
  175611. static void jpegWriteInit (j_compress_ptr) throw()
  175612. {
  175613. }
  175614. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  175615. {
  175616. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175617. const int numToWrite = bufferSize - dest->free_in_buffer;
  175618. dest->output->write (dest->buffer, numToWrite);
  175619. }
  175620. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  175621. {
  175622. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  175623. const int numToWrite = bufferSize;
  175624. dest->next_output_byte = (JOCTET*) dest->buffer;
  175625. dest->free_in_buffer = bufferSize;
  175626. return dest->output->write (dest->buffer, numToWrite);
  175627. }
  175628. bool juce_writeJPEGImageToStream (const Image& image,
  175629. OutputStream& out,
  175630. float quality) throw()
  175631. {
  175632. if (image.hasAlphaChannel())
  175633. {
  175634. // this method could fill the background in white and still save the image..
  175635. jassertfalse
  175636. return true;
  175637. }
  175638. struct jpeg_compress_struct jpegCompStruct;
  175639. struct jpeg_error_mgr jerr;
  175640. setupSilentErrorHandler (jerr);
  175641. jpegCompStruct.err = &jerr;
  175642. jpeg_create_compress (&jpegCompStruct);
  175643. JuceJpegDest dest;
  175644. jpegCompStruct.dest = &dest;
  175645. dest.output = &out;
  175646. dest.buffer = (char*) juce_malloc (bufferSize);
  175647. dest.next_output_byte = (JOCTET*) dest.buffer;
  175648. dest.free_in_buffer = bufferSize;
  175649. dest.init_destination = jpegWriteInit;
  175650. dest.empty_output_buffer = jpegWriteFlush;
  175651. dest.term_destination = jpegWriteTerminate;
  175652. jpegCompStruct.image_width = image.getWidth();
  175653. jpegCompStruct.image_height = image.getHeight();
  175654. jpegCompStruct.input_components = 3;
  175655. jpegCompStruct.in_color_space = JCS_RGB;
  175656. jpegCompStruct.write_JFIF_header = 1;
  175657. jpegCompStruct.X_density = 72;
  175658. jpegCompStruct.Y_density = 72;
  175659. jpeg_set_defaults (&jpegCompStruct);
  175660. jpegCompStruct.dct_method = JDCT_FLOAT;
  175661. jpegCompStruct.optimize_coding = 1;
  175662. // jpegCompStruct.smoothing_factor = 10;
  175663. if (quality < 0.0f)
  175664. quality = 0.85f;
  175665. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  175666. jpeg_start_compress (&jpegCompStruct, TRUE);
  175667. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  175668. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  175669. JPOOL_IMAGE,
  175670. strideBytes, 1);
  175671. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  175672. {
  175673. int stride, pixelStride;
  175674. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  175675. const uint8* src = pixels;
  175676. uint8* dst = *buffer;
  175677. for (int i = jpegCompStruct.image_width; --i >= 0;)
  175678. {
  175679. *dst++ = ((const PixelRGB*) src)->getRed();
  175680. *dst++ = ((const PixelRGB*) src)->getGreen();
  175681. *dst++ = ((const PixelRGB*) src)->getBlue();
  175682. src += pixelStride;
  175683. }
  175684. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  175685. image.releasePixelDataReadOnly (pixels);
  175686. }
  175687. jpeg_finish_compress (&jpegCompStruct);
  175688. jpeg_destroy_compress (&jpegCompStruct);
  175689. juce_free (dest.buffer);
  175690. out.flush();
  175691. return true;
  175692. }
  175693. END_JUCE_NAMESPACE
  175694. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  175695. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  175696. #ifdef _MSC_VER
  175697. #pragma warning (push)
  175698. #pragma warning (disable: 4390 4611)
  175699. #endif
  175700. namespace zlibNamespace
  175701. {
  175702. #if JUCE_INCLUDE_ZLIB_CODE
  175703. #undef OS_CODE
  175704. #undef fdopen
  175705. #undef OS_CODE
  175706. #else
  175707. #include <zlib.h>
  175708. #endif
  175709. }
  175710. namespace pnglibNamespace
  175711. {
  175712. using namespace zlibNamespace;
  175713. #if JUCE_INCLUDE_PNGLIB_CODE
  175714. #if _MSC_VER != 1310
  175715. using ::calloc; // (causes conflict in VS.NET 2003)
  175716. using ::malloc;
  175717. using ::free;
  175718. #endif
  175719. extern "C"
  175720. {
  175721. using ::abs;
  175722. #define PNG_INTERNAL
  175723. #define NO_DUMMY_DECL
  175724. #define PNG_SETJMP_NOT_SUPPORTED
  175725. /********* Start of inlined file: png.h *********/
  175726. /* png.h - header file for PNG reference library
  175727. *
  175728. * libpng version 1.2.21 - October 4, 2007
  175729. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  175730. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  175731. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  175732. *
  175733. * Authors and maintainers:
  175734. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  175735. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  175736. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  175737. * See also "Contributing Authors", below.
  175738. *
  175739. * Note about libpng version numbers:
  175740. *
  175741. * Due to various miscommunications, unforeseen code incompatibilities
  175742. * and occasional factors outside the authors' control, version numbering
  175743. * on the library has not always been consistent and straightforward.
  175744. * The following table summarizes matters since version 0.89c, which was
  175745. * the first widely used release:
  175746. *
  175747. * source png.h png.h shared-lib
  175748. * version string int version
  175749. * ------- ------ ----- ----------
  175750. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  175751. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  175752. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  175753. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  175754. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  175755. * 0.97c 0.97 97 2.0.97
  175756. * 0.98 0.98 98 2.0.98
  175757. * 0.99 0.99 98 2.0.99
  175758. * 0.99a-m 0.99 99 2.0.99
  175759. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  175760. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  175761. * 1.0.1 png.h string is 10001 2.1.0
  175762. * 1.0.1a-e identical to the 10002 from here on, the shared library
  175763. * 1.0.2 source version) 10002 is 2.V where V is the source code
  175764. * 1.0.2a-b 10003 version, except as noted.
  175765. * 1.0.3 10003
  175766. * 1.0.3a-d 10004
  175767. * 1.0.4 10004
  175768. * 1.0.4a-f 10005
  175769. * 1.0.5 (+ 2 patches) 10005
  175770. * 1.0.5a-d 10006
  175771. * 1.0.5e-r 10100 (not source compatible)
  175772. * 1.0.5s-v 10006 (not binary compatible)
  175773. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  175774. * 1.0.6d-f 10007 (still binary incompatible)
  175775. * 1.0.6g 10007
  175776. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  175777. * 1.0.6i 10007 10.6i
  175778. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  175779. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  175780. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  175781. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  175782. * 1.0.7 1 10007 (still compatible)
  175783. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  175784. * 1.0.8rc1 1 10008 2.1.0.8rc1
  175785. * 1.0.8 1 10008 2.1.0.8
  175786. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  175787. * 1.0.9rc1 1 10009 2.1.0.9rc1
  175788. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  175789. * 1.0.9rc2 1 10009 2.1.0.9rc2
  175790. * 1.0.9 1 10009 2.1.0.9
  175791. * 1.0.10beta1 1 10010 2.1.0.10beta1
  175792. * 1.0.10rc1 1 10010 2.1.0.10rc1
  175793. * 1.0.10 1 10010 2.1.0.10
  175794. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  175795. * 1.0.11rc1 1 10011 2.1.0.11rc1
  175796. * 1.0.11 1 10011 2.1.0.11
  175797. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  175798. * 1.0.12rc1 2 10012 2.1.0.12rc1
  175799. * 1.0.12 2 10012 2.1.0.12
  175800. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  175801. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  175802. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  175803. * 1.2.0rc1 3 10200 3.1.2.0rc1
  175804. * 1.2.0 3 10200 3.1.2.0
  175805. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  175806. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  175807. * 1.2.1 3 10201 3.1.2.1
  175808. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  175809. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  175810. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  175811. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  175812. * 1.0.13 10 10013 10.so.0.1.0.13
  175813. * 1.2.2 12 10202 12.so.0.1.2.2
  175814. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  175815. * 1.2.3 12 10203 12.so.0.1.2.3
  175816. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  175817. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  175818. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  175819. * 1.0.14 10 10014 10.so.0.1.0.14
  175820. * 1.2.4 13 10204 12.so.0.1.2.4
  175821. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  175822. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  175823. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  175824. * 1.0.15 10 10015 10.so.0.1.0.15
  175825. * 1.2.5 13 10205 12.so.0.1.2.5
  175826. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  175827. * 1.0.16 10 10016 10.so.0.1.0.16
  175828. * 1.2.6 13 10206 12.so.0.1.2.6
  175829. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  175830. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  175831. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  175832. * 1.0.17 10 10017 10.so.0.1.0.17
  175833. * 1.2.7 13 10207 12.so.0.1.2.7
  175834. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  175835. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  175836. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  175837. * 1.0.18 10 10018 10.so.0.1.0.18
  175838. * 1.2.8 13 10208 12.so.0.1.2.8
  175839. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  175840. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  175841. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  175842. * 1.2.9 13 10209 12.so.0.9[.0]
  175843. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  175844. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  175845. * 1.2.10 13 10210 12.so.0.10[.0]
  175846. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  175847. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  175848. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  175849. * 1.0.19 10 10019 10.so.0.19[.0]
  175850. * 1.2.11 13 10211 12.so.0.11[.0]
  175851. * 1.0.20 10 10020 10.so.0.20[.0]
  175852. * 1.2.12 13 10212 12.so.0.12[.0]
  175853. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  175854. * 1.0.21 10 10021 10.so.0.21[.0]
  175855. * 1.2.13 13 10213 12.so.0.13[.0]
  175856. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  175857. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  175858. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  175859. * 1.0.22 10 10022 10.so.0.22[.0]
  175860. * 1.2.14 13 10214 12.so.0.14[.0]
  175861. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  175862. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  175863. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  175864. * 1.0.23 10 10023 10.so.0.23[.0]
  175865. * 1.2.15 13 10215 12.so.0.15[.0]
  175866. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  175867. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  175868. * 1.0.24 10 10024 10.so.0.24[.0]
  175869. * 1.2.16 13 10216 12.so.0.16[.0]
  175870. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  175871. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  175872. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  175873. * 1.0.25 10 10025 10.so.0.25[.0]
  175874. * 1.2.17 13 10217 12.so.0.17[.0]
  175875. * 1.0.26 10 10026 10.so.0.26[.0]
  175876. * 1.2.18 13 10218 12.so.0.18[.0]
  175877. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  175878. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  175879. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  175880. * 1.0.27 10 10027 10.so.0.27[.0]
  175881. * 1.2.19 13 10219 12.so.0.19[.0]
  175882. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  175883. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  175884. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  175885. * 1.0.28 10 10028 10.so.0.28[.0]
  175886. * 1.2.20 13 10220 12.so.0.20[.0]
  175887. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  175888. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  175889. * 1.0.29 10 10029 10.so.0.29[.0]
  175890. * 1.2.21 13 10221 12.so.0.21[.0]
  175891. *
  175892. * Henceforth the source version will match the shared-library major
  175893. * and minor numbers; the shared-library major version number will be
  175894. * used for changes in backward compatibility, as it is intended. The
  175895. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  175896. * for applications, is an unsigned integer of the form xyyzz corresponding
  175897. * to the source version x.y.z (leading zeros in y and z). Beta versions
  175898. * were given the previous public release number plus a letter, until
  175899. * version 1.0.6j; from then on they were given the upcoming public
  175900. * release number plus "betaNN" or "rcN".
  175901. *
  175902. * Binary incompatibility exists only when applications make direct access
  175903. * to the info_ptr or png_ptr members through png.h, and the compiled
  175904. * application is loaded with a different version of the library.
  175905. *
  175906. * DLLNUM will change each time there are forward or backward changes
  175907. * in binary compatibility (e.g., when a new feature is added).
  175908. *
  175909. * See libpng.txt or libpng.3 for more information. The PNG specification
  175910. * is available as a W3C Recommendation and as an ISO Specification,
  175911. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  175912. */
  175913. /*
  175914. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  175915. *
  175916. * If you modify libpng you may insert additional notices immediately following
  175917. * this sentence.
  175918. *
  175919. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  175920. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  175921. * distributed according to the same disclaimer and license as libpng-1.2.5
  175922. * with the following individual added to the list of Contributing Authors:
  175923. *
  175924. * Cosmin Truta
  175925. *
  175926. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  175927. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  175928. * distributed according to the same disclaimer and license as libpng-1.0.6
  175929. * with the following individuals added to the list of Contributing Authors:
  175930. *
  175931. * Simon-Pierre Cadieux
  175932. * Eric S. Raymond
  175933. * Gilles Vollant
  175934. *
  175935. * and with the following additions to the disclaimer:
  175936. *
  175937. * There is no warranty against interference with your enjoyment of the
  175938. * library or against infringement. There is no warranty that our
  175939. * efforts or the library will fulfill any of your particular purposes
  175940. * or needs. This library is provided with all faults, and the entire
  175941. * risk of satisfactory quality, performance, accuracy, and effort is with
  175942. * the user.
  175943. *
  175944. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  175945. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  175946. * distributed according to the same disclaimer and license as libpng-0.96,
  175947. * with the following individuals added to the list of Contributing Authors:
  175948. *
  175949. * Tom Lane
  175950. * Glenn Randers-Pehrson
  175951. * Willem van Schaik
  175952. *
  175953. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  175954. * Copyright (c) 1996, 1997 Andreas Dilger
  175955. * Distributed according to the same disclaimer and license as libpng-0.88,
  175956. * with the following individuals added to the list of Contributing Authors:
  175957. *
  175958. * John Bowler
  175959. * Kevin Bracey
  175960. * Sam Bushell
  175961. * Magnus Holmgren
  175962. * Greg Roelofs
  175963. * Tom Tanner
  175964. *
  175965. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  175966. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  175967. *
  175968. * For the purposes of this copyright and license, "Contributing Authors"
  175969. * is defined as the following set of individuals:
  175970. *
  175971. * Andreas Dilger
  175972. * Dave Martindale
  175973. * Guy Eric Schalnat
  175974. * Paul Schmidt
  175975. * Tim Wegner
  175976. *
  175977. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  175978. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  175979. * including, without limitation, the warranties of merchantability and of
  175980. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  175981. * assume no liability for direct, indirect, incidental, special, exemplary,
  175982. * or consequential damages, which may result from the use of the PNG
  175983. * Reference Library, even if advised of the possibility of such damage.
  175984. *
  175985. * Permission is hereby granted to use, copy, modify, and distribute this
  175986. * source code, or portions hereof, for any purpose, without fee, subject
  175987. * to the following restrictions:
  175988. *
  175989. * 1. The origin of this source code must not be misrepresented.
  175990. *
  175991. * 2. Altered versions must be plainly marked as such and
  175992. * must not be misrepresented as being the original source.
  175993. *
  175994. * 3. This Copyright notice may not be removed or altered from
  175995. * any source or altered source distribution.
  175996. *
  175997. * The Contributing Authors and Group 42, Inc. specifically permit, without
  175998. * fee, and encourage the use of this source code as a component to
  175999. * supporting the PNG file format in commercial products. If you use this
  176000. * source code in a product, acknowledgment is not required but would be
  176001. * appreciated.
  176002. */
  176003. /*
  176004. * A "png_get_copyright" function is available, for convenient use in "about"
  176005. * boxes and the like:
  176006. *
  176007. * printf("%s",png_get_copyright(NULL));
  176008. *
  176009. * Also, the PNG logo (in PNG format, of course) is supplied in the
  176010. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  176011. */
  176012. /*
  176013. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  176014. * certification mark of the Open Source Initiative.
  176015. */
  176016. /*
  176017. * The contributing authors would like to thank all those who helped
  176018. * with testing, bug fixes, and patience. This wouldn't have been
  176019. * possible without all of you.
  176020. *
  176021. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  176022. */
  176023. /*
  176024. * Y2K compliance in libpng:
  176025. * =========================
  176026. *
  176027. * October 4, 2007
  176028. *
  176029. * Since the PNG Development group is an ad-hoc body, we can't make
  176030. * an official declaration.
  176031. *
  176032. * This is your unofficial assurance that libpng from version 0.71 and
  176033. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  176034. * versions were also Y2K compliant.
  176035. *
  176036. * Libpng only has three year fields. One is a 2-byte unsigned integer
  176037. * that will hold years up to 65535. The other two hold the date in text
  176038. * format, and will hold years up to 9999.
  176039. *
  176040. * The integer is
  176041. * "png_uint_16 year" in png_time_struct.
  176042. *
  176043. * The strings are
  176044. * "png_charp time_buffer" in png_struct and
  176045. * "near_time_buffer", which is a local character string in png.c.
  176046. *
  176047. * There are seven time-related functions:
  176048. * png.c: png_convert_to_rfc_1123() in png.c
  176049. * (formerly png_convert_to_rfc_1152() in error)
  176050. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  176051. * png_convert_from_time_t() in pngwrite.c
  176052. * png_get_tIME() in pngget.c
  176053. * png_handle_tIME() in pngrutil.c, called in pngread.c
  176054. * png_set_tIME() in pngset.c
  176055. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  176056. *
  176057. * All handle dates properly in a Y2K environment. The
  176058. * png_convert_from_time_t() function calls gmtime() to convert from system
  176059. * clock time, which returns (year - 1900), which we properly convert to
  176060. * the full 4-digit year. There is a possibility that applications using
  176061. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  176062. * function, or that they are incorrectly passing only a 2-digit year
  176063. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  176064. * but this is not under our control. The libpng documentation has always
  176065. * stated that it works with 4-digit years, and the APIs have been
  176066. * documented as such.
  176067. *
  176068. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  176069. * integer to hold the year, and can hold years as large as 65535.
  176070. *
  176071. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  176072. * no date-related code.
  176073. *
  176074. * Glenn Randers-Pehrson
  176075. * libpng maintainer
  176076. * PNG Development Group
  176077. */
  176078. #ifndef PNG_H
  176079. #define PNG_H
  176080. /* This is not the place to learn how to use libpng. The file libpng.txt
  176081. * describes how to use libpng, and the file example.c summarizes it
  176082. * with some code on which to build. This file is useful for looking
  176083. * at the actual function definitions and structure components.
  176084. */
  176085. /* Version information for png.h - this should match the version in png.c */
  176086. #define PNG_LIBPNG_VER_STRING "1.2.21"
  176087. #define PNG_HEADER_VERSION_STRING \
  176088. " libpng version 1.2.21 - October 4, 2007\n"
  176089. #define PNG_LIBPNG_VER_SONUM 0
  176090. #define PNG_LIBPNG_VER_DLLNUM 13
  176091. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  176092. #define PNG_LIBPNG_VER_MAJOR 1
  176093. #define PNG_LIBPNG_VER_MINOR 2
  176094. #define PNG_LIBPNG_VER_RELEASE 21
  176095. /* This should match the numeric part of the final component of
  176096. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  176097. #define PNG_LIBPNG_VER_BUILD 0
  176098. /* Release Status */
  176099. #define PNG_LIBPNG_BUILD_ALPHA 1
  176100. #define PNG_LIBPNG_BUILD_BETA 2
  176101. #define PNG_LIBPNG_BUILD_RC 3
  176102. #define PNG_LIBPNG_BUILD_STABLE 4
  176103. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  176104. /* Release-Specific Flags */
  176105. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  176106. PNG_LIBPNG_BUILD_STABLE only */
  176107. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  176108. PNG_LIBPNG_BUILD_SPECIAL */
  176109. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  176110. PNG_LIBPNG_BUILD_PRIVATE */
  176111. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  176112. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  176113. * We must not include leading zeros.
  176114. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  176115. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  176116. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  176117. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  176118. #ifndef PNG_VERSION_INFO_ONLY
  176119. /* include the compression library's header */
  176120. #endif
  176121. /* include all user configurable info, including optional assembler routines */
  176122. /********* Start of inlined file: pngconf.h *********/
  176123. /* pngconf.h - machine configurable file for libpng
  176124. *
  176125. * libpng version 1.2.21 - October 4, 2007
  176126. * For conditions of distribution and use, see copyright notice in png.h
  176127. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  176128. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  176129. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  176130. */
  176131. /* Any machine specific code is near the front of this file, so if you
  176132. * are configuring libpng for a machine, you may want to read the section
  176133. * starting here down to where it starts to typedef png_color, png_text,
  176134. * and png_info.
  176135. */
  176136. #ifndef PNGCONF_H
  176137. #define PNGCONF_H
  176138. #define PNG_1_2_X
  176139. // These are some Juce config settings that should remove any unnecessary code bloat..
  176140. #define PNG_NO_STDIO 1
  176141. #define PNG_DEBUG 0
  176142. #define PNG_NO_WARNINGS 1
  176143. #define PNG_NO_ERROR_TEXT 1
  176144. #define PNG_NO_ERROR_NUMBERS 1
  176145. #define PNG_NO_USER_MEM 1
  176146. #define PNG_NO_READ_iCCP 1
  176147. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  176148. #define PNG_NO_READ_USER_CHUNKS 1
  176149. #define PNG_NO_READ_iTXt 1
  176150. #define PNG_NO_READ_sCAL 1
  176151. #define PNG_NO_READ_sPLT 1
  176152. #define png_error(a, b) png_err(a)
  176153. #define png_warning(a, b)
  176154. #define png_chunk_error(a, b) png_err(a)
  176155. #define png_chunk_warning(a, b)
  176156. /*
  176157. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  176158. * includes the resource compiler for Windows DLL configurations.
  176159. */
  176160. #ifdef PNG_USER_CONFIG
  176161. # ifndef PNG_USER_PRIVATEBUILD
  176162. # define PNG_USER_PRIVATEBUILD
  176163. # endif
  176164. #include "pngusr.h"
  176165. #endif
  176166. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  176167. #ifdef PNG_CONFIGURE_LIBPNG
  176168. #ifdef HAVE_CONFIG_H
  176169. #include "config.h"
  176170. #endif
  176171. #endif
  176172. /*
  176173. * Added at libpng-1.2.8
  176174. *
  176175. * If you create a private DLL you need to define in "pngusr.h" the followings:
  176176. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  176177. * the DLL was built>
  176178. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  176179. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  176180. * distinguish your DLL from those of the official release. These
  176181. * correspond to the trailing letters that come after the version
  176182. * number and must match your private DLL name>
  176183. * e.g. // private DLL "libpng13gx.dll"
  176184. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  176185. *
  176186. * The following macros are also at your disposal if you want to complete the
  176187. * DLL VERSIONINFO structure.
  176188. * - PNG_USER_VERSIONINFO_COMMENTS
  176189. * - PNG_USER_VERSIONINFO_COMPANYNAME
  176190. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  176191. */
  176192. #ifdef __STDC__
  176193. #ifdef SPECIALBUILD
  176194. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  176195. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  176196. #endif
  176197. #ifdef PRIVATEBUILD
  176198. # pragma message("PRIVATEBUILD is deprecated.\
  176199. Use PNG_USER_PRIVATEBUILD instead.")
  176200. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  176201. #endif
  176202. #endif /* __STDC__ */
  176203. #ifndef PNG_VERSION_INFO_ONLY
  176204. /* End of material added to libpng-1.2.8 */
  176205. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  176206. Restored at libpng-1.2.21 */
  176207. # define PNG_WARN_UNINITIALIZED_ROW 1
  176208. /* End of material added at libpng-1.2.19/1.2.21 */
  176209. /* This is the size of the compression buffer, and thus the size of
  176210. * an IDAT chunk. Make this whatever size you feel is best for your
  176211. * machine. One of these will be allocated per png_struct. When this
  176212. * is full, it writes the data to the disk, and does some other
  176213. * calculations. Making this an extremely small size will slow
  176214. * the library down, but you may want to experiment to determine
  176215. * where it becomes significant, if you are concerned with memory
  176216. * usage. Note that zlib allocates at least 32Kb also. For readers,
  176217. * this describes the size of the buffer available to read the data in.
  176218. * Unless this gets smaller than the size of a row (compressed),
  176219. * it should not make much difference how big this is.
  176220. */
  176221. #ifndef PNG_ZBUF_SIZE
  176222. # define PNG_ZBUF_SIZE 8192
  176223. #endif
  176224. /* Enable if you want a write-only libpng */
  176225. #ifndef PNG_NO_READ_SUPPORTED
  176226. # define PNG_READ_SUPPORTED
  176227. #endif
  176228. /* Enable if you want a read-only libpng */
  176229. #ifndef PNG_NO_WRITE_SUPPORTED
  176230. # define PNG_WRITE_SUPPORTED
  176231. #endif
  176232. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  176233. support PNGs that are embedded in MNG datastreams */
  176234. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  176235. # ifndef PNG_MNG_FEATURES_SUPPORTED
  176236. # define PNG_MNG_FEATURES_SUPPORTED
  176237. # endif
  176238. #endif
  176239. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  176240. # ifndef PNG_FLOATING_POINT_SUPPORTED
  176241. # define PNG_FLOATING_POINT_SUPPORTED
  176242. # endif
  176243. #endif
  176244. /* If you are running on a machine where you cannot allocate more
  176245. * than 64K of memory at once, uncomment this. While libpng will not
  176246. * normally need that much memory in a chunk (unless you load up a very
  176247. * large file), zlib needs to know how big of a chunk it can use, and
  176248. * libpng thus makes sure to check any memory allocation to verify it
  176249. * will fit into memory.
  176250. #define PNG_MAX_MALLOC_64K
  176251. */
  176252. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  176253. # define PNG_MAX_MALLOC_64K
  176254. #endif
  176255. /* Special munging to support doing things the 'cygwin' way:
  176256. * 'Normal' png-on-win32 defines/defaults:
  176257. * PNG_BUILD_DLL -- building dll
  176258. * PNG_USE_DLL -- building an application, linking to dll
  176259. * (no define) -- building static library, or building an
  176260. * application and linking to the static lib
  176261. * 'Cygwin' defines/defaults:
  176262. * PNG_BUILD_DLL -- (ignored) building the dll
  176263. * (no define) -- (ignored) building an application, linking to the dll
  176264. * PNG_STATIC -- (ignored) building the static lib, or building an
  176265. * application that links to the static lib.
  176266. * ALL_STATIC -- (ignored) building various static libs, or building an
  176267. * application that links to the static libs.
  176268. * Thus,
  176269. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  176270. * this bit of #ifdefs will define the 'correct' config variables based on
  176271. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  176272. * unnecessary.
  176273. *
  176274. * Also, the precedence order is:
  176275. * ALL_STATIC (since we can't #undef something outside our namespace)
  176276. * PNG_BUILD_DLL
  176277. * PNG_STATIC
  176278. * (nothing) == PNG_USE_DLL
  176279. *
  176280. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  176281. * of auto-import in binutils, we no longer need to worry about
  176282. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  176283. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  176284. * to __declspec() stuff. However, we DO need to worry about
  176285. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  176286. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  176287. */
  176288. #if defined(__CYGWIN__)
  176289. # if defined(ALL_STATIC)
  176290. # if defined(PNG_BUILD_DLL)
  176291. # undef PNG_BUILD_DLL
  176292. # endif
  176293. # if defined(PNG_USE_DLL)
  176294. # undef PNG_USE_DLL
  176295. # endif
  176296. # if defined(PNG_DLL)
  176297. # undef PNG_DLL
  176298. # endif
  176299. # if !defined(PNG_STATIC)
  176300. # define PNG_STATIC
  176301. # endif
  176302. # else
  176303. # if defined (PNG_BUILD_DLL)
  176304. # if defined(PNG_STATIC)
  176305. # undef PNG_STATIC
  176306. # endif
  176307. # if defined(PNG_USE_DLL)
  176308. # undef PNG_USE_DLL
  176309. # endif
  176310. # if !defined(PNG_DLL)
  176311. # define PNG_DLL
  176312. # endif
  176313. # else
  176314. # if defined(PNG_STATIC)
  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. # else
  176322. # if !defined(PNG_USE_DLL)
  176323. # define PNG_USE_DLL
  176324. # endif
  176325. # if !defined(PNG_DLL)
  176326. # define PNG_DLL
  176327. # endif
  176328. # endif
  176329. # endif
  176330. # endif
  176331. #endif
  176332. /* This protects us against compilers that run on a windowing system
  176333. * and thus don't have or would rather us not use the stdio types:
  176334. * stdin, stdout, and stderr. The only one currently used is stderr
  176335. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  176336. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  176337. * will also prevent these, plus will prevent the entire set of stdio
  176338. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  176339. * unless (PNG_DEBUG > 0) has been #defined.
  176340. *
  176341. * #define PNG_NO_CONSOLE_IO
  176342. * #define PNG_NO_STDIO
  176343. */
  176344. #if defined(_WIN32_WCE)
  176345. # include <windows.h>
  176346. /* Console I/O functions are not supported on WindowsCE */
  176347. # define PNG_NO_CONSOLE_IO
  176348. # ifdef PNG_DEBUG
  176349. # undef PNG_DEBUG
  176350. # endif
  176351. #endif
  176352. #ifdef PNG_BUILD_DLL
  176353. # ifndef PNG_CONSOLE_IO_SUPPORTED
  176354. # ifndef PNG_NO_CONSOLE_IO
  176355. # define PNG_NO_CONSOLE_IO
  176356. # endif
  176357. # endif
  176358. #endif
  176359. # ifdef PNG_NO_STDIO
  176360. # ifndef PNG_NO_CONSOLE_IO
  176361. # define PNG_NO_CONSOLE_IO
  176362. # endif
  176363. # ifdef PNG_DEBUG
  176364. # if (PNG_DEBUG > 0)
  176365. # include <stdio.h>
  176366. # endif
  176367. # endif
  176368. # else
  176369. # if !defined(_WIN32_WCE)
  176370. /* "stdio.h" functions are not supported on WindowsCE */
  176371. # include <stdio.h>
  176372. # endif
  176373. # endif
  176374. /* This macro protects us against machines that don't have function
  176375. * prototypes (ie K&R style headers). If your compiler does not handle
  176376. * function prototypes, define this macro and use the included ansi2knr.
  176377. * I've always been able to use _NO_PROTO as the indicator, but you may
  176378. * need to drag the empty declaration out in front of here, or change the
  176379. * ifdef to suit your own needs.
  176380. */
  176381. #ifndef PNGARG
  176382. #ifdef OF /* zlib prototype munger */
  176383. # define PNGARG(arglist) OF(arglist)
  176384. #else
  176385. #ifdef _NO_PROTO
  176386. # define PNGARG(arglist) ()
  176387. # ifndef PNG_TYPECAST_NULL
  176388. # define PNG_TYPECAST_NULL
  176389. # endif
  176390. #else
  176391. # define PNGARG(arglist) arglist
  176392. #endif /* _NO_PROTO */
  176393. #endif /* OF */
  176394. #endif /* PNGARG */
  176395. /* Try to determine if we are compiling on a Mac. Note that testing for
  176396. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  176397. * on non-Mac platforms.
  176398. */
  176399. #ifndef MACOS
  176400. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  176401. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  176402. # define MACOS
  176403. # endif
  176404. #endif
  176405. /* enough people need this for various reasons to include it here */
  176406. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  176407. # include <sys/types.h>
  176408. #endif
  176409. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  176410. # define PNG_SETJMP_SUPPORTED
  176411. #endif
  176412. #ifdef PNG_SETJMP_SUPPORTED
  176413. /* This is an attempt to force a single setjmp behaviour on Linux. If
  176414. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  176415. */
  176416. # ifdef __linux__
  176417. # ifdef _BSD_SOURCE
  176418. # define PNG_SAVE_BSD_SOURCE
  176419. # undef _BSD_SOURCE
  176420. # endif
  176421. # ifdef _SETJMP_H
  176422. /* If you encounter a compiler error here, see the explanation
  176423. * near the end of INSTALL.
  176424. */
  176425. __png.h__ already includes setjmp.h;
  176426. __dont__ include it again.;
  176427. # endif
  176428. # endif /* __linux__ */
  176429. /* include setjmp.h for error handling */
  176430. # include <setjmp.h>
  176431. # ifdef __linux__
  176432. # ifdef PNG_SAVE_BSD_SOURCE
  176433. # define _BSD_SOURCE
  176434. # undef PNG_SAVE_BSD_SOURCE
  176435. # endif
  176436. # endif /* __linux__ */
  176437. #endif /* PNG_SETJMP_SUPPORTED */
  176438. #ifdef BSD
  176439. #if ! JUCE_MAC
  176440. # include <strings.h>
  176441. #endif
  176442. #else
  176443. # include <string.h>
  176444. #endif
  176445. /* Other defines for things like memory and the like can go here. */
  176446. #ifdef PNG_INTERNAL
  176447. #include <stdlib.h>
  176448. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  176449. * aren't usually used outside the library (as far as I know), so it is
  176450. * debatable if they should be exported at all. In the future, when it is
  176451. * possible to have run-time registry of chunk-handling functions, some of
  176452. * these will be made available again.
  176453. #define PNG_EXTERN extern
  176454. */
  176455. #define PNG_EXTERN
  176456. /* Other defines specific to compilers can go here. Try to keep
  176457. * them inside an appropriate ifdef/endif pair for portability.
  176458. */
  176459. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  176460. # if defined(MACOS)
  176461. /* We need to check that <math.h> hasn't already been included earlier
  176462. * as it seems it doesn't agree with <fp.h>, yet we should really use
  176463. * <fp.h> if possible.
  176464. */
  176465. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  176466. # include <fp.h>
  176467. # endif
  176468. # else
  176469. # include <math.h>
  176470. # endif
  176471. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  176472. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  176473. * MATH=68881
  176474. */
  176475. # include <m68881.h>
  176476. # endif
  176477. #endif
  176478. /* Codewarrior on NT has linking problems without this. */
  176479. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  176480. # define PNG_ALWAYS_EXTERN
  176481. #endif
  176482. /* This provides the non-ANSI (far) memory allocation routines. */
  176483. #if defined(__TURBOC__) && defined(__MSDOS__)
  176484. # include <mem.h>
  176485. # include <alloc.h>
  176486. #endif
  176487. /* I have no idea why is this necessary... */
  176488. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  176489. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  176490. # include <malloc.h>
  176491. #endif
  176492. /* This controls how fine the dithering gets. As this allocates
  176493. * a largish chunk of memory (32K), those who are not as concerned
  176494. * with dithering quality can decrease some or all of these.
  176495. */
  176496. #ifndef PNG_DITHER_RED_BITS
  176497. # define PNG_DITHER_RED_BITS 5
  176498. #endif
  176499. #ifndef PNG_DITHER_GREEN_BITS
  176500. # define PNG_DITHER_GREEN_BITS 5
  176501. #endif
  176502. #ifndef PNG_DITHER_BLUE_BITS
  176503. # define PNG_DITHER_BLUE_BITS 5
  176504. #endif
  176505. /* This controls how fine the gamma correction becomes when you
  176506. * are only interested in 8 bits anyway. Increasing this value
  176507. * results in more memory being used, and more pow() functions
  176508. * being called to fill in the gamma tables. Don't set this value
  176509. * less then 8, and even that may not work (I haven't tested it).
  176510. */
  176511. #ifndef PNG_MAX_GAMMA_8
  176512. # define PNG_MAX_GAMMA_8 11
  176513. #endif
  176514. /* This controls how much a difference in gamma we can tolerate before
  176515. * we actually start doing gamma conversion.
  176516. */
  176517. #ifndef PNG_GAMMA_THRESHOLD
  176518. # define PNG_GAMMA_THRESHOLD 0.05
  176519. #endif
  176520. #endif /* PNG_INTERNAL */
  176521. /* The following uses const char * instead of char * for error
  176522. * and warning message functions, so some compilers won't complain.
  176523. * If you do not want to use const, define PNG_NO_CONST here.
  176524. */
  176525. #ifndef PNG_NO_CONST
  176526. # define PNG_CONST const
  176527. #else
  176528. # define PNG_CONST
  176529. #endif
  176530. /* The following defines give you the ability to remove code from the
  176531. * library that you will not be using. I wish I could figure out how to
  176532. * automate this, but I can't do that without making it seriously hard
  176533. * on the users. So if you are not using an ability, change the #define
  176534. * to and #undef, and that part of the library will not be compiled. If
  176535. * your linker can't find a function, you may want to make sure the
  176536. * ability is defined here. Some of these depend upon some others being
  176537. * defined. I haven't figured out all the interactions here, so you may
  176538. * have to experiment awhile to get everything to compile. If you are
  176539. * creating or using a shared library, you probably shouldn't touch this,
  176540. * as it will affect the size of the structures, and this will cause bad
  176541. * things to happen if the library and/or application ever change.
  176542. */
  176543. /* Any features you will not be using can be undef'ed here */
  176544. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  176545. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  176546. * on the compile line, then pick and choose which ones to define without
  176547. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  176548. * if you only want to have a png-compliant reader/writer but don't need
  176549. * any of the extra transformations. This saves about 80 kbytes in a
  176550. * typical installation of the library. (PNG_NO_* form added in version
  176551. * 1.0.1c, for consistency)
  176552. */
  176553. /* The size of the png_text structure changed in libpng-1.0.6 when
  176554. * iTXt support was added. iTXt support was turned off by default through
  176555. * libpng-1.2.x, to support old apps that malloc the png_text structure
  176556. * instead of calling png_set_text() and letting libpng malloc it. It
  176557. * was turned on by default in libpng-1.3.0.
  176558. */
  176559. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176560. # ifndef PNG_NO_iTXt_SUPPORTED
  176561. # define PNG_NO_iTXt_SUPPORTED
  176562. # endif
  176563. # ifndef PNG_NO_READ_iTXt
  176564. # define PNG_NO_READ_iTXt
  176565. # endif
  176566. # ifndef PNG_NO_WRITE_iTXt
  176567. # define PNG_NO_WRITE_iTXt
  176568. # endif
  176569. #endif
  176570. #if !defined(PNG_NO_iTXt_SUPPORTED)
  176571. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  176572. # define PNG_READ_iTXt
  176573. # endif
  176574. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  176575. # define PNG_WRITE_iTXt
  176576. # endif
  176577. #endif
  176578. /* The following support, added after version 1.0.0, can be turned off here en
  176579. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  176580. * with old applications that require the length of png_struct and png_info
  176581. * to remain unchanged.
  176582. */
  176583. #ifdef PNG_LEGACY_SUPPORTED
  176584. # define PNG_NO_FREE_ME
  176585. # define PNG_NO_READ_UNKNOWN_CHUNKS
  176586. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  176587. # define PNG_NO_READ_USER_CHUNKS
  176588. # define PNG_NO_READ_iCCP
  176589. # define PNG_NO_WRITE_iCCP
  176590. # define PNG_NO_READ_iTXt
  176591. # define PNG_NO_WRITE_iTXt
  176592. # define PNG_NO_READ_sCAL
  176593. # define PNG_NO_WRITE_sCAL
  176594. # define PNG_NO_READ_sPLT
  176595. # define PNG_NO_WRITE_sPLT
  176596. # define PNG_NO_INFO_IMAGE
  176597. # define PNG_NO_READ_RGB_TO_GRAY
  176598. # define PNG_NO_READ_USER_TRANSFORM
  176599. # define PNG_NO_WRITE_USER_TRANSFORM
  176600. # define PNG_NO_USER_MEM
  176601. # define PNG_NO_READ_EMPTY_PLTE
  176602. # define PNG_NO_MNG_FEATURES
  176603. # define PNG_NO_FIXED_POINT_SUPPORTED
  176604. #endif
  176605. /* Ignore attempt to turn off both floating and fixed point support */
  176606. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  176607. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  176608. # define PNG_FIXED_POINT_SUPPORTED
  176609. #endif
  176610. #ifndef PNG_NO_FREE_ME
  176611. # define PNG_FREE_ME_SUPPORTED
  176612. #endif
  176613. #if defined(PNG_READ_SUPPORTED)
  176614. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  176615. !defined(PNG_NO_READ_TRANSFORMS)
  176616. # define PNG_READ_TRANSFORMS_SUPPORTED
  176617. #endif
  176618. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  176619. # ifndef PNG_NO_READ_EXPAND
  176620. # define PNG_READ_EXPAND_SUPPORTED
  176621. # endif
  176622. # ifndef PNG_NO_READ_SHIFT
  176623. # define PNG_READ_SHIFT_SUPPORTED
  176624. # endif
  176625. # ifndef PNG_NO_READ_PACK
  176626. # define PNG_READ_PACK_SUPPORTED
  176627. # endif
  176628. # ifndef PNG_NO_READ_BGR
  176629. # define PNG_READ_BGR_SUPPORTED
  176630. # endif
  176631. # ifndef PNG_NO_READ_SWAP
  176632. # define PNG_READ_SWAP_SUPPORTED
  176633. # endif
  176634. # ifndef PNG_NO_READ_PACKSWAP
  176635. # define PNG_READ_PACKSWAP_SUPPORTED
  176636. # endif
  176637. # ifndef PNG_NO_READ_INVERT
  176638. # define PNG_READ_INVERT_SUPPORTED
  176639. # endif
  176640. # ifndef PNG_NO_READ_DITHER
  176641. # define PNG_READ_DITHER_SUPPORTED
  176642. # endif
  176643. # ifndef PNG_NO_READ_BACKGROUND
  176644. # define PNG_READ_BACKGROUND_SUPPORTED
  176645. # endif
  176646. # ifndef PNG_NO_READ_16_TO_8
  176647. # define PNG_READ_16_TO_8_SUPPORTED
  176648. # endif
  176649. # ifndef PNG_NO_READ_FILLER
  176650. # define PNG_READ_FILLER_SUPPORTED
  176651. # endif
  176652. # ifndef PNG_NO_READ_GAMMA
  176653. # define PNG_READ_GAMMA_SUPPORTED
  176654. # endif
  176655. # ifndef PNG_NO_READ_GRAY_TO_RGB
  176656. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  176657. # endif
  176658. # ifndef PNG_NO_READ_SWAP_ALPHA
  176659. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  176660. # endif
  176661. # ifndef PNG_NO_READ_INVERT_ALPHA
  176662. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  176663. # endif
  176664. # ifndef PNG_NO_READ_STRIP_ALPHA
  176665. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  176666. # endif
  176667. # ifndef PNG_NO_READ_USER_TRANSFORM
  176668. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  176669. # endif
  176670. # ifndef PNG_NO_READ_RGB_TO_GRAY
  176671. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  176672. # endif
  176673. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  176674. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  176675. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  176676. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  176677. #endif /* about interlacing capability! You'll */
  176678. /* still have interlacing unless you change the following line: */
  176679. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  176680. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  176681. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  176682. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  176683. # endif
  176684. #endif
  176685. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176686. /* Deprecated, will be removed from version 2.0.0.
  176687. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  176688. #ifndef PNG_NO_READ_EMPTY_PLTE
  176689. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  176690. #endif
  176691. #endif
  176692. #endif /* PNG_READ_SUPPORTED */
  176693. #if defined(PNG_WRITE_SUPPORTED)
  176694. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  176695. !defined(PNG_NO_WRITE_TRANSFORMS)
  176696. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  176697. #endif
  176698. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  176699. # ifndef PNG_NO_WRITE_SHIFT
  176700. # define PNG_WRITE_SHIFT_SUPPORTED
  176701. # endif
  176702. # ifndef PNG_NO_WRITE_PACK
  176703. # define PNG_WRITE_PACK_SUPPORTED
  176704. # endif
  176705. # ifndef PNG_NO_WRITE_BGR
  176706. # define PNG_WRITE_BGR_SUPPORTED
  176707. # endif
  176708. # ifndef PNG_NO_WRITE_SWAP
  176709. # define PNG_WRITE_SWAP_SUPPORTED
  176710. # endif
  176711. # ifndef PNG_NO_WRITE_PACKSWAP
  176712. # define PNG_WRITE_PACKSWAP_SUPPORTED
  176713. # endif
  176714. # ifndef PNG_NO_WRITE_INVERT
  176715. # define PNG_WRITE_INVERT_SUPPORTED
  176716. # endif
  176717. # ifndef PNG_NO_WRITE_FILLER
  176718. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  176719. # endif
  176720. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  176721. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  176722. # endif
  176723. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  176724. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  176725. # endif
  176726. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  176727. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  176728. # endif
  176729. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  176730. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  176731. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176732. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  176733. encoders, but can cause trouble
  176734. if left undefined */
  176735. #endif
  176736. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  176737. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  176738. defined(PNG_FLOATING_POINT_SUPPORTED)
  176739. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  176740. #endif
  176741. #ifndef PNG_NO_WRITE_FLUSH
  176742. # define PNG_WRITE_FLUSH_SUPPORTED
  176743. #endif
  176744. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176745. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  176746. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  176747. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  176748. #endif
  176749. #endif
  176750. #endif /* PNG_WRITE_SUPPORTED */
  176751. #ifndef PNG_1_0_X
  176752. # ifndef PNG_NO_ERROR_NUMBERS
  176753. # define PNG_ERROR_NUMBERS_SUPPORTED
  176754. # endif
  176755. #endif /* PNG_1_0_X */
  176756. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176757. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  176758. # ifndef PNG_NO_USER_TRANSFORM_PTR
  176759. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  176760. # endif
  176761. #endif
  176762. #ifndef PNG_NO_STDIO
  176763. # define PNG_TIME_RFC1123_SUPPORTED
  176764. #endif
  176765. /* This adds extra functions in pngget.c for accessing data from the
  176766. * info pointer (added in version 0.99)
  176767. * png_get_image_width()
  176768. * png_get_image_height()
  176769. * png_get_bit_depth()
  176770. * png_get_color_type()
  176771. * png_get_compression_type()
  176772. * png_get_filter_type()
  176773. * png_get_interlace_type()
  176774. * png_get_pixel_aspect_ratio()
  176775. * png_get_pixels_per_meter()
  176776. * png_get_x_offset_pixels()
  176777. * png_get_y_offset_pixels()
  176778. * png_get_x_offset_microns()
  176779. * png_get_y_offset_microns()
  176780. */
  176781. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  176782. # define PNG_EASY_ACCESS_SUPPORTED
  176783. #endif
  176784. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  176785. * and removed from version 1.2.20. The following will be removed
  176786. * from libpng-1.4.0
  176787. */
  176788. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  176789. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  176790. # define PNG_OPTIMIZED_CODE_SUPPORTED
  176791. # endif
  176792. #endif
  176793. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  176794. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  176795. # define PNG_ASSEMBLER_CODE_SUPPORTED
  176796. # endif
  176797. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  176798. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  176799. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176800. # define PNG_NO_MMX_CODE
  176801. # endif
  176802. # endif
  176803. # if defined(__APPLE__)
  176804. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176805. # define PNG_NO_MMX_CODE
  176806. # endif
  176807. # endif
  176808. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  176809. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176810. # define PNG_NO_MMX_CODE
  176811. # endif
  176812. # endif
  176813. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  176814. # define PNG_MMX_CODE_SUPPORTED
  176815. # endif
  176816. #endif
  176817. /* end of obsolete code to be removed from libpng-1.4.0 */
  176818. #if !defined(PNG_1_0_X)
  176819. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  176820. # define PNG_USER_MEM_SUPPORTED
  176821. #endif
  176822. #endif /* PNG_1_0_X */
  176823. /* Added at libpng-1.2.6 */
  176824. #if !defined(PNG_1_0_X)
  176825. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  176826. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  176827. # define PNG_SET_USER_LIMITS_SUPPORTED
  176828. #endif
  176829. #endif
  176830. #endif /* PNG_1_0_X */
  176831. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  176832. * how large, set these limits to 0x7fffffffL
  176833. */
  176834. #ifndef PNG_USER_WIDTH_MAX
  176835. # define PNG_USER_WIDTH_MAX 1000000L
  176836. #endif
  176837. #ifndef PNG_USER_HEIGHT_MAX
  176838. # define PNG_USER_HEIGHT_MAX 1000000L
  176839. #endif
  176840. /* These are currently experimental features, define them if you want */
  176841. /* very little testing */
  176842. /*
  176843. #ifdef PNG_READ_SUPPORTED
  176844. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176845. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  176846. # endif
  176847. #endif
  176848. */
  176849. /* This is only for PowerPC big-endian and 680x0 systems */
  176850. /* some testing */
  176851. /*
  176852. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  176853. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  176854. #endif
  176855. */
  176856. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  176857. /*
  176858. #define PNG_NO_POINTER_INDEXING
  176859. */
  176860. /* These functions are turned off by default, as they will be phased out. */
  176861. /*
  176862. #define PNG_USELESS_TESTS_SUPPORTED
  176863. #define PNG_CORRECT_PALETTE_SUPPORTED
  176864. */
  176865. /* Any chunks you are not interested in, you can undef here. The
  176866. * ones that allocate memory may be expecially important (hIST,
  176867. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  176868. * a bit smaller.
  176869. */
  176870. #if defined(PNG_READ_SUPPORTED) && \
  176871. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176872. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  176873. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176874. #endif
  176875. #if defined(PNG_WRITE_SUPPORTED) && \
  176876. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  176877. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  176878. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176879. #endif
  176880. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  176881. #ifdef PNG_NO_READ_TEXT
  176882. # define PNG_NO_READ_iTXt
  176883. # define PNG_NO_READ_tEXt
  176884. # define PNG_NO_READ_zTXt
  176885. #endif
  176886. #ifndef PNG_NO_READ_bKGD
  176887. # define PNG_READ_bKGD_SUPPORTED
  176888. # define PNG_bKGD_SUPPORTED
  176889. #endif
  176890. #ifndef PNG_NO_READ_cHRM
  176891. # define PNG_READ_cHRM_SUPPORTED
  176892. # define PNG_cHRM_SUPPORTED
  176893. #endif
  176894. #ifndef PNG_NO_READ_gAMA
  176895. # define PNG_READ_gAMA_SUPPORTED
  176896. # define PNG_gAMA_SUPPORTED
  176897. #endif
  176898. #ifndef PNG_NO_READ_hIST
  176899. # define PNG_READ_hIST_SUPPORTED
  176900. # define PNG_hIST_SUPPORTED
  176901. #endif
  176902. #ifndef PNG_NO_READ_iCCP
  176903. # define PNG_READ_iCCP_SUPPORTED
  176904. # define PNG_iCCP_SUPPORTED
  176905. #endif
  176906. #ifndef PNG_NO_READ_iTXt
  176907. # ifndef PNG_READ_iTXt_SUPPORTED
  176908. # define PNG_READ_iTXt_SUPPORTED
  176909. # endif
  176910. # ifndef PNG_iTXt_SUPPORTED
  176911. # define PNG_iTXt_SUPPORTED
  176912. # endif
  176913. #endif
  176914. #ifndef PNG_NO_READ_oFFs
  176915. # define PNG_READ_oFFs_SUPPORTED
  176916. # define PNG_oFFs_SUPPORTED
  176917. #endif
  176918. #ifndef PNG_NO_READ_pCAL
  176919. # define PNG_READ_pCAL_SUPPORTED
  176920. # define PNG_pCAL_SUPPORTED
  176921. #endif
  176922. #ifndef PNG_NO_READ_sCAL
  176923. # define PNG_READ_sCAL_SUPPORTED
  176924. # define PNG_sCAL_SUPPORTED
  176925. #endif
  176926. #ifndef PNG_NO_READ_pHYs
  176927. # define PNG_READ_pHYs_SUPPORTED
  176928. # define PNG_pHYs_SUPPORTED
  176929. #endif
  176930. #ifndef PNG_NO_READ_sBIT
  176931. # define PNG_READ_sBIT_SUPPORTED
  176932. # define PNG_sBIT_SUPPORTED
  176933. #endif
  176934. #ifndef PNG_NO_READ_sPLT
  176935. # define PNG_READ_sPLT_SUPPORTED
  176936. # define PNG_sPLT_SUPPORTED
  176937. #endif
  176938. #ifndef PNG_NO_READ_sRGB
  176939. # define PNG_READ_sRGB_SUPPORTED
  176940. # define PNG_sRGB_SUPPORTED
  176941. #endif
  176942. #ifndef PNG_NO_READ_tEXt
  176943. # define PNG_READ_tEXt_SUPPORTED
  176944. # define PNG_tEXt_SUPPORTED
  176945. #endif
  176946. #ifndef PNG_NO_READ_tIME
  176947. # define PNG_READ_tIME_SUPPORTED
  176948. # define PNG_tIME_SUPPORTED
  176949. #endif
  176950. #ifndef PNG_NO_READ_tRNS
  176951. # define PNG_READ_tRNS_SUPPORTED
  176952. # define PNG_tRNS_SUPPORTED
  176953. #endif
  176954. #ifndef PNG_NO_READ_zTXt
  176955. # define PNG_READ_zTXt_SUPPORTED
  176956. # define PNG_zTXt_SUPPORTED
  176957. #endif
  176958. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  176959. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  176960. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  176961. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  176962. # endif
  176963. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  176964. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176965. # endif
  176966. #endif
  176967. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  176968. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  176969. # define PNG_READ_USER_CHUNKS_SUPPORTED
  176970. # define PNG_USER_CHUNKS_SUPPORTED
  176971. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  176972. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  176973. # endif
  176974. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  176975. # undef PNG_NO_HANDLE_AS_UNKNOWN
  176976. # endif
  176977. #endif
  176978. #ifndef PNG_NO_READ_OPT_PLTE
  176979. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  176980. #endif /* optional PLTE chunk in RGB and RGBA images */
  176981. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  176982. defined(PNG_READ_zTXt_SUPPORTED)
  176983. # define PNG_READ_TEXT_SUPPORTED
  176984. # define PNG_TEXT_SUPPORTED
  176985. #endif
  176986. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  176987. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  176988. #ifdef PNG_NO_WRITE_TEXT
  176989. # define PNG_NO_WRITE_iTXt
  176990. # define PNG_NO_WRITE_tEXt
  176991. # define PNG_NO_WRITE_zTXt
  176992. #endif
  176993. #ifndef PNG_NO_WRITE_bKGD
  176994. # define PNG_WRITE_bKGD_SUPPORTED
  176995. # ifndef PNG_bKGD_SUPPORTED
  176996. # define PNG_bKGD_SUPPORTED
  176997. # endif
  176998. #endif
  176999. #ifndef PNG_NO_WRITE_cHRM
  177000. # define PNG_WRITE_cHRM_SUPPORTED
  177001. # ifndef PNG_cHRM_SUPPORTED
  177002. # define PNG_cHRM_SUPPORTED
  177003. # endif
  177004. #endif
  177005. #ifndef PNG_NO_WRITE_gAMA
  177006. # define PNG_WRITE_gAMA_SUPPORTED
  177007. # ifndef PNG_gAMA_SUPPORTED
  177008. # define PNG_gAMA_SUPPORTED
  177009. # endif
  177010. #endif
  177011. #ifndef PNG_NO_WRITE_hIST
  177012. # define PNG_WRITE_hIST_SUPPORTED
  177013. # ifndef PNG_hIST_SUPPORTED
  177014. # define PNG_hIST_SUPPORTED
  177015. # endif
  177016. #endif
  177017. #ifndef PNG_NO_WRITE_iCCP
  177018. # define PNG_WRITE_iCCP_SUPPORTED
  177019. # ifndef PNG_iCCP_SUPPORTED
  177020. # define PNG_iCCP_SUPPORTED
  177021. # endif
  177022. #endif
  177023. #ifndef PNG_NO_WRITE_iTXt
  177024. # ifndef PNG_WRITE_iTXt_SUPPORTED
  177025. # define PNG_WRITE_iTXt_SUPPORTED
  177026. # endif
  177027. # ifndef PNG_iTXt_SUPPORTED
  177028. # define PNG_iTXt_SUPPORTED
  177029. # endif
  177030. #endif
  177031. #ifndef PNG_NO_WRITE_oFFs
  177032. # define PNG_WRITE_oFFs_SUPPORTED
  177033. # ifndef PNG_oFFs_SUPPORTED
  177034. # define PNG_oFFs_SUPPORTED
  177035. # endif
  177036. #endif
  177037. #ifndef PNG_NO_WRITE_pCAL
  177038. # define PNG_WRITE_pCAL_SUPPORTED
  177039. # ifndef PNG_pCAL_SUPPORTED
  177040. # define PNG_pCAL_SUPPORTED
  177041. # endif
  177042. #endif
  177043. #ifndef PNG_NO_WRITE_sCAL
  177044. # define PNG_WRITE_sCAL_SUPPORTED
  177045. # ifndef PNG_sCAL_SUPPORTED
  177046. # define PNG_sCAL_SUPPORTED
  177047. # endif
  177048. #endif
  177049. #ifndef PNG_NO_WRITE_pHYs
  177050. # define PNG_WRITE_pHYs_SUPPORTED
  177051. # ifndef PNG_pHYs_SUPPORTED
  177052. # define PNG_pHYs_SUPPORTED
  177053. # endif
  177054. #endif
  177055. #ifndef PNG_NO_WRITE_sBIT
  177056. # define PNG_WRITE_sBIT_SUPPORTED
  177057. # ifndef PNG_sBIT_SUPPORTED
  177058. # define PNG_sBIT_SUPPORTED
  177059. # endif
  177060. #endif
  177061. #ifndef PNG_NO_WRITE_sPLT
  177062. # define PNG_WRITE_sPLT_SUPPORTED
  177063. # ifndef PNG_sPLT_SUPPORTED
  177064. # define PNG_sPLT_SUPPORTED
  177065. # endif
  177066. #endif
  177067. #ifndef PNG_NO_WRITE_sRGB
  177068. # define PNG_WRITE_sRGB_SUPPORTED
  177069. # ifndef PNG_sRGB_SUPPORTED
  177070. # define PNG_sRGB_SUPPORTED
  177071. # endif
  177072. #endif
  177073. #ifndef PNG_NO_WRITE_tEXt
  177074. # define PNG_WRITE_tEXt_SUPPORTED
  177075. # ifndef PNG_tEXt_SUPPORTED
  177076. # define PNG_tEXt_SUPPORTED
  177077. # endif
  177078. #endif
  177079. #ifndef PNG_NO_WRITE_tIME
  177080. # define PNG_WRITE_tIME_SUPPORTED
  177081. # ifndef PNG_tIME_SUPPORTED
  177082. # define PNG_tIME_SUPPORTED
  177083. # endif
  177084. #endif
  177085. #ifndef PNG_NO_WRITE_tRNS
  177086. # define PNG_WRITE_tRNS_SUPPORTED
  177087. # ifndef PNG_tRNS_SUPPORTED
  177088. # define PNG_tRNS_SUPPORTED
  177089. # endif
  177090. #endif
  177091. #ifndef PNG_NO_WRITE_zTXt
  177092. # define PNG_WRITE_zTXt_SUPPORTED
  177093. # ifndef PNG_zTXt_SUPPORTED
  177094. # define PNG_zTXt_SUPPORTED
  177095. # endif
  177096. #endif
  177097. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  177098. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  177099. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  177100. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  177101. # endif
  177102. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  177103. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177104. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  177105. # endif
  177106. # endif
  177107. #endif
  177108. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  177109. defined(PNG_WRITE_zTXt_SUPPORTED)
  177110. # define PNG_WRITE_TEXT_SUPPORTED
  177111. # ifndef PNG_TEXT_SUPPORTED
  177112. # define PNG_TEXT_SUPPORTED
  177113. # endif
  177114. #endif
  177115. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  177116. /* Turn this off to disable png_read_png() and
  177117. * png_write_png() and leave the row_pointers member
  177118. * out of the info structure.
  177119. */
  177120. #ifndef PNG_NO_INFO_IMAGE
  177121. # define PNG_INFO_IMAGE_SUPPORTED
  177122. #endif
  177123. /* need the time information for reading tIME chunks */
  177124. #if defined(PNG_tIME_SUPPORTED)
  177125. # if !defined(_WIN32_WCE)
  177126. /* "time.h" functions are not supported on WindowsCE */
  177127. # include <time.h>
  177128. # endif
  177129. #endif
  177130. /* Some typedefs to get us started. These should be safe on most of the
  177131. * common platforms. The typedefs should be at least as large as the
  177132. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  177133. * don't have to be exactly that size. Some compilers dislike passing
  177134. * unsigned shorts as function parameters, so you may be better off using
  177135. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  177136. * want to have unsigned int for png_uint_32 instead of unsigned long.
  177137. */
  177138. typedef unsigned long png_uint_32;
  177139. typedef long png_int_32;
  177140. typedef unsigned short png_uint_16;
  177141. typedef short png_int_16;
  177142. typedef unsigned char png_byte;
  177143. /* This is usually size_t. It is typedef'ed just in case you need it to
  177144. change (I'm not sure if you will or not, so I thought I'd be safe) */
  177145. #ifdef PNG_SIZE_T
  177146. typedef PNG_SIZE_T png_size_t;
  177147. # define png_sizeof(x) png_convert_size(sizeof (x))
  177148. #else
  177149. typedef size_t png_size_t;
  177150. # define png_sizeof(x) sizeof (x)
  177151. #endif
  177152. /* The following is needed for medium model support. It cannot be in the
  177153. * PNG_INTERNAL section. Needs modification for other compilers besides
  177154. * MSC. Model independent support declares all arrays and pointers to be
  177155. * large using the far keyword. The zlib version used must also support
  177156. * model independent data. As of version zlib 1.0.4, the necessary changes
  177157. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  177158. * changes that are needed. (Tim Wegner)
  177159. */
  177160. /* Separate compiler dependencies (problem here is that zlib.h always
  177161. defines FAR. (SJT) */
  177162. #ifdef __BORLANDC__
  177163. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  177164. # define LDATA 1
  177165. # else
  177166. # define LDATA 0
  177167. # endif
  177168. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  177169. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  177170. # define PNG_MAX_MALLOC_64K
  177171. # if (LDATA != 1)
  177172. # ifndef FAR
  177173. # define FAR __far
  177174. # endif
  177175. # define USE_FAR_KEYWORD
  177176. # endif /* LDATA != 1 */
  177177. /* Possibly useful for moving data out of default segment.
  177178. * Uncomment it if you want. Could also define FARDATA as
  177179. * const if your compiler supports it. (SJT)
  177180. # define FARDATA FAR
  177181. */
  177182. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  177183. #endif /* __BORLANDC__ */
  177184. /* Suggest testing for specific compiler first before testing for
  177185. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  177186. * making reliance oncertain keywords suspect. (SJT)
  177187. */
  177188. /* MSC Medium model */
  177189. #if defined(FAR)
  177190. # if defined(M_I86MM)
  177191. # define USE_FAR_KEYWORD
  177192. # define FARDATA FAR
  177193. # include <dos.h>
  177194. # endif
  177195. #endif
  177196. /* SJT: default case */
  177197. #ifndef FAR
  177198. # define FAR
  177199. #endif
  177200. /* At this point FAR is always defined */
  177201. #ifndef FARDATA
  177202. # define FARDATA
  177203. #endif
  177204. /* Typedef for floating-point numbers that are converted
  177205. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  177206. typedef png_int_32 png_fixed_point;
  177207. /* Add typedefs for pointers */
  177208. typedef void FAR * png_voidp;
  177209. typedef png_byte FAR * png_bytep;
  177210. typedef png_uint_32 FAR * png_uint_32p;
  177211. typedef png_int_32 FAR * png_int_32p;
  177212. typedef png_uint_16 FAR * png_uint_16p;
  177213. typedef png_int_16 FAR * png_int_16p;
  177214. typedef PNG_CONST char FAR * png_const_charp;
  177215. typedef char FAR * png_charp;
  177216. typedef png_fixed_point FAR * png_fixed_point_p;
  177217. #ifndef PNG_NO_STDIO
  177218. #if defined(_WIN32_WCE)
  177219. typedef HANDLE png_FILE_p;
  177220. #else
  177221. typedef FILE * png_FILE_p;
  177222. #endif
  177223. #endif
  177224. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177225. typedef double FAR * png_doublep;
  177226. #endif
  177227. /* Pointers to pointers; i.e. arrays */
  177228. typedef png_byte FAR * FAR * png_bytepp;
  177229. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  177230. typedef png_int_32 FAR * FAR * png_int_32pp;
  177231. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  177232. typedef png_int_16 FAR * FAR * png_int_16pp;
  177233. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  177234. typedef char FAR * FAR * png_charpp;
  177235. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  177236. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177237. typedef double FAR * FAR * png_doublepp;
  177238. #endif
  177239. /* Pointers to pointers to pointers; i.e., pointer to array */
  177240. typedef char FAR * FAR * FAR * png_charppp;
  177241. #if 0
  177242. /* SPC - Is this stuff deprecated? */
  177243. /* It'll be removed as of libpng-1.3.0 - GR-P */
  177244. /* libpng typedefs for types in zlib. If zlib changes
  177245. * or another compression library is used, then change these.
  177246. * Eliminates need to change all the source files.
  177247. */
  177248. typedef charf * png_zcharp;
  177249. typedef charf * FAR * png_zcharpp;
  177250. typedef z_stream FAR * png_zstreamp;
  177251. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  177252. /*
  177253. * Define PNG_BUILD_DLL if the module being built is a Windows
  177254. * LIBPNG DLL.
  177255. *
  177256. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  177257. * It is equivalent to Microsoft predefined macro _DLL that is
  177258. * automatically defined when you compile using the share
  177259. * version of the CRT (C Run-Time library)
  177260. *
  177261. * The cygwin mods make this behavior a little different:
  177262. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  177263. * Define PNG_STATIC if you are building a static library for use with cygwin,
  177264. * -or- if you are building an application that you want to link to the
  177265. * static library.
  177266. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  177267. * the other flags is defined.
  177268. */
  177269. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  177270. # define PNG_DLL
  177271. #endif
  177272. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  177273. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  177274. * command-line override
  177275. */
  177276. #if defined(__CYGWIN__)
  177277. # if !defined(PNG_STATIC)
  177278. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177279. # undef PNG_USE_GLOBAL_ARRAYS
  177280. # endif
  177281. # if !defined(PNG_USE_LOCAL_ARRAYS)
  177282. # define PNG_USE_LOCAL_ARRAYS
  177283. # endif
  177284. # else
  177285. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  177286. # if defined(PNG_USE_GLOBAL_ARRAYS)
  177287. # undef PNG_USE_GLOBAL_ARRAYS
  177288. # endif
  177289. # endif
  177290. # endif
  177291. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177292. # define PNG_USE_LOCAL_ARRAYS
  177293. # endif
  177294. #endif
  177295. /* Do not use global arrays (helps with building DLL's)
  177296. * They are no longer used in libpng itself, since version 1.0.5c,
  177297. * but might be required for some pre-1.0.5c applications.
  177298. */
  177299. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  177300. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  177301. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  177302. # define PNG_USE_LOCAL_ARRAYS
  177303. # else
  177304. # define PNG_USE_GLOBAL_ARRAYS
  177305. # endif
  177306. #endif
  177307. #if defined(__CYGWIN__)
  177308. # undef PNGAPI
  177309. # define PNGAPI __cdecl
  177310. # undef PNG_IMPEXP
  177311. # define PNG_IMPEXP
  177312. #endif
  177313. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  177314. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  177315. * Don't ignore those warnings; you must also reset the default calling
  177316. * convention in your compiler to match your PNGAPI, and you must build
  177317. * zlib and your applications the same way you build libpng.
  177318. */
  177319. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  177320. # ifndef PNG_NO_MODULEDEF
  177321. # define PNG_NO_MODULEDEF
  177322. # endif
  177323. #endif
  177324. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  177325. # define PNG_IMPEXP
  177326. #endif
  177327. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  177328. (( defined(_Windows) || defined(_WINDOWS) || \
  177329. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  177330. # ifndef PNGAPI
  177331. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  177332. # define PNGAPI __cdecl
  177333. # else
  177334. # define PNGAPI _cdecl
  177335. # endif
  177336. # endif
  177337. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  177338. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  177339. # define PNG_IMPEXP
  177340. # endif
  177341. # if !defined(PNG_IMPEXP)
  177342. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177343. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  177344. /* Borland/Microsoft */
  177345. # if defined(_MSC_VER) || defined(__BORLANDC__)
  177346. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  177347. # define PNG_EXPORT PNG_EXPORT_TYPE1
  177348. # else
  177349. # define PNG_EXPORT PNG_EXPORT_TYPE2
  177350. # if defined(PNG_BUILD_DLL)
  177351. # define PNG_IMPEXP __export
  177352. # else
  177353. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  177354. VC++ */
  177355. # endif /* Exists in Borland C++ for
  177356. C++ classes (== huge) */
  177357. # endif
  177358. # endif
  177359. # if !defined(PNG_IMPEXP)
  177360. # if defined(PNG_BUILD_DLL)
  177361. # define PNG_IMPEXP __declspec(dllexport)
  177362. # else
  177363. # define PNG_IMPEXP __declspec(dllimport)
  177364. # endif
  177365. # endif
  177366. # endif /* PNG_IMPEXP */
  177367. #else /* !(DLL || non-cygwin WINDOWS) */
  177368. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  177369. # ifndef PNGAPI
  177370. # define PNGAPI _System
  177371. # endif
  177372. # else
  177373. # if 0 /* ... other platforms, with other meanings */
  177374. # endif
  177375. # endif
  177376. #endif
  177377. #ifndef PNGAPI
  177378. # define PNGAPI
  177379. #endif
  177380. #ifndef PNG_IMPEXP
  177381. # define PNG_IMPEXP
  177382. #endif
  177383. #ifdef PNG_BUILDSYMS
  177384. # ifndef PNG_EXPORT
  177385. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  177386. # endif
  177387. # ifdef PNG_USE_GLOBAL_ARRAYS
  177388. # ifndef PNG_EXPORT_VAR
  177389. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  177390. # endif
  177391. # endif
  177392. #endif
  177393. #ifndef PNG_EXPORT
  177394. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  177395. #endif
  177396. #ifdef PNG_USE_GLOBAL_ARRAYS
  177397. # ifndef PNG_EXPORT_VAR
  177398. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  177399. # endif
  177400. #endif
  177401. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  177402. * functions that are passed far data must be model independent.
  177403. */
  177404. #ifndef PNG_ABORT
  177405. # define PNG_ABORT() abort()
  177406. #endif
  177407. #ifdef PNG_SETJMP_SUPPORTED
  177408. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  177409. #else
  177410. # define png_jmpbuf(png_ptr) \
  177411. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  177412. #endif
  177413. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  177414. /* use this to make far-to-near assignments */
  177415. # define CHECK 1
  177416. # define NOCHECK 0
  177417. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  177418. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  177419. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  177420. # define png_strcpy _fstrcpy
  177421. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  177422. # define png_strlen _fstrlen
  177423. # define png_memcmp _fmemcmp /* SJT: added */
  177424. # define png_memcpy _fmemcpy
  177425. # define png_memset _fmemset
  177426. #else /* use the usual functions */
  177427. # define CVT_PTR(ptr) (ptr)
  177428. # define CVT_PTR_NOCHECK(ptr) (ptr)
  177429. # ifndef PNG_NO_SNPRINTF
  177430. # ifdef _MSC_VER
  177431. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  177432. # define png_snprintf2 _snprintf
  177433. # define png_snprintf6 _snprintf
  177434. # else
  177435. # define png_snprintf snprintf /* Added to v 1.2.19 */
  177436. # define png_snprintf2 snprintf
  177437. # define png_snprintf6 snprintf
  177438. # endif
  177439. # else
  177440. /* You don't have or don't want to use snprintf(). Caution: Using
  177441. * sprintf instead of snprintf exposes your application to accidental
  177442. * or malevolent buffer overflows. If you don't have snprintf()
  177443. * as a general rule you should provide one (you can get one from
  177444. * Portable OpenSSH). */
  177445. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  177446. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  177447. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  177448. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  177449. # endif
  177450. # define png_strcpy strcpy
  177451. # define png_strncpy strncpy /* Added to v 1.2.6 */
  177452. # define png_strlen strlen
  177453. # define png_memcmp memcmp /* SJT: added */
  177454. # define png_memcpy memcpy
  177455. # define png_memset memset
  177456. #endif
  177457. /* End of memory model independent support */
  177458. /* Just a little check that someone hasn't tried to define something
  177459. * contradictory.
  177460. */
  177461. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  177462. # undef PNG_ZBUF_SIZE
  177463. # define PNG_ZBUF_SIZE 65536L
  177464. #endif
  177465. /* Added at libpng-1.2.8 */
  177466. #endif /* PNG_VERSION_INFO_ONLY */
  177467. #endif /* PNGCONF_H */
  177468. /********* End of inlined file: pngconf.h *********/
  177469. #ifdef _MSC_VER
  177470. #pragma warning (disable: 4996 4100)
  177471. #endif
  177472. /*
  177473. * Added at libpng-1.2.8 */
  177474. /* Ref MSDN: Private as priority over Special
  177475. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  177476. * procedures. If this value is given, the StringFileInfo block must
  177477. * contain a PrivateBuild string.
  177478. *
  177479. * VS_FF_SPECIALBUILD File *was* built by the original company using
  177480. * standard release procedures but is a variation of the standard
  177481. * file of the same version number. If this value is given, the
  177482. * StringFileInfo block must contain a SpecialBuild string.
  177483. */
  177484. #if defined(PNG_USER_PRIVATEBUILD)
  177485. # define PNG_LIBPNG_BUILD_TYPE \
  177486. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  177487. #else
  177488. # if defined(PNG_LIBPNG_SPECIALBUILD)
  177489. # define PNG_LIBPNG_BUILD_TYPE \
  177490. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  177491. # else
  177492. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  177493. # endif
  177494. #endif
  177495. #ifndef PNG_VERSION_INFO_ONLY
  177496. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  177497. #ifdef __cplusplus
  177498. extern "C" {
  177499. #endif /* __cplusplus */
  177500. /* This file is arranged in several sections. The first section contains
  177501. * structure and type definitions. The second section contains the external
  177502. * library functions, while the third has the internal library functions,
  177503. * which applications aren't expected to use directly.
  177504. */
  177505. #ifndef PNG_NO_TYPECAST_NULL
  177506. #define int_p_NULL (int *)NULL
  177507. #define png_bytep_NULL (png_bytep)NULL
  177508. #define png_bytepp_NULL (png_bytepp)NULL
  177509. #define png_doublep_NULL (png_doublep)NULL
  177510. #define png_error_ptr_NULL (png_error_ptr)NULL
  177511. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  177512. #define png_free_ptr_NULL (png_free_ptr)NULL
  177513. #define png_infopp_NULL (png_infopp)NULL
  177514. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  177515. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  177516. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  177517. #define png_structp_NULL (png_structp)NULL
  177518. #define png_uint_16p_NULL (png_uint_16p)NULL
  177519. #define png_voidp_NULL (png_voidp)NULL
  177520. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  177521. #else
  177522. #define int_p_NULL NULL
  177523. #define png_bytep_NULL NULL
  177524. #define png_bytepp_NULL NULL
  177525. #define png_doublep_NULL NULL
  177526. #define png_error_ptr_NULL NULL
  177527. #define png_flush_ptr_NULL NULL
  177528. #define png_free_ptr_NULL NULL
  177529. #define png_infopp_NULL NULL
  177530. #define png_malloc_ptr_NULL NULL
  177531. #define png_read_status_ptr_NULL NULL
  177532. #define png_rw_ptr_NULL NULL
  177533. #define png_structp_NULL NULL
  177534. #define png_uint_16p_NULL NULL
  177535. #define png_voidp_NULL NULL
  177536. #define png_write_status_ptr_NULL NULL
  177537. #endif
  177538. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177539. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177540. /* Version information for C files, stored in png.c. This had better match
  177541. * the version above.
  177542. */
  177543. #ifdef PNG_USE_GLOBAL_ARRAYS
  177544. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  177545. /* need room for 99.99.99beta99z */
  177546. #else
  177547. #define png_libpng_ver png_get_header_ver(NULL)
  177548. #endif
  177549. #ifdef PNG_USE_GLOBAL_ARRAYS
  177550. /* This was removed in version 1.0.5c */
  177551. /* Structures to facilitate easy interlacing. See png.c for more details */
  177552. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  177553. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  177554. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  177555. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  177556. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  177557. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  177558. /* This isn't currently used. If you need it, see png.c for more details.
  177559. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  177560. */
  177561. #endif
  177562. #endif /* PNG_NO_EXTERN */
  177563. /* Three color definitions. The order of the red, green, and blue, (and the
  177564. * exact size) is not important, although the size of the fields need to
  177565. * be png_byte or png_uint_16 (as defined below).
  177566. */
  177567. typedef struct png_color_struct
  177568. {
  177569. png_byte red;
  177570. png_byte green;
  177571. png_byte blue;
  177572. } png_color;
  177573. typedef png_color FAR * png_colorp;
  177574. typedef png_color FAR * FAR * png_colorpp;
  177575. typedef struct png_color_16_struct
  177576. {
  177577. png_byte index; /* used for palette files */
  177578. png_uint_16 red; /* for use in red green blue files */
  177579. png_uint_16 green;
  177580. png_uint_16 blue;
  177581. png_uint_16 gray; /* for use in grayscale files */
  177582. } png_color_16;
  177583. typedef png_color_16 FAR * png_color_16p;
  177584. typedef png_color_16 FAR * FAR * png_color_16pp;
  177585. typedef struct png_color_8_struct
  177586. {
  177587. png_byte red; /* for use in red green blue files */
  177588. png_byte green;
  177589. png_byte blue;
  177590. png_byte gray; /* for use in grayscale files */
  177591. png_byte alpha; /* for alpha channel files */
  177592. } png_color_8;
  177593. typedef png_color_8 FAR * png_color_8p;
  177594. typedef png_color_8 FAR * FAR * png_color_8pp;
  177595. /*
  177596. * The following two structures are used for the in-core representation
  177597. * of sPLT chunks.
  177598. */
  177599. typedef struct png_sPLT_entry_struct
  177600. {
  177601. png_uint_16 red;
  177602. png_uint_16 green;
  177603. png_uint_16 blue;
  177604. png_uint_16 alpha;
  177605. png_uint_16 frequency;
  177606. } png_sPLT_entry;
  177607. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  177608. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  177609. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  177610. * occupy the LSB of their respective members, and the MSB of each member
  177611. * is zero-filled. The frequency member always occupies the full 16 bits.
  177612. */
  177613. typedef struct png_sPLT_struct
  177614. {
  177615. png_charp name; /* palette name */
  177616. png_byte depth; /* depth of palette samples */
  177617. png_sPLT_entryp entries; /* palette entries */
  177618. png_int_32 nentries; /* number of palette entries */
  177619. } png_sPLT_t;
  177620. typedef png_sPLT_t FAR * png_sPLT_tp;
  177621. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  177622. #ifdef PNG_TEXT_SUPPORTED
  177623. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  177624. * and whether that contents is compressed or not. The "key" field
  177625. * points to a regular zero-terminated C string. The "text", "lang", and
  177626. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  177627. * However, the * structure returned by png_get_text() will always contain
  177628. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  177629. * so they can be safely used in printf() and other string-handling functions.
  177630. */
  177631. typedef struct png_text_struct
  177632. {
  177633. int compression; /* compression value:
  177634. -1: tEXt, none
  177635. 0: zTXt, deflate
  177636. 1: iTXt, none
  177637. 2: iTXt, deflate */
  177638. png_charp key; /* keyword, 1-79 character description of "text" */
  177639. png_charp text; /* comment, may be an empty string (ie "")
  177640. or a NULL pointer */
  177641. png_size_t text_length; /* length of the text string */
  177642. #ifdef PNG_iTXt_SUPPORTED
  177643. png_size_t itxt_length; /* length of the itxt string */
  177644. png_charp lang; /* language code, 0-79 characters
  177645. or a NULL pointer */
  177646. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  177647. chars or a NULL pointer */
  177648. #endif
  177649. } png_text;
  177650. typedef png_text FAR * png_textp;
  177651. typedef png_text FAR * FAR * png_textpp;
  177652. #endif
  177653. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  177654. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  177655. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  177656. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  177657. #define PNG_TEXT_COMPRESSION_NONE -1
  177658. #define PNG_TEXT_COMPRESSION_zTXt 0
  177659. #define PNG_ITXT_COMPRESSION_NONE 1
  177660. #define PNG_ITXT_COMPRESSION_zTXt 2
  177661. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  177662. /* png_time is a way to hold the time in an machine independent way.
  177663. * Two conversions are provided, both from time_t and struct tm. There
  177664. * is no portable way to convert to either of these structures, as far
  177665. * as I know. If you know of a portable way, send it to me. As a side
  177666. * note - PNG has always been Year 2000 compliant!
  177667. */
  177668. typedef struct png_time_struct
  177669. {
  177670. png_uint_16 year; /* full year, as in, 1995 */
  177671. png_byte month; /* month of year, 1 - 12 */
  177672. png_byte day; /* day of month, 1 - 31 */
  177673. png_byte hour; /* hour of day, 0 - 23 */
  177674. png_byte minute; /* minute of hour, 0 - 59 */
  177675. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  177676. } png_time;
  177677. typedef png_time FAR * png_timep;
  177678. typedef png_time FAR * FAR * png_timepp;
  177679. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177680. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  177681. * no specific support. The idea is that we can use this to queue
  177682. * up private chunks for output even though the library doesn't actually
  177683. * know about their semantics.
  177684. */
  177685. typedef struct png_unknown_chunk_t
  177686. {
  177687. png_byte name[5];
  177688. png_byte *data;
  177689. png_size_t size;
  177690. /* libpng-using applications should NOT directly modify this byte. */
  177691. png_byte location; /* mode of operation at read time */
  177692. }
  177693. png_unknown_chunk;
  177694. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  177695. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  177696. #endif
  177697. /* png_info is a structure that holds the information in a PNG file so
  177698. * that the application can find out the characteristics of the image.
  177699. * If you are reading the file, this structure will tell you what is
  177700. * in the PNG file. If you are writing the file, fill in the information
  177701. * you want to put into the PNG file, then call png_write_info().
  177702. * The names chosen should be very close to the PNG specification, so
  177703. * consult that document for information about the meaning of each field.
  177704. *
  177705. * With libpng < 0.95, it was only possible to directly set and read the
  177706. * the values in the png_info_struct, which meant that the contents and
  177707. * order of the values had to remain fixed. With libpng 0.95 and later,
  177708. * however, there are now functions that abstract the contents of
  177709. * png_info_struct from the application, so this makes it easier to use
  177710. * libpng with dynamic libraries, and even makes it possible to use
  177711. * libraries that don't have all of the libpng ancillary chunk-handing
  177712. * functionality.
  177713. *
  177714. * In any case, the order of the parameters in png_info_struct should NOT
  177715. * be changed for as long as possible to keep compatibility with applications
  177716. * that use the old direct-access method with png_info_struct.
  177717. *
  177718. * The following members may have allocated storage attached that should be
  177719. * cleaned up before the structure is discarded: palette, trans, text,
  177720. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  177721. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  177722. * are automatically freed when the info structure is deallocated, if they were
  177723. * allocated internally by libpng. This behavior can be changed by means
  177724. * of the png_data_freer() function.
  177725. *
  177726. * More allocation details: all the chunk-reading functions that
  177727. * change these members go through the corresponding png_set_*
  177728. * functions. A function to clear these members is available: see
  177729. * png_free_data(). The png_set_* functions do not depend on being
  177730. * able to point info structure members to any of the storage they are
  177731. * passed (they make their own copies), EXCEPT that the png_set_text
  177732. * functions use the same storage passed to them in the text_ptr or
  177733. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  177734. * functions do not make their own copies.
  177735. */
  177736. typedef struct png_info_struct
  177737. {
  177738. /* the following are necessary for every PNG file */
  177739. png_uint_32 width; /* width of image in pixels (from IHDR) */
  177740. png_uint_32 height; /* height of image in pixels (from IHDR) */
  177741. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  177742. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  177743. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  177744. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  177745. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  177746. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  177747. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  177748. /* The following three should have been named *_method not *_type */
  177749. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  177750. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  177751. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  177752. /* The following is informational only on read, and not used on writes. */
  177753. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  177754. png_byte pixel_depth; /* number of bits per pixel */
  177755. png_byte spare_byte; /* to align the data, and for future use */
  177756. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  177757. /* The rest of the data is optional. If you are reading, check the
  177758. * valid field to see if the information in these are valid. If you
  177759. * are writing, set the valid field to those chunks you want written,
  177760. * and initialize the appropriate fields below.
  177761. */
  177762. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177763. /* The gAMA chunk describes the gamma characteristics of the system
  177764. * on which the image was created, normally in the range [1.0, 2.5].
  177765. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  177766. */
  177767. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  177768. #endif
  177769. #if defined(PNG_sRGB_SUPPORTED)
  177770. /* GR-P, 0.96a */
  177771. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  177772. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  177773. #endif
  177774. #if defined(PNG_TEXT_SUPPORTED)
  177775. /* The tEXt, and zTXt chunks contain human-readable textual data in
  177776. * uncompressed, compressed, and optionally compressed forms, respectively.
  177777. * The data in "text" is an array of pointers to uncompressed,
  177778. * null-terminated C strings. Each chunk has a keyword that describes the
  177779. * textual data contained in that chunk. Keywords are not required to be
  177780. * unique, and the text string may be empty. Any number of text chunks may
  177781. * be in an image.
  177782. */
  177783. int num_text; /* number of comments read/to write */
  177784. int max_text; /* current size of text array */
  177785. png_textp text; /* array of comments read/to write */
  177786. #endif /* PNG_TEXT_SUPPORTED */
  177787. #if defined(PNG_tIME_SUPPORTED)
  177788. /* The tIME chunk holds the last time the displayed image data was
  177789. * modified. See the png_time struct for the contents of this struct.
  177790. */
  177791. png_time mod_time;
  177792. #endif
  177793. #if defined(PNG_sBIT_SUPPORTED)
  177794. /* The sBIT chunk specifies the number of significant high-order bits
  177795. * in the pixel data. Values are in the range [1, bit_depth], and are
  177796. * only specified for the channels in the pixel data. The contents of
  177797. * the low-order bits is not specified. Data is valid if
  177798. * (valid & PNG_INFO_sBIT) is non-zero.
  177799. */
  177800. png_color_8 sig_bit; /* significant bits in color channels */
  177801. #endif
  177802. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  177803. defined(PNG_READ_BACKGROUND_SUPPORTED)
  177804. /* The tRNS chunk supplies transparency data for paletted images and
  177805. * other image types that don't need a full alpha channel. There are
  177806. * "num_trans" transparency values for a paletted image, stored in the
  177807. * same order as the palette colors, starting from index 0. Values
  177808. * for the data are in the range [0, 255], ranging from fully transparent
  177809. * to fully opaque, respectively. For non-paletted images, there is a
  177810. * single color specified that should be treated as fully transparent.
  177811. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  177812. */
  177813. png_bytep trans; /* transparent values for paletted image */
  177814. png_color_16 trans_values; /* transparent color for non-palette image */
  177815. #endif
  177816. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  177817. /* The bKGD chunk gives the suggested image background color if the
  177818. * display program does not have its own background color and the image
  177819. * is needs to composited onto a background before display. The colors
  177820. * in "background" are normally in the same color space/depth as the
  177821. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  177822. */
  177823. png_color_16 background;
  177824. #endif
  177825. #if defined(PNG_oFFs_SUPPORTED)
  177826. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  177827. * and downwards from the top-left corner of the display, page, or other
  177828. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  177829. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  177830. */
  177831. png_int_32 x_offset; /* x offset on page */
  177832. png_int_32 y_offset; /* y offset on page */
  177833. png_byte offset_unit_type; /* offset units type */
  177834. #endif
  177835. #if defined(PNG_pHYs_SUPPORTED)
  177836. /* The pHYs chunk gives the physical pixel density of the image for
  177837. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  177838. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  177839. */
  177840. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  177841. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  177842. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  177843. #endif
  177844. #if defined(PNG_hIST_SUPPORTED)
  177845. /* The hIST chunk contains the relative frequency or importance of the
  177846. * various palette entries, so that a viewer can intelligently select a
  177847. * reduced-color palette, if required. Data is an array of "num_palette"
  177848. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  177849. * is non-zero.
  177850. */
  177851. png_uint_16p hist;
  177852. #endif
  177853. #ifdef PNG_cHRM_SUPPORTED
  177854. /* The cHRM chunk describes the CIE color characteristics of the monitor
  177855. * on which the PNG was created. This data allows the viewer to do gamut
  177856. * mapping of the input image to ensure that the viewer sees the same
  177857. * colors in the image as the creator. Values are in the range
  177858. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  177859. */
  177860. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177861. float x_white;
  177862. float y_white;
  177863. float x_red;
  177864. float y_red;
  177865. float x_green;
  177866. float y_green;
  177867. float x_blue;
  177868. float y_blue;
  177869. #endif
  177870. #endif
  177871. #if defined(PNG_pCAL_SUPPORTED)
  177872. /* The pCAL chunk describes a transformation between the stored pixel
  177873. * values and original physical data values used to create the image.
  177874. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  177875. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  177876. * (possibly non-linear) transformation function given by "pcal_type"
  177877. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  177878. * defines below, and the PNG-Group's PNG extensions document for a
  177879. * complete description of the transformations and how they should be
  177880. * implemented, and for a description of the ASCII parameter strings.
  177881. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  177882. */
  177883. png_charp pcal_purpose; /* pCAL chunk description string */
  177884. png_int_32 pcal_X0; /* minimum value */
  177885. png_int_32 pcal_X1; /* maximum value */
  177886. png_charp pcal_units; /* Latin-1 string giving physical units */
  177887. png_charpp pcal_params; /* ASCII strings containing parameter values */
  177888. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  177889. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  177890. #endif
  177891. /* New members added in libpng-1.0.6 */
  177892. #ifdef PNG_FREE_ME_SUPPORTED
  177893. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  177894. #endif
  177895. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  177896. /* storage for unknown chunks that the library doesn't recognize. */
  177897. png_unknown_chunkp unknown_chunks;
  177898. png_size_t unknown_chunks_num;
  177899. #endif
  177900. #if defined(PNG_iCCP_SUPPORTED)
  177901. /* iCCP chunk data. */
  177902. png_charp iccp_name; /* profile name */
  177903. png_charp iccp_profile; /* International Color Consortium profile data */
  177904. /* Note to maintainer: should be png_bytep */
  177905. png_uint_32 iccp_proflen; /* ICC profile data length */
  177906. png_byte iccp_compression; /* Always zero */
  177907. #endif
  177908. #if defined(PNG_sPLT_SUPPORTED)
  177909. /* data on sPLT chunks (there may be more than one). */
  177910. png_sPLT_tp splt_palettes;
  177911. png_uint_32 splt_palettes_num;
  177912. #endif
  177913. #if defined(PNG_sCAL_SUPPORTED)
  177914. /* The sCAL chunk describes the actual physical dimensions of the
  177915. * subject matter of the graphic. The chunk contains a unit specification
  177916. * a byte value, and two ASCII strings representing floating-point
  177917. * values. The values are width and height corresponsing to one pixel
  177918. * in the image. This external representation is converted to double
  177919. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  177920. */
  177921. png_byte scal_unit; /* unit of physical scale */
  177922. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177923. double scal_pixel_width; /* width of one pixel */
  177924. double scal_pixel_height; /* height of one pixel */
  177925. #endif
  177926. #ifdef PNG_FIXED_POINT_SUPPORTED
  177927. png_charp scal_s_width; /* string containing height */
  177928. png_charp scal_s_height; /* string containing width */
  177929. #endif
  177930. #endif
  177931. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  177932. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  177933. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  177934. png_bytepp row_pointers; /* the image bits */
  177935. #endif
  177936. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  177937. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  177938. #endif
  177939. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  177940. png_fixed_point int_x_white;
  177941. png_fixed_point int_y_white;
  177942. png_fixed_point int_x_red;
  177943. png_fixed_point int_y_red;
  177944. png_fixed_point int_x_green;
  177945. png_fixed_point int_y_green;
  177946. png_fixed_point int_x_blue;
  177947. png_fixed_point int_y_blue;
  177948. #endif
  177949. } png_info;
  177950. typedef png_info FAR * png_infop;
  177951. typedef png_info FAR * FAR * png_infopp;
  177952. /* Maximum positive integer used in PNG is (2^31)-1 */
  177953. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  177954. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  177955. #define PNG_SIZE_MAX ((png_size_t)(-1))
  177956. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177957. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  177958. #define PNG_MAX_UINT PNG_UINT_31_MAX
  177959. #endif
  177960. /* These describe the color_type field in png_info. */
  177961. /* color type masks */
  177962. #define PNG_COLOR_MASK_PALETTE 1
  177963. #define PNG_COLOR_MASK_COLOR 2
  177964. #define PNG_COLOR_MASK_ALPHA 4
  177965. /* color types. Note that not all combinations are legal */
  177966. #define PNG_COLOR_TYPE_GRAY 0
  177967. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  177968. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  177969. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  177970. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  177971. /* aliases */
  177972. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  177973. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  177974. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  177975. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  177976. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  177977. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  177978. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  177979. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  177980. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  177981. /* These are for the interlacing type. These values should NOT be changed. */
  177982. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  177983. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  177984. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  177985. /* These are for the oFFs chunk. These values should NOT be changed. */
  177986. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  177987. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  177988. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  177989. /* These are for the pCAL chunk. These values should NOT be changed. */
  177990. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  177991. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  177992. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  177993. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  177994. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  177995. /* These are for the sCAL chunk. These values should NOT be changed. */
  177996. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  177997. #define PNG_SCALE_METER 1 /* meters per pixel */
  177998. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  177999. #define PNG_SCALE_LAST 3 /* Not a valid value */
  178000. /* These are for the pHYs chunk. These values should NOT be changed. */
  178001. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  178002. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  178003. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  178004. /* These are for the sRGB chunk. These values should NOT be changed. */
  178005. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  178006. #define PNG_sRGB_INTENT_RELATIVE 1
  178007. #define PNG_sRGB_INTENT_SATURATION 2
  178008. #define PNG_sRGB_INTENT_ABSOLUTE 3
  178009. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  178010. /* This is for text chunks */
  178011. #define PNG_KEYWORD_MAX_LENGTH 79
  178012. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  178013. #define PNG_MAX_PALETTE_LENGTH 256
  178014. /* These determine if an ancillary chunk's data has been successfully read
  178015. * from the PNG header, or if the application has filled in the corresponding
  178016. * data in the info_struct to be written into the output file. The values
  178017. * of the PNG_INFO_<chunk> defines should NOT be changed.
  178018. */
  178019. #define PNG_INFO_gAMA 0x0001
  178020. #define PNG_INFO_sBIT 0x0002
  178021. #define PNG_INFO_cHRM 0x0004
  178022. #define PNG_INFO_PLTE 0x0008
  178023. #define PNG_INFO_tRNS 0x0010
  178024. #define PNG_INFO_bKGD 0x0020
  178025. #define PNG_INFO_hIST 0x0040
  178026. #define PNG_INFO_pHYs 0x0080
  178027. #define PNG_INFO_oFFs 0x0100
  178028. #define PNG_INFO_tIME 0x0200
  178029. #define PNG_INFO_pCAL 0x0400
  178030. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  178031. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  178032. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  178033. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  178034. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  178035. /* This is used for the transformation routines, as some of them
  178036. * change these values for the row. It also should enable using
  178037. * the routines for other purposes.
  178038. */
  178039. typedef struct png_row_info_struct
  178040. {
  178041. png_uint_32 width; /* width of row */
  178042. png_uint_32 rowbytes; /* number of bytes in row */
  178043. png_byte color_type; /* color type of row */
  178044. png_byte bit_depth; /* bit depth of row */
  178045. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  178046. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  178047. } png_row_info;
  178048. typedef png_row_info FAR * png_row_infop;
  178049. typedef png_row_info FAR * FAR * png_row_infopp;
  178050. /* These are the function types for the I/O functions and for the functions
  178051. * that allow the user to override the default I/O functions with his or her
  178052. * own. The png_error_ptr type should match that of user-supplied warning
  178053. * and error functions, while the png_rw_ptr type should match that of the
  178054. * user read/write data functions.
  178055. */
  178056. typedef struct png_struct_def png_struct;
  178057. typedef png_struct FAR * png_structp;
  178058. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  178059. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  178060. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  178061. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  178062. int));
  178063. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  178064. int));
  178065. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178066. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  178067. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  178068. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  178069. png_uint_32, int));
  178070. #endif
  178071. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178072. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178073. defined(PNG_LEGACY_SUPPORTED)
  178074. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  178075. png_row_infop, png_bytep));
  178076. #endif
  178077. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178078. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  178079. #endif
  178080. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178081. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  178082. #endif
  178083. /* Transform masks for the high-level interface */
  178084. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  178085. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  178086. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  178087. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  178088. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  178089. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  178090. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  178091. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  178092. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  178093. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  178094. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  178095. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  178096. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  178097. /* Flags for MNG supported features */
  178098. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  178099. #define PNG_FLAG_MNG_FILTER_64 0x04
  178100. #define PNG_ALL_MNG_FEATURES 0x05
  178101. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  178102. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  178103. /* The structure that holds the information to read and write PNG files.
  178104. * The only people who need to care about what is inside of this are the
  178105. * people who will be modifying the library for their own special needs.
  178106. * It should NOT be accessed directly by an application, except to store
  178107. * the jmp_buf.
  178108. */
  178109. struct png_struct_def
  178110. {
  178111. #ifdef PNG_SETJMP_SUPPORTED
  178112. jmp_buf jmpbuf; /* used in png_error */
  178113. #endif
  178114. png_error_ptr error_fn; /* function for printing errors and aborting */
  178115. png_error_ptr warning_fn; /* function for printing warnings */
  178116. png_voidp error_ptr; /* user supplied struct for error functions */
  178117. png_rw_ptr write_data_fn; /* function for writing output data */
  178118. png_rw_ptr read_data_fn; /* function for reading input data */
  178119. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  178120. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  178121. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  178122. #endif
  178123. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178124. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  178125. #endif
  178126. /* These were added in libpng-1.0.2 */
  178127. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  178128. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178129. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  178130. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  178131. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  178132. png_byte user_transform_channels; /* channels in user transformed pixels */
  178133. #endif
  178134. #endif
  178135. png_uint_32 mode; /* tells us where we are in the PNG file */
  178136. png_uint_32 flags; /* flags indicating various things to libpng */
  178137. png_uint_32 transformations; /* which transformations to perform */
  178138. z_stream zstream; /* pointer to decompression structure (below) */
  178139. png_bytep zbuf; /* buffer for zlib */
  178140. png_size_t zbuf_size; /* size of zbuf */
  178141. int zlib_level; /* holds zlib compression level */
  178142. int zlib_method; /* holds zlib compression method */
  178143. int zlib_window_bits; /* holds zlib compression window bits */
  178144. int zlib_mem_level; /* holds zlib compression memory level */
  178145. int zlib_strategy; /* holds zlib compression strategy */
  178146. png_uint_32 width; /* width of image in pixels */
  178147. png_uint_32 height; /* height of image in pixels */
  178148. png_uint_32 num_rows; /* number of rows in current pass */
  178149. png_uint_32 usr_width; /* width of row at start of write */
  178150. png_uint_32 rowbytes; /* size of row in bytes */
  178151. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  178152. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  178153. png_uint_32 row_number; /* current row in interlace pass */
  178154. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  178155. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  178156. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  178157. png_bytep up_row; /* buffer to save "up" row when filtering */
  178158. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  178159. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  178160. png_row_info row_info; /* used for transformation routines */
  178161. png_uint_32 idat_size; /* current IDAT size for read */
  178162. png_uint_32 crc; /* current chunk CRC value */
  178163. png_colorp palette; /* palette from the input file */
  178164. png_uint_16 num_palette; /* number of color entries in palette */
  178165. png_uint_16 num_trans; /* number of transparency values */
  178166. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  178167. png_byte compression; /* file compression type (always 0) */
  178168. png_byte filter; /* file filter type (always 0) */
  178169. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  178170. png_byte pass; /* current interlace pass (0 - 6) */
  178171. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  178172. png_byte color_type; /* color type of file */
  178173. png_byte bit_depth; /* bit depth of file */
  178174. png_byte usr_bit_depth; /* bit depth of users row */
  178175. png_byte pixel_depth; /* number of bits per pixel */
  178176. png_byte channels; /* number of channels in file */
  178177. png_byte usr_channels; /* channels at start of write */
  178178. png_byte sig_bytes; /* magic bytes read/written from start of file */
  178179. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178180. #ifdef PNG_LEGACY_SUPPORTED
  178181. png_byte filler; /* filler byte for pixel expansion */
  178182. #else
  178183. png_uint_16 filler; /* filler bytes for pixel expansion */
  178184. #endif
  178185. #endif
  178186. #if defined(PNG_bKGD_SUPPORTED)
  178187. png_byte background_gamma_type;
  178188. # ifdef PNG_FLOATING_POINT_SUPPORTED
  178189. float background_gamma;
  178190. # endif
  178191. png_color_16 background; /* background color in screen gamma space */
  178192. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178193. png_color_16 background_1; /* background normalized to gamma 1.0 */
  178194. #endif
  178195. #endif /* PNG_bKGD_SUPPORTED */
  178196. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178197. png_flush_ptr output_flush_fn;/* Function for flushing output */
  178198. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  178199. png_uint_32 flush_rows; /* number of rows written since last flush */
  178200. #endif
  178201. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178202. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  178203. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178204. float gamma; /* file gamma value */
  178205. float screen_gamma; /* screen gamma value (display_exponent) */
  178206. #endif
  178207. #endif
  178208. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178209. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  178210. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  178211. png_bytep gamma_to_1; /* converts from file to 1.0 */
  178212. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  178213. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  178214. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  178215. #endif
  178216. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  178217. png_color_8 sig_bit; /* significant bits in each available channel */
  178218. #endif
  178219. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178220. png_color_8 shift; /* shift for significant bit tranformation */
  178221. #endif
  178222. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  178223. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178224. png_bytep trans; /* transparency values for paletted files */
  178225. png_color_16 trans_values; /* transparency values for non-paletted files */
  178226. #endif
  178227. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  178228. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  178229. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178230. png_progressive_info_ptr info_fn; /* called after header data fully read */
  178231. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  178232. png_progressive_end_ptr end_fn; /* called after image is complete */
  178233. png_bytep save_buffer_ptr; /* current location in save_buffer */
  178234. png_bytep save_buffer; /* buffer for previously read data */
  178235. png_bytep current_buffer_ptr; /* current location in current_buffer */
  178236. png_bytep current_buffer; /* buffer for recently used data */
  178237. png_uint_32 push_length; /* size of current input chunk */
  178238. png_uint_32 skip_length; /* bytes to skip in input data */
  178239. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  178240. png_size_t save_buffer_max; /* total size of save_buffer */
  178241. png_size_t buffer_size; /* total amount of available input data */
  178242. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  178243. int process_mode; /* what push library is currently doing */
  178244. int cur_palette; /* current push library palette index */
  178245. # if defined(PNG_TEXT_SUPPORTED)
  178246. png_size_t current_text_size; /* current size of text input data */
  178247. png_size_t current_text_left; /* how much text left to read in input */
  178248. png_charp current_text; /* current text chunk buffer */
  178249. png_charp current_text_ptr; /* current location in current_text */
  178250. # endif /* PNG_TEXT_SUPPORTED */
  178251. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178252. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  178253. /* for the Borland special 64K segment handler */
  178254. png_bytepp offset_table_ptr;
  178255. png_bytep offset_table;
  178256. png_uint_16 offset_table_number;
  178257. png_uint_16 offset_table_count;
  178258. png_uint_16 offset_table_count_free;
  178259. #endif
  178260. #if defined(PNG_READ_DITHER_SUPPORTED)
  178261. png_bytep palette_lookup; /* lookup table for dithering */
  178262. png_bytep dither_index; /* index translation for palette files */
  178263. #endif
  178264. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  178265. png_uint_16p hist; /* histogram */
  178266. #endif
  178267. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  178268. png_byte heuristic_method; /* heuristic for row filter selection */
  178269. png_byte num_prev_filters; /* number of weights for previous rows */
  178270. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  178271. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  178272. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  178273. png_uint_16p filter_costs; /* relative filter calculation cost */
  178274. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  178275. #endif
  178276. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178277. png_charp time_buffer; /* String to hold RFC 1123 time text */
  178278. #endif
  178279. /* New members added in libpng-1.0.6 */
  178280. #ifdef PNG_FREE_ME_SUPPORTED
  178281. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  178282. #endif
  178283. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  178284. png_voidp user_chunk_ptr;
  178285. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  178286. #endif
  178287. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178288. int num_chunk_list;
  178289. png_bytep chunk_list;
  178290. #endif
  178291. /* New members added in libpng-1.0.3 */
  178292. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178293. png_byte rgb_to_gray_status;
  178294. /* These were changed from png_byte in libpng-1.0.6 */
  178295. png_uint_16 rgb_to_gray_red_coeff;
  178296. png_uint_16 rgb_to_gray_green_coeff;
  178297. png_uint_16 rgb_to_gray_blue_coeff;
  178298. #endif
  178299. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  178300. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  178301. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178302. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178303. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  178304. #ifdef PNG_1_0_X
  178305. png_byte mng_features_permitted;
  178306. #else
  178307. png_uint_32 mng_features_permitted;
  178308. #endif /* PNG_1_0_X */
  178309. #endif
  178310. /* New member added in libpng-1.0.7 */
  178311. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  178312. png_fixed_point int_gamma;
  178313. #endif
  178314. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  178315. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  178316. png_byte filter_type;
  178317. #endif
  178318. #if defined(PNG_1_0_X)
  178319. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  178320. png_uint_32 row_buf_size;
  178321. #endif
  178322. /* New members added in libpng-1.2.0 */
  178323. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178324. # if !defined(PNG_1_0_X)
  178325. # if defined(PNG_MMX_CODE_SUPPORTED)
  178326. png_byte mmx_bitdepth_threshold;
  178327. png_uint_32 mmx_rowbytes_threshold;
  178328. # endif
  178329. png_uint_32 asm_flags;
  178330. # endif
  178331. #endif
  178332. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  178333. #ifdef PNG_USER_MEM_SUPPORTED
  178334. png_voidp mem_ptr; /* user supplied struct for mem functions */
  178335. png_malloc_ptr malloc_fn; /* function for allocating memory */
  178336. png_free_ptr free_fn; /* function for freeing memory */
  178337. #endif
  178338. /* New member added in libpng-1.0.13 and 1.2.0 */
  178339. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  178340. #if defined(PNG_READ_DITHER_SUPPORTED)
  178341. /* The following three members were added at version 1.0.14 and 1.2.4 */
  178342. png_bytep dither_sort; /* working sort array */
  178343. png_bytep index_to_palette; /* where the original index currently is */
  178344. /* in the palette */
  178345. png_bytep palette_to_index; /* which original index points to this */
  178346. /* palette color */
  178347. #endif
  178348. /* New members added in libpng-1.0.16 and 1.2.6 */
  178349. png_byte compression_type;
  178350. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  178351. png_uint_32 user_width_max;
  178352. png_uint_32 user_height_max;
  178353. #endif
  178354. /* New member added in libpng-1.0.25 and 1.2.17 */
  178355. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178356. /* storage for unknown chunk that the library doesn't recognize. */
  178357. png_unknown_chunk unknown_chunk;
  178358. #endif
  178359. };
  178360. /* This triggers a compiler error in png.c, if png.c and png.h
  178361. * do not agree upon the version number.
  178362. */
  178363. typedef png_structp version_1_2_21;
  178364. typedef png_struct FAR * FAR * png_structpp;
  178365. /* Here are the function definitions most commonly used. This is not
  178366. * the place to find out how to use libpng. See libpng.txt for the
  178367. * full explanation, see example.c for the summary. This just provides
  178368. * a simple one line description of the use of each function.
  178369. */
  178370. /* Returns the version number of the library */
  178371. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  178372. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  178373. * Handling more than 8 bytes from the beginning of the file is an error.
  178374. */
  178375. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  178376. int num_bytes));
  178377. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  178378. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  178379. * signature, and non-zero otherwise. Having num_to_check == 0 or
  178380. * start > 7 will always fail (ie return non-zero).
  178381. */
  178382. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  178383. png_size_t num_to_check));
  178384. /* Simple signature checking function. This is the same as calling
  178385. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  178386. */
  178387. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  178388. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  178389. extern PNG_EXPORT(png_structp,png_create_read_struct)
  178390. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178391. png_error_ptr error_fn, png_error_ptr warn_fn));
  178392. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  178393. extern PNG_EXPORT(png_structp,png_create_write_struct)
  178394. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178395. png_error_ptr error_fn, png_error_ptr warn_fn));
  178396. #ifdef PNG_WRITE_SUPPORTED
  178397. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  178398. PNGARG((png_structp png_ptr));
  178399. #endif
  178400. #ifdef PNG_WRITE_SUPPORTED
  178401. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  178402. PNGARG((png_structp png_ptr, png_uint_32 size));
  178403. #endif
  178404. /* Reset the compression stream */
  178405. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  178406. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  178407. #ifdef PNG_USER_MEM_SUPPORTED
  178408. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  178409. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178410. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178411. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178412. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  178413. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  178414. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  178415. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178416. #endif
  178417. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  178418. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  178419. png_bytep chunk_name, png_bytep data, png_size_t length));
  178420. /* Write the start of a PNG chunk - length and chunk name. */
  178421. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  178422. png_bytep chunk_name, png_uint_32 length));
  178423. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  178424. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  178425. png_bytep data, png_size_t length));
  178426. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  178427. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  178428. /* Allocate and initialize the info structure */
  178429. extern PNG_EXPORT(png_infop,png_create_info_struct)
  178430. PNGARG((png_structp png_ptr));
  178431. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178432. /* Initialize the info structure (old interface - DEPRECATED) */
  178433. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  178434. #undef png_info_init
  178435. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  178436. png_sizeof(png_info));
  178437. #endif
  178438. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  178439. png_size_t png_info_struct_size));
  178440. /* Writes all the PNG information before the image. */
  178441. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  178442. png_infop info_ptr));
  178443. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  178444. png_infop info_ptr));
  178445. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178446. /* read the information before the actual image data. */
  178447. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  178448. png_infop info_ptr));
  178449. #endif
  178450. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178451. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  178452. PNGARG((png_structp png_ptr, png_timep ptime));
  178453. #endif
  178454. #if !defined(_WIN32_WCE)
  178455. /* "time.h" functions are not supported on WindowsCE */
  178456. #if defined(PNG_WRITE_tIME_SUPPORTED)
  178457. /* convert from a struct tm to png_time */
  178458. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  178459. struct tm FAR * ttime));
  178460. /* convert from time_t to png_time. Uses gmtime() */
  178461. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  178462. time_t ttime));
  178463. #endif /* PNG_WRITE_tIME_SUPPORTED */
  178464. #endif /* _WIN32_WCE */
  178465. #if defined(PNG_READ_EXPAND_SUPPORTED)
  178466. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  178467. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  178468. #if !defined(PNG_1_0_X)
  178469. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  178470. png_ptr));
  178471. #endif
  178472. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  178473. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  178474. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178475. /* Deprecated */
  178476. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  178477. #endif
  178478. #endif
  178479. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  178480. /* Use blue, green, red order for pixels. */
  178481. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  178482. #endif
  178483. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  178484. /* Expand the grayscale to 24-bit RGB if necessary. */
  178485. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  178486. #endif
  178487. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  178488. /* Reduce RGB to grayscale. */
  178489. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178490. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  178491. int error_action, double red, double green ));
  178492. #endif
  178493. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  178494. int error_action, png_fixed_point red, png_fixed_point green ));
  178495. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  178496. png_ptr));
  178497. #endif
  178498. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  178499. png_colorp palette));
  178500. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  178501. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  178502. #endif
  178503. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  178504. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  178505. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  178506. #endif
  178507. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  178508. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  178509. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  178510. #endif
  178511. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  178512. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  178513. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  178514. png_uint_32 filler, int flags));
  178515. /* The values of the PNG_FILLER_ defines should NOT be changed */
  178516. #define PNG_FILLER_BEFORE 0
  178517. #define PNG_FILLER_AFTER 1
  178518. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  178519. #if !defined(PNG_1_0_X)
  178520. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  178521. png_uint_32 filler, int flags));
  178522. #endif
  178523. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  178524. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  178525. /* Swap bytes in 16-bit depth files. */
  178526. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  178527. #endif
  178528. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  178529. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  178530. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  178531. #endif
  178532. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  178533. /* Swap packing order of pixels in bytes. */
  178534. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  178535. #endif
  178536. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  178537. /* Converts files to legal bit depths. */
  178538. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  178539. png_color_8p true_bits));
  178540. #endif
  178541. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  178542. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  178543. /* Have the code handle the interlacing. Returns the number of passes. */
  178544. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  178545. #endif
  178546. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  178547. /* Invert monochrome files */
  178548. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  178549. #endif
  178550. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  178551. /* Handle alpha and tRNS by replacing with a background color. */
  178552. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178553. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  178554. png_color_16p background_color, int background_gamma_code,
  178555. int need_expand, double background_gamma));
  178556. #endif
  178557. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  178558. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  178559. #define PNG_BACKGROUND_GAMMA_FILE 2
  178560. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  178561. #endif
  178562. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  178563. /* strip the second byte of information from a 16-bit depth file. */
  178564. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  178565. #endif
  178566. #if defined(PNG_READ_DITHER_SUPPORTED)
  178567. /* Turn on dithering, and reduce the palette to the number of colors available. */
  178568. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  178569. png_colorp palette, int num_palette, int maximum_colors,
  178570. png_uint_16p histogram, int full_dither));
  178571. #endif
  178572. #if defined(PNG_READ_GAMMA_SUPPORTED)
  178573. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  178574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178575. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  178576. double screen_gamma, double default_file_gamma));
  178577. #endif
  178578. #endif
  178579. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  178580. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  178581. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  178582. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  178583. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  178584. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  178585. int empty_plte_permitted));
  178586. #endif
  178587. #endif
  178588. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  178589. /* Set how many lines between output flushes - 0 for no flushing */
  178590. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  178591. /* Flush the current PNG output buffer */
  178592. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  178593. #endif
  178594. /* optional update palette with requested transformations */
  178595. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  178596. /* optional call to update the users info structure */
  178597. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  178598. png_infop info_ptr));
  178599. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178600. /* read one or more rows of image data. */
  178601. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  178602. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  178603. #endif
  178604. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178605. /* read a row of data. */
  178606. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  178607. png_bytep row,
  178608. png_bytep display_row));
  178609. #endif
  178610. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178611. /* read the whole image into memory at once. */
  178612. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  178613. png_bytepp image));
  178614. #endif
  178615. /* write a row of image data */
  178616. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  178617. png_bytep row));
  178618. /* write a few rows of image data */
  178619. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  178620. png_bytepp row, png_uint_32 num_rows));
  178621. /* write the image data */
  178622. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  178623. png_bytepp image));
  178624. /* writes the end of the PNG file. */
  178625. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  178626. png_infop info_ptr));
  178627. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  178628. /* read the end of the PNG file. */
  178629. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  178630. png_infop info_ptr));
  178631. #endif
  178632. /* free any memory associated with the png_info_struct */
  178633. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  178634. png_infopp info_ptr_ptr));
  178635. /* free any memory associated with the png_struct and the png_info_structs */
  178636. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  178637. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  178638. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  178639. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  178640. png_infop end_info_ptr));
  178641. /* free any memory associated with the png_struct and the png_info_structs */
  178642. extern PNG_EXPORT(void,png_destroy_write_struct)
  178643. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  178644. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  178645. extern void png_write_destroy PNGARG((png_structp png_ptr));
  178646. /* set the libpng method of handling chunk CRC errors */
  178647. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  178648. int crit_action, int ancil_action));
  178649. /* Values for png_set_crc_action() to say how to handle CRC errors in
  178650. * ancillary and critical chunks, and whether to use the data contained
  178651. * therein. Note that it is impossible to "discard" data in a critical
  178652. * chunk. For versions prior to 0.90, the action was always error/quit,
  178653. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  178654. * chunks is warn/discard. These values should NOT be changed.
  178655. *
  178656. * value action:critical action:ancillary
  178657. */
  178658. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  178659. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  178660. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  178661. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  178662. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  178663. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  178664. /* These functions give the user control over the scan-line filtering in
  178665. * libpng and the compression methods used by zlib. These functions are
  178666. * mainly useful for testing, as the defaults should work with most users.
  178667. * Those users who are tight on memory or want faster performance at the
  178668. * expense of compression can modify them. See the compression library
  178669. * header file (zlib.h) for an explination of the compression functions.
  178670. */
  178671. /* set the filtering method(s) used by libpng. Currently, the only valid
  178672. * value for "method" is 0.
  178673. */
  178674. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  178675. int filters));
  178676. /* Flags for png_set_filter() to say which filters to use. The flags
  178677. * are chosen so that they don't conflict with real filter types
  178678. * below, in case they are supplied instead of the #defined constants.
  178679. * These values should NOT be changed.
  178680. */
  178681. #define PNG_NO_FILTERS 0x00
  178682. #define PNG_FILTER_NONE 0x08
  178683. #define PNG_FILTER_SUB 0x10
  178684. #define PNG_FILTER_UP 0x20
  178685. #define PNG_FILTER_AVG 0x40
  178686. #define PNG_FILTER_PAETH 0x80
  178687. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  178688. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  178689. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  178690. * These defines should NOT be changed.
  178691. */
  178692. #define PNG_FILTER_VALUE_NONE 0
  178693. #define PNG_FILTER_VALUE_SUB 1
  178694. #define PNG_FILTER_VALUE_UP 2
  178695. #define PNG_FILTER_VALUE_AVG 3
  178696. #define PNG_FILTER_VALUE_PAETH 4
  178697. #define PNG_FILTER_VALUE_LAST 5
  178698. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  178699. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  178700. * defines, either the default (minimum-sum-of-absolute-differences), or
  178701. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  178702. *
  178703. * Weights are factors >= 1.0, indicating how important it is to keep the
  178704. * filter type consistent between rows. Larger numbers mean the current
  178705. * filter is that many times as likely to be the same as the "num_weights"
  178706. * previous filters. This is cumulative for each previous row with a weight.
  178707. * There needs to be "num_weights" values in "filter_weights", or it can be
  178708. * NULL if the weights aren't being specified. Weights have no influence on
  178709. * the selection of the first row filter. Well chosen weights can (in theory)
  178710. * improve the compression for a given image.
  178711. *
  178712. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  178713. * filter type. Higher costs indicate more decoding expense, and are
  178714. * therefore less likely to be selected over a filter with lower computational
  178715. * costs. There needs to be a value in "filter_costs" for each valid filter
  178716. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  178717. * setting the costs. Costs try to improve the speed of decompression without
  178718. * unduly increasing the compressed image size.
  178719. *
  178720. * A negative weight or cost indicates the default value is to be used, and
  178721. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  178722. * The default values for both weights and costs are currently 1.0, but may
  178723. * change if good general weighting/cost heuristics can be found. If both
  178724. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  178725. * to the UNWEIGHTED method, but with added encoding time/computation.
  178726. */
  178727. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178728. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  178729. int heuristic_method, int num_weights, png_doublep filter_weights,
  178730. png_doublep filter_costs));
  178731. #endif
  178732. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  178733. /* Heuristic used for row filter selection. These defines should NOT be
  178734. * changed.
  178735. */
  178736. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  178737. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  178738. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  178739. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  178740. /* Set the library compression level. Currently, valid values range from
  178741. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  178742. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  178743. * shown that zlib compression levels 3-6 usually perform as well as level 9
  178744. * for PNG images, and do considerably fewer caclulations. In the future,
  178745. * these values may not correspond directly to the zlib compression levels.
  178746. */
  178747. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  178748. int level));
  178749. extern PNG_EXPORT(void,png_set_compression_mem_level)
  178750. PNGARG((png_structp png_ptr, int mem_level));
  178751. extern PNG_EXPORT(void,png_set_compression_strategy)
  178752. PNGARG((png_structp png_ptr, int strategy));
  178753. extern PNG_EXPORT(void,png_set_compression_window_bits)
  178754. PNGARG((png_structp png_ptr, int window_bits));
  178755. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  178756. int method));
  178757. /* These next functions are called for input/output, memory, and error
  178758. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  178759. * and call standard C I/O routines such as fread(), fwrite(), and
  178760. * fprintf(). These functions can be made to use other I/O routines
  178761. * at run time for those applications that need to handle I/O in a
  178762. * different manner by calling png_set_???_fn(). See libpng.txt for
  178763. * more information.
  178764. */
  178765. #if !defined(PNG_NO_STDIO)
  178766. /* Initialize the input/output for the PNG file to the default functions. */
  178767. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  178768. #endif
  178769. /* Replace the (error and abort), and warning functions with user
  178770. * supplied functions. If no messages are to be printed you must still
  178771. * write and use replacement functions. The replacement error_fn should
  178772. * still do a longjmp to the last setjmp location if you are using this
  178773. * method of error handling. If error_fn or warning_fn is NULL, the
  178774. * default function will be used.
  178775. */
  178776. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  178777. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  178778. /* Return the user pointer associated with the error functions */
  178779. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  178780. /* Replace the default data output functions with a user supplied one(s).
  178781. * If buffered output is not used, then output_flush_fn can be set to NULL.
  178782. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  178783. * output_flush_fn will be ignored (and thus can be NULL).
  178784. */
  178785. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  178786. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  178787. /* Replace the default data input function with a user supplied one. */
  178788. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  178789. png_voidp io_ptr, png_rw_ptr read_data_fn));
  178790. /* Return the user pointer associated with the I/O functions */
  178791. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  178792. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  178793. png_read_status_ptr read_row_fn));
  178794. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  178795. png_write_status_ptr write_row_fn));
  178796. #ifdef PNG_USER_MEM_SUPPORTED
  178797. /* Replace the default memory allocation functions with user supplied one(s). */
  178798. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  178799. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  178800. /* Return the user pointer associated with the memory functions */
  178801. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  178802. #endif
  178803. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178804. defined(PNG_LEGACY_SUPPORTED)
  178805. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  178806. png_ptr, png_user_transform_ptr read_user_transform_fn));
  178807. #endif
  178808. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178809. defined(PNG_LEGACY_SUPPORTED)
  178810. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  178811. png_ptr, png_user_transform_ptr write_user_transform_fn));
  178812. #endif
  178813. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  178814. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  178815. defined(PNG_LEGACY_SUPPORTED)
  178816. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  178817. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  178818. int user_transform_channels));
  178819. /* Return the user pointer associated with the user transform functions */
  178820. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  178821. PNGARG((png_structp png_ptr));
  178822. #endif
  178823. #ifdef PNG_USER_CHUNKS_SUPPORTED
  178824. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  178825. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  178826. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  178827. png_ptr));
  178828. #endif
  178829. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  178830. /* Sets the function callbacks for the push reader, and a pointer to a
  178831. * user-defined structure available to the callback functions.
  178832. */
  178833. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  178834. png_voidp progressive_ptr,
  178835. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  178836. png_progressive_end_ptr end_fn));
  178837. /* returns the user pointer associated with the push read functions */
  178838. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  178839. PNGARG((png_structp png_ptr));
  178840. /* function to be called when data becomes available */
  178841. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  178842. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  178843. /* function that combines rows. Not very much different than the
  178844. * png_combine_row() call. Is this even used?????
  178845. */
  178846. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  178847. png_bytep old_row, png_bytep new_row));
  178848. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  178849. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  178850. png_uint_32 size));
  178851. #if defined(PNG_1_0_X)
  178852. # define png_malloc_warn png_malloc
  178853. #else
  178854. /* Added at libpng version 1.2.4 */
  178855. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  178856. png_uint_32 size));
  178857. #endif
  178858. /* frees a pointer allocated by png_malloc() */
  178859. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  178860. #if defined(PNG_1_0_X)
  178861. /* Function to allocate memory for zlib. */
  178862. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  178863. uInt size));
  178864. /* Function to free memory for zlib */
  178865. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  178866. #endif
  178867. /* Free data that was allocated internally */
  178868. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  178869. png_infop info_ptr, png_uint_32 free_me, int num));
  178870. #ifdef PNG_FREE_ME_SUPPORTED
  178871. /* Reassign responsibility for freeing existing data, whether allocated
  178872. * by libpng or by the application */
  178873. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  178874. png_infop info_ptr, int freer, png_uint_32 mask));
  178875. #endif
  178876. /* assignments for png_data_freer */
  178877. #define PNG_DESTROY_WILL_FREE_DATA 1
  178878. #define PNG_SET_WILL_FREE_DATA 1
  178879. #define PNG_USER_WILL_FREE_DATA 2
  178880. /* Flags for png_ptr->free_me and info_ptr->free_me */
  178881. #define PNG_FREE_HIST 0x0008
  178882. #define PNG_FREE_ICCP 0x0010
  178883. #define PNG_FREE_SPLT 0x0020
  178884. #define PNG_FREE_ROWS 0x0040
  178885. #define PNG_FREE_PCAL 0x0080
  178886. #define PNG_FREE_SCAL 0x0100
  178887. #define PNG_FREE_UNKN 0x0200
  178888. #define PNG_FREE_LIST 0x0400
  178889. #define PNG_FREE_PLTE 0x1000
  178890. #define PNG_FREE_TRNS 0x2000
  178891. #define PNG_FREE_TEXT 0x4000
  178892. #define PNG_FREE_ALL 0x7fff
  178893. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  178894. #ifdef PNG_USER_MEM_SUPPORTED
  178895. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  178896. png_uint_32 size));
  178897. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  178898. png_voidp ptr));
  178899. #endif
  178900. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  178901. png_voidp s1, png_voidp s2, png_uint_32 size));
  178902. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  178903. png_voidp s1, int value, png_uint_32 size));
  178904. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  178905. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  178906. int check));
  178907. #endif /* USE_FAR_KEYWORD */
  178908. #ifndef PNG_NO_ERROR_TEXT
  178909. /* Fatal error in PNG image of libpng - can't continue */
  178910. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  178911. png_const_charp error_message));
  178912. /* The same, but the chunk name is prepended to the error string. */
  178913. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  178914. png_const_charp error_message));
  178915. #else
  178916. /* Fatal error in PNG image of libpng - can't continue */
  178917. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  178918. #endif
  178919. #ifndef PNG_NO_WARNINGS
  178920. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  178921. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  178922. png_const_charp warning_message));
  178923. #ifdef PNG_READ_SUPPORTED
  178924. /* Non-fatal error in libpng, chunk name is prepended to message. */
  178925. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  178926. png_const_charp warning_message));
  178927. #endif /* PNG_READ_SUPPORTED */
  178928. #endif /* PNG_NO_WARNINGS */
  178929. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  178930. * Similarly, the png_get_<chunk> calls are used to read values from the
  178931. * png_info_struct, either storing the parameters in the passed variables, or
  178932. * setting pointers into the png_info_struct where the data is stored. The
  178933. * png_get_<chunk> functions return a non-zero value if the data was available
  178934. * in info_ptr, or return zero and do not change any of the parameters if the
  178935. * data was not available.
  178936. *
  178937. * These functions should be used instead of directly accessing png_info
  178938. * to avoid problems with future changes in the size and internal layout of
  178939. * png_info_struct.
  178940. */
  178941. /* Returns "flag" if chunk data is valid in info_ptr. */
  178942. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  178943. png_infop info_ptr, png_uint_32 flag));
  178944. /* Returns number of bytes needed to hold a transformed row. */
  178945. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  178946. png_infop info_ptr));
  178947. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178948. /* Returns row_pointers, which is an array of pointers to scanlines that was
  178949. returned from png_read_png(). */
  178950. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  178951. png_infop info_ptr));
  178952. /* Set row_pointers, which is an array of pointers to scanlines for use
  178953. by png_write_png(). */
  178954. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  178955. png_infop info_ptr, png_bytepp row_pointers));
  178956. #endif
  178957. /* Returns number of color channels in image. */
  178958. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  178959. png_infop info_ptr));
  178960. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178961. /* Returns image width in pixels. */
  178962. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  178963. png_ptr, png_infop info_ptr));
  178964. /* Returns image height in pixels. */
  178965. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  178966. png_ptr, png_infop info_ptr));
  178967. /* Returns image bit_depth. */
  178968. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  178969. png_ptr, png_infop info_ptr));
  178970. /* Returns image color_type. */
  178971. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  178972. png_ptr, png_infop info_ptr));
  178973. /* Returns image filter_type. */
  178974. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  178975. png_ptr, png_infop info_ptr));
  178976. /* Returns image interlace_type. */
  178977. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  178978. png_ptr, png_infop info_ptr));
  178979. /* Returns image compression_type. */
  178980. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  178981. png_ptr, png_infop info_ptr));
  178982. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  178983. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  178984. png_ptr, png_infop info_ptr));
  178985. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  178986. png_ptr, png_infop info_ptr));
  178987. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  178988. png_ptr, png_infop info_ptr));
  178989. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  178990. #ifdef PNG_FLOATING_POINT_SUPPORTED
  178991. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  178992. png_ptr, png_infop info_ptr));
  178993. #endif
  178994. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  178995. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  178996. png_ptr, png_infop info_ptr));
  178997. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  178998. png_ptr, png_infop info_ptr));
  178999. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  179000. png_ptr, png_infop info_ptr));
  179001. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  179002. png_ptr, png_infop info_ptr));
  179003. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179004. /* Returns pointer to signature string read from PNG header */
  179005. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  179006. png_infop info_ptr));
  179007. #if defined(PNG_bKGD_SUPPORTED)
  179008. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  179009. png_infop info_ptr, png_color_16p *background));
  179010. #endif
  179011. #if defined(PNG_bKGD_SUPPORTED)
  179012. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  179013. png_infop info_ptr, png_color_16p background));
  179014. #endif
  179015. #if defined(PNG_cHRM_SUPPORTED)
  179016. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179017. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  179018. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  179019. double *red_y, double *green_x, double *green_y, double *blue_x,
  179020. double *blue_y));
  179021. #endif
  179022. #ifdef PNG_FIXED_POINT_SUPPORTED
  179023. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  179024. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  179025. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  179026. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  179027. *int_blue_x, png_fixed_point *int_blue_y));
  179028. #endif
  179029. #endif
  179030. #if defined(PNG_cHRM_SUPPORTED)
  179031. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179032. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  179033. png_infop info_ptr, double white_x, double white_y, double red_x,
  179034. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  179035. #endif
  179036. #ifdef PNG_FIXED_POINT_SUPPORTED
  179037. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  179038. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  179039. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179040. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179041. png_fixed_point int_blue_y));
  179042. #endif
  179043. #endif
  179044. #if defined(PNG_gAMA_SUPPORTED)
  179045. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179046. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  179047. png_infop info_ptr, double *file_gamma));
  179048. #endif
  179049. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  179050. png_infop info_ptr, png_fixed_point *int_file_gamma));
  179051. #endif
  179052. #if defined(PNG_gAMA_SUPPORTED)
  179053. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179054. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  179055. png_infop info_ptr, double file_gamma));
  179056. #endif
  179057. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  179058. png_infop info_ptr, png_fixed_point int_file_gamma));
  179059. #endif
  179060. #if defined(PNG_hIST_SUPPORTED)
  179061. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  179062. png_infop info_ptr, png_uint_16p *hist));
  179063. #endif
  179064. #if defined(PNG_hIST_SUPPORTED)
  179065. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  179066. png_infop info_ptr, png_uint_16p hist));
  179067. #endif
  179068. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  179069. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  179070. int *bit_depth, int *color_type, int *interlace_method,
  179071. int *compression_method, int *filter_method));
  179072. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  179073. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  179074. int color_type, int interlace_method, int compression_method,
  179075. int filter_method));
  179076. #if defined(PNG_oFFs_SUPPORTED)
  179077. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  179078. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  179079. int *unit_type));
  179080. #endif
  179081. #if defined(PNG_oFFs_SUPPORTED)
  179082. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  179083. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  179084. int unit_type));
  179085. #endif
  179086. #if defined(PNG_pCAL_SUPPORTED)
  179087. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  179088. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  179089. int *type, int *nparams, png_charp *units, png_charpp *params));
  179090. #endif
  179091. #if defined(PNG_pCAL_SUPPORTED)
  179092. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  179093. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  179094. int type, int nparams, png_charp units, png_charpp params));
  179095. #endif
  179096. #if defined(PNG_pHYs_SUPPORTED)
  179097. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  179098. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  179099. #endif
  179100. #if defined(PNG_pHYs_SUPPORTED)
  179101. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  179102. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  179103. #endif
  179104. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  179105. png_infop info_ptr, png_colorp *palette, int *num_palette));
  179106. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  179107. png_infop info_ptr, png_colorp palette, int num_palette));
  179108. #if defined(PNG_sBIT_SUPPORTED)
  179109. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  179110. png_infop info_ptr, png_color_8p *sig_bit));
  179111. #endif
  179112. #if defined(PNG_sBIT_SUPPORTED)
  179113. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  179114. png_infop info_ptr, png_color_8p sig_bit));
  179115. #endif
  179116. #if defined(PNG_sRGB_SUPPORTED)
  179117. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  179118. png_infop info_ptr, int *intent));
  179119. #endif
  179120. #if defined(PNG_sRGB_SUPPORTED)
  179121. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  179122. png_infop info_ptr, int intent));
  179123. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  179124. png_infop info_ptr, int intent));
  179125. #endif
  179126. #if defined(PNG_iCCP_SUPPORTED)
  179127. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  179128. png_infop info_ptr, png_charpp name, int *compression_type,
  179129. png_charpp profile, png_uint_32 *proflen));
  179130. /* Note to maintainer: profile should be png_bytepp */
  179131. #endif
  179132. #if defined(PNG_iCCP_SUPPORTED)
  179133. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  179134. png_infop info_ptr, png_charp name, int compression_type,
  179135. png_charp profile, png_uint_32 proflen));
  179136. /* Note to maintainer: profile should be png_bytep */
  179137. #endif
  179138. #if defined(PNG_sPLT_SUPPORTED)
  179139. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  179140. png_infop info_ptr, png_sPLT_tpp entries));
  179141. #endif
  179142. #if defined(PNG_sPLT_SUPPORTED)
  179143. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  179144. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  179145. #endif
  179146. #if defined(PNG_TEXT_SUPPORTED)
  179147. /* png_get_text also returns the number of text chunks in *num_text */
  179148. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  179149. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  179150. #endif
  179151. /*
  179152. * Note while png_set_text() will accept a structure whose text,
  179153. * language, and translated keywords are NULL pointers, the structure
  179154. * returned by png_get_text will always contain regular
  179155. * zero-terminated C strings. They might be empty strings but
  179156. * they will never be NULL pointers.
  179157. */
  179158. #if defined(PNG_TEXT_SUPPORTED)
  179159. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  179160. png_infop info_ptr, png_textp text_ptr, int num_text));
  179161. #endif
  179162. #if defined(PNG_tIME_SUPPORTED)
  179163. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  179164. png_infop info_ptr, png_timep *mod_time));
  179165. #endif
  179166. #if defined(PNG_tIME_SUPPORTED)
  179167. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  179168. png_infop info_ptr, png_timep mod_time));
  179169. #endif
  179170. #if defined(PNG_tRNS_SUPPORTED)
  179171. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  179172. png_infop info_ptr, png_bytep *trans, int *num_trans,
  179173. png_color_16p *trans_values));
  179174. #endif
  179175. #if defined(PNG_tRNS_SUPPORTED)
  179176. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  179177. png_infop info_ptr, png_bytep trans, int num_trans,
  179178. png_color_16p trans_values));
  179179. #endif
  179180. #if defined(PNG_tRNS_SUPPORTED)
  179181. #endif
  179182. #if defined(PNG_sCAL_SUPPORTED)
  179183. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179184. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  179185. png_infop info_ptr, int *unit, double *width, double *height));
  179186. #else
  179187. #ifdef PNG_FIXED_POINT_SUPPORTED
  179188. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  179189. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  179190. #endif
  179191. #endif
  179192. #endif /* PNG_sCAL_SUPPORTED */
  179193. #if defined(PNG_sCAL_SUPPORTED)
  179194. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179195. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  179196. png_infop info_ptr, int unit, double width, double height));
  179197. #else
  179198. #ifdef PNG_FIXED_POINT_SUPPORTED
  179199. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  179200. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  179201. #endif
  179202. #endif
  179203. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  179204. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179205. /* provide a list of chunks and how they are to be handled, if the built-in
  179206. handling or default unknown chunk handling is not desired. Any chunks not
  179207. listed will be handled in the default manner. The IHDR and IEND chunks
  179208. must not be listed.
  179209. keep = 0: follow default behaviour
  179210. = 1: do not keep
  179211. = 2: keep only if safe-to-copy
  179212. = 3: keep even if unsafe-to-copy
  179213. */
  179214. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  179215. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  179216. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  179217. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  179218. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  179219. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  179220. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  179221. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  179222. #endif
  179223. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  179224. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  179225. chunk_name));
  179226. #endif
  179227. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  179228. If you need to turn it off for a chunk that your application has freed,
  179229. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  179230. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  179231. png_infop info_ptr, int mask));
  179232. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  179233. /* The "params" pointer is currently not used and is for future expansion. */
  179234. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  179235. png_infop info_ptr,
  179236. int transforms,
  179237. png_voidp params));
  179238. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  179239. png_infop info_ptr,
  179240. int transforms,
  179241. png_voidp params));
  179242. #endif
  179243. /* Define PNG_DEBUG at compile time for debugging information. Higher
  179244. * numbers for PNG_DEBUG mean more debugging information. This has
  179245. * only been added since version 0.95 so it is not implemented throughout
  179246. * libpng yet, but more support will be added as needed.
  179247. */
  179248. #ifdef PNG_DEBUG
  179249. #if (PNG_DEBUG > 0)
  179250. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  179251. #include <crtdbg.h>
  179252. #if (PNG_DEBUG > 1)
  179253. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  179254. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  179255. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  179256. #endif
  179257. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  179258. #ifndef PNG_DEBUG_FILE
  179259. #define PNG_DEBUG_FILE stderr
  179260. #endif /* PNG_DEBUG_FILE */
  179261. #if (PNG_DEBUG > 1)
  179262. #define png_debug(l,m) \
  179263. { \
  179264. int num_tabs=l; \
  179265. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179266. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  179267. }
  179268. #define png_debug1(l,m,p1) \
  179269. { \
  179270. int num_tabs=l; \
  179271. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179272. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  179273. }
  179274. #define png_debug2(l,m,p1,p2) \
  179275. { \
  179276. int num_tabs=l; \
  179277. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  179278. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  179279. }
  179280. #endif /* (PNG_DEBUG > 1) */
  179281. #endif /* _MSC_VER */
  179282. #endif /* (PNG_DEBUG > 0) */
  179283. #endif /* PNG_DEBUG */
  179284. #ifndef png_debug
  179285. #define png_debug(l, m)
  179286. #endif
  179287. #ifndef png_debug1
  179288. #define png_debug1(l, m, p1)
  179289. #endif
  179290. #ifndef png_debug2
  179291. #define png_debug2(l, m, p1, p2)
  179292. #endif
  179293. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  179294. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  179295. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  179296. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  179297. #ifdef PNG_MNG_FEATURES_SUPPORTED
  179298. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  179299. png_ptr, png_uint_32 mng_features_permitted));
  179300. #endif
  179301. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  179302. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  179303. #define PNG_HANDLE_CHUNK_NEVER 1
  179304. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  179305. #define PNG_HANDLE_CHUNK_ALWAYS 3
  179306. /* Added to version 1.2.0 */
  179307. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  179308. #if defined(PNG_MMX_CODE_SUPPORTED)
  179309. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  179310. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  179311. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  179312. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  179313. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  179314. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  179315. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  179316. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  179317. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  179318. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  179319. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  179320. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  179321. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  179322. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  179323. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  179324. #define PNG_MMX_WRITE_FLAGS ( 0 )
  179325. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  179326. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  179327. | PNG_MMX_READ_FLAGS \
  179328. | PNG_MMX_WRITE_FLAGS )
  179329. #define PNG_SELECT_READ 1
  179330. #define PNG_SELECT_WRITE 2
  179331. #endif /* PNG_MMX_CODE_SUPPORTED */
  179332. #if !defined(PNG_1_0_X)
  179333. /* pngget.c */
  179334. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  179335. PNGARG((int flag_select, int *compilerID));
  179336. /* pngget.c */
  179337. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  179338. PNGARG((int flag_select));
  179339. /* pngget.c */
  179340. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  179341. PNGARG((png_structp png_ptr));
  179342. /* pngget.c */
  179343. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  179344. PNGARG((png_structp png_ptr));
  179345. /* pngget.c */
  179346. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  179347. PNGARG((png_structp png_ptr));
  179348. /* pngset.c */
  179349. extern PNG_EXPORT(void,png_set_asm_flags)
  179350. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  179351. /* pngset.c */
  179352. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  179353. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  179354. png_uint_32 mmx_rowbytes_threshold));
  179355. #endif /* PNG_1_0_X */
  179356. #if !defined(PNG_1_0_X)
  179357. /* png.c, pnggccrd.c, or pngvcrd.c */
  179358. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  179359. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  179360. /* Strip the prepended error numbers ("#nnn ") from error and warning
  179361. * messages before passing them to the error or warning handler. */
  179362. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  179363. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  179364. png_ptr, png_uint_32 strip_mode));
  179365. #endif
  179366. #endif /* PNG_1_0_X */
  179367. /* Added at libpng-1.2.6 */
  179368. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179369. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  179370. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  179371. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  179372. png_ptr));
  179373. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  179374. png_ptr));
  179375. #endif
  179376. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  179377. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  179378. /* With these routines we avoid an integer divide, which will be slower on
  179379. * most machines. However, it does take more operations than the corresponding
  179380. * divide method, so it may be slower on a few RISC systems. There are two
  179381. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  179382. *
  179383. * Note that the rounding factors are NOT supposed to be the same! 128 and
  179384. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  179385. * standard method.
  179386. *
  179387. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  179388. */
  179389. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  179390. # define png_composite(composite, fg, alpha, bg) \
  179391. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  179392. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  179393. (png_uint_16)(alpha)) + (png_uint_16)128); \
  179394. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  179395. # define png_composite_16(composite, fg, alpha, bg) \
  179396. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  179397. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  179398. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  179399. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  179400. #else /* standard method using integer division */
  179401. # define png_composite(composite, fg, alpha, bg) \
  179402. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  179403. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  179404. (png_uint_16)127) / 255)
  179405. # define png_composite_16(composite, fg, alpha, bg) \
  179406. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  179407. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  179408. (png_uint_32)32767) / (png_uint_32)65535L)
  179409. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  179410. /* Inline macros to do direct reads of bytes from the input buffer. These
  179411. * require that you are using an architecture that uses PNG byte ordering
  179412. * (MSB first) and supports unaligned data storage. I think that PowerPC
  179413. * in big-endian mode and 680x0 are the only ones that will support this.
  179414. * The x86 line of processors definitely do not. The png_get_int_32()
  179415. * routine also assumes we are using two's complement format for negative
  179416. * values, which is almost certainly true.
  179417. */
  179418. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  179419. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  179420. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  179421. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  179422. #else
  179423. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  179424. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  179425. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  179426. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  179427. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  179428. PNGARG((png_structp png_ptr, png_bytep buf));
  179429. /* No png_get_int_16 -- may be added if there's a real need for it. */
  179430. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  179431. */
  179432. extern PNG_EXPORT(void,png_save_uint_32)
  179433. PNGARG((png_bytep buf, png_uint_32 i));
  179434. extern PNG_EXPORT(void,png_save_int_32)
  179435. PNGARG((png_bytep buf, png_int_32 i));
  179436. /* Place a 16-bit number into a buffer in PNG byte order.
  179437. * The parameter is declared unsigned int, not png_uint_16,
  179438. * just to avoid potential problems on pre-ANSI C compilers.
  179439. */
  179440. extern PNG_EXPORT(void,png_save_uint_16)
  179441. PNGARG((png_bytep buf, unsigned int i));
  179442. /* No png_save_int_16 -- may be added if there's a real need for it. */
  179443. /* ************************************************************************* */
  179444. /* These next functions are used internally in the code. They generally
  179445. * shouldn't be used unless you are writing code to add or replace some
  179446. * functionality in libpng. More information about most functions can
  179447. * be found in the files where the functions are located.
  179448. */
  179449. /* Various modes of operation, that are visible to applications because
  179450. * they are used for unknown chunk location.
  179451. */
  179452. #define PNG_HAVE_IHDR 0x01
  179453. #define PNG_HAVE_PLTE 0x02
  179454. #define PNG_HAVE_IDAT 0x04
  179455. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  179456. #define PNG_HAVE_IEND 0x10
  179457. #if defined(PNG_INTERNAL)
  179458. /* More modes of operation. Note that after an init, mode is set to
  179459. * zero automatically when the structure is created.
  179460. */
  179461. #define PNG_HAVE_gAMA 0x20
  179462. #define PNG_HAVE_cHRM 0x40
  179463. #define PNG_HAVE_sRGB 0x80
  179464. #define PNG_HAVE_CHUNK_HEADER 0x100
  179465. #define PNG_WROTE_tIME 0x200
  179466. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  179467. #define PNG_BACKGROUND_IS_GRAY 0x800
  179468. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  179469. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  179470. /* flags for the transformations the PNG library does on the image data */
  179471. #define PNG_BGR 0x0001
  179472. #define PNG_INTERLACE 0x0002
  179473. #define PNG_PACK 0x0004
  179474. #define PNG_SHIFT 0x0008
  179475. #define PNG_SWAP_BYTES 0x0010
  179476. #define PNG_INVERT_MONO 0x0020
  179477. #define PNG_DITHER 0x0040
  179478. #define PNG_BACKGROUND 0x0080
  179479. #define PNG_BACKGROUND_EXPAND 0x0100
  179480. /* 0x0200 unused */
  179481. #define PNG_16_TO_8 0x0400
  179482. #define PNG_RGBA 0x0800
  179483. #define PNG_EXPAND 0x1000
  179484. #define PNG_GAMMA 0x2000
  179485. #define PNG_GRAY_TO_RGB 0x4000
  179486. #define PNG_FILLER 0x8000L
  179487. #define PNG_PACKSWAP 0x10000L
  179488. #define PNG_SWAP_ALPHA 0x20000L
  179489. #define PNG_STRIP_ALPHA 0x40000L
  179490. #define PNG_INVERT_ALPHA 0x80000L
  179491. #define PNG_USER_TRANSFORM 0x100000L
  179492. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  179493. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  179494. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  179495. /* 0x800000L Unused */
  179496. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  179497. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  179498. /* 0x4000000L unused */
  179499. /* 0x8000000L unused */
  179500. /* 0x10000000L unused */
  179501. /* 0x20000000L unused */
  179502. /* 0x40000000L unused */
  179503. /* flags for png_create_struct */
  179504. #define PNG_STRUCT_PNG 0x0001
  179505. #define PNG_STRUCT_INFO 0x0002
  179506. /* Scaling factor for filter heuristic weighting calculations */
  179507. #define PNG_WEIGHT_SHIFT 8
  179508. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  179509. #define PNG_COST_SHIFT 3
  179510. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  179511. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  179512. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  179513. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  179514. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  179515. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  179516. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  179517. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  179518. #define PNG_FLAG_ROW_INIT 0x0040
  179519. #define PNG_FLAG_FILLER_AFTER 0x0080
  179520. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  179521. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  179522. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  179523. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  179524. #define PNG_FLAG_FREE_PLTE 0x1000
  179525. #define PNG_FLAG_FREE_TRNS 0x2000
  179526. #define PNG_FLAG_FREE_HIST 0x4000
  179527. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  179528. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  179529. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  179530. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  179531. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  179532. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  179533. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  179534. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  179535. /* 0x800000L unused */
  179536. /* 0x1000000L unused */
  179537. /* 0x2000000L unused */
  179538. /* 0x4000000L unused */
  179539. /* 0x8000000L unused */
  179540. /* 0x10000000L unused */
  179541. /* 0x20000000L unused */
  179542. /* 0x40000000L unused */
  179543. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  179544. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  179545. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  179546. PNG_FLAG_CRC_CRITICAL_IGNORE)
  179547. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  179548. PNG_FLAG_CRC_CRITICAL_MASK)
  179549. /* save typing and make code easier to understand */
  179550. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  179551. abs((int)((c1).green) - (int)((c2).green)) + \
  179552. abs((int)((c1).blue) - (int)((c2).blue)))
  179553. /* Added to libpng-1.2.6 JB */
  179554. #define PNG_ROWBYTES(pixel_bits, width) \
  179555. ((pixel_bits) >= 8 ? \
  179556. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  179557. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  179558. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  179559. ideal-delta..ideal+delta. Each argument is evaluated twice.
  179560. "ideal" and "delta" should be constants, normally simple
  179561. integers, "value" a variable. Added to libpng-1.2.6 JB */
  179562. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  179563. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  179564. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  179565. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  179566. /* place to hold the signature string for a PNG file. */
  179567. #ifdef PNG_USE_GLOBAL_ARRAYS
  179568. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  179569. #else
  179570. #endif
  179571. #endif /* PNG_NO_EXTERN */
  179572. /* Constant strings for known chunk types. If you need to add a chunk,
  179573. * define the name here, and add an invocation of the macro in png.c and
  179574. * wherever it's needed.
  179575. */
  179576. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  179577. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  179578. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  179579. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  179580. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  179581. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  179582. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  179583. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  179584. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  179585. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  179586. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  179587. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  179588. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  179589. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  179590. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  179591. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  179592. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  179593. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  179594. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  179595. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  179596. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  179597. #ifdef PNG_USE_GLOBAL_ARRAYS
  179598. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  179599. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  179600. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  179601. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  179602. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  179603. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  179604. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  179605. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  179606. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  179607. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  179608. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  179609. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  179610. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  179611. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  179612. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  179613. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  179614. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  179615. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  179616. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  179617. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  179618. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  179619. #endif /* PNG_USE_GLOBAL_ARRAYS */
  179620. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179621. /* Initialize png_ptr struct for reading, and allocate any other memory.
  179622. * (old interface - DEPRECATED - use png_create_read_struct instead).
  179623. */
  179624. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  179625. #undef png_read_init
  179626. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  179627. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179628. #endif
  179629. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  179630. png_const_charp user_png_ver, png_size_t png_struct_size));
  179631. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179632. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  179633. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179634. png_info_size));
  179635. #endif
  179636. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  179637. /* Initialize png_ptr struct for writing, and allocate any other memory.
  179638. * (old interface - DEPRECATED - use png_create_write_struct instead).
  179639. */
  179640. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  179641. #undef png_write_init
  179642. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  179643. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  179644. #endif
  179645. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  179646. png_const_charp user_png_ver, png_size_t png_struct_size));
  179647. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  179648. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  179649. png_info_size));
  179650. /* Allocate memory for an internal libpng struct */
  179651. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  179652. /* Free memory from internal libpng struct */
  179653. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  179654. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  179655. malloc_fn, png_voidp mem_ptr));
  179656. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  179657. png_free_ptr free_fn, png_voidp mem_ptr));
  179658. /* Free any memory that info_ptr points to and reset struct. */
  179659. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  179660. png_infop info_ptr));
  179661. #ifndef PNG_1_0_X
  179662. /* Function to allocate memory for zlib. */
  179663. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  179664. /* Function to free memory for zlib */
  179665. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  179666. #ifdef PNG_SIZE_T
  179667. /* Function to convert a sizeof an item to png_sizeof item */
  179668. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  179669. #endif
  179670. /* Next four functions are used internally as callbacks. PNGAPI is required
  179671. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  179672. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  179673. png_bytep data, png_size_t length));
  179674. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179675. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  179676. png_bytep buffer, png_size_t length));
  179677. #endif
  179678. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  179679. png_bytep data, png_size_t length));
  179680. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179681. #if !defined(PNG_NO_STDIO)
  179682. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  179683. #endif
  179684. #endif
  179685. #else /* PNG_1_0_X */
  179686. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  179687. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  179688. png_bytep buffer, png_size_t length));
  179689. #endif
  179690. #endif /* PNG_1_0_X */
  179691. /* Reset the CRC variable */
  179692. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  179693. /* Write the "data" buffer to whatever output you are using. */
  179694. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  179695. png_size_t length));
  179696. /* Read data from whatever input you are using into the "data" buffer */
  179697. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  179698. png_size_t length));
  179699. /* Read bytes into buf, and update png_ptr->crc */
  179700. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  179701. png_size_t length));
  179702. /* Decompress data in a chunk that uses compression */
  179703. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  179704. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  179705. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  179706. int comp_type, png_charp chunkdata, png_size_t chunklength,
  179707. png_size_t prefix_length, png_size_t *data_length));
  179708. #endif
  179709. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  179710. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  179711. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  179712. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  179713. /* Calculate the CRC over a section of data. Note that we are only
  179714. * passing a maximum of 64K on systems that have this as a memory limit,
  179715. * since this is the maximum buffer size we can specify.
  179716. */
  179717. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  179718. png_size_t length));
  179719. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  179720. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  179721. #endif
  179722. /* simple function to write the signature */
  179723. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  179724. /* write various chunks */
  179725. /* Write the IHDR chunk, and update the png_struct with the necessary
  179726. * information.
  179727. */
  179728. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  179729. png_uint_32 height,
  179730. int bit_depth, int color_type, int compression_method, int filter_method,
  179731. int interlace_method));
  179732. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  179733. png_uint_32 num_pal));
  179734. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  179735. png_size_t length));
  179736. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  179737. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  179738. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179739. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  179740. #endif
  179741. #ifdef PNG_FIXED_POINT_SUPPORTED
  179742. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  179743. file_gamma));
  179744. #endif
  179745. #endif
  179746. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  179747. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  179748. int color_type));
  179749. #endif
  179750. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  179751. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179752. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  179753. double white_x, double white_y,
  179754. double red_x, double red_y, double green_x, double green_y,
  179755. double blue_x, double blue_y));
  179756. #endif
  179757. #ifdef PNG_FIXED_POINT_SUPPORTED
  179758. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  179759. png_fixed_point int_white_x, png_fixed_point int_white_y,
  179760. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  179761. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  179762. png_fixed_point int_blue_y));
  179763. #endif
  179764. #endif
  179765. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  179766. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  179767. int intent));
  179768. #endif
  179769. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  179770. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  179771. png_charp name, int compression_type,
  179772. png_charp profile, int proflen));
  179773. /* Note to maintainer: profile should be png_bytep */
  179774. #endif
  179775. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  179776. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  179777. png_sPLT_tp palette));
  179778. #endif
  179779. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  179780. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  179781. png_color_16p values, int number, int color_type));
  179782. #endif
  179783. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  179784. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  179785. png_color_16p values, int color_type));
  179786. #endif
  179787. #if defined(PNG_WRITE_hIST_SUPPORTED)
  179788. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  179789. int num_hist));
  179790. #endif
  179791. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  179792. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  179793. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  179794. png_charp key, png_charpp new_key));
  179795. #endif
  179796. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  179797. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  179798. png_charp text, png_size_t text_len));
  179799. #endif
  179800. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  179801. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  179802. png_charp text, png_size_t text_len, int compression));
  179803. #endif
  179804. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  179805. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  179806. int compression, png_charp key, png_charp lang, png_charp lang_key,
  179807. png_charp text));
  179808. #endif
  179809. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  179810. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  179811. png_infop info_ptr, png_textp text_ptr, int num_text));
  179812. #endif
  179813. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  179814. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  179815. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  179816. #endif
  179817. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  179818. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  179819. png_int_32 X0, png_int_32 X1, int type, int nparams,
  179820. png_charp units, png_charpp params));
  179821. #endif
  179822. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  179823. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  179824. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  179825. int unit_type));
  179826. #endif
  179827. #if defined(PNG_WRITE_tIME_SUPPORTED)
  179828. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  179829. png_timep mod_time));
  179830. #endif
  179831. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  179832. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  179833. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  179834. int unit, double width, double height));
  179835. #else
  179836. #ifdef PNG_FIXED_POINT_SUPPORTED
  179837. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  179838. int unit, png_charp width, png_charp height));
  179839. #endif
  179840. #endif
  179841. #endif
  179842. /* Called when finished processing a row of data */
  179843. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  179844. /* Internal use only. Called before first row of data */
  179845. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  179846. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179847. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  179848. #endif
  179849. /* combine a row of data, dealing with alpha, etc. if requested */
  179850. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  179851. int mask));
  179852. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  179853. /* expand an interlaced row */
  179854. /* OLD pre-1.0.9 interface:
  179855. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  179856. png_bytep row, int pass, png_uint_32 transformations));
  179857. */
  179858. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  179859. #endif
  179860. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  179861. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  179862. /* grab pixels out of a row for an interlaced pass */
  179863. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  179864. png_bytep row, int pass));
  179865. #endif
  179866. /* unfilter a row */
  179867. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  179868. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  179869. /* Choose the best filter to use and filter the row data */
  179870. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  179871. png_row_infop row_info));
  179872. /* Write out the filtered row. */
  179873. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  179874. png_bytep filtered_row));
  179875. /* finish a row while reading, dealing with interlacing passes, etc. */
  179876. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  179877. /* initialize the row buffers, etc. */
  179878. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  179879. /* optional call to update the users info structure */
  179880. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  179881. png_infop info_ptr));
  179882. /* these are the functions that do the transformations */
  179883. #if defined(PNG_READ_FILLER_SUPPORTED)
  179884. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  179885. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  179886. #endif
  179887. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  179888. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  179889. png_bytep row));
  179890. #endif
  179891. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  179892. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  179893. png_bytep row));
  179894. #endif
  179895. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  179896. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  179897. png_bytep row));
  179898. #endif
  179899. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  179900. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  179901. png_bytep row));
  179902. #endif
  179903. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  179904. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  179905. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  179906. png_bytep row, png_uint_32 flags));
  179907. #endif
  179908. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  179909. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  179910. #endif
  179911. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  179912. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  179913. #endif
  179914. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179915. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  179916. row_info, png_bytep row));
  179917. #endif
  179918. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  179919. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  179920. png_bytep row));
  179921. #endif
  179922. #if defined(PNG_READ_PACK_SUPPORTED)
  179923. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  179924. #endif
  179925. #if defined(PNG_READ_SHIFT_SUPPORTED)
  179926. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  179927. png_color_8p sig_bits));
  179928. #endif
  179929. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  179930. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  179931. #endif
  179932. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  179933. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  179934. #endif
  179935. #if defined(PNG_READ_DITHER_SUPPORTED)
  179936. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  179937. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  179938. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  179939. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  179940. png_colorp palette, int num_palette));
  179941. # endif
  179942. #endif
  179943. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  179944. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  179945. #endif
  179946. #if defined(PNG_WRITE_PACK_SUPPORTED)
  179947. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  179948. png_bytep row, png_uint_32 bit_depth));
  179949. #endif
  179950. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  179951. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  179952. png_color_8p bit_depth));
  179953. #endif
  179954. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  179955. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179956. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179957. png_color_16p trans_values, png_color_16p background,
  179958. png_color_16p background_1,
  179959. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  179960. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  179961. png_uint_16pp gamma_16_to_1, int gamma_shift));
  179962. #else
  179963. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  179964. png_color_16p trans_values, png_color_16p background));
  179965. #endif
  179966. #endif
  179967. #if defined(PNG_READ_GAMMA_SUPPORTED)
  179968. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  179969. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  179970. int gamma_shift));
  179971. #endif
  179972. #if defined(PNG_READ_EXPAND_SUPPORTED)
  179973. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  179974. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  179975. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  179976. png_bytep row, png_color_16p trans_value));
  179977. #endif
  179978. /* The following decodes the appropriate chunks, and does error correction,
  179979. * then calls the appropriate callback for the chunk if it is valid.
  179980. */
  179981. /* decode the IHDR chunk */
  179982. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  179983. png_uint_32 length));
  179984. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  179985. png_uint_32 length));
  179986. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  179987. png_uint_32 length));
  179988. #if defined(PNG_READ_bKGD_SUPPORTED)
  179989. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  179990. png_uint_32 length));
  179991. #endif
  179992. #if defined(PNG_READ_cHRM_SUPPORTED)
  179993. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  179994. png_uint_32 length));
  179995. #endif
  179996. #if defined(PNG_READ_gAMA_SUPPORTED)
  179997. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  179998. png_uint_32 length));
  179999. #endif
  180000. #if defined(PNG_READ_hIST_SUPPORTED)
  180001. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  180002. png_uint_32 length));
  180003. #endif
  180004. #if defined(PNG_READ_iCCP_SUPPORTED)
  180005. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  180006. png_uint_32 length));
  180007. #endif /* PNG_READ_iCCP_SUPPORTED */
  180008. #if defined(PNG_READ_iTXt_SUPPORTED)
  180009. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180010. png_uint_32 length));
  180011. #endif
  180012. #if defined(PNG_READ_oFFs_SUPPORTED)
  180013. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180014. png_uint_32 length));
  180015. #endif
  180016. #if defined(PNG_READ_pCAL_SUPPORTED)
  180017. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180018. png_uint_32 length));
  180019. #endif
  180020. #if defined(PNG_READ_pHYs_SUPPORTED)
  180021. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  180022. png_uint_32 length));
  180023. #endif
  180024. #if defined(PNG_READ_sBIT_SUPPORTED)
  180025. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180026. png_uint_32 length));
  180027. #endif
  180028. #if defined(PNG_READ_sCAL_SUPPORTED)
  180029. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  180030. png_uint_32 length));
  180031. #endif
  180032. #if defined(PNG_READ_sPLT_SUPPORTED)
  180033. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  180034. png_uint_32 length));
  180035. #endif /* PNG_READ_sPLT_SUPPORTED */
  180036. #if defined(PNG_READ_sRGB_SUPPORTED)
  180037. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  180038. png_uint_32 length));
  180039. #endif
  180040. #if defined(PNG_READ_tEXt_SUPPORTED)
  180041. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180042. png_uint_32 length));
  180043. #endif
  180044. #if defined(PNG_READ_tIME_SUPPORTED)
  180045. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  180046. png_uint_32 length));
  180047. #endif
  180048. #if defined(PNG_READ_tRNS_SUPPORTED)
  180049. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  180050. png_uint_32 length));
  180051. #endif
  180052. #if defined(PNG_READ_zTXt_SUPPORTED)
  180053. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  180054. png_uint_32 length));
  180055. #endif
  180056. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  180057. png_infop info_ptr, png_uint_32 length));
  180058. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  180059. png_bytep chunk_name));
  180060. /* handle the transformations for reading and writing */
  180061. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  180062. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  180063. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  180064. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  180065. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  180066. png_infop info_ptr));
  180067. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  180068. png_infop info_ptr));
  180069. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  180070. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  180071. png_uint_32 length));
  180072. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  180073. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  180074. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  180075. png_bytep buffer, png_size_t buffer_length));
  180076. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  180077. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  180078. png_bytep buffer, png_size_t buffer_length));
  180079. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  180080. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  180081. png_infop info_ptr, png_uint_32 length));
  180082. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  180083. png_infop info_ptr));
  180084. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  180085. png_infop info_ptr));
  180086. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  180087. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  180088. png_infop info_ptr));
  180089. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  180090. png_infop info_ptr));
  180091. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  180092. #if defined(PNG_READ_tEXt_SUPPORTED)
  180093. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  180094. png_infop info_ptr, png_uint_32 length));
  180095. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  180096. png_infop info_ptr));
  180097. #endif
  180098. #if defined(PNG_READ_zTXt_SUPPORTED)
  180099. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  180100. png_infop info_ptr, png_uint_32 length));
  180101. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  180102. png_infop info_ptr));
  180103. #endif
  180104. #if defined(PNG_READ_iTXt_SUPPORTED)
  180105. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  180106. png_infop info_ptr, png_uint_32 length));
  180107. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  180108. png_infop info_ptr));
  180109. #endif
  180110. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  180111. #ifdef PNG_MNG_FEATURES_SUPPORTED
  180112. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  180113. png_bytep row));
  180114. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  180115. png_bytep row));
  180116. #endif
  180117. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180118. #if defined(PNG_MMX_CODE_SUPPORTED)
  180119. /* png.c */ /* PRIVATE */
  180120. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  180121. #endif
  180122. #endif
  180123. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  180124. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  180125. png_infop info_ptr));
  180126. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  180127. png_infop info_ptr));
  180128. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  180129. png_infop info_ptr));
  180130. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  180131. png_infop info_ptr));
  180132. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  180133. png_infop info_ptr));
  180134. #if defined(PNG_pHYs_SUPPORTED)
  180135. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  180136. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  180137. #endif /* PNG_pHYs_SUPPORTED */
  180138. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  180139. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  180140. #endif /* PNG_INTERNAL */
  180141. #ifdef __cplusplus
  180142. }
  180143. #endif
  180144. #endif /* PNG_VERSION_INFO_ONLY */
  180145. /* do not put anything past this line */
  180146. #endif /* PNG_H */
  180147. /********* End of inlined file: png.h *********/
  180148. #define PNG_NO_EXTERN
  180149. /********* Start of inlined file: png.c *********/
  180150. /* png.c - location for general purpose libpng functions
  180151. *
  180152. * Last changed in libpng 1.2.21 [October 4, 2007]
  180153. * For conditions of distribution and use, see copyright notice in png.h
  180154. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180155. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180156. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180157. */
  180158. #define PNG_INTERNAL
  180159. #define PNG_NO_EXTERN
  180160. /* Generate a compiler error if there is an old png.h in the search path. */
  180161. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  180162. /* Version information for C files. This had better match the version
  180163. * string defined in png.h. */
  180164. #ifdef PNG_USE_GLOBAL_ARRAYS
  180165. /* png_libpng_ver was changed to a function in version 1.0.5c */
  180166. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  180167. #ifdef PNG_READ_SUPPORTED
  180168. /* png_sig was changed to a function in version 1.0.5c */
  180169. /* Place to hold the signature string for a PNG file. */
  180170. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180171. #endif /* PNG_READ_SUPPORTED */
  180172. /* Invoke global declarations for constant strings for known chunk types */
  180173. PNG_IHDR;
  180174. PNG_IDAT;
  180175. PNG_IEND;
  180176. PNG_PLTE;
  180177. PNG_bKGD;
  180178. PNG_cHRM;
  180179. PNG_gAMA;
  180180. PNG_hIST;
  180181. PNG_iCCP;
  180182. PNG_iTXt;
  180183. PNG_oFFs;
  180184. PNG_pCAL;
  180185. PNG_sCAL;
  180186. PNG_pHYs;
  180187. PNG_sBIT;
  180188. PNG_sPLT;
  180189. PNG_sRGB;
  180190. PNG_tEXt;
  180191. PNG_tIME;
  180192. PNG_tRNS;
  180193. PNG_zTXt;
  180194. #ifdef PNG_READ_SUPPORTED
  180195. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  180196. /* start of interlace block */
  180197. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  180198. /* offset to next interlace block */
  180199. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  180200. /* start of interlace block in the y direction */
  180201. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  180202. /* offset to next interlace block in the y direction */
  180203. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  180204. /* Height of interlace block. This is not currently used - if you need
  180205. * it, uncomment it here and in png.h
  180206. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  180207. */
  180208. /* Mask to determine which pixels are valid in a pass */
  180209. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180210. /* Mask to determine which pixels to overwrite while displaying */
  180211. PNG_CONST int FARDATA png_pass_dsp_mask[]
  180212. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  180213. #endif /* PNG_READ_SUPPORTED */
  180214. #endif /* PNG_USE_GLOBAL_ARRAYS */
  180215. /* Tells libpng that we have already handled the first "num_bytes" bytes
  180216. * of the PNG file signature. If the PNG data is embedded into another
  180217. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  180218. * or write any of the magic bytes before it starts on the IHDR.
  180219. */
  180220. #ifdef PNG_READ_SUPPORTED
  180221. void PNGAPI
  180222. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  180223. {
  180224. if(png_ptr == NULL) return;
  180225. png_debug(1, "in png_set_sig_bytes\n");
  180226. if (num_bytes > 8)
  180227. png_error(png_ptr, "Too many bytes for PNG signature.");
  180228. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  180229. }
  180230. /* Checks whether the supplied bytes match the PNG signature. We allow
  180231. * checking less than the full 8-byte signature so that those apps that
  180232. * already read the first few bytes of a file to determine the file type
  180233. * can simply check the remaining bytes for extra assurance. Returns
  180234. * an integer less than, equal to, or greater than zero if sig is found,
  180235. * respectively, to be less than, to match, or be greater than the correct
  180236. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  180237. */
  180238. int PNGAPI
  180239. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  180240. {
  180241. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  180242. if (num_to_check > 8)
  180243. num_to_check = 8;
  180244. else if (num_to_check < 1)
  180245. return (-1);
  180246. if (start > 7)
  180247. return (-1);
  180248. if (start + num_to_check > 8)
  180249. num_to_check = 8 - start;
  180250. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  180251. }
  180252. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180253. /* (Obsolete) function to check signature bytes. It does not allow one
  180254. * to check a partial signature. This function might be removed in the
  180255. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  180256. */
  180257. int PNGAPI
  180258. png_check_sig(png_bytep sig, int num)
  180259. {
  180260. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  180261. }
  180262. #endif
  180263. #endif /* PNG_READ_SUPPORTED */
  180264. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180265. /* Function to allocate memory for zlib and clear it to 0. */
  180266. #ifdef PNG_1_0_X
  180267. voidpf PNGAPI
  180268. #else
  180269. voidpf /* private */
  180270. #endif
  180271. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  180272. {
  180273. png_voidp ptr;
  180274. png_structp p=(png_structp)png_ptr;
  180275. png_uint_32 save_flags=p->flags;
  180276. png_uint_32 num_bytes;
  180277. if(png_ptr == NULL) return (NULL);
  180278. if (items > PNG_UINT_32_MAX/size)
  180279. {
  180280. png_warning (p, "Potential overflow in png_zalloc()");
  180281. return (NULL);
  180282. }
  180283. num_bytes = (png_uint_32)items * size;
  180284. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180285. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  180286. p->flags=save_flags;
  180287. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  180288. if (ptr == NULL)
  180289. return ((voidpf)ptr);
  180290. if (num_bytes > (png_uint_32)0x8000L)
  180291. {
  180292. png_memset(ptr, 0, (png_size_t)0x8000L);
  180293. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  180294. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  180295. }
  180296. else
  180297. {
  180298. png_memset(ptr, 0, (png_size_t)num_bytes);
  180299. }
  180300. #endif
  180301. return ((voidpf)ptr);
  180302. }
  180303. /* function to free memory for zlib */
  180304. #ifdef PNG_1_0_X
  180305. void PNGAPI
  180306. #else
  180307. void /* private */
  180308. #endif
  180309. png_zfree(voidpf png_ptr, voidpf ptr)
  180310. {
  180311. png_free((png_structp)png_ptr, (png_voidp)ptr);
  180312. }
  180313. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  180314. * in case CRC is > 32 bits to leave the top bits 0.
  180315. */
  180316. void /* PRIVATE */
  180317. png_reset_crc(png_structp png_ptr)
  180318. {
  180319. png_ptr->crc = crc32(0, Z_NULL, 0);
  180320. }
  180321. /* Calculate the CRC over a section of data. We can only pass as
  180322. * much data to this routine as the largest single buffer size. We
  180323. * also check that this data will actually be used before going to the
  180324. * trouble of calculating it.
  180325. */
  180326. void /* PRIVATE */
  180327. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  180328. {
  180329. int need_crc = 1;
  180330. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  180331. {
  180332. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  180333. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  180334. need_crc = 0;
  180335. }
  180336. else /* critical */
  180337. {
  180338. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  180339. need_crc = 0;
  180340. }
  180341. if (need_crc)
  180342. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  180343. }
  180344. /* Allocate the memory for an info_struct for the application. We don't
  180345. * really need the png_ptr, but it could potentially be useful in the
  180346. * future. This should be used in favour of malloc(png_sizeof(png_info))
  180347. * and png_info_init() so that applications that want to use a shared
  180348. * libpng don't have to be recompiled if png_info changes size.
  180349. */
  180350. png_infop PNGAPI
  180351. png_create_info_struct(png_structp png_ptr)
  180352. {
  180353. png_infop info_ptr;
  180354. png_debug(1, "in png_create_info_struct\n");
  180355. if(png_ptr == NULL) return (NULL);
  180356. #ifdef PNG_USER_MEM_SUPPORTED
  180357. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  180358. png_ptr->malloc_fn, png_ptr->mem_ptr);
  180359. #else
  180360. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180361. #endif
  180362. if (info_ptr != NULL)
  180363. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180364. return (info_ptr);
  180365. }
  180366. /* This function frees the memory associated with a single info struct.
  180367. * Normally, one would use either png_destroy_read_struct() or
  180368. * png_destroy_write_struct() to free an info struct, but this may be
  180369. * useful for some applications.
  180370. */
  180371. void PNGAPI
  180372. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  180373. {
  180374. png_infop info_ptr = NULL;
  180375. if(png_ptr == NULL) return;
  180376. png_debug(1, "in png_destroy_info_struct\n");
  180377. if (info_ptr_ptr != NULL)
  180378. info_ptr = *info_ptr_ptr;
  180379. if (info_ptr != NULL)
  180380. {
  180381. png_info_destroy(png_ptr, info_ptr);
  180382. #ifdef PNG_USER_MEM_SUPPORTED
  180383. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  180384. png_ptr->mem_ptr);
  180385. #else
  180386. png_destroy_struct((png_voidp)info_ptr);
  180387. #endif
  180388. *info_ptr_ptr = NULL;
  180389. }
  180390. }
  180391. /* Initialize the info structure. This is now an internal function (0.89)
  180392. * and applications using it are urged to use png_create_info_struct()
  180393. * instead.
  180394. */
  180395. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180396. #undef png_info_init
  180397. void PNGAPI
  180398. png_info_init(png_infop info_ptr)
  180399. {
  180400. /* We only come here via pre-1.0.12-compiled applications */
  180401. png_info_init_3(&info_ptr, 0);
  180402. }
  180403. #endif
  180404. void PNGAPI
  180405. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  180406. {
  180407. png_infop info_ptr = *ptr_ptr;
  180408. if(info_ptr == NULL) return;
  180409. png_debug(1, "in png_info_init_3\n");
  180410. if(png_sizeof(png_info) > png_info_struct_size)
  180411. {
  180412. png_destroy_struct(info_ptr);
  180413. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  180414. *ptr_ptr = info_ptr;
  180415. }
  180416. /* set everything to 0 */
  180417. png_memset(info_ptr, 0, png_sizeof (png_info));
  180418. }
  180419. #ifdef PNG_FREE_ME_SUPPORTED
  180420. void PNGAPI
  180421. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  180422. int freer, png_uint_32 mask)
  180423. {
  180424. png_debug(1, "in png_data_freer\n");
  180425. if (png_ptr == NULL || info_ptr == NULL)
  180426. return;
  180427. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  180428. info_ptr->free_me |= mask;
  180429. else if(freer == PNG_USER_WILL_FREE_DATA)
  180430. info_ptr->free_me &= ~mask;
  180431. else
  180432. png_warning(png_ptr,
  180433. "Unknown freer parameter in png_data_freer.");
  180434. }
  180435. #endif
  180436. void PNGAPI
  180437. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  180438. int num)
  180439. {
  180440. png_debug(1, "in png_free_data\n");
  180441. if (png_ptr == NULL || info_ptr == NULL)
  180442. return;
  180443. #if defined(PNG_TEXT_SUPPORTED)
  180444. /* free text item num or (if num == -1) all text items */
  180445. #ifdef PNG_FREE_ME_SUPPORTED
  180446. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  180447. #else
  180448. if (mask & PNG_FREE_TEXT)
  180449. #endif
  180450. {
  180451. if (num != -1)
  180452. {
  180453. if (info_ptr->text && info_ptr->text[num].key)
  180454. {
  180455. png_free(png_ptr, info_ptr->text[num].key);
  180456. info_ptr->text[num].key = NULL;
  180457. }
  180458. }
  180459. else
  180460. {
  180461. int i;
  180462. for (i = 0; i < info_ptr->num_text; i++)
  180463. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  180464. png_free(png_ptr, info_ptr->text);
  180465. info_ptr->text = NULL;
  180466. info_ptr->num_text=0;
  180467. }
  180468. }
  180469. #endif
  180470. #if defined(PNG_tRNS_SUPPORTED)
  180471. /* free any tRNS entry */
  180472. #ifdef PNG_FREE_ME_SUPPORTED
  180473. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  180474. #else
  180475. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  180476. #endif
  180477. {
  180478. png_free(png_ptr, info_ptr->trans);
  180479. info_ptr->valid &= ~PNG_INFO_tRNS;
  180480. #ifndef PNG_FREE_ME_SUPPORTED
  180481. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  180482. #endif
  180483. info_ptr->trans = NULL;
  180484. }
  180485. #endif
  180486. #if defined(PNG_sCAL_SUPPORTED)
  180487. /* free any sCAL entry */
  180488. #ifdef PNG_FREE_ME_SUPPORTED
  180489. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  180490. #else
  180491. if (mask & PNG_FREE_SCAL)
  180492. #endif
  180493. {
  180494. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  180495. png_free(png_ptr, info_ptr->scal_s_width);
  180496. png_free(png_ptr, info_ptr->scal_s_height);
  180497. info_ptr->scal_s_width = NULL;
  180498. info_ptr->scal_s_height = NULL;
  180499. #endif
  180500. info_ptr->valid &= ~PNG_INFO_sCAL;
  180501. }
  180502. #endif
  180503. #if defined(PNG_pCAL_SUPPORTED)
  180504. /* free any pCAL entry */
  180505. #ifdef PNG_FREE_ME_SUPPORTED
  180506. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  180507. #else
  180508. if (mask & PNG_FREE_PCAL)
  180509. #endif
  180510. {
  180511. png_free(png_ptr, info_ptr->pcal_purpose);
  180512. png_free(png_ptr, info_ptr->pcal_units);
  180513. info_ptr->pcal_purpose = NULL;
  180514. info_ptr->pcal_units = NULL;
  180515. if (info_ptr->pcal_params != NULL)
  180516. {
  180517. int i;
  180518. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  180519. {
  180520. png_free(png_ptr, info_ptr->pcal_params[i]);
  180521. info_ptr->pcal_params[i]=NULL;
  180522. }
  180523. png_free(png_ptr, info_ptr->pcal_params);
  180524. info_ptr->pcal_params = NULL;
  180525. }
  180526. info_ptr->valid &= ~PNG_INFO_pCAL;
  180527. }
  180528. #endif
  180529. #if defined(PNG_iCCP_SUPPORTED)
  180530. /* free any iCCP entry */
  180531. #ifdef PNG_FREE_ME_SUPPORTED
  180532. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  180533. #else
  180534. if (mask & PNG_FREE_ICCP)
  180535. #endif
  180536. {
  180537. png_free(png_ptr, info_ptr->iccp_name);
  180538. png_free(png_ptr, info_ptr->iccp_profile);
  180539. info_ptr->iccp_name = NULL;
  180540. info_ptr->iccp_profile = NULL;
  180541. info_ptr->valid &= ~PNG_INFO_iCCP;
  180542. }
  180543. #endif
  180544. #if defined(PNG_sPLT_SUPPORTED)
  180545. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  180546. #ifdef PNG_FREE_ME_SUPPORTED
  180547. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  180548. #else
  180549. if (mask & PNG_FREE_SPLT)
  180550. #endif
  180551. {
  180552. if (num != -1)
  180553. {
  180554. if(info_ptr->splt_palettes)
  180555. {
  180556. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  180557. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  180558. info_ptr->splt_palettes[num].name = NULL;
  180559. info_ptr->splt_palettes[num].entries = NULL;
  180560. }
  180561. }
  180562. else
  180563. {
  180564. if(info_ptr->splt_palettes_num)
  180565. {
  180566. int i;
  180567. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  180568. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  180569. png_free(png_ptr, info_ptr->splt_palettes);
  180570. info_ptr->splt_palettes = NULL;
  180571. info_ptr->splt_palettes_num = 0;
  180572. }
  180573. info_ptr->valid &= ~PNG_INFO_sPLT;
  180574. }
  180575. }
  180576. #endif
  180577. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180578. if(png_ptr->unknown_chunk.data)
  180579. {
  180580. png_free(png_ptr, png_ptr->unknown_chunk.data);
  180581. png_ptr->unknown_chunk.data = NULL;
  180582. }
  180583. #ifdef PNG_FREE_ME_SUPPORTED
  180584. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  180585. #else
  180586. if (mask & PNG_FREE_UNKN)
  180587. #endif
  180588. {
  180589. if (num != -1)
  180590. {
  180591. if(info_ptr->unknown_chunks)
  180592. {
  180593. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  180594. info_ptr->unknown_chunks[num].data = NULL;
  180595. }
  180596. }
  180597. else
  180598. {
  180599. int i;
  180600. if(info_ptr->unknown_chunks_num)
  180601. {
  180602. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  180603. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  180604. png_free(png_ptr, info_ptr->unknown_chunks);
  180605. info_ptr->unknown_chunks = NULL;
  180606. info_ptr->unknown_chunks_num = 0;
  180607. }
  180608. }
  180609. }
  180610. #endif
  180611. #if defined(PNG_hIST_SUPPORTED)
  180612. /* free any hIST entry */
  180613. #ifdef PNG_FREE_ME_SUPPORTED
  180614. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  180615. #else
  180616. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  180617. #endif
  180618. {
  180619. png_free(png_ptr, info_ptr->hist);
  180620. info_ptr->hist = NULL;
  180621. info_ptr->valid &= ~PNG_INFO_hIST;
  180622. #ifndef PNG_FREE_ME_SUPPORTED
  180623. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  180624. #endif
  180625. }
  180626. #endif
  180627. /* free any PLTE entry that was internally allocated */
  180628. #ifdef PNG_FREE_ME_SUPPORTED
  180629. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  180630. #else
  180631. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  180632. #endif
  180633. {
  180634. png_zfree(png_ptr, info_ptr->palette);
  180635. info_ptr->palette = NULL;
  180636. info_ptr->valid &= ~PNG_INFO_PLTE;
  180637. #ifndef PNG_FREE_ME_SUPPORTED
  180638. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  180639. #endif
  180640. info_ptr->num_palette = 0;
  180641. }
  180642. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  180643. /* free any image bits attached to the info structure */
  180644. #ifdef PNG_FREE_ME_SUPPORTED
  180645. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  180646. #else
  180647. if (mask & PNG_FREE_ROWS)
  180648. #endif
  180649. {
  180650. if(info_ptr->row_pointers)
  180651. {
  180652. int row;
  180653. for (row = 0; row < (int)info_ptr->height; row++)
  180654. {
  180655. png_free(png_ptr, info_ptr->row_pointers[row]);
  180656. info_ptr->row_pointers[row]=NULL;
  180657. }
  180658. png_free(png_ptr, info_ptr->row_pointers);
  180659. info_ptr->row_pointers=NULL;
  180660. }
  180661. info_ptr->valid &= ~PNG_INFO_IDAT;
  180662. }
  180663. #endif
  180664. #ifdef PNG_FREE_ME_SUPPORTED
  180665. if(num == -1)
  180666. info_ptr->free_me &= ~mask;
  180667. else
  180668. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  180669. #endif
  180670. }
  180671. /* This is an internal routine to free any memory that the info struct is
  180672. * pointing to before re-using it or freeing the struct itself. Recall
  180673. * that png_free() checks for NULL pointers for us.
  180674. */
  180675. void /* PRIVATE */
  180676. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  180677. {
  180678. png_debug(1, "in png_info_destroy\n");
  180679. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  180680. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  180681. if (png_ptr->num_chunk_list)
  180682. {
  180683. png_free(png_ptr, png_ptr->chunk_list);
  180684. png_ptr->chunk_list=NULL;
  180685. png_ptr->num_chunk_list=0;
  180686. }
  180687. #endif
  180688. png_info_init_3(&info_ptr, png_sizeof(png_info));
  180689. }
  180690. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180691. /* This function returns a pointer to the io_ptr associated with the user
  180692. * functions. The application should free any memory associated with this
  180693. * pointer before png_write_destroy() or png_read_destroy() are called.
  180694. */
  180695. png_voidp PNGAPI
  180696. png_get_io_ptr(png_structp png_ptr)
  180697. {
  180698. if(png_ptr == NULL) return (NULL);
  180699. return (png_ptr->io_ptr);
  180700. }
  180701. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180702. #if !defined(PNG_NO_STDIO)
  180703. /* Initialize the default input/output functions for the PNG file. If you
  180704. * use your own read or write routines, you can call either png_set_read_fn()
  180705. * or png_set_write_fn() instead of png_init_io(). If you have defined
  180706. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  180707. * necessarily available.
  180708. */
  180709. void PNGAPI
  180710. png_init_io(png_structp png_ptr, png_FILE_p fp)
  180711. {
  180712. png_debug(1, "in png_init_io\n");
  180713. if(png_ptr == NULL) return;
  180714. png_ptr->io_ptr = (png_voidp)fp;
  180715. }
  180716. #endif
  180717. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  180718. /* Convert the supplied time into an RFC 1123 string suitable for use in
  180719. * a "Creation Time" or other text-based time string.
  180720. */
  180721. png_charp PNGAPI
  180722. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  180723. {
  180724. static PNG_CONST char short_months[12][4] =
  180725. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  180726. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  180727. if(png_ptr == NULL) return (NULL);
  180728. if (png_ptr->time_buffer == NULL)
  180729. {
  180730. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  180731. png_sizeof(char)));
  180732. }
  180733. #if defined(_WIN32_WCE)
  180734. {
  180735. wchar_t time_buf[29];
  180736. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  180737. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180738. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180739. ptime->second % 61);
  180740. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  180741. NULL, NULL);
  180742. }
  180743. #else
  180744. #ifdef USE_FAR_KEYWORD
  180745. {
  180746. char near_time_buf[29];
  180747. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  180748. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180749. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180750. ptime->second % 61);
  180751. png_memcpy(png_ptr->time_buffer, near_time_buf,
  180752. 29*png_sizeof(char));
  180753. }
  180754. #else
  180755. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  180756. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  180757. ptime->year, ptime->hour % 24, ptime->minute % 60,
  180758. ptime->second % 61);
  180759. #endif
  180760. #endif /* _WIN32_WCE */
  180761. return ((png_charp)png_ptr->time_buffer);
  180762. }
  180763. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  180764. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180765. png_charp PNGAPI
  180766. png_get_copyright(png_structp png_ptr)
  180767. {
  180768. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180769. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  180770. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  180771. Copyright (c) 1996-1997 Andreas Dilger\n\
  180772. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  180773. }
  180774. /* The following return the library version as a short string in the
  180775. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  180776. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  180777. * is defined in png.h.
  180778. * Note: now there is no difference between png_get_libpng_ver() and
  180779. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  180780. * it is guaranteed that png.c uses the correct version of png.h.
  180781. */
  180782. png_charp PNGAPI
  180783. png_get_libpng_ver(png_structp png_ptr)
  180784. {
  180785. /* Version of *.c files used when building libpng */
  180786. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180787. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180788. }
  180789. png_charp PNGAPI
  180790. png_get_header_ver(png_structp png_ptr)
  180791. {
  180792. /* Version of *.h files used when building libpng */
  180793. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180794. return ((png_charp) PNG_LIBPNG_VER_STRING);
  180795. }
  180796. png_charp PNGAPI
  180797. png_get_header_version(png_structp png_ptr)
  180798. {
  180799. /* Returns longer string containing both version and date */
  180800. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  180801. return ((png_charp) PNG_HEADER_VERSION_STRING
  180802. #ifndef PNG_READ_SUPPORTED
  180803. " (NO READ SUPPORT)"
  180804. #endif
  180805. "\n");
  180806. }
  180807. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180808. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180809. int PNGAPI
  180810. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  180811. {
  180812. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  180813. int i;
  180814. png_bytep p;
  180815. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  180816. return 0;
  180817. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  180818. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  180819. if (!png_memcmp(chunk_name, p, 4))
  180820. return ((int)*(p+4));
  180821. return 0;
  180822. }
  180823. #endif
  180824. /* This function, added to libpng-1.0.6g, is untested. */
  180825. int PNGAPI
  180826. png_reset_zstream(png_structp png_ptr)
  180827. {
  180828. if (png_ptr == NULL) return Z_STREAM_ERROR;
  180829. return (inflateReset(&png_ptr->zstream));
  180830. }
  180831. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180832. /* This function was added to libpng-1.0.7 */
  180833. png_uint_32 PNGAPI
  180834. png_access_version_number(void)
  180835. {
  180836. /* Version of *.c files used when building libpng */
  180837. return((png_uint_32) PNG_LIBPNG_VER);
  180838. }
  180839. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  180840. #if !defined(PNG_1_0_X)
  180841. /* this function was added to libpng 1.2.0 */
  180842. int PNGAPI
  180843. png_mmx_support(void)
  180844. {
  180845. /* obsolete, to be removed from libpng-1.4.0 */
  180846. return -1;
  180847. }
  180848. #endif /* PNG_1_0_X */
  180849. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  180850. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180851. #ifdef PNG_SIZE_T
  180852. /* Added at libpng version 1.2.6 */
  180853. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  180854. png_size_t PNGAPI
  180855. png_convert_size(size_t size)
  180856. {
  180857. if (size > (png_size_t)-1)
  180858. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  180859. return ((png_size_t)size);
  180860. }
  180861. #endif /* PNG_SIZE_T */
  180862. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  180863. /********* End of inlined file: png.c *********/
  180864. /********* Start of inlined file: pngerror.c *********/
  180865. /* pngerror.c - stub functions for i/o and memory allocation
  180866. *
  180867. * Last changed in libpng 1.2.20 October 4, 2007
  180868. * For conditions of distribution and use, see copyright notice in png.h
  180869. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180870. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180871. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180872. *
  180873. * This file provides a location for all error handling. Users who
  180874. * need special error handling are expected to write replacement functions
  180875. * and use png_set_error_fn() to use those functions. See the instructions
  180876. * at each function.
  180877. */
  180878. #define PNG_INTERNAL
  180879. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  180880. static void /* PRIVATE */
  180881. png_default_error PNGARG((png_structp png_ptr,
  180882. png_const_charp error_message));
  180883. #ifndef PNG_NO_WARNINGS
  180884. static void /* PRIVATE */
  180885. png_default_warning PNGARG((png_structp png_ptr,
  180886. png_const_charp warning_message));
  180887. #endif /* PNG_NO_WARNINGS */
  180888. /* This function is called whenever there is a fatal error. This function
  180889. * should not be changed. If there is a need to handle errors differently,
  180890. * you should supply a replacement error function and use png_set_error_fn()
  180891. * to replace the error function at run-time.
  180892. */
  180893. #ifndef PNG_NO_ERROR_TEXT
  180894. void PNGAPI
  180895. png_error(png_structp png_ptr, png_const_charp error_message)
  180896. {
  180897. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180898. char msg[16];
  180899. if (png_ptr != NULL)
  180900. {
  180901. if (png_ptr->flags&
  180902. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180903. {
  180904. if (*error_message == '#')
  180905. {
  180906. int offset;
  180907. for (offset=1; offset<15; offset++)
  180908. if (*(error_message+offset) == ' ')
  180909. break;
  180910. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180911. {
  180912. int i;
  180913. for (i=0; i<offset-1; i++)
  180914. msg[i]=error_message[i+1];
  180915. msg[i]='\0';
  180916. error_message=msg;
  180917. }
  180918. else
  180919. error_message+=offset;
  180920. }
  180921. else
  180922. {
  180923. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  180924. {
  180925. msg[0]='0';
  180926. msg[1]='\0';
  180927. error_message=msg;
  180928. }
  180929. }
  180930. }
  180931. }
  180932. #endif
  180933. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180934. (*(png_ptr->error_fn))(png_ptr, error_message);
  180935. /* If the custom handler doesn't exist, or if it returns,
  180936. use the default handler, which will not return. */
  180937. png_default_error(png_ptr, error_message);
  180938. }
  180939. #else
  180940. void PNGAPI
  180941. png_err(png_structp png_ptr)
  180942. {
  180943. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  180944. (*(png_ptr->error_fn))(png_ptr, '\0');
  180945. /* If the custom handler doesn't exist, or if it returns,
  180946. use the default handler, which will not return. */
  180947. png_default_error(png_ptr, '\0');
  180948. }
  180949. #endif /* PNG_NO_ERROR_TEXT */
  180950. #ifndef PNG_NO_WARNINGS
  180951. /* This function is called whenever there is a non-fatal error. This function
  180952. * should not be changed. If there is a need to handle warnings differently,
  180953. * you should supply a replacement warning function and use
  180954. * png_set_error_fn() to replace the warning function at run-time.
  180955. */
  180956. void PNGAPI
  180957. png_warning(png_structp png_ptr, png_const_charp warning_message)
  180958. {
  180959. int offset = 0;
  180960. if (png_ptr != NULL)
  180961. {
  180962. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180963. if (png_ptr->flags&
  180964. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  180965. #endif
  180966. {
  180967. if (*warning_message == '#')
  180968. {
  180969. for (offset=1; offset<15; offset++)
  180970. if (*(warning_message+offset) == ' ')
  180971. break;
  180972. }
  180973. }
  180974. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  180975. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  180976. }
  180977. else
  180978. png_default_warning(png_ptr, warning_message+offset);
  180979. }
  180980. #endif /* PNG_NO_WARNINGS */
  180981. /* These utilities are used internally to build an error message that relates
  180982. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  180983. * this is used to prefix the message. The message is limited in length
  180984. * to 63 bytes, the name characters are output as hex digits wrapped in []
  180985. * if the character is invalid.
  180986. */
  180987. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  180988. /*static PNG_CONST char png_digit[16] = {
  180989. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  180990. 'A', 'B', 'C', 'D', 'E', 'F'
  180991. };*/
  180992. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  180993. static void /* PRIVATE */
  180994. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  180995. error_message)
  180996. {
  180997. int iout = 0, iin = 0;
  180998. while (iin < 4)
  180999. {
  181000. int c = png_ptr->chunk_name[iin++];
  181001. if (isnonalpha(c))
  181002. {
  181003. buffer[iout++] = '[';
  181004. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  181005. buffer[iout++] = png_digit[c & 0x0f];
  181006. buffer[iout++] = ']';
  181007. }
  181008. else
  181009. {
  181010. buffer[iout++] = (png_byte)c;
  181011. }
  181012. }
  181013. if (error_message == NULL)
  181014. buffer[iout] = 0;
  181015. else
  181016. {
  181017. buffer[iout++] = ':';
  181018. buffer[iout++] = ' ';
  181019. png_strncpy(buffer+iout, error_message, 63);
  181020. buffer[iout+63] = 0;
  181021. }
  181022. }
  181023. #ifdef PNG_READ_SUPPORTED
  181024. void PNGAPI
  181025. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  181026. {
  181027. char msg[18+64];
  181028. if (png_ptr == NULL)
  181029. png_error(png_ptr, error_message);
  181030. else
  181031. {
  181032. png_format_buffer(png_ptr, msg, error_message);
  181033. png_error(png_ptr, msg);
  181034. }
  181035. }
  181036. #endif /* PNG_READ_SUPPORTED */
  181037. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  181038. #ifndef PNG_NO_WARNINGS
  181039. void PNGAPI
  181040. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  181041. {
  181042. char msg[18+64];
  181043. if (png_ptr == NULL)
  181044. png_warning(png_ptr, warning_message);
  181045. else
  181046. {
  181047. png_format_buffer(png_ptr, msg, warning_message);
  181048. png_warning(png_ptr, msg);
  181049. }
  181050. }
  181051. #endif /* PNG_NO_WARNINGS */
  181052. /* This is the default error handling function. Note that replacements for
  181053. * this function MUST NOT RETURN, or the program will likely crash. This
  181054. * function is used by default, or if the program supplies NULL for the
  181055. * error function pointer in png_set_error_fn().
  181056. */
  181057. static void /* PRIVATE */
  181058. png_default_error(png_structp png_ptr, png_const_charp error_message)
  181059. {
  181060. #ifndef PNG_NO_CONSOLE_IO
  181061. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181062. if (*error_message == '#')
  181063. {
  181064. int offset;
  181065. char error_number[16];
  181066. for (offset=0; offset<15; offset++)
  181067. {
  181068. error_number[offset] = *(error_message+offset+1);
  181069. if (*(error_message+offset) == ' ')
  181070. break;
  181071. }
  181072. if((offset > 1) && (offset < 15))
  181073. {
  181074. error_number[offset-1]='\0';
  181075. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  181076. error_message+offset);
  181077. }
  181078. else
  181079. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  181080. }
  181081. else
  181082. #endif
  181083. fprintf(stderr, "libpng error: %s\n", error_message);
  181084. #endif
  181085. #ifdef PNG_SETJMP_SUPPORTED
  181086. if (png_ptr)
  181087. {
  181088. # ifdef USE_FAR_KEYWORD
  181089. {
  181090. jmp_buf jmpbuf;
  181091. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  181092. longjmp(jmpbuf, 1);
  181093. }
  181094. # else
  181095. longjmp(png_ptr->jmpbuf, 1);
  181096. # endif
  181097. }
  181098. #else
  181099. PNG_ABORT();
  181100. #endif
  181101. #ifdef PNG_NO_CONSOLE_IO
  181102. error_message = error_message; /* make compiler happy */
  181103. #endif
  181104. }
  181105. #ifndef PNG_NO_WARNINGS
  181106. /* This function is called when there is a warning, but the library thinks
  181107. * it can continue anyway. Replacement functions don't have to do anything
  181108. * here if you don't want them to. In the default configuration, png_ptr is
  181109. * not used, but it is passed in case it may be useful.
  181110. */
  181111. static void /* PRIVATE */
  181112. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  181113. {
  181114. #ifndef PNG_NO_CONSOLE_IO
  181115. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181116. if (*warning_message == '#')
  181117. {
  181118. int offset;
  181119. char warning_number[16];
  181120. for (offset=0; offset<15; offset++)
  181121. {
  181122. warning_number[offset]=*(warning_message+offset+1);
  181123. if (*(warning_message+offset) == ' ')
  181124. break;
  181125. }
  181126. if((offset > 1) && (offset < 15))
  181127. {
  181128. warning_number[offset-1]='\0';
  181129. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  181130. warning_message+offset);
  181131. }
  181132. else
  181133. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181134. }
  181135. else
  181136. # endif
  181137. fprintf(stderr, "libpng warning: %s\n", warning_message);
  181138. #else
  181139. warning_message = warning_message; /* make compiler happy */
  181140. #endif
  181141. png_ptr = png_ptr; /* make compiler happy */
  181142. }
  181143. #endif /* PNG_NO_WARNINGS */
  181144. /* This function is called when the application wants to use another method
  181145. * of handling errors and warnings. Note that the error function MUST NOT
  181146. * return to the calling routine or serious problems will occur. The return
  181147. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  181148. */
  181149. void PNGAPI
  181150. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  181151. png_error_ptr error_fn, png_error_ptr warning_fn)
  181152. {
  181153. if (png_ptr == NULL)
  181154. return;
  181155. png_ptr->error_ptr = error_ptr;
  181156. png_ptr->error_fn = error_fn;
  181157. png_ptr->warning_fn = warning_fn;
  181158. }
  181159. /* This function returns a pointer to the error_ptr associated with the user
  181160. * functions. The application should free any memory associated with this
  181161. * pointer before png_write_destroy and png_read_destroy are called.
  181162. */
  181163. png_voidp PNGAPI
  181164. png_get_error_ptr(png_structp png_ptr)
  181165. {
  181166. if (png_ptr == NULL)
  181167. return NULL;
  181168. return ((png_voidp)png_ptr->error_ptr);
  181169. }
  181170. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  181171. void PNGAPI
  181172. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  181173. {
  181174. if(png_ptr != NULL)
  181175. {
  181176. png_ptr->flags &=
  181177. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  181178. }
  181179. }
  181180. #endif
  181181. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  181182. /********* End of inlined file: pngerror.c *********/
  181183. /********* Start of inlined file: pngget.c *********/
  181184. /* pngget.c - retrieval of values from info struct
  181185. *
  181186. * Last changed in libpng 1.2.15 January 5, 2007
  181187. * For conditions of distribution and use, see copyright notice in png.h
  181188. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181189. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181190. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181191. */
  181192. #define PNG_INTERNAL
  181193. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  181194. png_uint_32 PNGAPI
  181195. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  181196. {
  181197. if (png_ptr != NULL && info_ptr != NULL)
  181198. return(info_ptr->valid & flag);
  181199. else
  181200. return(0);
  181201. }
  181202. png_uint_32 PNGAPI
  181203. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  181204. {
  181205. if (png_ptr != NULL && info_ptr != NULL)
  181206. return(info_ptr->rowbytes);
  181207. else
  181208. return(0);
  181209. }
  181210. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181211. png_bytepp PNGAPI
  181212. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  181213. {
  181214. if (png_ptr != NULL && info_ptr != NULL)
  181215. return(info_ptr->row_pointers);
  181216. else
  181217. return(0);
  181218. }
  181219. #endif
  181220. #ifdef PNG_EASY_ACCESS_SUPPORTED
  181221. /* easy access to info, added in libpng-0.99 */
  181222. png_uint_32 PNGAPI
  181223. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  181224. {
  181225. if (png_ptr != NULL && info_ptr != NULL)
  181226. {
  181227. return info_ptr->width;
  181228. }
  181229. return (0);
  181230. }
  181231. png_uint_32 PNGAPI
  181232. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  181233. {
  181234. if (png_ptr != NULL && info_ptr != NULL)
  181235. {
  181236. return info_ptr->height;
  181237. }
  181238. return (0);
  181239. }
  181240. png_byte PNGAPI
  181241. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  181242. {
  181243. if (png_ptr != NULL && info_ptr != NULL)
  181244. {
  181245. return info_ptr->bit_depth;
  181246. }
  181247. return (0);
  181248. }
  181249. png_byte PNGAPI
  181250. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  181251. {
  181252. if (png_ptr != NULL && info_ptr != NULL)
  181253. {
  181254. return info_ptr->color_type;
  181255. }
  181256. return (0);
  181257. }
  181258. png_byte PNGAPI
  181259. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  181260. {
  181261. if (png_ptr != NULL && info_ptr != NULL)
  181262. {
  181263. return info_ptr->filter_type;
  181264. }
  181265. return (0);
  181266. }
  181267. png_byte PNGAPI
  181268. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  181269. {
  181270. if (png_ptr != NULL && info_ptr != NULL)
  181271. {
  181272. return info_ptr->interlace_type;
  181273. }
  181274. return (0);
  181275. }
  181276. png_byte PNGAPI
  181277. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  181278. {
  181279. if (png_ptr != NULL && info_ptr != NULL)
  181280. {
  181281. return info_ptr->compression_type;
  181282. }
  181283. return (0);
  181284. }
  181285. png_uint_32 PNGAPI
  181286. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181287. {
  181288. if (png_ptr != NULL && info_ptr != NULL)
  181289. #if defined(PNG_pHYs_SUPPORTED)
  181290. if (info_ptr->valid & PNG_INFO_pHYs)
  181291. {
  181292. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  181293. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181294. return (0);
  181295. else return (info_ptr->x_pixels_per_unit);
  181296. }
  181297. #else
  181298. return (0);
  181299. #endif
  181300. return (0);
  181301. }
  181302. png_uint_32 PNGAPI
  181303. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181304. {
  181305. if (png_ptr != NULL && info_ptr != NULL)
  181306. #if defined(PNG_pHYs_SUPPORTED)
  181307. if (info_ptr->valid & PNG_INFO_pHYs)
  181308. {
  181309. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  181310. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  181311. return (0);
  181312. else return (info_ptr->y_pixels_per_unit);
  181313. }
  181314. #else
  181315. return (0);
  181316. #endif
  181317. return (0);
  181318. }
  181319. png_uint_32 PNGAPI
  181320. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  181321. {
  181322. if (png_ptr != NULL && info_ptr != NULL)
  181323. #if defined(PNG_pHYs_SUPPORTED)
  181324. if (info_ptr->valid & PNG_INFO_pHYs)
  181325. {
  181326. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  181327. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  181328. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  181329. return (0);
  181330. else return (info_ptr->x_pixels_per_unit);
  181331. }
  181332. #else
  181333. return (0);
  181334. #endif
  181335. return (0);
  181336. }
  181337. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181338. float PNGAPI
  181339. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  181340. {
  181341. if (png_ptr != NULL && info_ptr != NULL)
  181342. #if defined(PNG_pHYs_SUPPORTED)
  181343. if (info_ptr->valid & PNG_INFO_pHYs)
  181344. {
  181345. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  181346. if (info_ptr->x_pixels_per_unit == 0)
  181347. return ((float)0.0);
  181348. else
  181349. return ((float)((float)info_ptr->y_pixels_per_unit
  181350. /(float)info_ptr->x_pixels_per_unit));
  181351. }
  181352. #else
  181353. return (0.0);
  181354. #endif
  181355. return ((float)0.0);
  181356. }
  181357. #endif
  181358. png_int_32 PNGAPI
  181359. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181360. {
  181361. if (png_ptr != NULL && info_ptr != NULL)
  181362. #if defined(PNG_oFFs_SUPPORTED)
  181363. if (info_ptr->valid & PNG_INFO_oFFs)
  181364. {
  181365. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181366. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181367. return (0);
  181368. else return (info_ptr->x_offset);
  181369. }
  181370. #else
  181371. return (0);
  181372. #endif
  181373. return (0);
  181374. }
  181375. png_int_32 PNGAPI
  181376. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  181377. {
  181378. if (png_ptr != NULL && info_ptr != NULL)
  181379. #if defined(PNG_oFFs_SUPPORTED)
  181380. if (info_ptr->valid & PNG_INFO_oFFs)
  181381. {
  181382. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181383. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  181384. return (0);
  181385. else return (info_ptr->y_offset);
  181386. }
  181387. #else
  181388. return (0);
  181389. #endif
  181390. return (0);
  181391. }
  181392. png_int_32 PNGAPI
  181393. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181394. {
  181395. if (png_ptr != NULL && info_ptr != NULL)
  181396. #if defined(PNG_oFFs_SUPPORTED)
  181397. if (info_ptr->valid & PNG_INFO_oFFs)
  181398. {
  181399. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  181400. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181401. return (0);
  181402. else return (info_ptr->x_offset);
  181403. }
  181404. #else
  181405. return (0);
  181406. #endif
  181407. return (0);
  181408. }
  181409. png_int_32 PNGAPI
  181410. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  181411. {
  181412. if (png_ptr != NULL && info_ptr != NULL)
  181413. #if defined(PNG_oFFs_SUPPORTED)
  181414. if (info_ptr->valid & PNG_INFO_oFFs)
  181415. {
  181416. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  181417. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  181418. return (0);
  181419. else return (info_ptr->y_offset);
  181420. }
  181421. #else
  181422. return (0);
  181423. #endif
  181424. return (0);
  181425. }
  181426. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  181427. png_uint_32 PNGAPI
  181428. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181429. {
  181430. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  181431. *.0254 +.5));
  181432. }
  181433. png_uint_32 PNGAPI
  181434. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181435. {
  181436. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  181437. *.0254 +.5));
  181438. }
  181439. png_uint_32 PNGAPI
  181440. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  181441. {
  181442. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  181443. *.0254 +.5));
  181444. }
  181445. float PNGAPI
  181446. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181447. {
  181448. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  181449. *.00003937);
  181450. }
  181451. float PNGAPI
  181452. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  181453. {
  181454. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  181455. *.00003937);
  181456. }
  181457. #if defined(PNG_pHYs_SUPPORTED)
  181458. png_uint_32 PNGAPI
  181459. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  181460. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181461. {
  181462. png_uint_32 retval = 0;
  181463. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  181464. {
  181465. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181466. if (res_x != NULL)
  181467. {
  181468. *res_x = info_ptr->x_pixels_per_unit;
  181469. retval |= PNG_INFO_pHYs;
  181470. }
  181471. if (res_y != NULL)
  181472. {
  181473. *res_y = info_ptr->y_pixels_per_unit;
  181474. retval |= PNG_INFO_pHYs;
  181475. }
  181476. if (unit_type != NULL)
  181477. {
  181478. *unit_type = (int)info_ptr->phys_unit_type;
  181479. retval |= PNG_INFO_pHYs;
  181480. if(*unit_type == 1)
  181481. {
  181482. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  181483. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  181484. }
  181485. }
  181486. }
  181487. return (retval);
  181488. }
  181489. #endif /* PNG_pHYs_SUPPORTED */
  181490. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  181491. /* png_get_channels really belongs in here, too, but it's been around longer */
  181492. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  181493. png_byte PNGAPI
  181494. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  181495. {
  181496. if (png_ptr != NULL && info_ptr != NULL)
  181497. return(info_ptr->channels);
  181498. else
  181499. return (0);
  181500. }
  181501. png_bytep PNGAPI
  181502. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  181503. {
  181504. if (png_ptr != NULL && info_ptr != NULL)
  181505. return(info_ptr->signature);
  181506. else
  181507. return (NULL);
  181508. }
  181509. #if defined(PNG_bKGD_SUPPORTED)
  181510. png_uint_32 PNGAPI
  181511. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  181512. png_color_16p *background)
  181513. {
  181514. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  181515. && background != NULL)
  181516. {
  181517. png_debug1(1, "in %s retrieval function\n", "bKGD");
  181518. *background = &(info_ptr->background);
  181519. return (PNG_INFO_bKGD);
  181520. }
  181521. return (0);
  181522. }
  181523. #endif
  181524. #if defined(PNG_cHRM_SUPPORTED)
  181525. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181526. png_uint_32 PNGAPI
  181527. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  181528. double *white_x, double *white_y, double *red_x, double *red_y,
  181529. double *green_x, double *green_y, double *blue_x, double *blue_y)
  181530. {
  181531. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181532. {
  181533. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181534. if (white_x != NULL)
  181535. *white_x = (double)info_ptr->x_white;
  181536. if (white_y != NULL)
  181537. *white_y = (double)info_ptr->y_white;
  181538. if (red_x != NULL)
  181539. *red_x = (double)info_ptr->x_red;
  181540. if (red_y != NULL)
  181541. *red_y = (double)info_ptr->y_red;
  181542. if (green_x != NULL)
  181543. *green_x = (double)info_ptr->x_green;
  181544. if (green_y != NULL)
  181545. *green_y = (double)info_ptr->y_green;
  181546. if (blue_x != NULL)
  181547. *blue_x = (double)info_ptr->x_blue;
  181548. if (blue_y != NULL)
  181549. *blue_y = (double)info_ptr->y_blue;
  181550. return (PNG_INFO_cHRM);
  181551. }
  181552. return (0);
  181553. }
  181554. #endif
  181555. #ifdef PNG_FIXED_POINT_SUPPORTED
  181556. png_uint_32 PNGAPI
  181557. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  181558. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  181559. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  181560. png_fixed_point *blue_x, png_fixed_point *blue_y)
  181561. {
  181562. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  181563. {
  181564. png_debug1(1, "in %s retrieval function\n", "cHRM");
  181565. if (white_x != NULL)
  181566. *white_x = info_ptr->int_x_white;
  181567. if (white_y != NULL)
  181568. *white_y = info_ptr->int_y_white;
  181569. if (red_x != NULL)
  181570. *red_x = info_ptr->int_x_red;
  181571. if (red_y != NULL)
  181572. *red_y = info_ptr->int_y_red;
  181573. if (green_x != NULL)
  181574. *green_x = info_ptr->int_x_green;
  181575. if (green_y != NULL)
  181576. *green_y = info_ptr->int_y_green;
  181577. if (blue_x != NULL)
  181578. *blue_x = info_ptr->int_x_blue;
  181579. if (blue_y != NULL)
  181580. *blue_y = info_ptr->int_y_blue;
  181581. return (PNG_INFO_cHRM);
  181582. }
  181583. return (0);
  181584. }
  181585. #endif
  181586. #endif
  181587. #if defined(PNG_gAMA_SUPPORTED)
  181588. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181589. png_uint_32 PNGAPI
  181590. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  181591. {
  181592. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181593. && file_gamma != NULL)
  181594. {
  181595. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181596. *file_gamma = (double)info_ptr->gamma;
  181597. return (PNG_INFO_gAMA);
  181598. }
  181599. return (0);
  181600. }
  181601. #endif
  181602. #ifdef PNG_FIXED_POINT_SUPPORTED
  181603. png_uint_32 PNGAPI
  181604. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  181605. png_fixed_point *int_file_gamma)
  181606. {
  181607. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  181608. && int_file_gamma != NULL)
  181609. {
  181610. png_debug1(1, "in %s retrieval function\n", "gAMA");
  181611. *int_file_gamma = info_ptr->int_gamma;
  181612. return (PNG_INFO_gAMA);
  181613. }
  181614. return (0);
  181615. }
  181616. #endif
  181617. #endif
  181618. #if defined(PNG_sRGB_SUPPORTED)
  181619. png_uint_32 PNGAPI
  181620. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  181621. {
  181622. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  181623. && file_srgb_intent != NULL)
  181624. {
  181625. png_debug1(1, "in %s retrieval function\n", "sRGB");
  181626. *file_srgb_intent = (int)info_ptr->srgb_intent;
  181627. return (PNG_INFO_sRGB);
  181628. }
  181629. return (0);
  181630. }
  181631. #endif
  181632. #if defined(PNG_iCCP_SUPPORTED)
  181633. png_uint_32 PNGAPI
  181634. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  181635. png_charpp name, int *compression_type,
  181636. png_charpp profile, png_uint_32 *proflen)
  181637. {
  181638. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  181639. && name != NULL && profile != NULL && proflen != NULL)
  181640. {
  181641. png_debug1(1, "in %s retrieval function\n", "iCCP");
  181642. *name = info_ptr->iccp_name;
  181643. *profile = info_ptr->iccp_profile;
  181644. /* compression_type is a dummy so the API won't have to change
  181645. if we introduce multiple compression types later. */
  181646. *proflen = (int)info_ptr->iccp_proflen;
  181647. *compression_type = (int)info_ptr->iccp_compression;
  181648. return (PNG_INFO_iCCP);
  181649. }
  181650. return (0);
  181651. }
  181652. #endif
  181653. #if defined(PNG_sPLT_SUPPORTED)
  181654. png_uint_32 PNGAPI
  181655. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  181656. png_sPLT_tpp spalettes)
  181657. {
  181658. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  181659. {
  181660. *spalettes = info_ptr->splt_palettes;
  181661. return ((png_uint_32)info_ptr->splt_palettes_num);
  181662. }
  181663. return (0);
  181664. }
  181665. #endif
  181666. #if defined(PNG_hIST_SUPPORTED)
  181667. png_uint_32 PNGAPI
  181668. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  181669. {
  181670. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  181671. && hist != NULL)
  181672. {
  181673. png_debug1(1, "in %s retrieval function\n", "hIST");
  181674. *hist = info_ptr->hist;
  181675. return (PNG_INFO_hIST);
  181676. }
  181677. return (0);
  181678. }
  181679. #endif
  181680. png_uint_32 PNGAPI
  181681. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  181682. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  181683. int *color_type, int *interlace_type, int *compression_type,
  181684. int *filter_type)
  181685. {
  181686. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  181687. bit_depth != NULL && color_type != NULL)
  181688. {
  181689. png_debug1(1, "in %s retrieval function\n", "IHDR");
  181690. *width = info_ptr->width;
  181691. *height = info_ptr->height;
  181692. *bit_depth = info_ptr->bit_depth;
  181693. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  181694. png_error(png_ptr, "Invalid bit depth");
  181695. *color_type = info_ptr->color_type;
  181696. if (info_ptr->color_type > 6)
  181697. png_error(png_ptr, "Invalid color type");
  181698. if (compression_type != NULL)
  181699. *compression_type = info_ptr->compression_type;
  181700. if (filter_type != NULL)
  181701. *filter_type = info_ptr->filter_type;
  181702. if (interlace_type != NULL)
  181703. *interlace_type = info_ptr->interlace_type;
  181704. /* check for potential overflow of rowbytes */
  181705. if (*width == 0 || *width > PNG_UINT_31_MAX)
  181706. png_error(png_ptr, "Invalid image width");
  181707. if (*height == 0 || *height > PNG_UINT_31_MAX)
  181708. png_error(png_ptr, "Invalid image height");
  181709. if (info_ptr->width > (PNG_UINT_32_MAX
  181710. >> 3) /* 8-byte RGBA pixels */
  181711. - 64 /* bigrowbuf hack */
  181712. - 1 /* filter byte */
  181713. - 7*8 /* rounding of width to multiple of 8 pixels */
  181714. - 8) /* extra max_pixel_depth pad */
  181715. {
  181716. png_warning(png_ptr,
  181717. "Width too large for libpng to process image data.");
  181718. }
  181719. return (1);
  181720. }
  181721. return (0);
  181722. }
  181723. #if defined(PNG_oFFs_SUPPORTED)
  181724. png_uint_32 PNGAPI
  181725. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  181726. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  181727. {
  181728. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  181729. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  181730. {
  181731. png_debug1(1, "in %s retrieval function\n", "oFFs");
  181732. *offset_x = info_ptr->x_offset;
  181733. *offset_y = info_ptr->y_offset;
  181734. *unit_type = (int)info_ptr->offset_unit_type;
  181735. return (PNG_INFO_oFFs);
  181736. }
  181737. return (0);
  181738. }
  181739. #endif
  181740. #if defined(PNG_pCAL_SUPPORTED)
  181741. png_uint_32 PNGAPI
  181742. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  181743. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  181744. png_charp *units, png_charpp *params)
  181745. {
  181746. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  181747. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  181748. nparams != NULL && units != NULL && params != NULL)
  181749. {
  181750. png_debug1(1, "in %s retrieval function\n", "pCAL");
  181751. *purpose = info_ptr->pcal_purpose;
  181752. *X0 = info_ptr->pcal_X0;
  181753. *X1 = info_ptr->pcal_X1;
  181754. *type = (int)info_ptr->pcal_type;
  181755. *nparams = (int)info_ptr->pcal_nparams;
  181756. *units = info_ptr->pcal_units;
  181757. *params = info_ptr->pcal_params;
  181758. return (PNG_INFO_pCAL);
  181759. }
  181760. return (0);
  181761. }
  181762. #endif
  181763. #if defined(PNG_sCAL_SUPPORTED)
  181764. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181765. png_uint_32 PNGAPI
  181766. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  181767. int *unit, double *width, double *height)
  181768. {
  181769. if (png_ptr != NULL && info_ptr != NULL &&
  181770. (info_ptr->valid & PNG_INFO_sCAL))
  181771. {
  181772. *unit = info_ptr->scal_unit;
  181773. *width = info_ptr->scal_pixel_width;
  181774. *height = info_ptr->scal_pixel_height;
  181775. return (PNG_INFO_sCAL);
  181776. }
  181777. return(0);
  181778. }
  181779. #else
  181780. #ifdef PNG_FIXED_POINT_SUPPORTED
  181781. png_uint_32 PNGAPI
  181782. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  181783. int *unit, png_charpp width, png_charpp height)
  181784. {
  181785. if (png_ptr != NULL && info_ptr != NULL &&
  181786. (info_ptr->valid & PNG_INFO_sCAL))
  181787. {
  181788. *unit = info_ptr->scal_unit;
  181789. *width = info_ptr->scal_s_width;
  181790. *height = info_ptr->scal_s_height;
  181791. return (PNG_INFO_sCAL);
  181792. }
  181793. return(0);
  181794. }
  181795. #endif
  181796. #endif
  181797. #endif
  181798. #if defined(PNG_pHYs_SUPPORTED)
  181799. png_uint_32 PNGAPI
  181800. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  181801. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  181802. {
  181803. png_uint_32 retval = 0;
  181804. if (png_ptr != NULL && info_ptr != NULL &&
  181805. (info_ptr->valid & PNG_INFO_pHYs))
  181806. {
  181807. png_debug1(1, "in %s retrieval function\n", "pHYs");
  181808. if (res_x != NULL)
  181809. {
  181810. *res_x = info_ptr->x_pixels_per_unit;
  181811. retval |= PNG_INFO_pHYs;
  181812. }
  181813. if (res_y != NULL)
  181814. {
  181815. *res_y = info_ptr->y_pixels_per_unit;
  181816. retval |= PNG_INFO_pHYs;
  181817. }
  181818. if (unit_type != NULL)
  181819. {
  181820. *unit_type = (int)info_ptr->phys_unit_type;
  181821. retval |= PNG_INFO_pHYs;
  181822. }
  181823. }
  181824. return (retval);
  181825. }
  181826. #endif
  181827. png_uint_32 PNGAPI
  181828. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  181829. int *num_palette)
  181830. {
  181831. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  181832. && palette != NULL)
  181833. {
  181834. png_debug1(1, "in %s retrieval function\n", "PLTE");
  181835. *palette = info_ptr->palette;
  181836. *num_palette = info_ptr->num_palette;
  181837. png_debug1(3, "num_palette = %d\n", *num_palette);
  181838. return (PNG_INFO_PLTE);
  181839. }
  181840. return (0);
  181841. }
  181842. #if defined(PNG_sBIT_SUPPORTED)
  181843. png_uint_32 PNGAPI
  181844. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  181845. {
  181846. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  181847. && sig_bit != NULL)
  181848. {
  181849. png_debug1(1, "in %s retrieval function\n", "sBIT");
  181850. *sig_bit = &(info_ptr->sig_bit);
  181851. return (PNG_INFO_sBIT);
  181852. }
  181853. return (0);
  181854. }
  181855. #endif
  181856. #if defined(PNG_TEXT_SUPPORTED)
  181857. png_uint_32 PNGAPI
  181858. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  181859. int *num_text)
  181860. {
  181861. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  181862. {
  181863. png_debug1(1, "in %s retrieval function\n",
  181864. (png_ptr->chunk_name[0] == '\0' ? "text"
  181865. : (png_const_charp)png_ptr->chunk_name));
  181866. if (text_ptr != NULL)
  181867. *text_ptr = info_ptr->text;
  181868. if (num_text != NULL)
  181869. *num_text = info_ptr->num_text;
  181870. return ((png_uint_32)info_ptr->num_text);
  181871. }
  181872. if (num_text != NULL)
  181873. *num_text = 0;
  181874. return(0);
  181875. }
  181876. #endif
  181877. #if defined(PNG_tIME_SUPPORTED)
  181878. png_uint_32 PNGAPI
  181879. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  181880. {
  181881. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  181882. && mod_time != NULL)
  181883. {
  181884. png_debug1(1, "in %s retrieval function\n", "tIME");
  181885. *mod_time = &(info_ptr->mod_time);
  181886. return (PNG_INFO_tIME);
  181887. }
  181888. return (0);
  181889. }
  181890. #endif
  181891. #if defined(PNG_tRNS_SUPPORTED)
  181892. png_uint_32 PNGAPI
  181893. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  181894. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  181895. {
  181896. png_uint_32 retval = 0;
  181897. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  181898. {
  181899. png_debug1(1, "in %s retrieval function\n", "tRNS");
  181900. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  181901. {
  181902. if (trans != NULL)
  181903. {
  181904. *trans = info_ptr->trans;
  181905. retval |= PNG_INFO_tRNS;
  181906. }
  181907. if (trans_values != NULL)
  181908. *trans_values = &(info_ptr->trans_values);
  181909. }
  181910. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  181911. {
  181912. if (trans_values != NULL)
  181913. {
  181914. *trans_values = &(info_ptr->trans_values);
  181915. retval |= PNG_INFO_tRNS;
  181916. }
  181917. if(trans != NULL)
  181918. *trans = NULL;
  181919. }
  181920. if(num_trans != NULL)
  181921. {
  181922. *num_trans = info_ptr->num_trans;
  181923. retval |= PNG_INFO_tRNS;
  181924. }
  181925. }
  181926. return (retval);
  181927. }
  181928. #endif
  181929. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  181930. png_uint_32 PNGAPI
  181931. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  181932. png_unknown_chunkpp unknowns)
  181933. {
  181934. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  181935. {
  181936. *unknowns = info_ptr->unknown_chunks;
  181937. return ((png_uint_32)info_ptr->unknown_chunks_num);
  181938. }
  181939. return (0);
  181940. }
  181941. #endif
  181942. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  181943. png_byte PNGAPI
  181944. png_get_rgb_to_gray_status (png_structp png_ptr)
  181945. {
  181946. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  181947. }
  181948. #endif
  181949. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  181950. png_voidp PNGAPI
  181951. png_get_user_chunk_ptr(png_structp png_ptr)
  181952. {
  181953. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  181954. }
  181955. #endif
  181956. #ifdef PNG_WRITE_SUPPORTED
  181957. png_uint_32 PNGAPI
  181958. png_get_compression_buffer_size(png_structp png_ptr)
  181959. {
  181960. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  181961. }
  181962. #endif
  181963. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  181964. #ifndef PNG_1_0_X
  181965. /* this function was added to libpng 1.2.0 and should exist by default */
  181966. png_uint_32 PNGAPI
  181967. png_get_asm_flags (png_structp png_ptr)
  181968. {
  181969. /* obsolete, to be removed from libpng-1.4.0 */
  181970. return (png_ptr? 0L: 0L);
  181971. }
  181972. /* this function was added to libpng 1.2.0 and should exist by default */
  181973. png_uint_32 PNGAPI
  181974. png_get_asm_flagmask (int flag_select)
  181975. {
  181976. /* obsolete, to be removed from libpng-1.4.0 */
  181977. flag_select=flag_select;
  181978. return 0L;
  181979. }
  181980. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  181981. /* this function was added to libpng 1.2.0 */
  181982. png_uint_32 PNGAPI
  181983. png_get_mmx_flagmask (int flag_select, int *compilerID)
  181984. {
  181985. /* obsolete, to be removed from libpng-1.4.0 */
  181986. flag_select=flag_select;
  181987. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  181988. return 0L;
  181989. }
  181990. /* this function was added to libpng 1.2.0 */
  181991. png_byte PNGAPI
  181992. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  181993. {
  181994. /* obsolete, to be removed from libpng-1.4.0 */
  181995. return (png_ptr? 0: 0);
  181996. }
  181997. /* this function was added to libpng 1.2.0 */
  181998. png_uint_32 PNGAPI
  181999. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  182000. {
  182001. /* obsolete, to be removed from libpng-1.4.0 */
  182002. return (png_ptr? 0L: 0L);
  182003. }
  182004. #endif /* ?PNG_1_0_X */
  182005. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  182006. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182007. /* these functions were added to libpng 1.2.6 */
  182008. png_uint_32 PNGAPI
  182009. png_get_user_width_max (png_structp png_ptr)
  182010. {
  182011. return (png_ptr? png_ptr->user_width_max : 0);
  182012. }
  182013. png_uint_32 PNGAPI
  182014. png_get_user_height_max (png_structp png_ptr)
  182015. {
  182016. return (png_ptr? png_ptr->user_height_max : 0);
  182017. }
  182018. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  182019. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182020. /********* End of inlined file: pngget.c *********/
  182021. /********* Start of inlined file: pngmem.c *********/
  182022. /* pngmem.c - stub functions for memory allocation
  182023. *
  182024. * Last changed in libpng 1.2.13 November 13, 2006
  182025. * For conditions of distribution and use, see copyright notice in png.h
  182026. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  182027. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182028. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182029. *
  182030. * This file provides a location for all memory allocation. Users who
  182031. * need special memory handling are expected to supply replacement
  182032. * functions for png_malloc() and png_free(), and to use
  182033. * png_create_read_struct_2() and png_create_write_struct_2() to
  182034. * identify the replacement functions.
  182035. */
  182036. #define PNG_INTERNAL
  182037. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  182038. /* Borland DOS special memory handler */
  182039. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182040. /* if you change this, be sure to change the one in png.h also */
  182041. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  182042. by a single call to calloc() if this is thought to improve performance. */
  182043. png_voidp /* PRIVATE */
  182044. png_create_struct(int type)
  182045. {
  182046. #ifdef PNG_USER_MEM_SUPPORTED
  182047. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182048. }
  182049. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  182050. png_voidp /* PRIVATE */
  182051. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182052. {
  182053. #endif /* PNG_USER_MEM_SUPPORTED */
  182054. png_size_t size;
  182055. png_voidp struct_ptr;
  182056. if (type == PNG_STRUCT_INFO)
  182057. size = png_sizeof(png_info);
  182058. else if (type == PNG_STRUCT_PNG)
  182059. size = png_sizeof(png_struct);
  182060. else
  182061. return (png_get_copyright(NULL));
  182062. #ifdef PNG_USER_MEM_SUPPORTED
  182063. if(malloc_fn != NULL)
  182064. {
  182065. png_struct dummy_struct;
  182066. png_structp png_ptr = &dummy_struct;
  182067. png_ptr->mem_ptr=mem_ptr;
  182068. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  182069. }
  182070. else
  182071. #endif /* PNG_USER_MEM_SUPPORTED */
  182072. struct_ptr = (png_voidp)farmalloc(size);
  182073. if (struct_ptr != NULL)
  182074. png_memset(struct_ptr, 0, size);
  182075. return (struct_ptr);
  182076. }
  182077. /* Free memory allocated by a png_create_struct() call */
  182078. void /* PRIVATE */
  182079. png_destroy_struct(png_voidp struct_ptr)
  182080. {
  182081. #ifdef PNG_USER_MEM_SUPPORTED
  182082. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182083. }
  182084. /* Free memory allocated by a png_create_struct() call */
  182085. void /* PRIVATE */
  182086. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182087. png_voidp mem_ptr)
  182088. {
  182089. #endif
  182090. if (struct_ptr != NULL)
  182091. {
  182092. #ifdef PNG_USER_MEM_SUPPORTED
  182093. if(free_fn != NULL)
  182094. {
  182095. png_struct dummy_struct;
  182096. png_structp png_ptr = &dummy_struct;
  182097. png_ptr->mem_ptr=mem_ptr;
  182098. (*(free_fn))(png_ptr, struct_ptr);
  182099. return;
  182100. }
  182101. #endif /* PNG_USER_MEM_SUPPORTED */
  182102. farfree (struct_ptr);
  182103. }
  182104. }
  182105. /* Allocate memory. For reasonable files, size should never exceed
  182106. * 64K. However, zlib may allocate more then 64K if you don't tell
  182107. * it not to. See zconf.h and png.h for more information. zlib does
  182108. * need to allocate exactly 64K, so whatever you call here must
  182109. * have the ability to do that.
  182110. *
  182111. * Borland seems to have a problem in DOS mode for exactly 64K.
  182112. * It gives you a segment with an offset of 8 (perhaps to store its
  182113. * memory stuff). zlib doesn't like this at all, so we have to
  182114. * detect and deal with it. This code should not be needed in
  182115. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  182116. * been updated by Alexander Lehmann for version 0.89 to waste less
  182117. * memory.
  182118. *
  182119. * Note that we can't use png_size_t for the "size" declaration,
  182120. * since on some systems a png_size_t is a 16-bit quantity, and as a
  182121. * result, we would be truncating potentially larger memory requests
  182122. * (which should cause a fatal error) and introducing major problems.
  182123. */
  182124. png_voidp PNGAPI
  182125. png_malloc(png_structp png_ptr, png_uint_32 size)
  182126. {
  182127. png_voidp ret;
  182128. if (png_ptr == NULL || size == 0)
  182129. return (NULL);
  182130. #ifdef PNG_USER_MEM_SUPPORTED
  182131. if(png_ptr->malloc_fn != NULL)
  182132. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182133. else
  182134. ret = (png_malloc_default(png_ptr, size));
  182135. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182136. png_error(png_ptr, "Out of memory!");
  182137. return (ret);
  182138. }
  182139. png_voidp PNGAPI
  182140. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182141. {
  182142. png_voidp ret;
  182143. #endif /* PNG_USER_MEM_SUPPORTED */
  182144. if (png_ptr == NULL || size == 0)
  182145. return (NULL);
  182146. #ifdef PNG_MAX_MALLOC_64K
  182147. if (size > (png_uint_32)65536L)
  182148. {
  182149. png_warning(png_ptr, "Cannot Allocate > 64K");
  182150. ret = NULL;
  182151. }
  182152. else
  182153. #endif
  182154. if (size != (size_t)size)
  182155. ret = NULL;
  182156. else if (size == (png_uint_32)65536L)
  182157. {
  182158. if (png_ptr->offset_table == NULL)
  182159. {
  182160. /* try to see if we need to do any of this fancy stuff */
  182161. ret = farmalloc(size);
  182162. if (ret == NULL || ((png_size_t)ret & 0xffff))
  182163. {
  182164. int num_blocks;
  182165. png_uint_32 total_size;
  182166. png_bytep table;
  182167. int i;
  182168. png_byte huge * hptr;
  182169. if (ret != NULL)
  182170. {
  182171. farfree(ret);
  182172. ret = NULL;
  182173. }
  182174. if(png_ptr->zlib_window_bits > 14)
  182175. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  182176. else
  182177. num_blocks = 1;
  182178. if (png_ptr->zlib_mem_level >= 7)
  182179. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  182180. else
  182181. num_blocks++;
  182182. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  182183. table = farmalloc(total_size);
  182184. if (table == NULL)
  182185. {
  182186. #ifndef PNG_USER_MEM_SUPPORTED
  182187. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182188. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  182189. else
  182190. png_warning(png_ptr, "Out Of Memory.");
  182191. #endif
  182192. return (NULL);
  182193. }
  182194. if ((png_size_t)table & 0xfff0)
  182195. {
  182196. #ifndef PNG_USER_MEM_SUPPORTED
  182197. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182198. png_error(png_ptr,
  182199. "Farmalloc didn't return normalized pointer");
  182200. else
  182201. png_warning(png_ptr,
  182202. "Farmalloc didn't return normalized pointer");
  182203. #endif
  182204. return (NULL);
  182205. }
  182206. png_ptr->offset_table = table;
  182207. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  182208. png_sizeof (png_bytep));
  182209. if (png_ptr->offset_table_ptr == NULL)
  182210. {
  182211. #ifndef PNG_USER_MEM_SUPPORTED
  182212. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182213. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  182214. else
  182215. png_warning(png_ptr, "Out Of memory.");
  182216. #endif
  182217. return (NULL);
  182218. }
  182219. hptr = (png_byte huge *)table;
  182220. if ((png_size_t)hptr & 0xf)
  182221. {
  182222. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  182223. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  182224. }
  182225. for (i = 0; i < num_blocks; i++)
  182226. {
  182227. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  182228. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  182229. }
  182230. png_ptr->offset_table_number = num_blocks;
  182231. png_ptr->offset_table_count = 0;
  182232. png_ptr->offset_table_count_free = 0;
  182233. }
  182234. }
  182235. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  182236. {
  182237. #ifndef PNG_USER_MEM_SUPPORTED
  182238. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182239. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  182240. else
  182241. png_warning(png_ptr, "Out of Memory.");
  182242. #endif
  182243. return (NULL);
  182244. }
  182245. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  182246. }
  182247. else
  182248. ret = farmalloc(size);
  182249. #ifndef PNG_USER_MEM_SUPPORTED
  182250. if (ret == NULL)
  182251. {
  182252. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182253. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182254. else
  182255. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  182256. }
  182257. #endif
  182258. return (ret);
  182259. }
  182260. /* free a pointer allocated by png_malloc(). In the default
  182261. configuration, png_ptr is not used, but is passed in case it
  182262. is needed. If ptr is NULL, return without taking any action. */
  182263. void PNGAPI
  182264. png_free(png_structp png_ptr, png_voidp ptr)
  182265. {
  182266. if (png_ptr == NULL || ptr == NULL)
  182267. return;
  182268. #ifdef PNG_USER_MEM_SUPPORTED
  182269. if (png_ptr->free_fn != NULL)
  182270. {
  182271. (*(png_ptr->free_fn))(png_ptr, ptr);
  182272. return;
  182273. }
  182274. else png_free_default(png_ptr, ptr);
  182275. }
  182276. void PNGAPI
  182277. png_free_default(png_structp png_ptr, png_voidp ptr)
  182278. {
  182279. #endif /* PNG_USER_MEM_SUPPORTED */
  182280. if(png_ptr == NULL) return;
  182281. if (png_ptr->offset_table != NULL)
  182282. {
  182283. int i;
  182284. for (i = 0; i < png_ptr->offset_table_count; i++)
  182285. {
  182286. if (ptr == png_ptr->offset_table_ptr[i])
  182287. {
  182288. ptr = NULL;
  182289. png_ptr->offset_table_count_free++;
  182290. break;
  182291. }
  182292. }
  182293. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  182294. {
  182295. farfree(png_ptr->offset_table);
  182296. farfree(png_ptr->offset_table_ptr);
  182297. png_ptr->offset_table = NULL;
  182298. png_ptr->offset_table_ptr = NULL;
  182299. }
  182300. }
  182301. if (ptr != NULL)
  182302. {
  182303. farfree(ptr);
  182304. }
  182305. }
  182306. #else /* Not the Borland DOS special memory handler */
  182307. /* Allocate memory for a png_struct or a png_info. The malloc and
  182308. memset can be replaced by a single call to calloc() if this is thought
  182309. to improve performance noticably. */
  182310. png_voidp /* PRIVATE */
  182311. png_create_struct(int type)
  182312. {
  182313. #ifdef PNG_USER_MEM_SUPPORTED
  182314. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  182315. }
  182316. /* Allocate memory for a png_struct or a png_info. The malloc and
  182317. memset can be replaced by a single call to calloc() if this is thought
  182318. to improve performance noticably. */
  182319. png_voidp /* PRIVATE */
  182320. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  182321. {
  182322. #endif /* PNG_USER_MEM_SUPPORTED */
  182323. png_size_t size;
  182324. png_voidp struct_ptr;
  182325. if (type == PNG_STRUCT_INFO)
  182326. size = png_sizeof(png_info);
  182327. else if (type == PNG_STRUCT_PNG)
  182328. size = png_sizeof(png_struct);
  182329. else
  182330. return (NULL);
  182331. #ifdef PNG_USER_MEM_SUPPORTED
  182332. if(malloc_fn != NULL)
  182333. {
  182334. png_struct dummy_struct;
  182335. png_structp png_ptr = &dummy_struct;
  182336. png_ptr->mem_ptr=mem_ptr;
  182337. struct_ptr = (*(malloc_fn))(png_ptr, size);
  182338. if (struct_ptr != NULL)
  182339. png_memset(struct_ptr, 0, size);
  182340. return (struct_ptr);
  182341. }
  182342. #endif /* PNG_USER_MEM_SUPPORTED */
  182343. #if defined(__TURBOC__) && !defined(__FLAT__)
  182344. struct_ptr = (png_voidp)farmalloc(size);
  182345. #else
  182346. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182347. struct_ptr = (png_voidp)halloc(size,1);
  182348. # else
  182349. struct_ptr = (png_voidp)malloc(size);
  182350. # endif
  182351. #endif
  182352. if (struct_ptr != NULL)
  182353. png_memset(struct_ptr, 0, size);
  182354. return (struct_ptr);
  182355. }
  182356. /* Free memory allocated by a png_create_struct() call */
  182357. void /* PRIVATE */
  182358. png_destroy_struct(png_voidp struct_ptr)
  182359. {
  182360. #ifdef PNG_USER_MEM_SUPPORTED
  182361. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  182362. }
  182363. /* Free memory allocated by a png_create_struct() call */
  182364. void /* PRIVATE */
  182365. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  182366. png_voidp mem_ptr)
  182367. {
  182368. #endif /* PNG_USER_MEM_SUPPORTED */
  182369. if (struct_ptr != NULL)
  182370. {
  182371. #ifdef PNG_USER_MEM_SUPPORTED
  182372. if(free_fn != NULL)
  182373. {
  182374. png_struct dummy_struct;
  182375. png_structp png_ptr = &dummy_struct;
  182376. png_ptr->mem_ptr=mem_ptr;
  182377. (*(free_fn))(png_ptr, struct_ptr);
  182378. return;
  182379. }
  182380. #endif /* PNG_USER_MEM_SUPPORTED */
  182381. #if defined(__TURBOC__) && !defined(__FLAT__)
  182382. farfree(struct_ptr);
  182383. #else
  182384. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182385. hfree(struct_ptr);
  182386. # else
  182387. free(struct_ptr);
  182388. # endif
  182389. #endif
  182390. }
  182391. }
  182392. /* Allocate memory. For reasonable files, size should never exceed
  182393. 64K. However, zlib may allocate more then 64K if you don't tell
  182394. it not to. See zconf.h and png.h for more information. zlib does
  182395. need to allocate exactly 64K, so whatever you call here must
  182396. have the ability to do that. */
  182397. png_voidp PNGAPI
  182398. png_malloc(png_structp png_ptr, png_uint_32 size)
  182399. {
  182400. png_voidp ret;
  182401. #ifdef PNG_USER_MEM_SUPPORTED
  182402. if (png_ptr == NULL || size == 0)
  182403. return (NULL);
  182404. if(png_ptr->malloc_fn != NULL)
  182405. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  182406. else
  182407. ret = (png_malloc_default(png_ptr, size));
  182408. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182409. png_error(png_ptr, "Out of Memory!");
  182410. return (ret);
  182411. }
  182412. png_voidp PNGAPI
  182413. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  182414. {
  182415. png_voidp ret;
  182416. #endif /* PNG_USER_MEM_SUPPORTED */
  182417. if (png_ptr == NULL || size == 0)
  182418. return (NULL);
  182419. #ifdef PNG_MAX_MALLOC_64K
  182420. if (size > (png_uint_32)65536L)
  182421. {
  182422. #ifndef PNG_USER_MEM_SUPPORTED
  182423. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182424. png_error(png_ptr, "Cannot Allocate > 64K");
  182425. else
  182426. #endif
  182427. return NULL;
  182428. }
  182429. #endif
  182430. /* Check for overflow */
  182431. #if defined(__TURBOC__) && !defined(__FLAT__)
  182432. if (size != (unsigned long)size)
  182433. ret = NULL;
  182434. else
  182435. ret = farmalloc(size);
  182436. #else
  182437. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182438. if (size != (unsigned long)size)
  182439. ret = NULL;
  182440. else
  182441. ret = halloc(size, 1);
  182442. # else
  182443. if (size != (size_t)size)
  182444. ret = NULL;
  182445. else
  182446. ret = malloc((size_t)size);
  182447. # endif
  182448. #endif
  182449. #ifndef PNG_USER_MEM_SUPPORTED
  182450. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  182451. png_error(png_ptr, "Out of Memory");
  182452. #endif
  182453. return (ret);
  182454. }
  182455. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  182456. without taking any action. */
  182457. void PNGAPI
  182458. png_free(png_structp png_ptr, png_voidp ptr)
  182459. {
  182460. if (png_ptr == NULL || ptr == NULL)
  182461. return;
  182462. #ifdef PNG_USER_MEM_SUPPORTED
  182463. if (png_ptr->free_fn != NULL)
  182464. {
  182465. (*(png_ptr->free_fn))(png_ptr, ptr);
  182466. return;
  182467. }
  182468. else png_free_default(png_ptr, ptr);
  182469. }
  182470. void PNGAPI
  182471. png_free_default(png_structp png_ptr, png_voidp ptr)
  182472. {
  182473. if (png_ptr == NULL || ptr == NULL)
  182474. return;
  182475. #endif /* PNG_USER_MEM_SUPPORTED */
  182476. #if defined(__TURBOC__) && !defined(__FLAT__)
  182477. farfree(ptr);
  182478. #else
  182479. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  182480. hfree(ptr);
  182481. # else
  182482. free(ptr);
  182483. # endif
  182484. #endif
  182485. }
  182486. #endif /* Not Borland DOS special memory handler */
  182487. #if defined(PNG_1_0_X)
  182488. # define png_malloc_warn png_malloc
  182489. #else
  182490. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  182491. * function will set up png_malloc() to issue a png_warning and return NULL
  182492. * instead of issuing a png_error, if it fails to allocate the requested
  182493. * memory.
  182494. */
  182495. png_voidp PNGAPI
  182496. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  182497. {
  182498. png_voidp ptr;
  182499. png_uint_32 save_flags;
  182500. if(png_ptr == NULL) return (NULL);
  182501. save_flags=png_ptr->flags;
  182502. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  182503. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  182504. png_ptr->flags=save_flags;
  182505. return(ptr);
  182506. }
  182507. #endif
  182508. png_voidp PNGAPI
  182509. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  182510. png_uint_32 length)
  182511. {
  182512. png_size_t size;
  182513. size = (png_size_t)length;
  182514. if ((png_uint_32)size != length)
  182515. png_error(png_ptr,"Overflow in png_memcpy_check.");
  182516. return(png_memcpy (s1, s2, size));
  182517. }
  182518. png_voidp PNGAPI
  182519. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  182520. png_uint_32 length)
  182521. {
  182522. png_size_t size;
  182523. size = (png_size_t)length;
  182524. if ((png_uint_32)size != length)
  182525. png_error(png_ptr,"Overflow in png_memset_check.");
  182526. return (png_memset (s1, value, size));
  182527. }
  182528. #ifdef PNG_USER_MEM_SUPPORTED
  182529. /* This function is called when the application wants to use another method
  182530. * of allocating and freeing memory.
  182531. */
  182532. void PNGAPI
  182533. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  182534. malloc_fn, png_free_ptr free_fn)
  182535. {
  182536. if(png_ptr != NULL) {
  182537. png_ptr->mem_ptr = mem_ptr;
  182538. png_ptr->malloc_fn = malloc_fn;
  182539. png_ptr->free_fn = free_fn;
  182540. }
  182541. }
  182542. /* This function returns a pointer to the mem_ptr associated with the user
  182543. * functions. The application should free any memory associated with this
  182544. * pointer before png_write_destroy and png_read_destroy are called.
  182545. */
  182546. png_voidp PNGAPI
  182547. png_get_mem_ptr(png_structp png_ptr)
  182548. {
  182549. if(png_ptr == NULL) return (NULL);
  182550. return ((png_voidp)png_ptr->mem_ptr);
  182551. }
  182552. #endif /* PNG_USER_MEM_SUPPORTED */
  182553. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  182554. /********* End of inlined file: pngmem.c *********/
  182555. /********* Start of inlined file: pngread.c *********/
  182556. /* pngread.c - read a PNG file
  182557. *
  182558. * Last changed in libpng 1.2.20 September 7, 2007
  182559. * For conditions of distribution and use, see copyright notice in png.h
  182560. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  182561. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  182562. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  182563. *
  182564. * This file contains routines that an application calls directly to
  182565. * read a PNG file or stream.
  182566. */
  182567. #define PNG_INTERNAL
  182568. #if defined(PNG_READ_SUPPORTED)
  182569. /* Create a PNG structure for reading, and allocate any memory needed. */
  182570. png_structp PNGAPI
  182571. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  182572. png_error_ptr error_fn, png_error_ptr warn_fn)
  182573. {
  182574. #ifdef PNG_USER_MEM_SUPPORTED
  182575. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  182576. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  182577. }
  182578. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  182579. png_structp PNGAPI
  182580. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  182581. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182582. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  182583. {
  182584. #endif /* PNG_USER_MEM_SUPPORTED */
  182585. png_structp png_ptr;
  182586. #ifdef PNG_SETJMP_SUPPORTED
  182587. #ifdef USE_FAR_KEYWORD
  182588. jmp_buf jmpbuf;
  182589. #endif
  182590. #endif
  182591. int i;
  182592. png_debug(1, "in png_create_read_struct\n");
  182593. #ifdef PNG_USER_MEM_SUPPORTED
  182594. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  182595. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  182596. #else
  182597. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182598. #endif
  182599. if (png_ptr == NULL)
  182600. return (NULL);
  182601. /* added at libpng-1.2.6 */
  182602. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182603. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182604. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182605. #endif
  182606. #ifdef PNG_SETJMP_SUPPORTED
  182607. #ifdef USE_FAR_KEYWORD
  182608. if (setjmp(jmpbuf))
  182609. #else
  182610. if (setjmp(png_ptr->jmpbuf))
  182611. #endif
  182612. {
  182613. png_free(png_ptr, png_ptr->zbuf);
  182614. png_ptr->zbuf=NULL;
  182615. #ifdef PNG_USER_MEM_SUPPORTED
  182616. png_destroy_struct_2((png_voidp)png_ptr,
  182617. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  182618. #else
  182619. png_destroy_struct((png_voidp)png_ptr);
  182620. #endif
  182621. return (NULL);
  182622. }
  182623. #ifdef USE_FAR_KEYWORD
  182624. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182625. #endif
  182626. #endif
  182627. #ifdef PNG_USER_MEM_SUPPORTED
  182628. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  182629. #endif
  182630. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  182631. i=0;
  182632. do
  182633. {
  182634. if(user_png_ver[i] != png_libpng_ver[i])
  182635. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182636. } while (png_libpng_ver[i++]);
  182637. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  182638. {
  182639. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  182640. * we must recompile any applications that use any older library version.
  182641. * For versions after libpng 1.0, we will be compatible, so we need
  182642. * only check the first digit.
  182643. */
  182644. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  182645. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  182646. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  182647. {
  182648. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182649. char msg[80];
  182650. if (user_png_ver)
  182651. {
  182652. png_snprintf(msg, 80,
  182653. "Application was compiled with png.h from libpng-%.20s",
  182654. user_png_ver);
  182655. png_warning(png_ptr, msg);
  182656. }
  182657. png_snprintf(msg, 80,
  182658. "Application is running with png.c from libpng-%.20s",
  182659. png_libpng_ver);
  182660. png_warning(png_ptr, msg);
  182661. #endif
  182662. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182663. png_ptr->flags=0;
  182664. #endif
  182665. png_error(png_ptr,
  182666. "Incompatible libpng version in application and library");
  182667. }
  182668. }
  182669. /* initialize zbuf - compression buffer */
  182670. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182671. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182672. (png_uint_32)png_ptr->zbuf_size);
  182673. png_ptr->zstream.zalloc = png_zalloc;
  182674. png_ptr->zstream.zfree = png_zfree;
  182675. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182676. switch (inflateInit(&png_ptr->zstream))
  182677. {
  182678. case Z_OK: /* Do nothing */ break;
  182679. case Z_MEM_ERROR:
  182680. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  182681. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  182682. default: png_error(png_ptr, "Unknown zlib error");
  182683. }
  182684. png_ptr->zstream.next_out = png_ptr->zbuf;
  182685. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182686. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182687. #ifdef PNG_SETJMP_SUPPORTED
  182688. /* Applications that neglect to set up their own setjmp() and then encounter
  182689. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  182690. abort instead of returning. */
  182691. #ifdef USE_FAR_KEYWORD
  182692. if (setjmp(jmpbuf))
  182693. PNG_ABORT();
  182694. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  182695. #else
  182696. if (setjmp(png_ptr->jmpbuf))
  182697. PNG_ABORT();
  182698. #endif
  182699. #endif
  182700. return (png_ptr);
  182701. }
  182702. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  182703. /* Initialize PNG structure for reading, and allocate any memory needed.
  182704. This interface is deprecated in favour of the png_create_read_struct(),
  182705. and it will disappear as of libpng-1.3.0. */
  182706. #undef png_read_init
  182707. void PNGAPI
  182708. png_read_init(png_structp png_ptr)
  182709. {
  182710. /* We only come here via pre-1.0.7-compiled applications */
  182711. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  182712. }
  182713. void PNGAPI
  182714. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  182715. png_size_t png_struct_size, png_size_t png_info_size)
  182716. {
  182717. /* We only come here via pre-1.0.12-compiled applications */
  182718. if(png_ptr == NULL) return;
  182719. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  182720. if(png_sizeof(png_struct) > png_struct_size ||
  182721. png_sizeof(png_info) > png_info_size)
  182722. {
  182723. char msg[80];
  182724. png_ptr->warning_fn=NULL;
  182725. if (user_png_ver)
  182726. {
  182727. png_snprintf(msg, 80,
  182728. "Application was compiled with png.h from libpng-%.20s",
  182729. user_png_ver);
  182730. png_warning(png_ptr, msg);
  182731. }
  182732. png_snprintf(msg, 80,
  182733. "Application is running with png.c from libpng-%.20s",
  182734. png_libpng_ver);
  182735. png_warning(png_ptr, msg);
  182736. }
  182737. #endif
  182738. if(png_sizeof(png_struct) > png_struct_size)
  182739. {
  182740. png_ptr->error_fn=NULL;
  182741. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182742. png_ptr->flags=0;
  182743. #endif
  182744. png_error(png_ptr,
  182745. "The png struct allocated by the application for reading is too small.");
  182746. }
  182747. if(png_sizeof(png_info) > png_info_size)
  182748. {
  182749. png_ptr->error_fn=NULL;
  182750. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  182751. png_ptr->flags=0;
  182752. #endif
  182753. png_error(png_ptr,
  182754. "The info struct allocated by application for reading is too small.");
  182755. }
  182756. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  182757. }
  182758. #endif /* PNG_1_0_X || PNG_1_2_X */
  182759. void PNGAPI
  182760. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  182761. png_size_t png_struct_size)
  182762. {
  182763. #ifdef PNG_SETJMP_SUPPORTED
  182764. jmp_buf tmp_jmp; /* to save current jump buffer */
  182765. #endif
  182766. int i=0;
  182767. png_structp png_ptr=*ptr_ptr;
  182768. if(png_ptr == NULL) return;
  182769. do
  182770. {
  182771. if(user_png_ver[i] != png_libpng_ver[i])
  182772. {
  182773. #ifdef PNG_LEGACY_SUPPORTED
  182774. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  182775. #else
  182776. png_ptr->warning_fn=NULL;
  182777. png_warning(png_ptr,
  182778. "Application uses deprecated png_read_init() and should be recompiled.");
  182779. break;
  182780. #endif
  182781. }
  182782. } while (png_libpng_ver[i++]);
  182783. png_debug(1, "in png_read_init_3\n");
  182784. #ifdef PNG_SETJMP_SUPPORTED
  182785. /* save jump buffer and error functions */
  182786. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  182787. #endif
  182788. if(png_sizeof(png_struct) > png_struct_size)
  182789. {
  182790. png_destroy_struct(png_ptr);
  182791. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  182792. png_ptr = *ptr_ptr;
  182793. }
  182794. /* reset all variables to 0 */
  182795. png_memset(png_ptr, 0, png_sizeof (png_struct));
  182796. #ifdef PNG_SETJMP_SUPPORTED
  182797. /* restore jump buffer */
  182798. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  182799. #endif
  182800. /* added at libpng-1.2.6 */
  182801. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182802. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  182803. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  182804. #endif
  182805. /* initialize zbuf - compression buffer */
  182806. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  182807. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  182808. (png_uint_32)png_ptr->zbuf_size);
  182809. png_ptr->zstream.zalloc = png_zalloc;
  182810. png_ptr->zstream.zfree = png_zfree;
  182811. png_ptr->zstream.opaque = (voidpf)png_ptr;
  182812. switch (inflateInit(&png_ptr->zstream))
  182813. {
  182814. case Z_OK: /* Do nothing */ break;
  182815. case Z_MEM_ERROR:
  182816. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  182817. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  182818. default: png_error(png_ptr, "Unknown zlib error");
  182819. }
  182820. png_ptr->zstream.next_out = png_ptr->zbuf;
  182821. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182822. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  182823. }
  182824. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182825. /* Read the information before the actual image data. This has been
  182826. * changed in v0.90 to allow reading a file that already has the magic
  182827. * bytes read from the stream. You can tell libpng how many bytes have
  182828. * been read from the beginning of the stream (up to the maximum of 8)
  182829. * via png_set_sig_bytes(), and we will only check the remaining bytes
  182830. * here. The application can then have access to the signature bytes we
  182831. * read if it is determined that this isn't a valid PNG file.
  182832. */
  182833. void PNGAPI
  182834. png_read_info(png_structp png_ptr, png_infop info_ptr)
  182835. {
  182836. if(png_ptr == NULL) return;
  182837. png_debug(1, "in png_read_info\n");
  182838. /* If we haven't checked all of the PNG signature bytes, do so now. */
  182839. if (png_ptr->sig_bytes < 8)
  182840. {
  182841. png_size_t num_checked = png_ptr->sig_bytes,
  182842. num_to_check = 8 - num_checked;
  182843. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  182844. png_ptr->sig_bytes = 8;
  182845. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  182846. {
  182847. if (num_checked < 4 &&
  182848. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  182849. png_error(png_ptr, "Not a PNG file");
  182850. else
  182851. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  182852. }
  182853. if (num_checked < 3)
  182854. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  182855. }
  182856. for(;;)
  182857. {
  182858. #ifdef PNG_USE_LOCAL_ARRAYS
  182859. PNG_CONST PNG_IHDR;
  182860. PNG_CONST PNG_IDAT;
  182861. PNG_CONST PNG_IEND;
  182862. PNG_CONST PNG_PLTE;
  182863. #if defined(PNG_READ_bKGD_SUPPORTED)
  182864. PNG_CONST PNG_bKGD;
  182865. #endif
  182866. #if defined(PNG_READ_cHRM_SUPPORTED)
  182867. PNG_CONST PNG_cHRM;
  182868. #endif
  182869. #if defined(PNG_READ_gAMA_SUPPORTED)
  182870. PNG_CONST PNG_gAMA;
  182871. #endif
  182872. #if defined(PNG_READ_hIST_SUPPORTED)
  182873. PNG_CONST PNG_hIST;
  182874. #endif
  182875. #if defined(PNG_READ_iCCP_SUPPORTED)
  182876. PNG_CONST PNG_iCCP;
  182877. #endif
  182878. #if defined(PNG_READ_iTXt_SUPPORTED)
  182879. PNG_CONST PNG_iTXt;
  182880. #endif
  182881. #if defined(PNG_READ_oFFs_SUPPORTED)
  182882. PNG_CONST PNG_oFFs;
  182883. #endif
  182884. #if defined(PNG_READ_pCAL_SUPPORTED)
  182885. PNG_CONST PNG_pCAL;
  182886. #endif
  182887. #if defined(PNG_READ_pHYs_SUPPORTED)
  182888. PNG_CONST PNG_pHYs;
  182889. #endif
  182890. #if defined(PNG_READ_sBIT_SUPPORTED)
  182891. PNG_CONST PNG_sBIT;
  182892. #endif
  182893. #if defined(PNG_READ_sCAL_SUPPORTED)
  182894. PNG_CONST PNG_sCAL;
  182895. #endif
  182896. #if defined(PNG_READ_sPLT_SUPPORTED)
  182897. PNG_CONST PNG_sPLT;
  182898. #endif
  182899. #if defined(PNG_READ_sRGB_SUPPORTED)
  182900. PNG_CONST PNG_sRGB;
  182901. #endif
  182902. #if defined(PNG_READ_tEXt_SUPPORTED)
  182903. PNG_CONST PNG_tEXt;
  182904. #endif
  182905. #if defined(PNG_READ_tIME_SUPPORTED)
  182906. PNG_CONST PNG_tIME;
  182907. #endif
  182908. #if defined(PNG_READ_tRNS_SUPPORTED)
  182909. PNG_CONST PNG_tRNS;
  182910. #endif
  182911. #if defined(PNG_READ_zTXt_SUPPORTED)
  182912. PNG_CONST PNG_zTXt;
  182913. #endif
  182914. #endif /* PNG_USE_LOCAL_ARRAYS */
  182915. png_byte chunk_length[4];
  182916. png_uint_32 length;
  182917. png_read_data(png_ptr, chunk_length, 4);
  182918. length = png_get_uint_31(png_ptr,chunk_length);
  182919. png_reset_crc(png_ptr);
  182920. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182921. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  182922. length);
  182923. /* This should be a binary subdivision search or a hash for
  182924. * matching the chunk name rather than a linear search.
  182925. */
  182926. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182927. if(png_ptr->mode & PNG_AFTER_IDAT)
  182928. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  182929. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  182930. png_handle_IHDR(png_ptr, info_ptr, length);
  182931. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  182932. png_handle_IEND(png_ptr, info_ptr, length);
  182933. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182934. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  182935. {
  182936. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182937. png_ptr->mode |= PNG_HAVE_IDAT;
  182938. png_handle_unknown(png_ptr, info_ptr, length);
  182939. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182940. png_ptr->mode |= PNG_HAVE_PLTE;
  182941. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182942. {
  182943. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182944. png_error(png_ptr, "Missing IHDR before IDAT");
  182945. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182946. !(png_ptr->mode & PNG_HAVE_PLTE))
  182947. png_error(png_ptr, "Missing PLTE before IDAT");
  182948. break;
  182949. }
  182950. }
  182951. #endif
  182952. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  182953. png_handle_PLTE(png_ptr, info_ptr, length);
  182954. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182955. {
  182956. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  182957. png_error(png_ptr, "Missing IHDR before IDAT");
  182958. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  182959. !(png_ptr->mode & PNG_HAVE_PLTE))
  182960. png_error(png_ptr, "Missing PLTE before IDAT");
  182961. png_ptr->idat_size = length;
  182962. png_ptr->mode |= PNG_HAVE_IDAT;
  182963. break;
  182964. }
  182965. #if defined(PNG_READ_bKGD_SUPPORTED)
  182966. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182967. png_handle_bKGD(png_ptr, info_ptr, length);
  182968. #endif
  182969. #if defined(PNG_READ_cHRM_SUPPORTED)
  182970. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  182971. png_handle_cHRM(png_ptr, info_ptr, length);
  182972. #endif
  182973. #if defined(PNG_READ_gAMA_SUPPORTED)
  182974. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  182975. png_handle_gAMA(png_ptr, info_ptr, length);
  182976. #endif
  182977. #if defined(PNG_READ_hIST_SUPPORTED)
  182978. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182979. png_handle_hIST(png_ptr, info_ptr, length);
  182980. #endif
  182981. #if defined(PNG_READ_oFFs_SUPPORTED)
  182982. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182983. png_handle_oFFs(png_ptr, info_ptr, length);
  182984. #endif
  182985. #if defined(PNG_READ_pCAL_SUPPORTED)
  182986. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182987. png_handle_pCAL(png_ptr, info_ptr, length);
  182988. #endif
  182989. #if defined(PNG_READ_sCAL_SUPPORTED)
  182990. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182991. png_handle_sCAL(png_ptr, info_ptr, length);
  182992. #endif
  182993. #if defined(PNG_READ_pHYs_SUPPORTED)
  182994. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182995. png_handle_pHYs(png_ptr, info_ptr, length);
  182996. #endif
  182997. #if defined(PNG_READ_sBIT_SUPPORTED)
  182998. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  182999. png_handle_sBIT(png_ptr, info_ptr, length);
  183000. #endif
  183001. #if defined(PNG_READ_sRGB_SUPPORTED)
  183002. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183003. png_handle_sRGB(png_ptr, info_ptr, length);
  183004. #endif
  183005. #if defined(PNG_READ_iCCP_SUPPORTED)
  183006. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183007. png_handle_iCCP(png_ptr, info_ptr, length);
  183008. #endif
  183009. #if defined(PNG_READ_sPLT_SUPPORTED)
  183010. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183011. png_handle_sPLT(png_ptr, info_ptr, length);
  183012. #endif
  183013. #if defined(PNG_READ_tEXt_SUPPORTED)
  183014. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183015. png_handle_tEXt(png_ptr, info_ptr, length);
  183016. #endif
  183017. #if defined(PNG_READ_tIME_SUPPORTED)
  183018. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183019. png_handle_tIME(png_ptr, info_ptr, length);
  183020. #endif
  183021. #if defined(PNG_READ_tRNS_SUPPORTED)
  183022. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183023. png_handle_tRNS(png_ptr, info_ptr, length);
  183024. #endif
  183025. #if defined(PNG_READ_zTXt_SUPPORTED)
  183026. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183027. png_handle_zTXt(png_ptr, info_ptr, length);
  183028. #endif
  183029. #if defined(PNG_READ_iTXt_SUPPORTED)
  183030. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183031. png_handle_iTXt(png_ptr, info_ptr, length);
  183032. #endif
  183033. else
  183034. png_handle_unknown(png_ptr, info_ptr, length);
  183035. }
  183036. }
  183037. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183038. /* optional call to update the users info_ptr structure */
  183039. void PNGAPI
  183040. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  183041. {
  183042. png_debug(1, "in png_read_update_info\n");
  183043. if(png_ptr == NULL) return;
  183044. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183045. png_read_start_row(png_ptr);
  183046. else
  183047. png_warning(png_ptr,
  183048. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  183049. png_read_transform_info(png_ptr, info_ptr);
  183050. }
  183051. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183052. /* Initialize palette, background, etc, after transformations
  183053. * are set, but before any reading takes place. This allows
  183054. * the user to obtain a gamma-corrected palette, for example.
  183055. * If the user doesn't call this, we will do it ourselves.
  183056. */
  183057. void PNGAPI
  183058. png_start_read_image(png_structp png_ptr)
  183059. {
  183060. png_debug(1, "in png_start_read_image\n");
  183061. if(png_ptr == NULL) return;
  183062. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183063. png_read_start_row(png_ptr);
  183064. }
  183065. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183066. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183067. void PNGAPI
  183068. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  183069. {
  183070. #ifdef PNG_USE_LOCAL_ARRAYS
  183071. PNG_CONST PNG_IDAT;
  183072. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  183073. 0xff};
  183074. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  183075. #endif
  183076. int ret;
  183077. if(png_ptr == NULL) return;
  183078. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  183079. png_ptr->row_number, png_ptr->pass);
  183080. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  183081. png_read_start_row(png_ptr);
  183082. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  183083. {
  183084. /* check for transforms that have been set but were defined out */
  183085. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  183086. if (png_ptr->transformations & PNG_INVERT_MONO)
  183087. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  183088. #endif
  183089. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  183090. if (png_ptr->transformations & PNG_FILLER)
  183091. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  183092. #endif
  183093. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  183094. if (png_ptr->transformations & PNG_PACKSWAP)
  183095. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  183096. #endif
  183097. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  183098. if (png_ptr->transformations & PNG_PACK)
  183099. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  183100. #endif
  183101. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  183102. if (png_ptr->transformations & PNG_SHIFT)
  183103. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  183104. #endif
  183105. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  183106. if (png_ptr->transformations & PNG_BGR)
  183107. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  183108. #endif
  183109. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  183110. if (png_ptr->transformations & PNG_SWAP_BYTES)
  183111. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  183112. #endif
  183113. }
  183114. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183115. /* if interlaced and we do not need a new row, combine row and return */
  183116. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  183117. {
  183118. switch (png_ptr->pass)
  183119. {
  183120. case 0:
  183121. if (png_ptr->row_number & 0x07)
  183122. {
  183123. if (dsp_row != NULL)
  183124. png_combine_row(png_ptr, dsp_row,
  183125. png_pass_dsp_mask[png_ptr->pass]);
  183126. png_read_finish_row(png_ptr);
  183127. return;
  183128. }
  183129. break;
  183130. case 1:
  183131. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  183132. {
  183133. if (dsp_row != NULL)
  183134. png_combine_row(png_ptr, dsp_row,
  183135. png_pass_dsp_mask[png_ptr->pass]);
  183136. png_read_finish_row(png_ptr);
  183137. return;
  183138. }
  183139. break;
  183140. case 2:
  183141. if ((png_ptr->row_number & 0x07) != 4)
  183142. {
  183143. if (dsp_row != NULL && (png_ptr->row_number & 4))
  183144. png_combine_row(png_ptr, dsp_row,
  183145. png_pass_dsp_mask[png_ptr->pass]);
  183146. png_read_finish_row(png_ptr);
  183147. return;
  183148. }
  183149. break;
  183150. case 3:
  183151. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  183152. {
  183153. if (dsp_row != NULL)
  183154. png_combine_row(png_ptr, dsp_row,
  183155. png_pass_dsp_mask[png_ptr->pass]);
  183156. png_read_finish_row(png_ptr);
  183157. return;
  183158. }
  183159. break;
  183160. case 4:
  183161. if ((png_ptr->row_number & 3) != 2)
  183162. {
  183163. if (dsp_row != NULL && (png_ptr->row_number & 2))
  183164. png_combine_row(png_ptr, dsp_row,
  183165. png_pass_dsp_mask[png_ptr->pass]);
  183166. png_read_finish_row(png_ptr);
  183167. return;
  183168. }
  183169. break;
  183170. case 5:
  183171. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  183172. {
  183173. if (dsp_row != NULL)
  183174. png_combine_row(png_ptr, dsp_row,
  183175. png_pass_dsp_mask[png_ptr->pass]);
  183176. png_read_finish_row(png_ptr);
  183177. return;
  183178. }
  183179. break;
  183180. case 6:
  183181. if (!(png_ptr->row_number & 1))
  183182. {
  183183. png_read_finish_row(png_ptr);
  183184. return;
  183185. }
  183186. break;
  183187. }
  183188. }
  183189. #endif
  183190. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  183191. png_error(png_ptr, "Invalid attempt to read row data");
  183192. png_ptr->zstream.next_out = png_ptr->row_buf;
  183193. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  183194. do
  183195. {
  183196. if (!(png_ptr->zstream.avail_in))
  183197. {
  183198. while (!png_ptr->idat_size)
  183199. {
  183200. png_byte chunk_length[4];
  183201. png_crc_finish(png_ptr, 0);
  183202. png_read_data(png_ptr, chunk_length, 4);
  183203. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  183204. png_reset_crc(png_ptr);
  183205. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183206. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183207. png_error(png_ptr, "Not enough image data");
  183208. }
  183209. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  183210. png_ptr->zstream.next_in = png_ptr->zbuf;
  183211. if (png_ptr->zbuf_size > png_ptr->idat_size)
  183212. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  183213. png_crc_read(png_ptr, png_ptr->zbuf,
  183214. (png_size_t)png_ptr->zstream.avail_in);
  183215. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  183216. }
  183217. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  183218. if (ret == Z_STREAM_END)
  183219. {
  183220. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  183221. png_ptr->idat_size)
  183222. png_error(png_ptr, "Extra compressed data");
  183223. png_ptr->mode |= PNG_AFTER_IDAT;
  183224. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  183225. break;
  183226. }
  183227. if (ret != Z_OK)
  183228. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  183229. "Decompression error");
  183230. } while (png_ptr->zstream.avail_out);
  183231. png_ptr->row_info.color_type = png_ptr->color_type;
  183232. png_ptr->row_info.width = png_ptr->iwidth;
  183233. png_ptr->row_info.channels = png_ptr->channels;
  183234. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  183235. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  183236. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  183237. png_ptr->row_info.width);
  183238. if(png_ptr->row_buf[0])
  183239. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  183240. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  183241. (int)(png_ptr->row_buf[0]));
  183242. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  183243. png_ptr->rowbytes + 1);
  183244. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183245. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  183246. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  183247. {
  183248. /* Intrapixel differencing */
  183249. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  183250. }
  183251. #endif
  183252. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  183253. png_do_read_transformations(png_ptr);
  183254. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  183255. /* blow up interlaced rows to full size */
  183256. if (png_ptr->interlaced &&
  183257. (png_ptr->transformations & PNG_INTERLACE))
  183258. {
  183259. if (png_ptr->pass < 6)
  183260. /* old interface (pre-1.0.9):
  183261. png_do_read_interlace(&(png_ptr->row_info),
  183262. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  183263. */
  183264. png_do_read_interlace(png_ptr);
  183265. if (dsp_row != NULL)
  183266. png_combine_row(png_ptr, dsp_row,
  183267. png_pass_dsp_mask[png_ptr->pass]);
  183268. if (row != NULL)
  183269. png_combine_row(png_ptr, row,
  183270. png_pass_mask[png_ptr->pass]);
  183271. }
  183272. else
  183273. #endif
  183274. {
  183275. if (row != NULL)
  183276. png_combine_row(png_ptr, row, 0xff);
  183277. if (dsp_row != NULL)
  183278. png_combine_row(png_ptr, dsp_row, 0xff);
  183279. }
  183280. png_read_finish_row(png_ptr);
  183281. if (png_ptr->read_row_fn != NULL)
  183282. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  183283. }
  183284. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183285. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183286. /* Read one or more rows of image data. If the image is interlaced,
  183287. * and png_set_interlace_handling() has been called, the rows need to
  183288. * contain the contents of the rows from the previous pass. If the
  183289. * image has alpha or transparency, and png_handle_alpha()[*] has been
  183290. * called, the rows contents must be initialized to the contents of the
  183291. * screen.
  183292. *
  183293. * "row" holds the actual image, and pixels are placed in it
  183294. * as they arrive. If the image is displayed after each pass, it will
  183295. * appear to "sparkle" in. "display_row" can be used to display a
  183296. * "chunky" progressive image, with finer detail added as it becomes
  183297. * available. If you do not want this "chunky" display, you may pass
  183298. * NULL for display_row. If you do not want the sparkle display, and
  183299. * you have not called png_handle_alpha(), you may pass NULL for rows.
  183300. * If you have called png_handle_alpha(), and the image has either an
  183301. * alpha channel or a transparency chunk, you must provide a buffer for
  183302. * rows. In this case, you do not have to provide a display_row buffer
  183303. * also, but you may. If the image is not interlaced, or if you have
  183304. * not called png_set_interlace_handling(), the display_row buffer will
  183305. * be ignored, so pass NULL to it.
  183306. *
  183307. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183308. */
  183309. void PNGAPI
  183310. png_read_rows(png_structp png_ptr, png_bytepp row,
  183311. png_bytepp display_row, png_uint_32 num_rows)
  183312. {
  183313. png_uint_32 i;
  183314. png_bytepp rp;
  183315. png_bytepp dp;
  183316. png_debug(1, "in png_read_rows\n");
  183317. if(png_ptr == NULL) return;
  183318. rp = row;
  183319. dp = display_row;
  183320. if (rp != NULL && dp != NULL)
  183321. for (i = 0; i < num_rows; i++)
  183322. {
  183323. png_bytep rptr = *rp++;
  183324. png_bytep dptr = *dp++;
  183325. png_read_row(png_ptr, rptr, dptr);
  183326. }
  183327. else if(rp != NULL)
  183328. for (i = 0; i < num_rows; i++)
  183329. {
  183330. png_bytep rptr = *rp;
  183331. png_read_row(png_ptr, rptr, png_bytep_NULL);
  183332. rp++;
  183333. }
  183334. else if(dp != NULL)
  183335. for (i = 0; i < num_rows; i++)
  183336. {
  183337. png_bytep dptr = *dp;
  183338. png_read_row(png_ptr, png_bytep_NULL, dptr);
  183339. dp++;
  183340. }
  183341. }
  183342. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183343. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183344. /* Read the entire image. If the image has an alpha channel or a tRNS
  183345. * chunk, and you have called png_handle_alpha()[*], you will need to
  183346. * initialize the image to the current image that PNG will be overlaying.
  183347. * We set the num_rows again here, in case it was incorrectly set in
  183348. * png_read_start_row() by a call to png_read_update_info() or
  183349. * png_start_read_image() if png_set_interlace_handling() wasn't called
  183350. * prior to either of these functions like it should have been. You can
  183351. * only call this function once. If you desire to have an image for
  183352. * each pass of a interlaced image, use png_read_rows() instead.
  183353. *
  183354. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  183355. */
  183356. void PNGAPI
  183357. png_read_image(png_structp png_ptr, png_bytepp image)
  183358. {
  183359. png_uint_32 i,image_height;
  183360. int pass, j;
  183361. png_bytepp rp;
  183362. png_debug(1, "in png_read_image\n");
  183363. if(png_ptr == NULL) return;
  183364. #ifdef PNG_READ_INTERLACING_SUPPORTED
  183365. pass = png_set_interlace_handling(png_ptr);
  183366. #else
  183367. if (png_ptr->interlaced)
  183368. png_error(png_ptr,
  183369. "Cannot read interlaced image -- interlace handler disabled.");
  183370. pass = 1;
  183371. #endif
  183372. image_height=png_ptr->height;
  183373. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  183374. for (j = 0; j < pass; j++)
  183375. {
  183376. rp = image;
  183377. for (i = 0; i < image_height; i++)
  183378. {
  183379. png_read_row(png_ptr, *rp, png_bytep_NULL);
  183380. rp++;
  183381. }
  183382. }
  183383. }
  183384. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183385. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183386. /* Read the end of the PNG file. Will not read past the end of the
  183387. * file, will verify the end is accurate, and will read any comments
  183388. * or time information at the end of the file, if info is not NULL.
  183389. */
  183390. void PNGAPI
  183391. png_read_end(png_structp png_ptr, png_infop info_ptr)
  183392. {
  183393. png_byte chunk_length[4];
  183394. png_uint_32 length;
  183395. png_debug(1, "in png_read_end\n");
  183396. if(png_ptr == NULL) return;
  183397. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  183398. do
  183399. {
  183400. #ifdef PNG_USE_LOCAL_ARRAYS
  183401. PNG_CONST PNG_IHDR;
  183402. PNG_CONST PNG_IDAT;
  183403. PNG_CONST PNG_IEND;
  183404. PNG_CONST PNG_PLTE;
  183405. #if defined(PNG_READ_bKGD_SUPPORTED)
  183406. PNG_CONST PNG_bKGD;
  183407. #endif
  183408. #if defined(PNG_READ_cHRM_SUPPORTED)
  183409. PNG_CONST PNG_cHRM;
  183410. #endif
  183411. #if defined(PNG_READ_gAMA_SUPPORTED)
  183412. PNG_CONST PNG_gAMA;
  183413. #endif
  183414. #if defined(PNG_READ_hIST_SUPPORTED)
  183415. PNG_CONST PNG_hIST;
  183416. #endif
  183417. #if defined(PNG_READ_iCCP_SUPPORTED)
  183418. PNG_CONST PNG_iCCP;
  183419. #endif
  183420. #if defined(PNG_READ_iTXt_SUPPORTED)
  183421. PNG_CONST PNG_iTXt;
  183422. #endif
  183423. #if defined(PNG_READ_oFFs_SUPPORTED)
  183424. PNG_CONST PNG_oFFs;
  183425. #endif
  183426. #if defined(PNG_READ_pCAL_SUPPORTED)
  183427. PNG_CONST PNG_pCAL;
  183428. #endif
  183429. #if defined(PNG_READ_pHYs_SUPPORTED)
  183430. PNG_CONST PNG_pHYs;
  183431. #endif
  183432. #if defined(PNG_READ_sBIT_SUPPORTED)
  183433. PNG_CONST PNG_sBIT;
  183434. #endif
  183435. #if defined(PNG_READ_sCAL_SUPPORTED)
  183436. PNG_CONST PNG_sCAL;
  183437. #endif
  183438. #if defined(PNG_READ_sPLT_SUPPORTED)
  183439. PNG_CONST PNG_sPLT;
  183440. #endif
  183441. #if defined(PNG_READ_sRGB_SUPPORTED)
  183442. PNG_CONST PNG_sRGB;
  183443. #endif
  183444. #if defined(PNG_READ_tEXt_SUPPORTED)
  183445. PNG_CONST PNG_tEXt;
  183446. #endif
  183447. #if defined(PNG_READ_tIME_SUPPORTED)
  183448. PNG_CONST PNG_tIME;
  183449. #endif
  183450. #if defined(PNG_READ_tRNS_SUPPORTED)
  183451. PNG_CONST PNG_tRNS;
  183452. #endif
  183453. #if defined(PNG_READ_zTXt_SUPPORTED)
  183454. PNG_CONST PNG_zTXt;
  183455. #endif
  183456. #endif /* PNG_USE_LOCAL_ARRAYS */
  183457. png_read_data(png_ptr, chunk_length, 4);
  183458. length = png_get_uint_31(png_ptr,chunk_length);
  183459. png_reset_crc(png_ptr);
  183460. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  183461. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  183462. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  183463. png_handle_IHDR(png_ptr, info_ptr, length);
  183464. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  183465. png_handle_IEND(png_ptr, info_ptr, length);
  183466. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183467. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  183468. {
  183469. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183470. {
  183471. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183472. png_error(png_ptr, "Too many IDAT's found");
  183473. }
  183474. png_handle_unknown(png_ptr, info_ptr, length);
  183475. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183476. png_ptr->mode |= PNG_HAVE_PLTE;
  183477. }
  183478. #endif
  183479. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  183480. {
  183481. /* Zero length IDATs are legal after the last IDAT has been
  183482. * read, but not after other chunks have been read.
  183483. */
  183484. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  183485. png_error(png_ptr, "Too many IDAT's found");
  183486. png_crc_finish(png_ptr, length);
  183487. }
  183488. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  183489. png_handle_PLTE(png_ptr, info_ptr, length);
  183490. #if defined(PNG_READ_bKGD_SUPPORTED)
  183491. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  183492. png_handle_bKGD(png_ptr, info_ptr, length);
  183493. #endif
  183494. #if defined(PNG_READ_cHRM_SUPPORTED)
  183495. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  183496. png_handle_cHRM(png_ptr, info_ptr, length);
  183497. #endif
  183498. #if defined(PNG_READ_gAMA_SUPPORTED)
  183499. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  183500. png_handle_gAMA(png_ptr, info_ptr, length);
  183501. #endif
  183502. #if defined(PNG_READ_hIST_SUPPORTED)
  183503. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  183504. png_handle_hIST(png_ptr, info_ptr, length);
  183505. #endif
  183506. #if defined(PNG_READ_oFFs_SUPPORTED)
  183507. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  183508. png_handle_oFFs(png_ptr, info_ptr, length);
  183509. #endif
  183510. #if defined(PNG_READ_pCAL_SUPPORTED)
  183511. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  183512. png_handle_pCAL(png_ptr, info_ptr, length);
  183513. #endif
  183514. #if defined(PNG_READ_sCAL_SUPPORTED)
  183515. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  183516. png_handle_sCAL(png_ptr, info_ptr, length);
  183517. #endif
  183518. #if defined(PNG_READ_pHYs_SUPPORTED)
  183519. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  183520. png_handle_pHYs(png_ptr, info_ptr, length);
  183521. #endif
  183522. #if defined(PNG_READ_sBIT_SUPPORTED)
  183523. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  183524. png_handle_sBIT(png_ptr, info_ptr, length);
  183525. #endif
  183526. #if defined(PNG_READ_sRGB_SUPPORTED)
  183527. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  183528. png_handle_sRGB(png_ptr, info_ptr, length);
  183529. #endif
  183530. #if defined(PNG_READ_iCCP_SUPPORTED)
  183531. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  183532. png_handle_iCCP(png_ptr, info_ptr, length);
  183533. #endif
  183534. #if defined(PNG_READ_sPLT_SUPPORTED)
  183535. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  183536. png_handle_sPLT(png_ptr, info_ptr, length);
  183537. #endif
  183538. #if defined(PNG_READ_tEXt_SUPPORTED)
  183539. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  183540. png_handle_tEXt(png_ptr, info_ptr, length);
  183541. #endif
  183542. #if defined(PNG_READ_tIME_SUPPORTED)
  183543. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  183544. png_handle_tIME(png_ptr, info_ptr, length);
  183545. #endif
  183546. #if defined(PNG_READ_tRNS_SUPPORTED)
  183547. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  183548. png_handle_tRNS(png_ptr, info_ptr, length);
  183549. #endif
  183550. #if defined(PNG_READ_zTXt_SUPPORTED)
  183551. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  183552. png_handle_zTXt(png_ptr, info_ptr, length);
  183553. #endif
  183554. #if defined(PNG_READ_iTXt_SUPPORTED)
  183555. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  183556. png_handle_iTXt(png_ptr, info_ptr, length);
  183557. #endif
  183558. else
  183559. png_handle_unknown(png_ptr, info_ptr, length);
  183560. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  183561. }
  183562. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183563. /* free all memory used by the read */
  183564. void PNGAPI
  183565. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  183566. png_infopp end_info_ptr_ptr)
  183567. {
  183568. png_structp png_ptr = NULL;
  183569. png_infop info_ptr = NULL, end_info_ptr = NULL;
  183570. #ifdef PNG_USER_MEM_SUPPORTED
  183571. png_free_ptr free_fn;
  183572. png_voidp mem_ptr;
  183573. #endif
  183574. png_debug(1, "in png_destroy_read_struct\n");
  183575. if (png_ptr_ptr != NULL)
  183576. png_ptr = *png_ptr_ptr;
  183577. if (info_ptr_ptr != NULL)
  183578. info_ptr = *info_ptr_ptr;
  183579. if (end_info_ptr_ptr != NULL)
  183580. end_info_ptr = *end_info_ptr_ptr;
  183581. #ifdef PNG_USER_MEM_SUPPORTED
  183582. free_fn = png_ptr->free_fn;
  183583. mem_ptr = png_ptr->mem_ptr;
  183584. #endif
  183585. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  183586. if (info_ptr != NULL)
  183587. {
  183588. #if defined(PNG_TEXT_SUPPORTED)
  183589. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  183590. #endif
  183591. #ifdef PNG_USER_MEM_SUPPORTED
  183592. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  183593. (png_voidp)mem_ptr);
  183594. #else
  183595. png_destroy_struct((png_voidp)info_ptr);
  183596. #endif
  183597. *info_ptr_ptr = NULL;
  183598. }
  183599. if (end_info_ptr != NULL)
  183600. {
  183601. #if defined(PNG_READ_TEXT_SUPPORTED)
  183602. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  183603. #endif
  183604. #ifdef PNG_USER_MEM_SUPPORTED
  183605. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  183606. (png_voidp)mem_ptr);
  183607. #else
  183608. png_destroy_struct((png_voidp)end_info_ptr);
  183609. #endif
  183610. *end_info_ptr_ptr = NULL;
  183611. }
  183612. if (png_ptr != NULL)
  183613. {
  183614. #ifdef PNG_USER_MEM_SUPPORTED
  183615. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  183616. (png_voidp)mem_ptr);
  183617. #else
  183618. png_destroy_struct((png_voidp)png_ptr);
  183619. #endif
  183620. *png_ptr_ptr = NULL;
  183621. }
  183622. }
  183623. /* free all memory used by the read (old method) */
  183624. void /* PRIVATE */
  183625. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  183626. {
  183627. #ifdef PNG_SETJMP_SUPPORTED
  183628. jmp_buf tmp_jmp;
  183629. #endif
  183630. png_error_ptr error_fn;
  183631. png_error_ptr warning_fn;
  183632. png_voidp error_ptr;
  183633. #ifdef PNG_USER_MEM_SUPPORTED
  183634. png_free_ptr free_fn;
  183635. #endif
  183636. png_debug(1, "in png_read_destroy\n");
  183637. if (info_ptr != NULL)
  183638. png_info_destroy(png_ptr, info_ptr);
  183639. if (end_info_ptr != NULL)
  183640. png_info_destroy(png_ptr, end_info_ptr);
  183641. png_free(png_ptr, png_ptr->zbuf);
  183642. png_free(png_ptr, png_ptr->big_row_buf);
  183643. png_free(png_ptr, png_ptr->prev_row);
  183644. #if defined(PNG_READ_DITHER_SUPPORTED)
  183645. png_free(png_ptr, png_ptr->palette_lookup);
  183646. png_free(png_ptr, png_ptr->dither_index);
  183647. #endif
  183648. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183649. png_free(png_ptr, png_ptr->gamma_table);
  183650. #endif
  183651. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183652. png_free(png_ptr, png_ptr->gamma_from_1);
  183653. png_free(png_ptr, png_ptr->gamma_to_1);
  183654. #endif
  183655. #ifdef PNG_FREE_ME_SUPPORTED
  183656. if (png_ptr->free_me & PNG_FREE_PLTE)
  183657. png_zfree(png_ptr, png_ptr->palette);
  183658. png_ptr->free_me &= ~PNG_FREE_PLTE;
  183659. #else
  183660. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  183661. png_zfree(png_ptr, png_ptr->palette);
  183662. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  183663. #endif
  183664. #if defined(PNG_tRNS_SUPPORTED) || \
  183665. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183666. #ifdef PNG_FREE_ME_SUPPORTED
  183667. if (png_ptr->free_me & PNG_FREE_TRNS)
  183668. png_free(png_ptr, png_ptr->trans);
  183669. png_ptr->free_me &= ~PNG_FREE_TRNS;
  183670. #else
  183671. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  183672. png_free(png_ptr, png_ptr->trans);
  183673. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  183674. #endif
  183675. #endif
  183676. #if defined(PNG_READ_hIST_SUPPORTED)
  183677. #ifdef PNG_FREE_ME_SUPPORTED
  183678. if (png_ptr->free_me & PNG_FREE_HIST)
  183679. png_free(png_ptr, png_ptr->hist);
  183680. png_ptr->free_me &= ~PNG_FREE_HIST;
  183681. #else
  183682. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  183683. png_free(png_ptr, png_ptr->hist);
  183684. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  183685. #endif
  183686. #endif
  183687. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183688. if (png_ptr->gamma_16_table != NULL)
  183689. {
  183690. int i;
  183691. int istop = (1 << (8 - png_ptr->gamma_shift));
  183692. for (i = 0; i < istop; i++)
  183693. {
  183694. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  183695. }
  183696. png_free(png_ptr, png_ptr->gamma_16_table);
  183697. }
  183698. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183699. if (png_ptr->gamma_16_from_1 != NULL)
  183700. {
  183701. int i;
  183702. int istop = (1 << (8 - png_ptr->gamma_shift));
  183703. for (i = 0; i < istop; i++)
  183704. {
  183705. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  183706. }
  183707. png_free(png_ptr, png_ptr->gamma_16_from_1);
  183708. }
  183709. if (png_ptr->gamma_16_to_1 != NULL)
  183710. {
  183711. int i;
  183712. int istop = (1 << (8 - png_ptr->gamma_shift));
  183713. for (i = 0; i < istop; i++)
  183714. {
  183715. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  183716. }
  183717. png_free(png_ptr, png_ptr->gamma_16_to_1);
  183718. }
  183719. #endif
  183720. #endif
  183721. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183722. png_free(png_ptr, png_ptr->time_buffer);
  183723. #endif
  183724. inflateEnd(&png_ptr->zstream);
  183725. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183726. png_free(png_ptr, png_ptr->save_buffer);
  183727. #endif
  183728. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183729. #ifdef PNG_TEXT_SUPPORTED
  183730. png_free(png_ptr, png_ptr->current_text);
  183731. #endif /* PNG_TEXT_SUPPORTED */
  183732. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183733. /* Save the important info out of the png_struct, in case it is
  183734. * being used again.
  183735. */
  183736. #ifdef PNG_SETJMP_SUPPORTED
  183737. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  183738. #endif
  183739. error_fn = png_ptr->error_fn;
  183740. warning_fn = png_ptr->warning_fn;
  183741. error_ptr = png_ptr->error_ptr;
  183742. #ifdef PNG_USER_MEM_SUPPORTED
  183743. free_fn = png_ptr->free_fn;
  183744. #endif
  183745. png_memset(png_ptr, 0, png_sizeof (png_struct));
  183746. png_ptr->error_fn = error_fn;
  183747. png_ptr->warning_fn = warning_fn;
  183748. png_ptr->error_ptr = error_ptr;
  183749. #ifdef PNG_USER_MEM_SUPPORTED
  183750. png_ptr->free_fn = free_fn;
  183751. #endif
  183752. #ifdef PNG_SETJMP_SUPPORTED
  183753. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  183754. #endif
  183755. }
  183756. void PNGAPI
  183757. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  183758. {
  183759. if(png_ptr == NULL) return;
  183760. png_ptr->read_row_fn = read_row_fn;
  183761. }
  183762. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183763. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183764. void PNGAPI
  183765. png_read_png(png_structp png_ptr, png_infop info_ptr,
  183766. int transforms,
  183767. voidp params)
  183768. {
  183769. int row;
  183770. if(png_ptr == NULL) return;
  183771. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183772. /* invert the alpha channel from opacity to transparency
  183773. */
  183774. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  183775. png_set_invert_alpha(png_ptr);
  183776. #endif
  183777. /* png_read_info() gives us all of the information from the
  183778. * PNG file before the first IDAT (image data chunk).
  183779. */
  183780. png_read_info(png_ptr, info_ptr);
  183781. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  183782. png_error(png_ptr,"Image is too high to process with png_read_png()");
  183783. /* -------------- image transformations start here ------------------- */
  183784. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183785. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  183786. */
  183787. if (transforms & PNG_TRANSFORM_STRIP_16)
  183788. png_set_strip_16(png_ptr);
  183789. #endif
  183790. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183791. /* Strip alpha bytes from the input data without combining with
  183792. * the background (not recommended).
  183793. */
  183794. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  183795. png_set_strip_alpha(png_ptr);
  183796. #endif
  183797. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  183798. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  183799. * byte into separate bytes (useful for paletted and grayscale images).
  183800. */
  183801. if (transforms & PNG_TRANSFORM_PACKING)
  183802. png_set_packing(png_ptr);
  183803. #endif
  183804. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  183805. /* Change the order of packed pixels to least significant bit first
  183806. * (not useful if you are using png_set_packing).
  183807. */
  183808. if (transforms & PNG_TRANSFORM_PACKSWAP)
  183809. png_set_packswap(png_ptr);
  183810. #endif
  183811. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183812. /* Expand paletted colors into true RGB triplets
  183813. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  183814. * Expand paletted or RGB images with transparency to full alpha
  183815. * channels so the data will be available as RGBA quartets.
  183816. */
  183817. if (transforms & PNG_TRANSFORM_EXPAND)
  183818. if ((png_ptr->bit_depth < 8) ||
  183819. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  183820. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  183821. png_set_expand(png_ptr);
  183822. #endif
  183823. /* We don't handle background color or gamma transformation or dithering.
  183824. */
  183825. #if defined(PNG_READ_INVERT_SUPPORTED)
  183826. /* invert monochrome files to have 0 as white and 1 as black
  183827. */
  183828. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  183829. png_set_invert_mono(png_ptr);
  183830. #endif
  183831. #if defined(PNG_READ_SHIFT_SUPPORTED)
  183832. /* If you want to shift the pixel values from the range [0,255] or
  183833. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  183834. * colors were originally in:
  183835. */
  183836. if ((transforms & PNG_TRANSFORM_SHIFT)
  183837. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  183838. {
  183839. png_color_8p sig_bit;
  183840. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  183841. png_set_shift(png_ptr, sig_bit);
  183842. }
  183843. #endif
  183844. #if defined(PNG_READ_BGR_SUPPORTED)
  183845. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  183846. */
  183847. if (transforms & PNG_TRANSFORM_BGR)
  183848. png_set_bgr(png_ptr);
  183849. #endif
  183850. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  183851. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  183852. */
  183853. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  183854. png_set_swap_alpha(png_ptr);
  183855. #endif
  183856. #if defined(PNG_READ_SWAP_SUPPORTED)
  183857. /* swap bytes of 16 bit files to least significant byte first
  183858. */
  183859. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  183860. png_set_swap(png_ptr);
  183861. #endif
  183862. /* We don't handle adding filler bytes */
  183863. /* Optional call to gamma correct and add the background to the palette
  183864. * and update info structure. REQUIRED if you are expecting libpng to
  183865. * update the palette for you (i.e., you selected such a transform above).
  183866. */
  183867. png_read_update_info(png_ptr, info_ptr);
  183868. /* -------------- image transformations end here ------------------- */
  183869. #ifdef PNG_FREE_ME_SUPPORTED
  183870. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  183871. #endif
  183872. if(info_ptr->row_pointers == NULL)
  183873. {
  183874. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  183875. info_ptr->height * png_sizeof(png_bytep));
  183876. #ifdef PNG_FREE_ME_SUPPORTED
  183877. info_ptr->free_me |= PNG_FREE_ROWS;
  183878. #endif
  183879. for (row = 0; row < (int)info_ptr->height; row++)
  183880. {
  183881. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  183882. png_get_rowbytes(png_ptr, info_ptr));
  183883. }
  183884. }
  183885. png_read_image(png_ptr, info_ptr->row_pointers);
  183886. info_ptr->valid |= PNG_INFO_IDAT;
  183887. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  183888. png_read_end(png_ptr, info_ptr);
  183889. transforms = transforms; /* quiet compiler warnings */
  183890. params = params;
  183891. }
  183892. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  183893. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  183894. #endif /* PNG_READ_SUPPORTED */
  183895. /********* End of inlined file: pngread.c *********/
  183896. /********* Start of inlined file: pngpread.c *********/
  183897. /* pngpread.c - read a png file in push mode
  183898. *
  183899. * Last changed in libpng 1.2.21 October 4, 2007
  183900. * For conditions of distribution and use, see copyright notice in png.h
  183901. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183902. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183903. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183904. */
  183905. #define PNG_INTERNAL
  183906. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183907. /* push model modes */
  183908. #define PNG_READ_SIG_MODE 0
  183909. #define PNG_READ_CHUNK_MODE 1
  183910. #define PNG_READ_IDAT_MODE 2
  183911. #define PNG_SKIP_MODE 3
  183912. #define PNG_READ_tEXt_MODE 4
  183913. #define PNG_READ_zTXt_MODE 5
  183914. #define PNG_READ_DONE_MODE 6
  183915. #define PNG_READ_iTXt_MODE 7
  183916. #define PNG_ERROR_MODE 8
  183917. void PNGAPI
  183918. png_process_data(png_structp png_ptr, png_infop info_ptr,
  183919. png_bytep buffer, png_size_t buffer_size)
  183920. {
  183921. if(png_ptr == NULL) return;
  183922. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  183923. while (png_ptr->buffer_size)
  183924. {
  183925. png_process_some_data(png_ptr, info_ptr);
  183926. }
  183927. }
  183928. /* What we do with the incoming data depends on what we were previously
  183929. * doing before we ran out of data...
  183930. */
  183931. void /* PRIVATE */
  183932. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  183933. {
  183934. if(png_ptr == NULL) return;
  183935. switch (png_ptr->process_mode)
  183936. {
  183937. case PNG_READ_SIG_MODE:
  183938. {
  183939. png_push_read_sig(png_ptr, info_ptr);
  183940. break;
  183941. }
  183942. case PNG_READ_CHUNK_MODE:
  183943. {
  183944. png_push_read_chunk(png_ptr, info_ptr);
  183945. break;
  183946. }
  183947. case PNG_READ_IDAT_MODE:
  183948. {
  183949. png_push_read_IDAT(png_ptr);
  183950. break;
  183951. }
  183952. #if defined(PNG_READ_tEXt_SUPPORTED)
  183953. case PNG_READ_tEXt_MODE:
  183954. {
  183955. png_push_read_tEXt(png_ptr, info_ptr);
  183956. break;
  183957. }
  183958. #endif
  183959. #if defined(PNG_READ_zTXt_SUPPORTED)
  183960. case PNG_READ_zTXt_MODE:
  183961. {
  183962. png_push_read_zTXt(png_ptr, info_ptr);
  183963. break;
  183964. }
  183965. #endif
  183966. #if defined(PNG_READ_iTXt_SUPPORTED)
  183967. case PNG_READ_iTXt_MODE:
  183968. {
  183969. png_push_read_iTXt(png_ptr, info_ptr);
  183970. break;
  183971. }
  183972. #endif
  183973. case PNG_SKIP_MODE:
  183974. {
  183975. png_push_crc_finish(png_ptr);
  183976. break;
  183977. }
  183978. default:
  183979. {
  183980. png_ptr->buffer_size = 0;
  183981. break;
  183982. }
  183983. }
  183984. }
  183985. /* Read any remaining signature bytes from the stream and compare them with
  183986. * the correct PNG signature. It is possible that this routine is called
  183987. * with bytes already read from the signature, either because they have been
  183988. * checked by the calling application, or because of multiple calls to this
  183989. * routine.
  183990. */
  183991. void /* PRIVATE */
  183992. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  183993. {
  183994. png_size_t num_checked = png_ptr->sig_bytes,
  183995. num_to_check = 8 - num_checked;
  183996. if (png_ptr->buffer_size < num_to_check)
  183997. {
  183998. num_to_check = png_ptr->buffer_size;
  183999. }
  184000. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  184001. num_to_check);
  184002. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  184003. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  184004. {
  184005. if (num_checked < 4 &&
  184006. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  184007. png_error(png_ptr, "Not a PNG file");
  184008. else
  184009. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  184010. }
  184011. else
  184012. {
  184013. if (png_ptr->sig_bytes >= 8)
  184014. {
  184015. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184016. }
  184017. }
  184018. }
  184019. void /* PRIVATE */
  184020. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  184021. {
  184022. #ifdef PNG_USE_LOCAL_ARRAYS
  184023. PNG_CONST PNG_IHDR;
  184024. PNG_CONST PNG_IDAT;
  184025. PNG_CONST PNG_IEND;
  184026. PNG_CONST PNG_PLTE;
  184027. #if defined(PNG_READ_bKGD_SUPPORTED)
  184028. PNG_CONST PNG_bKGD;
  184029. #endif
  184030. #if defined(PNG_READ_cHRM_SUPPORTED)
  184031. PNG_CONST PNG_cHRM;
  184032. #endif
  184033. #if defined(PNG_READ_gAMA_SUPPORTED)
  184034. PNG_CONST PNG_gAMA;
  184035. #endif
  184036. #if defined(PNG_READ_hIST_SUPPORTED)
  184037. PNG_CONST PNG_hIST;
  184038. #endif
  184039. #if defined(PNG_READ_iCCP_SUPPORTED)
  184040. PNG_CONST PNG_iCCP;
  184041. #endif
  184042. #if defined(PNG_READ_iTXt_SUPPORTED)
  184043. PNG_CONST PNG_iTXt;
  184044. #endif
  184045. #if defined(PNG_READ_oFFs_SUPPORTED)
  184046. PNG_CONST PNG_oFFs;
  184047. #endif
  184048. #if defined(PNG_READ_pCAL_SUPPORTED)
  184049. PNG_CONST PNG_pCAL;
  184050. #endif
  184051. #if defined(PNG_READ_pHYs_SUPPORTED)
  184052. PNG_CONST PNG_pHYs;
  184053. #endif
  184054. #if defined(PNG_READ_sBIT_SUPPORTED)
  184055. PNG_CONST PNG_sBIT;
  184056. #endif
  184057. #if defined(PNG_READ_sCAL_SUPPORTED)
  184058. PNG_CONST PNG_sCAL;
  184059. #endif
  184060. #if defined(PNG_READ_sRGB_SUPPORTED)
  184061. PNG_CONST PNG_sRGB;
  184062. #endif
  184063. #if defined(PNG_READ_sPLT_SUPPORTED)
  184064. PNG_CONST PNG_sPLT;
  184065. #endif
  184066. #if defined(PNG_READ_tEXt_SUPPORTED)
  184067. PNG_CONST PNG_tEXt;
  184068. #endif
  184069. #if defined(PNG_READ_tIME_SUPPORTED)
  184070. PNG_CONST PNG_tIME;
  184071. #endif
  184072. #if defined(PNG_READ_tRNS_SUPPORTED)
  184073. PNG_CONST PNG_tRNS;
  184074. #endif
  184075. #if defined(PNG_READ_zTXt_SUPPORTED)
  184076. PNG_CONST PNG_zTXt;
  184077. #endif
  184078. #endif /* PNG_USE_LOCAL_ARRAYS */
  184079. /* First we make sure we have enough data for the 4 byte chunk name
  184080. * and the 4 byte chunk length before proceeding with decoding the
  184081. * chunk data. To fully decode each of these chunks, we also make
  184082. * sure we have enough data in the buffer for the 4 byte CRC at the
  184083. * end of every chunk (except IDAT, which is handled separately).
  184084. */
  184085. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184086. {
  184087. png_byte chunk_length[4];
  184088. if (png_ptr->buffer_size < 8)
  184089. {
  184090. png_push_save_buffer(png_ptr);
  184091. return;
  184092. }
  184093. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184094. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184095. png_reset_crc(png_ptr);
  184096. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184097. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184098. }
  184099. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184100. if(png_ptr->mode & PNG_AFTER_IDAT)
  184101. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  184102. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  184103. {
  184104. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184105. {
  184106. png_push_save_buffer(png_ptr);
  184107. return;
  184108. }
  184109. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  184110. }
  184111. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  184112. {
  184113. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184114. {
  184115. png_push_save_buffer(png_ptr);
  184116. return;
  184117. }
  184118. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  184119. png_ptr->process_mode = PNG_READ_DONE_MODE;
  184120. png_push_have_end(png_ptr, info_ptr);
  184121. }
  184122. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184123. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  184124. {
  184125. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184126. {
  184127. png_push_save_buffer(png_ptr);
  184128. return;
  184129. }
  184130. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184131. png_ptr->mode |= PNG_HAVE_IDAT;
  184132. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184133. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184134. png_ptr->mode |= PNG_HAVE_PLTE;
  184135. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184136. {
  184137. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184138. png_error(png_ptr, "Missing IHDR before IDAT");
  184139. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184140. !(png_ptr->mode & PNG_HAVE_PLTE))
  184141. png_error(png_ptr, "Missing PLTE before IDAT");
  184142. }
  184143. }
  184144. #endif
  184145. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  184146. {
  184147. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184148. {
  184149. png_push_save_buffer(png_ptr);
  184150. return;
  184151. }
  184152. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  184153. }
  184154. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184155. {
  184156. /* If we reach an IDAT chunk, this means we have read all of the
  184157. * header chunks, and we can start reading the image (or if this
  184158. * is called after the image has been read - we have an error).
  184159. */
  184160. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  184161. png_error(png_ptr, "Missing IHDR before IDAT");
  184162. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  184163. !(png_ptr->mode & PNG_HAVE_PLTE))
  184164. png_error(png_ptr, "Missing PLTE before IDAT");
  184165. if (png_ptr->mode & PNG_HAVE_IDAT)
  184166. {
  184167. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  184168. if (png_ptr->push_length == 0)
  184169. return;
  184170. if (png_ptr->mode & PNG_AFTER_IDAT)
  184171. png_error(png_ptr, "Too many IDAT's found");
  184172. }
  184173. png_ptr->idat_size = png_ptr->push_length;
  184174. png_ptr->mode |= PNG_HAVE_IDAT;
  184175. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  184176. png_push_have_info(png_ptr, info_ptr);
  184177. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184178. png_ptr->zstream.next_out = png_ptr->row_buf;
  184179. return;
  184180. }
  184181. #if defined(PNG_READ_gAMA_SUPPORTED)
  184182. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  184183. {
  184184. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184185. {
  184186. png_push_save_buffer(png_ptr);
  184187. return;
  184188. }
  184189. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  184190. }
  184191. #endif
  184192. #if defined(PNG_READ_sBIT_SUPPORTED)
  184193. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  184194. {
  184195. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184196. {
  184197. png_push_save_buffer(png_ptr);
  184198. return;
  184199. }
  184200. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  184201. }
  184202. #endif
  184203. #if defined(PNG_READ_cHRM_SUPPORTED)
  184204. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 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_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  184212. }
  184213. #endif
  184214. #if defined(PNG_READ_sRGB_SUPPORTED)
  184215. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 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_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  184223. }
  184224. #endif
  184225. #if defined(PNG_READ_iCCP_SUPPORTED)
  184226. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 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_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  184234. }
  184235. #endif
  184236. #if defined(PNG_READ_sPLT_SUPPORTED)
  184237. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 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_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  184245. }
  184246. #endif
  184247. #if defined(PNG_READ_tRNS_SUPPORTED)
  184248. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 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_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  184256. }
  184257. #endif
  184258. #if defined(PNG_READ_bKGD_SUPPORTED)
  184259. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 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_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  184267. }
  184268. #endif
  184269. #if defined(PNG_READ_hIST_SUPPORTED)
  184270. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 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_hIST(png_ptr, info_ptr, png_ptr->push_length);
  184278. }
  184279. #endif
  184280. #if defined(PNG_READ_pHYs_SUPPORTED)
  184281. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 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_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  184289. }
  184290. #endif
  184291. #if defined(PNG_READ_oFFs_SUPPORTED)
  184292. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 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_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  184300. }
  184301. #endif
  184302. #if defined(PNG_READ_pCAL_SUPPORTED)
  184303. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 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_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  184311. }
  184312. #endif
  184313. #if defined(PNG_READ_sCAL_SUPPORTED)
  184314. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 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_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  184322. }
  184323. #endif
  184324. #if defined(PNG_READ_tIME_SUPPORTED)
  184325. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 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_tIME(png_ptr, info_ptr, png_ptr->push_length);
  184333. }
  184334. #endif
  184335. #if defined(PNG_READ_tEXt_SUPPORTED)
  184336. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 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_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  184344. }
  184345. #endif
  184346. #if defined(PNG_READ_zTXt_SUPPORTED)
  184347. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 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_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  184355. }
  184356. #endif
  184357. #if defined(PNG_READ_iTXt_SUPPORTED)
  184358. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 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_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  184366. }
  184367. #endif
  184368. else
  184369. {
  184370. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  184371. {
  184372. png_push_save_buffer(png_ptr);
  184373. return;
  184374. }
  184375. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  184376. }
  184377. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184378. }
  184379. void /* PRIVATE */
  184380. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  184381. {
  184382. png_ptr->process_mode = PNG_SKIP_MODE;
  184383. png_ptr->skip_length = skip;
  184384. }
  184385. void /* PRIVATE */
  184386. png_push_crc_finish(png_structp png_ptr)
  184387. {
  184388. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  184389. {
  184390. png_size_t save_size;
  184391. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  184392. save_size = (png_size_t)png_ptr->skip_length;
  184393. else
  184394. save_size = png_ptr->save_buffer_size;
  184395. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184396. png_ptr->skip_length -= save_size;
  184397. png_ptr->buffer_size -= save_size;
  184398. png_ptr->save_buffer_size -= save_size;
  184399. png_ptr->save_buffer_ptr += save_size;
  184400. }
  184401. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  184402. {
  184403. png_size_t save_size;
  184404. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  184405. save_size = (png_size_t)png_ptr->skip_length;
  184406. else
  184407. save_size = png_ptr->current_buffer_size;
  184408. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184409. png_ptr->skip_length -= save_size;
  184410. png_ptr->buffer_size -= save_size;
  184411. png_ptr->current_buffer_size -= save_size;
  184412. png_ptr->current_buffer_ptr += save_size;
  184413. }
  184414. if (!png_ptr->skip_length)
  184415. {
  184416. if (png_ptr->buffer_size < 4)
  184417. {
  184418. png_push_save_buffer(png_ptr);
  184419. return;
  184420. }
  184421. png_crc_finish(png_ptr, 0);
  184422. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184423. }
  184424. }
  184425. void PNGAPI
  184426. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  184427. {
  184428. png_bytep ptr;
  184429. if(png_ptr == NULL) return;
  184430. ptr = buffer;
  184431. if (png_ptr->save_buffer_size)
  184432. {
  184433. png_size_t save_size;
  184434. if (length < png_ptr->save_buffer_size)
  184435. save_size = length;
  184436. else
  184437. save_size = png_ptr->save_buffer_size;
  184438. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  184439. length -= save_size;
  184440. ptr += save_size;
  184441. png_ptr->buffer_size -= save_size;
  184442. png_ptr->save_buffer_size -= save_size;
  184443. png_ptr->save_buffer_ptr += save_size;
  184444. }
  184445. if (length && png_ptr->current_buffer_size)
  184446. {
  184447. png_size_t save_size;
  184448. if (length < png_ptr->current_buffer_size)
  184449. save_size = length;
  184450. else
  184451. save_size = png_ptr->current_buffer_size;
  184452. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  184453. png_ptr->buffer_size -= save_size;
  184454. png_ptr->current_buffer_size -= save_size;
  184455. png_ptr->current_buffer_ptr += save_size;
  184456. }
  184457. }
  184458. void /* PRIVATE */
  184459. png_push_save_buffer(png_structp png_ptr)
  184460. {
  184461. if (png_ptr->save_buffer_size)
  184462. {
  184463. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  184464. {
  184465. png_size_t i,istop;
  184466. png_bytep sp;
  184467. png_bytep dp;
  184468. istop = png_ptr->save_buffer_size;
  184469. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  184470. i < istop; i++, sp++, dp++)
  184471. {
  184472. *dp = *sp;
  184473. }
  184474. }
  184475. }
  184476. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  184477. png_ptr->save_buffer_max)
  184478. {
  184479. png_size_t new_max;
  184480. png_bytep old_buffer;
  184481. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  184482. (png_ptr->current_buffer_size + 256))
  184483. {
  184484. png_error(png_ptr, "Potential overflow of save_buffer");
  184485. }
  184486. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  184487. old_buffer = png_ptr->save_buffer;
  184488. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  184489. (png_uint_32)new_max);
  184490. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  184491. png_free(png_ptr, old_buffer);
  184492. png_ptr->save_buffer_max = new_max;
  184493. }
  184494. if (png_ptr->current_buffer_size)
  184495. {
  184496. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  184497. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  184498. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  184499. png_ptr->current_buffer_size = 0;
  184500. }
  184501. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  184502. png_ptr->buffer_size = 0;
  184503. }
  184504. void /* PRIVATE */
  184505. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  184506. png_size_t buffer_length)
  184507. {
  184508. png_ptr->current_buffer = buffer;
  184509. png_ptr->current_buffer_size = buffer_length;
  184510. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  184511. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  184512. }
  184513. void /* PRIVATE */
  184514. png_push_read_IDAT(png_structp png_ptr)
  184515. {
  184516. #ifdef PNG_USE_LOCAL_ARRAYS
  184517. PNG_CONST PNG_IDAT;
  184518. #endif
  184519. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  184520. {
  184521. png_byte chunk_length[4];
  184522. if (png_ptr->buffer_size < 8)
  184523. {
  184524. png_push_save_buffer(png_ptr);
  184525. return;
  184526. }
  184527. png_push_fill_buffer(png_ptr, chunk_length, 4);
  184528. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  184529. png_reset_crc(png_ptr);
  184530. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  184531. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  184532. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  184533. {
  184534. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  184535. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184536. png_error(png_ptr, "Not enough compressed data");
  184537. return;
  184538. }
  184539. png_ptr->idat_size = png_ptr->push_length;
  184540. }
  184541. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  184542. {
  184543. png_size_t save_size;
  184544. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  184545. {
  184546. save_size = (png_size_t)png_ptr->idat_size;
  184547. /* check for overflow */
  184548. if((png_uint_32)save_size != png_ptr->idat_size)
  184549. png_error(png_ptr, "save_size overflowed in pngpread");
  184550. }
  184551. else
  184552. save_size = png_ptr->save_buffer_size;
  184553. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184554. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184555. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  184556. png_ptr->idat_size -= save_size;
  184557. png_ptr->buffer_size -= save_size;
  184558. png_ptr->save_buffer_size -= save_size;
  184559. png_ptr->save_buffer_ptr += save_size;
  184560. }
  184561. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  184562. {
  184563. png_size_t save_size;
  184564. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  184565. {
  184566. save_size = (png_size_t)png_ptr->idat_size;
  184567. /* check for overflow */
  184568. if((png_uint_32)save_size != png_ptr->idat_size)
  184569. png_error(png_ptr, "save_size overflowed in pngpread");
  184570. }
  184571. else
  184572. save_size = png_ptr->current_buffer_size;
  184573. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184574. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  184575. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  184576. png_ptr->idat_size -= save_size;
  184577. png_ptr->buffer_size -= save_size;
  184578. png_ptr->current_buffer_size -= save_size;
  184579. png_ptr->current_buffer_ptr += save_size;
  184580. }
  184581. if (!png_ptr->idat_size)
  184582. {
  184583. if (png_ptr->buffer_size < 4)
  184584. {
  184585. png_push_save_buffer(png_ptr);
  184586. return;
  184587. }
  184588. png_crc_finish(png_ptr, 0);
  184589. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  184590. png_ptr->mode |= PNG_AFTER_IDAT;
  184591. }
  184592. }
  184593. void /* PRIVATE */
  184594. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  184595. png_size_t buffer_length)
  184596. {
  184597. int ret;
  184598. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  184599. png_error(png_ptr, "Extra compression data");
  184600. png_ptr->zstream.next_in = buffer;
  184601. png_ptr->zstream.avail_in = (uInt)buffer_length;
  184602. for(;;)
  184603. {
  184604. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  184605. if (ret != Z_OK)
  184606. {
  184607. if (ret == Z_STREAM_END)
  184608. {
  184609. if (png_ptr->zstream.avail_in)
  184610. png_error(png_ptr, "Extra compressed data");
  184611. if (!(png_ptr->zstream.avail_out))
  184612. {
  184613. png_push_process_row(png_ptr);
  184614. }
  184615. png_ptr->mode |= PNG_AFTER_IDAT;
  184616. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184617. break;
  184618. }
  184619. else if (ret == Z_BUF_ERROR)
  184620. break;
  184621. else
  184622. png_error(png_ptr, "Decompression Error");
  184623. }
  184624. if (!(png_ptr->zstream.avail_out))
  184625. {
  184626. if ((
  184627. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184628. png_ptr->interlaced && png_ptr->pass > 6) ||
  184629. (!png_ptr->interlaced &&
  184630. #endif
  184631. png_ptr->row_number == png_ptr->num_rows))
  184632. {
  184633. if (png_ptr->zstream.avail_in)
  184634. {
  184635. png_warning(png_ptr, "Too much data in IDAT chunks");
  184636. }
  184637. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  184638. break;
  184639. }
  184640. png_push_process_row(png_ptr);
  184641. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  184642. png_ptr->zstream.next_out = png_ptr->row_buf;
  184643. }
  184644. else
  184645. break;
  184646. }
  184647. }
  184648. void /* PRIVATE */
  184649. png_push_process_row(png_structp png_ptr)
  184650. {
  184651. png_ptr->row_info.color_type = png_ptr->color_type;
  184652. png_ptr->row_info.width = png_ptr->iwidth;
  184653. png_ptr->row_info.channels = png_ptr->channels;
  184654. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  184655. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  184656. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184657. png_ptr->row_info.width);
  184658. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  184659. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  184660. (int)(png_ptr->row_buf[0]));
  184661. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  184662. png_ptr->rowbytes + 1);
  184663. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  184664. png_do_read_transformations(png_ptr);
  184665. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184666. /* blow up interlaced rows to full size */
  184667. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  184668. {
  184669. if (png_ptr->pass < 6)
  184670. /* old interface (pre-1.0.9):
  184671. png_do_read_interlace(&(png_ptr->row_info),
  184672. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  184673. */
  184674. png_do_read_interlace(png_ptr);
  184675. switch (png_ptr->pass)
  184676. {
  184677. case 0:
  184678. {
  184679. int i;
  184680. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  184681. {
  184682. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184683. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  184684. }
  184685. if (png_ptr->pass == 2) /* pass 1 might be empty */
  184686. {
  184687. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184688. {
  184689. png_push_have_row(png_ptr, png_bytep_NULL);
  184690. png_read_push_finish_row(png_ptr);
  184691. }
  184692. }
  184693. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  184694. {
  184695. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184696. {
  184697. png_push_have_row(png_ptr, png_bytep_NULL);
  184698. png_read_push_finish_row(png_ptr);
  184699. }
  184700. }
  184701. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  184702. {
  184703. png_push_have_row(png_ptr, png_bytep_NULL);
  184704. png_read_push_finish_row(png_ptr);
  184705. }
  184706. break;
  184707. }
  184708. case 1:
  184709. {
  184710. int i;
  184711. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  184712. {
  184713. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184714. png_read_push_finish_row(png_ptr);
  184715. }
  184716. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  184717. {
  184718. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184719. {
  184720. png_push_have_row(png_ptr, png_bytep_NULL);
  184721. png_read_push_finish_row(png_ptr);
  184722. }
  184723. }
  184724. break;
  184725. }
  184726. case 2:
  184727. {
  184728. int i;
  184729. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184730. {
  184731. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184732. png_read_push_finish_row(png_ptr);
  184733. }
  184734. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  184735. {
  184736. png_push_have_row(png_ptr, png_bytep_NULL);
  184737. png_read_push_finish_row(png_ptr);
  184738. }
  184739. if (png_ptr->pass == 4) /* pass 3 might be empty */
  184740. {
  184741. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184742. {
  184743. png_push_have_row(png_ptr, png_bytep_NULL);
  184744. png_read_push_finish_row(png_ptr);
  184745. }
  184746. }
  184747. break;
  184748. }
  184749. case 3:
  184750. {
  184751. int i;
  184752. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  184753. {
  184754. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184755. png_read_push_finish_row(png_ptr);
  184756. }
  184757. if (png_ptr->pass == 4) /* skip top two generated rows */
  184758. {
  184759. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184760. {
  184761. png_push_have_row(png_ptr, png_bytep_NULL);
  184762. png_read_push_finish_row(png_ptr);
  184763. }
  184764. }
  184765. break;
  184766. }
  184767. case 4:
  184768. {
  184769. int i;
  184770. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184771. {
  184772. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184773. png_read_push_finish_row(png_ptr);
  184774. }
  184775. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  184776. {
  184777. png_push_have_row(png_ptr, png_bytep_NULL);
  184778. png_read_push_finish_row(png_ptr);
  184779. }
  184780. if (png_ptr->pass == 6) /* pass 5 might be empty */
  184781. {
  184782. png_push_have_row(png_ptr, png_bytep_NULL);
  184783. png_read_push_finish_row(png_ptr);
  184784. }
  184785. break;
  184786. }
  184787. case 5:
  184788. {
  184789. int i;
  184790. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  184791. {
  184792. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184793. png_read_push_finish_row(png_ptr);
  184794. }
  184795. if (png_ptr->pass == 6) /* skip top generated row */
  184796. {
  184797. png_push_have_row(png_ptr, png_bytep_NULL);
  184798. png_read_push_finish_row(png_ptr);
  184799. }
  184800. break;
  184801. }
  184802. case 6:
  184803. {
  184804. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184805. png_read_push_finish_row(png_ptr);
  184806. if (png_ptr->pass != 6)
  184807. break;
  184808. png_push_have_row(png_ptr, png_bytep_NULL);
  184809. png_read_push_finish_row(png_ptr);
  184810. }
  184811. }
  184812. }
  184813. else
  184814. #endif
  184815. {
  184816. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  184817. png_read_push_finish_row(png_ptr);
  184818. }
  184819. }
  184820. void /* PRIVATE */
  184821. png_read_push_finish_row(png_structp png_ptr)
  184822. {
  184823. #ifdef PNG_USE_LOCAL_ARRAYS
  184824. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184825. /* start of interlace block */
  184826. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184827. /* offset to next interlace block */
  184828. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184829. /* start of interlace block in the y direction */
  184830. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184831. /* offset to next interlace block in the y direction */
  184832. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184833. /* Height of interlace block. This is not currently used - if you need
  184834. * it, uncomment it here and in png.h
  184835. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184836. */
  184837. #endif
  184838. png_ptr->row_number++;
  184839. if (png_ptr->row_number < png_ptr->num_rows)
  184840. return;
  184841. if (png_ptr->interlaced)
  184842. {
  184843. png_ptr->row_number = 0;
  184844. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  184845. png_ptr->rowbytes + 1);
  184846. do
  184847. {
  184848. png_ptr->pass++;
  184849. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  184850. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  184851. (png_ptr->pass == 5 && png_ptr->width < 2))
  184852. png_ptr->pass++;
  184853. if (png_ptr->pass > 7)
  184854. png_ptr->pass--;
  184855. if (png_ptr->pass >= 7)
  184856. break;
  184857. png_ptr->iwidth = (png_ptr->width +
  184858. png_pass_inc[png_ptr->pass] - 1 -
  184859. png_pass_start[png_ptr->pass]) /
  184860. png_pass_inc[png_ptr->pass];
  184861. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  184862. png_ptr->iwidth) + 1;
  184863. if (png_ptr->transformations & PNG_INTERLACE)
  184864. break;
  184865. png_ptr->num_rows = (png_ptr->height +
  184866. png_pass_yinc[png_ptr->pass] - 1 -
  184867. png_pass_ystart[png_ptr->pass]) /
  184868. png_pass_yinc[png_ptr->pass];
  184869. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  184870. }
  184871. }
  184872. #if defined(PNG_READ_tEXt_SUPPORTED)
  184873. void /* PRIVATE */
  184874. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184875. length)
  184876. {
  184877. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184878. {
  184879. png_error(png_ptr, "Out of place tEXt");
  184880. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184881. }
  184882. #ifdef PNG_MAX_MALLOC_64K
  184883. png_ptr->skip_length = 0; /* This may not be necessary */
  184884. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  184885. {
  184886. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  184887. png_ptr->skip_length = length - (png_uint_32)65535L;
  184888. length = (png_uint_32)65535L;
  184889. }
  184890. #endif
  184891. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184892. (png_uint_32)(length+1));
  184893. png_ptr->current_text[length] = '\0';
  184894. png_ptr->current_text_ptr = png_ptr->current_text;
  184895. png_ptr->current_text_size = (png_size_t)length;
  184896. png_ptr->current_text_left = (png_size_t)length;
  184897. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  184898. }
  184899. void /* PRIVATE */
  184900. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  184901. {
  184902. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184903. {
  184904. png_size_t text_size;
  184905. if (png_ptr->buffer_size < png_ptr->current_text_left)
  184906. text_size = png_ptr->buffer_size;
  184907. else
  184908. text_size = png_ptr->current_text_left;
  184909. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184910. png_ptr->current_text_left -= text_size;
  184911. png_ptr->current_text_ptr += text_size;
  184912. }
  184913. if (!(png_ptr->current_text_left))
  184914. {
  184915. png_textp text_ptr;
  184916. png_charp text;
  184917. png_charp key;
  184918. int ret;
  184919. if (png_ptr->buffer_size < 4)
  184920. {
  184921. png_push_save_buffer(png_ptr);
  184922. return;
  184923. }
  184924. png_push_crc_finish(png_ptr);
  184925. #if defined(PNG_MAX_MALLOC_64K)
  184926. if (png_ptr->skip_length)
  184927. return;
  184928. #endif
  184929. key = png_ptr->current_text;
  184930. for (text = key; *text; text++)
  184931. /* empty loop */ ;
  184932. if (text < key + png_ptr->current_text_size)
  184933. text++;
  184934. text_ptr = (png_textp)png_malloc(png_ptr,
  184935. (png_uint_32)png_sizeof(png_text));
  184936. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  184937. text_ptr->key = key;
  184938. #ifdef PNG_iTXt_SUPPORTED
  184939. text_ptr->lang = NULL;
  184940. text_ptr->lang_key = NULL;
  184941. #endif
  184942. text_ptr->text = text;
  184943. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  184944. png_free(png_ptr, key);
  184945. png_free(png_ptr, text_ptr);
  184946. png_ptr->current_text = NULL;
  184947. if (ret)
  184948. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  184949. }
  184950. }
  184951. #endif
  184952. #if defined(PNG_READ_zTXt_SUPPORTED)
  184953. void /* PRIVATE */
  184954. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  184955. length)
  184956. {
  184957. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  184958. {
  184959. png_error(png_ptr, "Out of place zTXt");
  184960. info_ptr = info_ptr; /* to quiet some compiler warnings */
  184961. }
  184962. #ifdef PNG_MAX_MALLOC_64K
  184963. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  184964. * to be able to store the uncompressed data. Actually, the threshold
  184965. * is probably around 32K, but it isn't as definite as 64K is.
  184966. */
  184967. if (length > (png_uint_32)65535L)
  184968. {
  184969. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  184970. png_push_crc_skip(png_ptr, length);
  184971. return;
  184972. }
  184973. #endif
  184974. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  184975. (png_uint_32)(length+1));
  184976. png_ptr->current_text[length] = '\0';
  184977. png_ptr->current_text_ptr = png_ptr->current_text;
  184978. png_ptr->current_text_size = (png_size_t)length;
  184979. png_ptr->current_text_left = (png_size_t)length;
  184980. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  184981. }
  184982. void /* PRIVATE */
  184983. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  184984. {
  184985. if (png_ptr->buffer_size && png_ptr->current_text_left)
  184986. {
  184987. png_size_t text_size;
  184988. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  184989. text_size = png_ptr->buffer_size;
  184990. else
  184991. text_size = png_ptr->current_text_left;
  184992. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  184993. png_ptr->current_text_left -= text_size;
  184994. png_ptr->current_text_ptr += text_size;
  184995. }
  184996. if (!(png_ptr->current_text_left))
  184997. {
  184998. png_textp text_ptr;
  184999. png_charp text;
  185000. png_charp key;
  185001. int ret;
  185002. png_size_t text_size, key_size;
  185003. if (png_ptr->buffer_size < 4)
  185004. {
  185005. png_push_save_buffer(png_ptr);
  185006. return;
  185007. }
  185008. png_push_crc_finish(png_ptr);
  185009. key = png_ptr->current_text;
  185010. for (text = key; *text; text++)
  185011. /* empty loop */ ;
  185012. /* zTXt can't have zero text */
  185013. if (text >= key + png_ptr->current_text_size)
  185014. {
  185015. png_ptr->current_text = NULL;
  185016. png_free(png_ptr, key);
  185017. return;
  185018. }
  185019. text++;
  185020. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  185021. {
  185022. png_ptr->current_text = NULL;
  185023. png_free(png_ptr, key);
  185024. return;
  185025. }
  185026. text++;
  185027. png_ptr->zstream.next_in = (png_bytep )text;
  185028. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  185029. (text - key));
  185030. png_ptr->zstream.next_out = png_ptr->zbuf;
  185031. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185032. key_size = text - key;
  185033. text_size = 0;
  185034. text = NULL;
  185035. ret = Z_STREAM_END;
  185036. while (png_ptr->zstream.avail_in)
  185037. {
  185038. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  185039. if (ret != Z_OK && ret != Z_STREAM_END)
  185040. {
  185041. inflateReset(&png_ptr->zstream);
  185042. png_ptr->zstream.avail_in = 0;
  185043. png_ptr->current_text = NULL;
  185044. png_free(png_ptr, key);
  185045. png_free(png_ptr, text);
  185046. return;
  185047. }
  185048. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  185049. {
  185050. if (text == NULL)
  185051. {
  185052. text = (png_charp)png_malloc(png_ptr,
  185053. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185054. + key_size + 1));
  185055. png_memcpy(text + key_size, png_ptr->zbuf,
  185056. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185057. png_memcpy(text, key, key_size);
  185058. text_size = key_size + png_ptr->zbuf_size -
  185059. png_ptr->zstream.avail_out;
  185060. *(text + text_size) = '\0';
  185061. }
  185062. else
  185063. {
  185064. png_charp tmp;
  185065. tmp = text;
  185066. text = (png_charp)png_malloc(png_ptr, text_size +
  185067. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  185068. + 1));
  185069. png_memcpy(text, tmp, text_size);
  185070. png_free(png_ptr, tmp);
  185071. png_memcpy(text + text_size, png_ptr->zbuf,
  185072. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  185073. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  185074. *(text + text_size) = '\0';
  185075. }
  185076. if (ret != Z_STREAM_END)
  185077. {
  185078. png_ptr->zstream.next_out = png_ptr->zbuf;
  185079. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  185080. }
  185081. }
  185082. else
  185083. {
  185084. break;
  185085. }
  185086. if (ret == Z_STREAM_END)
  185087. break;
  185088. }
  185089. inflateReset(&png_ptr->zstream);
  185090. png_ptr->zstream.avail_in = 0;
  185091. if (ret != Z_STREAM_END)
  185092. {
  185093. png_ptr->current_text = NULL;
  185094. png_free(png_ptr, key);
  185095. png_free(png_ptr, text);
  185096. return;
  185097. }
  185098. png_ptr->current_text = NULL;
  185099. png_free(png_ptr, key);
  185100. key = text;
  185101. text += key_size;
  185102. text_ptr = (png_textp)png_malloc(png_ptr,
  185103. (png_uint_32)png_sizeof(png_text));
  185104. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  185105. text_ptr->key = key;
  185106. #ifdef PNG_iTXt_SUPPORTED
  185107. text_ptr->lang = NULL;
  185108. text_ptr->lang_key = NULL;
  185109. #endif
  185110. text_ptr->text = text;
  185111. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185112. png_free(png_ptr, key);
  185113. png_free(png_ptr, text_ptr);
  185114. if (ret)
  185115. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  185116. }
  185117. }
  185118. #endif
  185119. #if defined(PNG_READ_iTXt_SUPPORTED)
  185120. void /* PRIVATE */
  185121. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185122. length)
  185123. {
  185124. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  185125. {
  185126. png_error(png_ptr, "Out of place iTXt");
  185127. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185128. }
  185129. #ifdef PNG_MAX_MALLOC_64K
  185130. png_ptr->skip_length = 0; /* This may not be necessary */
  185131. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  185132. {
  185133. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  185134. png_ptr->skip_length = length - (png_uint_32)65535L;
  185135. length = (png_uint_32)65535L;
  185136. }
  185137. #endif
  185138. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  185139. (png_uint_32)(length+1));
  185140. png_ptr->current_text[length] = '\0';
  185141. png_ptr->current_text_ptr = png_ptr->current_text;
  185142. png_ptr->current_text_size = (png_size_t)length;
  185143. png_ptr->current_text_left = (png_size_t)length;
  185144. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  185145. }
  185146. void /* PRIVATE */
  185147. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  185148. {
  185149. if (png_ptr->buffer_size && png_ptr->current_text_left)
  185150. {
  185151. png_size_t text_size;
  185152. if (png_ptr->buffer_size < png_ptr->current_text_left)
  185153. text_size = png_ptr->buffer_size;
  185154. else
  185155. text_size = png_ptr->current_text_left;
  185156. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  185157. png_ptr->current_text_left -= text_size;
  185158. png_ptr->current_text_ptr += text_size;
  185159. }
  185160. if (!(png_ptr->current_text_left))
  185161. {
  185162. png_textp text_ptr;
  185163. png_charp key;
  185164. int comp_flag;
  185165. png_charp lang;
  185166. png_charp lang_key;
  185167. png_charp text;
  185168. int ret;
  185169. if (png_ptr->buffer_size < 4)
  185170. {
  185171. png_push_save_buffer(png_ptr);
  185172. return;
  185173. }
  185174. png_push_crc_finish(png_ptr);
  185175. #if defined(PNG_MAX_MALLOC_64K)
  185176. if (png_ptr->skip_length)
  185177. return;
  185178. #endif
  185179. key = png_ptr->current_text;
  185180. for (lang = key; *lang; lang++)
  185181. /* empty loop */ ;
  185182. if (lang < key + png_ptr->current_text_size - 3)
  185183. lang++;
  185184. comp_flag = *lang++;
  185185. lang++; /* skip comp_type, always zero */
  185186. for (lang_key = lang; *lang_key; lang_key++)
  185187. /* empty loop */ ;
  185188. lang_key++; /* skip NUL separator */
  185189. text=lang_key;
  185190. if (lang_key < key + png_ptr->current_text_size - 1)
  185191. {
  185192. for (; *text; text++)
  185193. /* empty loop */ ;
  185194. }
  185195. if (text < key + png_ptr->current_text_size)
  185196. text++;
  185197. text_ptr = (png_textp)png_malloc(png_ptr,
  185198. (png_uint_32)png_sizeof(png_text));
  185199. text_ptr->compression = comp_flag + 2;
  185200. text_ptr->key = key;
  185201. text_ptr->lang = lang;
  185202. text_ptr->lang_key = lang_key;
  185203. text_ptr->text = text;
  185204. text_ptr->text_length = 0;
  185205. text_ptr->itxt_length = png_strlen(text);
  185206. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  185207. png_ptr->current_text = NULL;
  185208. png_free(png_ptr, text_ptr);
  185209. if (ret)
  185210. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  185211. }
  185212. }
  185213. #endif
  185214. /* This function is called when we haven't found a handler for this
  185215. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  185216. * name or a critical chunk), the chunk is (currently) silently ignored.
  185217. */
  185218. void /* PRIVATE */
  185219. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  185220. length)
  185221. {
  185222. png_uint_32 skip=0;
  185223. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  185224. if (!(png_ptr->chunk_name[0] & 0x20))
  185225. {
  185226. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185227. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185228. PNG_HANDLE_CHUNK_ALWAYS
  185229. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185230. && png_ptr->read_user_chunk_fn == NULL
  185231. #endif
  185232. )
  185233. #endif
  185234. png_chunk_error(png_ptr, "unknown critical chunk");
  185235. info_ptr = info_ptr; /* to quiet some compiler warnings */
  185236. }
  185237. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  185238. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  185239. {
  185240. #ifdef PNG_MAX_MALLOC_64K
  185241. if (length > (png_uint_32)65535L)
  185242. {
  185243. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  185244. skip = length - (png_uint_32)65535L;
  185245. length = (png_uint_32)65535L;
  185246. }
  185247. #endif
  185248. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  185249. (png_charp)png_ptr->chunk_name, 5);
  185250. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  185251. png_ptr->unknown_chunk.size = (png_size_t)length;
  185252. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  185253. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  185254. if(png_ptr->read_user_chunk_fn != NULL)
  185255. {
  185256. /* callback to user unknown chunk handler */
  185257. int ret;
  185258. ret = (*(png_ptr->read_user_chunk_fn))
  185259. (png_ptr, &png_ptr->unknown_chunk);
  185260. if (ret < 0)
  185261. png_chunk_error(png_ptr, "error in user chunk");
  185262. if (ret == 0)
  185263. {
  185264. if (!(png_ptr->chunk_name[0] & 0x20))
  185265. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  185266. PNG_HANDLE_CHUNK_ALWAYS)
  185267. png_chunk_error(png_ptr, "unknown critical chunk");
  185268. png_set_unknown_chunks(png_ptr, info_ptr,
  185269. &png_ptr->unknown_chunk, 1);
  185270. }
  185271. }
  185272. #else
  185273. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  185274. #endif
  185275. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185276. png_ptr->unknown_chunk.data = NULL;
  185277. }
  185278. else
  185279. #endif
  185280. skip=length;
  185281. png_push_crc_skip(png_ptr, skip);
  185282. }
  185283. void /* PRIVATE */
  185284. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  185285. {
  185286. if (png_ptr->info_fn != NULL)
  185287. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  185288. }
  185289. void /* PRIVATE */
  185290. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  185291. {
  185292. if (png_ptr->end_fn != NULL)
  185293. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  185294. }
  185295. void /* PRIVATE */
  185296. png_push_have_row(png_structp png_ptr, png_bytep row)
  185297. {
  185298. if (png_ptr->row_fn != NULL)
  185299. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  185300. (int)png_ptr->pass);
  185301. }
  185302. void PNGAPI
  185303. png_progressive_combine_row (png_structp png_ptr,
  185304. png_bytep old_row, png_bytep new_row)
  185305. {
  185306. #ifdef PNG_USE_LOCAL_ARRAYS
  185307. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  185308. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  185309. #endif
  185310. if(png_ptr == NULL) return;
  185311. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  185312. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  185313. }
  185314. void PNGAPI
  185315. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  185316. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  185317. png_progressive_end_ptr end_fn)
  185318. {
  185319. if(png_ptr == NULL) return;
  185320. png_ptr->info_fn = info_fn;
  185321. png_ptr->row_fn = row_fn;
  185322. png_ptr->end_fn = end_fn;
  185323. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  185324. }
  185325. png_voidp PNGAPI
  185326. png_get_progressive_ptr(png_structp png_ptr)
  185327. {
  185328. if(png_ptr == NULL) return (NULL);
  185329. return png_ptr->io_ptr;
  185330. }
  185331. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185332. /********* End of inlined file: pngpread.c *********/
  185333. /********* Start of inlined file: pngrio.c *********/
  185334. /* pngrio.c - functions for data input
  185335. *
  185336. * Last changed in libpng 1.2.13 November 13, 2006
  185337. * For conditions of distribution and use, see copyright notice in png.h
  185338. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  185339. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185340. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185341. *
  185342. * This file provides a location for all input. Users who need
  185343. * special handling are expected to write a function that has the same
  185344. * arguments as this and performs a similar function, but that possibly
  185345. * has a different input method. Note that you shouldn't change this
  185346. * function, but rather write a replacement function and then make
  185347. * libpng use it at run time with png_set_read_fn(...).
  185348. */
  185349. #define PNG_INTERNAL
  185350. #if defined(PNG_READ_SUPPORTED)
  185351. /* Read the data from whatever input you are using. The default routine
  185352. reads from a file pointer. Note that this routine sometimes gets called
  185353. with very small lengths, so you should implement some kind of simple
  185354. buffering if you are using unbuffered reads. This should never be asked
  185355. to read more then 64K on a 16 bit machine. */
  185356. void /* PRIVATE */
  185357. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185358. {
  185359. png_debug1(4,"reading %d bytes\n", (int)length);
  185360. if (png_ptr->read_data_fn != NULL)
  185361. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  185362. else
  185363. png_error(png_ptr, "Call to NULL read function");
  185364. }
  185365. #if !defined(PNG_NO_STDIO)
  185366. /* This is the function that does the actual reading of data. If you are
  185367. not reading from a standard C stream, you should create a replacement
  185368. read_data function and use it at run time with png_set_read_fn(), rather
  185369. than changing the library. */
  185370. #ifndef USE_FAR_KEYWORD
  185371. void PNGAPI
  185372. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185373. {
  185374. png_size_t check;
  185375. if(png_ptr == NULL) return;
  185376. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  185377. * instead of an int, which is what fread() actually returns.
  185378. */
  185379. #if defined(_WIN32_WCE)
  185380. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185381. check = 0;
  185382. #else
  185383. check = (png_size_t)fread(data, (png_size_t)1, length,
  185384. (png_FILE_p)png_ptr->io_ptr);
  185385. #endif
  185386. if (check != length)
  185387. png_error(png_ptr, "Read Error");
  185388. }
  185389. #else
  185390. /* this is the model-independent version. Since the standard I/O library
  185391. can't handle far buffers in the medium and small models, we have to copy
  185392. the data.
  185393. */
  185394. #define NEAR_BUF_SIZE 1024
  185395. #define MIN(a,b) (a <= b ? a : b)
  185396. static void PNGAPI
  185397. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  185398. {
  185399. int check;
  185400. png_byte *n_data;
  185401. png_FILE_p io_ptr;
  185402. if(png_ptr == NULL) return;
  185403. /* Check if data really is near. If so, use usual code. */
  185404. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  185405. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  185406. if ((png_bytep)n_data == data)
  185407. {
  185408. #if defined(_WIN32_WCE)
  185409. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  185410. check = 0;
  185411. #else
  185412. check = fread(n_data, 1, length, io_ptr);
  185413. #endif
  185414. }
  185415. else
  185416. {
  185417. png_byte buf[NEAR_BUF_SIZE];
  185418. png_size_t read, remaining, err;
  185419. check = 0;
  185420. remaining = length;
  185421. do
  185422. {
  185423. read = MIN(NEAR_BUF_SIZE, remaining);
  185424. #if defined(_WIN32_WCE)
  185425. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  185426. err = 0;
  185427. #else
  185428. err = fread(buf, (png_size_t)1, read, io_ptr);
  185429. #endif
  185430. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  185431. if(err != read)
  185432. break;
  185433. else
  185434. check += err;
  185435. data += read;
  185436. remaining -= read;
  185437. }
  185438. while (remaining != 0);
  185439. }
  185440. if ((png_uint_32)check != (png_uint_32)length)
  185441. png_error(png_ptr, "read Error");
  185442. }
  185443. #endif
  185444. #endif
  185445. /* This function allows the application to supply a new input function
  185446. for libpng if standard C streams aren't being used.
  185447. This function takes as its arguments:
  185448. png_ptr - pointer to a png input data structure
  185449. io_ptr - pointer to user supplied structure containing info about
  185450. the input functions. May be NULL.
  185451. read_data_fn - pointer to a new input function that takes as its
  185452. arguments a pointer to a png_struct, a pointer to
  185453. a location where input data can be stored, and a 32-bit
  185454. unsigned int that is the number of bytes to be read.
  185455. To exit and output any fatal error messages the new write
  185456. function should call png_error(png_ptr, "Error msg"). */
  185457. void PNGAPI
  185458. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  185459. png_rw_ptr read_data_fn)
  185460. {
  185461. if(png_ptr == NULL) return;
  185462. png_ptr->io_ptr = io_ptr;
  185463. #if !defined(PNG_NO_STDIO)
  185464. if (read_data_fn != NULL)
  185465. png_ptr->read_data_fn = read_data_fn;
  185466. else
  185467. png_ptr->read_data_fn = png_default_read_data;
  185468. #else
  185469. png_ptr->read_data_fn = read_data_fn;
  185470. #endif
  185471. /* It is an error to write to a read device */
  185472. if (png_ptr->write_data_fn != NULL)
  185473. {
  185474. png_ptr->write_data_fn = NULL;
  185475. png_warning(png_ptr,
  185476. "It's an error to set both read_data_fn and write_data_fn in the ");
  185477. png_warning(png_ptr,
  185478. "same structure. Resetting write_data_fn to NULL.");
  185479. }
  185480. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185481. png_ptr->output_flush_fn = NULL;
  185482. #endif
  185483. }
  185484. #endif /* PNG_READ_SUPPORTED */
  185485. /********* End of inlined file: pngrio.c *********/
  185486. /********* Start of inlined file: pngrtran.c *********/
  185487. /* pngrtran.c - transforms the data in a row for PNG readers
  185488. *
  185489. * Last changed in libpng 1.2.21 [October 4, 2007]
  185490. * For conditions of distribution and use, see copyright notice in png.h
  185491. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185492. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185493. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185494. *
  185495. * This file contains functions optionally called by an application
  185496. * in order to tell libpng how to handle data when reading a PNG.
  185497. * Transformations that are used in both reading and writing are
  185498. * in pngtrans.c.
  185499. */
  185500. #define PNG_INTERNAL
  185501. #if defined(PNG_READ_SUPPORTED)
  185502. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  185503. void PNGAPI
  185504. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  185505. {
  185506. png_debug(1, "in png_set_crc_action\n");
  185507. /* Tell libpng how we react to CRC errors in critical chunks */
  185508. if(png_ptr == NULL) return;
  185509. switch (crit_action)
  185510. {
  185511. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185512. break;
  185513. case PNG_CRC_WARN_USE: /* warn/use data */
  185514. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185515. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  185516. break;
  185517. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185518. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185519. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  185520. PNG_FLAG_CRC_CRITICAL_IGNORE;
  185521. break;
  185522. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  185523. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  185524. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185525. case PNG_CRC_DEFAULT:
  185526. default:
  185527. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  185528. break;
  185529. }
  185530. switch (ancil_action)
  185531. {
  185532. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  185533. break;
  185534. case PNG_CRC_WARN_USE: /* warn/use data */
  185535. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185536. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  185537. break;
  185538. case PNG_CRC_QUIET_USE: /* quiet/use data */
  185539. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185540. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  185541. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185542. break;
  185543. case PNG_CRC_ERROR_QUIT: /* error/quit */
  185544. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185545. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  185546. break;
  185547. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  185548. case PNG_CRC_DEFAULT:
  185549. default:
  185550. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  185551. break;
  185552. }
  185553. }
  185554. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185555. defined(PNG_FLOATING_POINT_SUPPORTED)
  185556. /* handle alpha and tRNS via a background color */
  185557. void PNGAPI
  185558. png_set_background(png_structp png_ptr,
  185559. png_color_16p background_color, int background_gamma_code,
  185560. int need_expand, double background_gamma)
  185561. {
  185562. png_debug(1, "in png_set_background\n");
  185563. if(png_ptr == NULL) return;
  185564. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  185565. {
  185566. png_warning(png_ptr, "Application must supply a known background gamma");
  185567. return;
  185568. }
  185569. png_ptr->transformations |= PNG_BACKGROUND;
  185570. png_memcpy(&(png_ptr->background), background_color,
  185571. png_sizeof(png_color_16));
  185572. png_ptr->background_gamma = (float)background_gamma;
  185573. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  185574. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  185575. }
  185576. #endif
  185577. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185578. /* strip 16 bit depth files to 8 bit depth */
  185579. void PNGAPI
  185580. png_set_strip_16(png_structp png_ptr)
  185581. {
  185582. png_debug(1, "in png_set_strip_16\n");
  185583. if(png_ptr == NULL) return;
  185584. png_ptr->transformations |= PNG_16_TO_8;
  185585. }
  185586. #endif
  185587. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185588. void PNGAPI
  185589. png_set_strip_alpha(png_structp png_ptr)
  185590. {
  185591. png_debug(1, "in png_set_strip_alpha\n");
  185592. if(png_ptr == NULL) return;
  185593. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  185594. }
  185595. #endif
  185596. #if defined(PNG_READ_DITHER_SUPPORTED)
  185597. /* Dither file to 8 bit. Supply a palette, the current number
  185598. * of elements in the palette, the maximum number of elements
  185599. * allowed, and a histogram if possible. If the current number
  185600. * of colors is greater then the maximum number, the palette will be
  185601. * modified to fit in the maximum number. "full_dither" indicates
  185602. * whether we need a dithering cube set up for RGB images, or if we
  185603. * simply are reducing the number of colors in a paletted image.
  185604. */
  185605. typedef struct png_dsort_struct
  185606. {
  185607. struct png_dsort_struct FAR * next;
  185608. png_byte left;
  185609. png_byte right;
  185610. } png_dsort;
  185611. typedef png_dsort FAR * png_dsortp;
  185612. typedef png_dsort FAR * FAR * png_dsortpp;
  185613. void PNGAPI
  185614. png_set_dither(png_structp png_ptr, png_colorp palette,
  185615. int num_palette, int maximum_colors, png_uint_16p histogram,
  185616. int full_dither)
  185617. {
  185618. png_debug(1, "in png_set_dither\n");
  185619. if(png_ptr == NULL) return;
  185620. png_ptr->transformations |= PNG_DITHER;
  185621. if (!full_dither)
  185622. {
  185623. int i;
  185624. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  185625. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185626. for (i = 0; i < num_palette; i++)
  185627. png_ptr->dither_index[i] = (png_byte)i;
  185628. }
  185629. if (num_palette > maximum_colors)
  185630. {
  185631. if (histogram != NULL)
  185632. {
  185633. /* This is easy enough, just throw out the least used colors.
  185634. Perhaps not the best solution, but good enough. */
  185635. int i;
  185636. /* initialize an array to sort colors */
  185637. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  185638. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185639. /* initialize the dither_sort array */
  185640. for (i = 0; i < num_palette; i++)
  185641. png_ptr->dither_sort[i] = (png_byte)i;
  185642. /* Find the least used palette entries by starting a
  185643. bubble sort, and running it until we have sorted
  185644. out enough colors. Note that we don't care about
  185645. sorting all the colors, just finding which are
  185646. least used. */
  185647. for (i = num_palette - 1; i >= maximum_colors; i--)
  185648. {
  185649. int done; /* to stop early if the list is pre-sorted */
  185650. int j;
  185651. done = 1;
  185652. for (j = 0; j < i; j++)
  185653. {
  185654. if (histogram[png_ptr->dither_sort[j]]
  185655. < histogram[png_ptr->dither_sort[j + 1]])
  185656. {
  185657. png_byte t;
  185658. t = png_ptr->dither_sort[j];
  185659. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  185660. png_ptr->dither_sort[j + 1] = t;
  185661. done = 0;
  185662. }
  185663. }
  185664. if (done)
  185665. break;
  185666. }
  185667. /* swap the palette around, and set up a table, if necessary */
  185668. if (full_dither)
  185669. {
  185670. int j = num_palette;
  185671. /* put all the useful colors within the max, but don't
  185672. move the others */
  185673. for (i = 0; i < maximum_colors; i++)
  185674. {
  185675. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185676. {
  185677. do
  185678. j--;
  185679. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185680. palette[i] = palette[j];
  185681. }
  185682. }
  185683. }
  185684. else
  185685. {
  185686. int j = num_palette;
  185687. /* move all the used colors inside the max limit, and
  185688. develop a translation table */
  185689. for (i = 0; i < maximum_colors; i++)
  185690. {
  185691. /* only move the colors we need to */
  185692. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  185693. {
  185694. png_color tmp_color;
  185695. do
  185696. j--;
  185697. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  185698. tmp_color = palette[j];
  185699. palette[j] = palette[i];
  185700. palette[i] = tmp_color;
  185701. /* indicate where the color went */
  185702. png_ptr->dither_index[j] = (png_byte)i;
  185703. png_ptr->dither_index[i] = (png_byte)j;
  185704. }
  185705. }
  185706. /* find closest color for those colors we are not using */
  185707. for (i = 0; i < num_palette; i++)
  185708. {
  185709. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  185710. {
  185711. int min_d, k, min_k, d_index;
  185712. /* find the closest color to one we threw out */
  185713. d_index = png_ptr->dither_index[i];
  185714. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  185715. for (k = 1, min_k = 0; k < maximum_colors; k++)
  185716. {
  185717. int d;
  185718. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  185719. if (d < min_d)
  185720. {
  185721. min_d = d;
  185722. min_k = k;
  185723. }
  185724. }
  185725. /* point to closest color */
  185726. png_ptr->dither_index[i] = (png_byte)min_k;
  185727. }
  185728. }
  185729. }
  185730. png_free(png_ptr, png_ptr->dither_sort);
  185731. png_ptr->dither_sort=NULL;
  185732. }
  185733. else
  185734. {
  185735. /* This is much harder to do simply (and quickly). Perhaps
  185736. we need to go through a median cut routine, but those
  185737. don't always behave themselves with only a few colors
  185738. as input. So we will just find the closest two colors,
  185739. and throw out one of them (chosen somewhat randomly).
  185740. [We don't understand this at all, so if someone wants to
  185741. work on improving it, be our guest - AED, GRP]
  185742. */
  185743. int i;
  185744. int max_d;
  185745. int num_new_palette;
  185746. png_dsortp t;
  185747. png_dsortpp hash;
  185748. t=NULL;
  185749. /* initialize palette index arrays */
  185750. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  185751. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185752. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  185753. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  185754. /* initialize the sort array */
  185755. for (i = 0; i < num_palette; i++)
  185756. {
  185757. png_ptr->index_to_palette[i] = (png_byte)i;
  185758. png_ptr->palette_to_index[i] = (png_byte)i;
  185759. }
  185760. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  185761. png_sizeof (png_dsortp)));
  185762. for (i = 0; i < 769; i++)
  185763. hash[i] = NULL;
  185764. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  185765. num_new_palette = num_palette;
  185766. /* initial wild guess at how far apart the farthest pixel
  185767. pair we will be eliminating will be. Larger
  185768. numbers mean more areas will be allocated, Smaller
  185769. numbers run the risk of not saving enough data, and
  185770. having to do this all over again.
  185771. I have not done extensive checking on this number.
  185772. */
  185773. max_d = 96;
  185774. while (num_new_palette > maximum_colors)
  185775. {
  185776. for (i = 0; i < num_new_palette - 1; i++)
  185777. {
  185778. int j;
  185779. for (j = i + 1; j < num_new_palette; j++)
  185780. {
  185781. int d;
  185782. d = PNG_COLOR_DIST(palette[i], palette[j]);
  185783. if (d <= max_d)
  185784. {
  185785. t = (png_dsortp)png_malloc_warn(png_ptr,
  185786. (png_uint_32)(png_sizeof(png_dsort)));
  185787. if (t == NULL)
  185788. break;
  185789. t->next = hash[d];
  185790. t->left = (png_byte)i;
  185791. t->right = (png_byte)j;
  185792. hash[d] = t;
  185793. }
  185794. }
  185795. if (t == NULL)
  185796. break;
  185797. }
  185798. if (t != NULL)
  185799. for (i = 0; i <= max_d; i++)
  185800. {
  185801. if (hash[i] != NULL)
  185802. {
  185803. png_dsortp p;
  185804. for (p = hash[i]; p; p = p->next)
  185805. {
  185806. if ((int)png_ptr->index_to_palette[p->left]
  185807. < num_new_palette &&
  185808. (int)png_ptr->index_to_palette[p->right]
  185809. < num_new_palette)
  185810. {
  185811. int j, next_j;
  185812. if (num_new_palette & 0x01)
  185813. {
  185814. j = p->left;
  185815. next_j = p->right;
  185816. }
  185817. else
  185818. {
  185819. j = p->right;
  185820. next_j = p->left;
  185821. }
  185822. num_new_palette--;
  185823. palette[png_ptr->index_to_palette[j]]
  185824. = palette[num_new_palette];
  185825. if (!full_dither)
  185826. {
  185827. int k;
  185828. for (k = 0; k < num_palette; k++)
  185829. {
  185830. if (png_ptr->dither_index[k] ==
  185831. png_ptr->index_to_palette[j])
  185832. png_ptr->dither_index[k] =
  185833. png_ptr->index_to_palette[next_j];
  185834. if ((int)png_ptr->dither_index[k] ==
  185835. num_new_palette)
  185836. png_ptr->dither_index[k] =
  185837. png_ptr->index_to_palette[j];
  185838. }
  185839. }
  185840. png_ptr->index_to_palette[png_ptr->palette_to_index
  185841. [num_new_palette]] = png_ptr->index_to_palette[j];
  185842. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  185843. = png_ptr->palette_to_index[num_new_palette];
  185844. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  185845. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  185846. }
  185847. if (num_new_palette <= maximum_colors)
  185848. break;
  185849. }
  185850. if (num_new_palette <= maximum_colors)
  185851. break;
  185852. }
  185853. }
  185854. for (i = 0; i < 769; i++)
  185855. {
  185856. if (hash[i] != NULL)
  185857. {
  185858. png_dsortp p = hash[i];
  185859. while (p)
  185860. {
  185861. t = p->next;
  185862. png_free(png_ptr, p);
  185863. p = t;
  185864. }
  185865. }
  185866. hash[i] = 0;
  185867. }
  185868. max_d += 96;
  185869. }
  185870. png_free(png_ptr, hash);
  185871. png_free(png_ptr, png_ptr->palette_to_index);
  185872. png_free(png_ptr, png_ptr->index_to_palette);
  185873. png_ptr->palette_to_index=NULL;
  185874. png_ptr->index_to_palette=NULL;
  185875. }
  185876. num_palette = maximum_colors;
  185877. }
  185878. if (png_ptr->palette == NULL)
  185879. {
  185880. png_ptr->palette = palette;
  185881. }
  185882. png_ptr->num_palette = (png_uint_16)num_palette;
  185883. if (full_dither)
  185884. {
  185885. int i;
  185886. png_bytep distance;
  185887. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  185888. PNG_DITHER_BLUE_BITS;
  185889. int num_red = (1 << PNG_DITHER_RED_BITS);
  185890. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  185891. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  185892. png_size_t num_entries = ((png_size_t)1 << total_bits);
  185893. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  185894. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  185895. png_memset(png_ptr->palette_lookup, 0, num_entries *
  185896. png_sizeof (png_byte));
  185897. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  185898. png_sizeof(png_byte)));
  185899. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  185900. for (i = 0; i < num_palette; i++)
  185901. {
  185902. int ir, ig, ib;
  185903. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  185904. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  185905. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  185906. for (ir = 0; ir < num_red; ir++)
  185907. {
  185908. /* int dr = abs(ir - r); */
  185909. int dr = ((ir > r) ? ir - r : r - ir);
  185910. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  185911. for (ig = 0; ig < num_green; ig++)
  185912. {
  185913. /* int dg = abs(ig - g); */
  185914. int dg = ((ig > g) ? ig - g : g - ig);
  185915. int dt = dr + dg;
  185916. int dm = ((dr > dg) ? dr : dg);
  185917. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  185918. for (ib = 0; ib < num_blue; ib++)
  185919. {
  185920. int d_index = index_g | ib;
  185921. /* int db = abs(ib - b); */
  185922. int db = ((ib > b) ? ib - b : b - ib);
  185923. int dmax = ((dm > db) ? dm : db);
  185924. int d = dmax + dt + db;
  185925. if (d < (int)distance[d_index])
  185926. {
  185927. distance[d_index] = (png_byte)d;
  185928. png_ptr->palette_lookup[d_index] = (png_byte)i;
  185929. }
  185930. }
  185931. }
  185932. }
  185933. }
  185934. png_free(png_ptr, distance);
  185935. }
  185936. }
  185937. #endif
  185938. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185939. /* Transform the image from the file_gamma to the screen_gamma. We
  185940. * only do transformations on images where the file_gamma and screen_gamma
  185941. * are not close reciprocals, otherwise it slows things down slightly, and
  185942. * also needlessly introduces small errors.
  185943. *
  185944. * We will turn off gamma transformation later if no semitransparent entries
  185945. * are present in the tRNS array for palette images. We can't do it here
  185946. * because we don't necessarily have the tRNS chunk yet.
  185947. */
  185948. void PNGAPI
  185949. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  185950. {
  185951. png_debug(1, "in png_set_gamma\n");
  185952. if(png_ptr == NULL) return;
  185953. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  185954. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  185955. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  185956. png_ptr->transformations |= PNG_GAMMA;
  185957. png_ptr->gamma = (float)file_gamma;
  185958. png_ptr->screen_gamma = (float)scrn_gamma;
  185959. }
  185960. #endif
  185961. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185962. /* Expand paletted images to RGB, expand grayscale images of
  185963. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  185964. * to alpha channels.
  185965. */
  185966. void PNGAPI
  185967. png_set_expand(png_structp png_ptr)
  185968. {
  185969. png_debug(1, "in png_set_expand\n");
  185970. if(png_ptr == NULL) return;
  185971. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185972. #ifdef PNG_WARN_UNINITIALIZED_ROW
  185973. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  185974. #endif
  185975. }
  185976. /* GRR 19990627: the following three functions currently are identical
  185977. * to png_set_expand(). However, it is entirely reasonable that someone
  185978. * might wish to expand an indexed image to RGB but *not* expand a single,
  185979. * fully transparent palette entry to a full alpha channel--perhaps instead
  185980. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  185981. * the transparent color with a particular RGB value, or drop tRNS entirely.
  185982. * IOW, a future version of the library may make the transformations flag
  185983. * a bit more fine-grained, with separate bits for each of these three
  185984. * functions.
  185985. *
  185986. * More to the point, these functions make it obvious what libpng will be
  185987. * doing, whereas "expand" can (and does) mean any number of things.
  185988. *
  185989. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  185990. * to expand only the sample depth but not to expand the tRNS to alpha.
  185991. */
  185992. /* Expand paletted images to RGB. */
  185993. void PNGAPI
  185994. png_set_palette_to_rgb(png_structp png_ptr)
  185995. {
  185996. png_debug(1, "in png_set_palette_to_rgb\n");
  185997. if(png_ptr == NULL) return;
  185998. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  185999. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186000. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  186001. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186002. #endif
  186003. }
  186004. #if !defined(PNG_1_0_X)
  186005. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186006. void PNGAPI
  186007. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  186008. {
  186009. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  186010. if(png_ptr == NULL) return;
  186011. png_ptr->transformations |= PNG_EXPAND;
  186012. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186013. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186014. #endif
  186015. }
  186016. #endif
  186017. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  186018. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  186019. /* Deprecated as of libpng-1.2.9 */
  186020. void PNGAPI
  186021. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  186022. {
  186023. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  186024. if(png_ptr == NULL) return;
  186025. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186026. }
  186027. #endif
  186028. /* Expand tRNS chunks to alpha channels. */
  186029. void PNGAPI
  186030. png_set_tRNS_to_alpha(png_structp png_ptr)
  186031. {
  186032. png_debug(1, "in png_set_tRNS_to_alpha\n");
  186033. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  186034. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186035. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186036. #endif
  186037. }
  186038. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  186039. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186040. void PNGAPI
  186041. png_set_gray_to_rgb(png_structp png_ptr)
  186042. {
  186043. png_debug(1, "in png_set_gray_to_rgb\n");
  186044. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  186045. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186046. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  186047. #endif
  186048. }
  186049. #endif
  186050. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186051. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  186052. /* Convert a RGB image to a grayscale of the same width. This allows us,
  186053. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  186054. */
  186055. void PNGAPI
  186056. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  186057. double green)
  186058. {
  186059. int red_fixed = (int)((float)red*100000.0 + 0.5);
  186060. int green_fixed = (int)((float)green*100000.0 + 0.5);
  186061. if(png_ptr == NULL) return;
  186062. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  186063. }
  186064. #endif
  186065. void PNGAPI
  186066. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  186067. png_fixed_point red, png_fixed_point green)
  186068. {
  186069. png_debug(1, "in png_set_rgb_to_gray\n");
  186070. if(png_ptr == NULL) return;
  186071. switch(error_action)
  186072. {
  186073. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  186074. break;
  186075. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  186076. break;
  186077. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  186078. }
  186079. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186080. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186081. png_ptr->transformations |= PNG_EXPAND;
  186082. #else
  186083. {
  186084. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  186085. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  186086. }
  186087. #endif
  186088. {
  186089. png_uint_16 red_int, green_int;
  186090. if(red < 0 || green < 0)
  186091. {
  186092. red_int = 6968; /* .212671 * 32768 + .5 */
  186093. green_int = 23434; /* .715160 * 32768 + .5 */
  186094. }
  186095. else if(red + green < 100000L)
  186096. {
  186097. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  186098. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  186099. }
  186100. else
  186101. {
  186102. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  186103. red_int = 6968;
  186104. green_int = 23434;
  186105. }
  186106. png_ptr->rgb_to_gray_red_coeff = red_int;
  186107. png_ptr->rgb_to_gray_green_coeff = green_int;
  186108. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  186109. }
  186110. }
  186111. #endif
  186112. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  186113. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  186114. defined(PNG_LEGACY_SUPPORTED)
  186115. void PNGAPI
  186116. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  186117. read_user_transform_fn)
  186118. {
  186119. png_debug(1, "in png_set_read_user_transform_fn\n");
  186120. if(png_ptr == NULL) return;
  186121. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186122. png_ptr->transformations |= PNG_USER_TRANSFORM;
  186123. png_ptr->read_user_transform_fn = read_user_transform_fn;
  186124. #endif
  186125. #ifdef PNG_LEGACY_SUPPORTED
  186126. if(read_user_transform_fn)
  186127. png_warning(png_ptr,
  186128. "This version of libpng does not support user transforms");
  186129. #endif
  186130. }
  186131. #endif
  186132. /* Initialize everything needed for the read. This includes modifying
  186133. * the palette.
  186134. */
  186135. void /* PRIVATE */
  186136. png_init_read_transformations(png_structp png_ptr)
  186137. {
  186138. png_debug(1, "in png_init_read_transformations\n");
  186139. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186140. if(png_ptr != NULL)
  186141. #endif
  186142. {
  186143. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  186144. || defined(PNG_READ_GAMMA_SUPPORTED)
  186145. int color_type = png_ptr->color_type;
  186146. #endif
  186147. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  186148. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186149. /* Detect gray background and attempt to enable optimization
  186150. * for gray --> RGB case */
  186151. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  186152. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  186153. * background color might actually be gray yet not be flagged as such.
  186154. * This is not a problem for the current code, which uses
  186155. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  186156. * png_do_gray_to_rgb() transformation.
  186157. */
  186158. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186159. !(color_type & PNG_COLOR_MASK_COLOR))
  186160. {
  186161. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186162. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186163. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186164. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186165. png_ptr->background.red == png_ptr->background.green &&
  186166. png_ptr->background.red == png_ptr->background.blue)
  186167. {
  186168. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  186169. png_ptr->background.gray = png_ptr->background.red;
  186170. }
  186171. #endif
  186172. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  186173. (png_ptr->transformations & PNG_EXPAND))
  186174. {
  186175. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  186176. {
  186177. /* expand background and tRNS chunks */
  186178. switch (png_ptr->bit_depth)
  186179. {
  186180. case 1:
  186181. png_ptr->background.gray *= (png_uint_16)0xff;
  186182. png_ptr->background.red = png_ptr->background.green
  186183. = png_ptr->background.blue = png_ptr->background.gray;
  186184. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186185. {
  186186. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  186187. png_ptr->trans_values.red = png_ptr->trans_values.green
  186188. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186189. }
  186190. break;
  186191. case 2:
  186192. png_ptr->background.gray *= (png_uint_16)0x55;
  186193. png_ptr->background.red = png_ptr->background.green
  186194. = png_ptr->background.blue = png_ptr->background.gray;
  186195. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186196. {
  186197. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  186198. png_ptr->trans_values.red = png_ptr->trans_values.green
  186199. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  186200. }
  186201. break;
  186202. case 4:
  186203. png_ptr->background.gray *= (png_uint_16)0x11;
  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)0x11;
  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 8:
  186214. case 16:
  186215. png_ptr->background.red = png_ptr->background.green
  186216. = png_ptr->background.blue = png_ptr->background.gray;
  186217. break;
  186218. }
  186219. }
  186220. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  186221. {
  186222. png_ptr->background.red =
  186223. png_ptr->palette[png_ptr->background.index].red;
  186224. png_ptr->background.green =
  186225. png_ptr->palette[png_ptr->background.index].green;
  186226. png_ptr->background.blue =
  186227. png_ptr->palette[png_ptr->background.index].blue;
  186228. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186229. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186230. {
  186231. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186232. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  186233. #endif
  186234. {
  186235. /* invert the alpha channel (in tRNS) unless the pixels are
  186236. going to be expanded, in which case leave it for later */
  186237. int i,istop;
  186238. istop=(int)png_ptr->num_trans;
  186239. for (i=0; i<istop; i++)
  186240. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  186241. }
  186242. }
  186243. #endif
  186244. }
  186245. }
  186246. #endif
  186247. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  186248. png_ptr->background_1 = png_ptr->background;
  186249. #endif
  186250. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186251. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  186252. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  186253. < PNG_GAMMA_THRESHOLD))
  186254. {
  186255. int i,k;
  186256. k=0;
  186257. for (i=0; i<png_ptr->num_trans; i++)
  186258. {
  186259. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  186260. k=1; /* partial transparency is present */
  186261. }
  186262. if (k == 0)
  186263. png_ptr->transformations &= (~PNG_GAMMA);
  186264. }
  186265. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  186266. png_ptr->gamma != 0.0)
  186267. {
  186268. png_build_gamma_table(png_ptr);
  186269. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186270. if (png_ptr->transformations & PNG_BACKGROUND)
  186271. {
  186272. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186273. {
  186274. /* could skip if no transparency and
  186275. */
  186276. png_color back, back_1;
  186277. png_colorp palette = png_ptr->palette;
  186278. int num_palette = png_ptr->num_palette;
  186279. int i;
  186280. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  186281. {
  186282. back.red = png_ptr->gamma_table[png_ptr->background.red];
  186283. back.green = png_ptr->gamma_table[png_ptr->background.green];
  186284. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  186285. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  186286. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  186287. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  186288. }
  186289. else
  186290. {
  186291. double g, gs;
  186292. switch (png_ptr->background_gamma_type)
  186293. {
  186294. case PNG_BACKGROUND_GAMMA_SCREEN:
  186295. g = (png_ptr->screen_gamma);
  186296. gs = 1.0;
  186297. break;
  186298. case PNG_BACKGROUND_GAMMA_FILE:
  186299. g = 1.0 / (png_ptr->gamma);
  186300. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186301. break;
  186302. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186303. g = 1.0 / (png_ptr->background_gamma);
  186304. gs = 1.0 / (png_ptr->background_gamma *
  186305. png_ptr->screen_gamma);
  186306. break;
  186307. default:
  186308. g = 1.0; /* back_1 */
  186309. gs = 1.0; /* back */
  186310. }
  186311. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  186312. {
  186313. back.red = (png_byte)png_ptr->background.red;
  186314. back.green = (png_byte)png_ptr->background.green;
  186315. back.blue = (png_byte)png_ptr->background.blue;
  186316. }
  186317. else
  186318. {
  186319. back.red = (png_byte)(pow(
  186320. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  186321. back.green = (png_byte)(pow(
  186322. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  186323. back.blue = (png_byte)(pow(
  186324. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  186325. }
  186326. back_1.red = (png_byte)(pow(
  186327. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  186328. back_1.green = (png_byte)(pow(
  186329. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  186330. back_1.blue = (png_byte)(pow(
  186331. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  186332. }
  186333. for (i = 0; i < num_palette; i++)
  186334. {
  186335. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  186336. {
  186337. if (png_ptr->trans[i] == 0)
  186338. {
  186339. palette[i] = back;
  186340. }
  186341. else /* if (png_ptr->trans[i] != 0xff) */
  186342. {
  186343. png_byte v, w;
  186344. v = png_ptr->gamma_to_1[palette[i].red];
  186345. png_composite(w, v, png_ptr->trans[i], back_1.red);
  186346. palette[i].red = png_ptr->gamma_from_1[w];
  186347. v = png_ptr->gamma_to_1[palette[i].green];
  186348. png_composite(w, v, png_ptr->trans[i], back_1.green);
  186349. palette[i].green = png_ptr->gamma_from_1[w];
  186350. v = png_ptr->gamma_to_1[palette[i].blue];
  186351. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  186352. palette[i].blue = png_ptr->gamma_from_1[w];
  186353. }
  186354. }
  186355. else
  186356. {
  186357. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186358. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186359. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186360. }
  186361. }
  186362. }
  186363. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  186364. else
  186365. /* color_type != PNG_COLOR_TYPE_PALETTE */
  186366. {
  186367. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  186368. double g = 1.0;
  186369. double gs = 1.0;
  186370. switch (png_ptr->background_gamma_type)
  186371. {
  186372. case PNG_BACKGROUND_GAMMA_SCREEN:
  186373. g = (png_ptr->screen_gamma);
  186374. gs = 1.0;
  186375. break;
  186376. case PNG_BACKGROUND_GAMMA_FILE:
  186377. g = 1.0 / (png_ptr->gamma);
  186378. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  186379. break;
  186380. case PNG_BACKGROUND_GAMMA_UNIQUE:
  186381. g = 1.0 / (png_ptr->background_gamma);
  186382. gs = 1.0 / (png_ptr->background_gamma *
  186383. png_ptr->screen_gamma);
  186384. break;
  186385. }
  186386. png_ptr->background_1.gray = (png_uint_16)(pow(
  186387. (double)png_ptr->background.gray / m, g) * m + .5);
  186388. png_ptr->background.gray = (png_uint_16)(pow(
  186389. (double)png_ptr->background.gray / m, gs) * m + .5);
  186390. if ((png_ptr->background.red != png_ptr->background.green) ||
  186391. (png_ptr->background.red != png_ptr->background.blue) ||
  186392. (png_ptr->background.red != png_ptr->background.gray))
  186393. {
  186394. /* RGB or RGBA with color background */
  186395. png_ptr->background_1.red = (png_uint_16)(pow(
  186396. (double)png_ptr->background.red / m, g) * m + .5);
  186397. png_ptr->background_1.green = (png_uint_16)(pow(
  186398. (double)png_ptr->background.green / m, g) * m + .5);
  186399. png_ptr->background_1.blue = (png_uint_16)(pow(
  186400. (double)png_ptr->background.blue / m, g) * m + .5);
  186401. png_ptr->background.red = (png_uint_16)(pow(
  186402. (double)png_ptr->background.red / m, gs) * m + .5);
  186403. png_ptr->background.green = (png_uint_16)(pow(
  186404. (double)png_ptr->background.green / m, gs) * m + .5);
  186405. png_ptr->background.blue = (png_uint_16)(pow(
  186406. (double)png_ptr->background.blue / m, gs) * m + .5);
  186407. }
  186408. else
  186409. {
  186410. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  186411. png_ptr->background_1.red = png_ptr->background_1.green
  186412. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  186413. png_ptr->background.red = png_ptr->background.green
  186414. = png_ptr->background.blue = png_ptr->background.gray;
  186415. }
  186416. }
  186417. }
  186418. else
  186419. /* transformation does not include PNG_BACKGROUND */
  186420. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186421. if (color_type == PNG_COLOR_TYPE_PALETTE)
  186422. {
  186423. png_colorp palette = png_ptr->palette;
  186424. int num_palette = png_ptr->num_palette;
  186425. int i;
  186426. for (i = 0; i < num_palette; i++)
  186427. {
  186428. palette[i].red = png_ptr->gamma_table[palette[i].red];
  186429. palette[i].green = png_ptr->gamma_table[palette[i].green];
  186430. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  186431. }
  186432. }
  186433. }
  186434. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186435. else
  186436. #endif
  186437. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  186438. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186439. /* No GAMMA transformation */
  186440. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186441. (color_type == PNG_COLOR_TYPE_PALETTE))
  186442. {
  186443. int i;
  186444. int istop = (int)png_ptr->num_trans;
  186445. png_color back;
  186446. png_colorp palette = png_ptr->palette;
  186447. back.red = (png_byte)png_ptr->background.red;
  186448. back.green = (png_byte)png_ptr->background.green;
  186449. back.blue = (png_byte)png_ptr->background.blue;
  186450. for (i = 0; i < istop; i++)
  186451. {
  186452. if (png_ptr->trans[i] == 0)
  186453. {
  186454. palette[i] = back;
  186455. }
  186456. else if (png_ptr->trans[i] != 0xff)
  186457. {
  186458. /* The png_composite() macro is defined in png.h */
  186459. png_composite(palette[i].red, palette[i].red,
  186460. png_ptr->trans[i], back.red);
  186461. png_composite(palette[i].green, palette[i].green,
  186462. png_ptr->trans[i], back.green);
  186463. png_composite(palette[i].blue, palette[i].blue,
  186464. png_ptr->trans[i], back.blue);
  186465. }
  186466. }
  186467. }
  186468. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  186469. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186470. if ((png_ptr->transformations & PNG_SHIFT) &&
  186471. (color_type == PNG_COLOR_TYPE_PALETTE))
  186472. {
  186473. png_uint_16 i;
  186474. png_uint_16 istop = png_ptr->num_palette;
  186475. int sr = 8 - png_ptr->sig_bit.red;
  186476. int sg = 8 - png_ptr->sig_bit.green;
  186477. int sb = 8 - png_ptr->sig_bit.blue;
  186478. if (sr < 0 || sr > 8)
  186479. sr = 0;
  186480. if (sg < 0 || sg > 8)
  186481. sg = 0;
  186482. if (sb < 0 || sb > 8)
  186483. sb = 0;
  186484. for (i = 0; i < istop; i++)
  186485. {
  186486. png_ptr->palette[i].red >>= sr;
  186487. png_ptr->palette[i].green >>= sg;
  186488. png_ptr->palette[i].blue >>= sb;
  186489. }
  186490. }
  186491. #endif /* PNG_READ_SHIFT_SUPPORTED */
  186492. }
  186493. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  186494. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  186495. if(png_ptr)
  186496. return;
  186497. #endif
  186498. }
  186499. /* Modify the info structure to reflect the transformations. The
  186500. * info should be updated so a PNG file could be written with it,
  186501. * assuming the transformations result in valid PNG data.
  186502. */
  186503. void /* PRIVATE */
  186504. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  186505. {
  186506. png_debug(1, "in png_read_transform_info\n");
  186507. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186508. if (png_ptr->transformations & PNG_EXPAND)
  186509. {
  186510. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186511. {
  186512. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  186513. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186514. else
  186515. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  186516. info_ptr->bit_depth = 8;
  186517. info_ptr->num_trans = 0;
  186518. }
  186519. else
  186520. {
  186521. if (png_ptr->num_trans)
  186522. {
  186523. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  186524. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186525. else
  186526. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186527. }
  186528. if (info_ptr->bit_depth < 8)
  186529. info_ptr->bit_depth = 8;
  186530. info_ptr->num_trans = 0;
  186531. }
  186532. }
  186533. #endif
  186534. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186535. if (png_ptr->transformations & PNG_BACKGROUND)
  186536. {
  186537. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186538. info_ptr->num_trans = 0;
  186539. info_ptr->background = png_ptr->background;
  186540. }
  186541. #endif
  186542. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186543. if (png_ptr->transformations & PNG_GAMMA)
  186544. {
  186545. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186546. info_ptr->gamma = png_ptr->gamma;
  186547. #endif
  186548. #ifdef PNG_FIXED_POINT_SUPPORTED
  186549. info_ptr->int_gamma = png_ptr->int_gamma;
  186550. #endif
  186551. }
  186552. #endif
  186553. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186554. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  186555. info_ptr->bit_depth = 8;
  186556. #endif
  186557. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186558. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  186559. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  186560. #endif
  186561. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186562. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186563. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  186564. #endif
  186565. #if defined(PNG_READ_DITHER_SUPPORTED)
  186566. if (png_ptr->transformations & PNG_DITHER)
  186567. {
  186568. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186569. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  186570. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  186571. {
  186572. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  186573. }
  186574. }
  186575. #endif
  186576. #if defined(PNG_READ_PACK_SUPPORTED)
  186577. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  186578. info_ptr->bit_depth = 8;
  186579. #endif
  186580. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186581. info_ptr->channels = 1;
  186582. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  186583. info_ptr->channels = 3;
  186584. else
  186585. info_ptr->channels = 1;
  186586. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186587. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186588. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186589. #endif
  186590. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  186591. info_ptr->channels++;
  186592. #if defined(PNG_READ_FILLER_SUPPORTED)
  186593. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  186594. if ((png_ptr->transformations & PNG_FILLER) &&
  186595. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  186596. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  186597. {
  186598. info_ptr->channels++;
  186599. /* if adding a true alpha channel not just filler */
  186600. #if !defined(PNG_1_0_X)
  186601. if (png_ptr->transformations & PNG_ADD_ALPHA)
  186602. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  186603. #endif
  186604. }
  186605. #endif
  186606. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  186607. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186608. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  186609. {
  186610. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  186611. info_ptr->bit_depth = png_ptr->user_transform_depth;
  186612. if(info_ptr->channels < png_ptr->user_transform_channels)
  186613. info_ptr->channels = png_ptr->user_transform_channels;
  186614. }
  186615. #endif
  186616. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  186617. info_ptr->bit_depth);
  186618. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  186619. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  186620. if(png_ptr)
  186621. return;
  186622. #endif
  186623. }
  186624. /* Transform the row. The order of transformations is significant,
  186625. * and is very touchy. If you add a transformation, take care to
  186626. * decide how it fits in with the other transformations here.
  186627. */
  186628. void /* PRIVATE */
  186629. png_do_read_transformations(png_structp png_ptr)
  186630. {
  186631. png_debug(1, "in png_do_read_transformations\n");
  186632. if (png_ptr->row_buf == NULL)
  186633. {
  186634. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  186635. char msg[50];
  186636. png_snprintf2(msg, 50,
  186637. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  186638. png_ptr->pass);
  186639. png_error(png_ptr, msg);
  186640. #else
  186641. png_error(png_ptr, "NULL row buffer");
  186642. #endif
  186643. }
  186644. #ifdef PNG_WARN_UNINITIALIZED_ROW
  186645. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  186646. /* Application has failed to call either png_read_start_image()
  186647. * or png_read_update_info() after setting transforms that expand
  186648. * pixels. This check added to libpng-1.2.19 */
  186649. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  186650. png_error(png_ptr, "Uninitialized row");
  186651. #else
  186652. png_warning(png_ptr, "Uninitialized row");
  186653. #endif
  186654. #endif
  186655. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186656. if (png_ptr->transformations & PNG_EXPAND)
  186657. {
  186658. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  186659. {
  186660. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186661. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  186662. }
  186663. else
  186664. {
  186665. if (png_ptr->num_trans &&
  186666. (png_ptr->transformations & PNG_EXPAND_tRNS))
  186667. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186668. &(png_ptr->trans_values));
  186669. else
  186670. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186671. NULL);
  186672. }
  186673. }
  186674. #endif
  186675. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  186676. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  186677. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186678. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  186679. #endif
  186680. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186681. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  186682. {
  186683. int rgb_error =
  186684. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  186685. if(rgb_error)
  186686. {
  186687. png_ptr->rgb_to_gray_status=1;
  186688. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186689. PNG_RGB_TO_GRAY_WARN)
  186690. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186691. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  186692. PNG_RGB_TO_GRAY_ERR)
  186693. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  186694. }
  186695. }
  186696. #endif
  186697. /*
  186698. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  186699. In most cases, the "simple transparency" should be done prior to doing
  186700. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  186701. pixel is transparent. You would also need to make sure that the
  186702. transparency information is upgraded to RGB.
  186703. To summarize, the current flow is:
  186704. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  186705. with background "in place" if transparent,
  186706. convert to RGB if necessary
  186707. - Gray + alpha -> composite with gray background and remove alpha bytes,
  186708. convert to RGB if necessary
  186709. To support RGB backgrounds for gray images we need:
  186710. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  186711. 3 or 6 bytes and composite with background
  186712. "in place" if transparent (3x compare/pixel
  186713. compared to doing composite with gray bkgrnd)
  186714. - Gray + alpha -> convert to RGB + alpha, composite with background and
  186715. remove alpha bytes (3x float operations/pixel
  186716. compared with composite on gray background)
  186717. Greg's change will do this. The reason it wasn't done before is for
  186718. performance, as this increases the per-pixel operations. If we would check
  186719. in advance if the background was gray or RGB, and position the gray-to-RGB
  186720. transform appropriately, then it would save a lot of work/time.
  186721. */
  186722. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186723. /* if gray -> RGB, do so now only if background is non-gray; else do later
  186724. * for performance reasons */
  186725. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186726. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186727. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186728. #endif
  186729. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186730. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  186731. ((png_ptr->num_trans != 0 ) ||
  186732. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  186733. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186734. &(png_ptr->trans_values), &(png_ptr->background)
  186735. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186736. , &(png_ptr->background_1),
  186737. png_ptr->gamma_table, png_ptr->gamma_from_1,
  186738. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  186739. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  186740. png_ptr->gamma_shift
  186741. #endif
  186742. );
  186743. #endif
  186744. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186745. if ((png_ptr->transformations & PNG_GAMMA) &&
  186746. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  186747. !((png_ptr->transformations & PNG_BACKGROUND) &&
  186748. ((png_ptr->num_trans != 0) ||
  186749. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  186750. #endif
  186751. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  186752. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186753. png_ptr->gamma_table, png_ptr->gamma_16_table,
  186754. png_ptr->gamma_shift);
  186755. #endif
  186756. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  186757. if (png_ptr->transformations & PNG_16_TO_8)
  186758. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186759. #endif
  186760. #if defined(PNG_READ_DITHER_SUPPORTED)
  186761. if (png_ptr->transformations & PNG_DITHER)
  186762. {
  186763. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  186764. png_ptr->palette_lookup, png_ptr->dither_index);
  186765. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  186766. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  186767. }
  186768. #endif
  186769. #if defined(PNG_READ_INVERT_SUPPORTED)
  186770. if (png_ptr->transformations & PNG_INVERT_MONO)
  186771. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186772. #endif
  186773. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186774. if (png_ptr->transformations & PNG_SHIFT)
  186775. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186776. &(png_ptr->shift));
  186777. #endif
  186778. #if defined(PNG_READ_PACK_SUPPORTED)
  186779. if (png_ptr->transformations & PNG_PACK)
  186780. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186781. #endif
  186782. #if defined(PNG_READ_BGR_SUPPORTED)
  186783. if (png_ptr->transformations & PNG_BGR)
  186784. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186785. #endif
  186786. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  186787. if (png_ptr->transformations & PNG_PACKSWAP)
  186788. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186789. #endif
  186790. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  186791. /* if gray -> RGB, do so now only if we did not do so above */
  186792. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  186793. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  186794. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186795. #endif
  186796. #if defined(PNG_READ_FILLER_SUPPORTED)
  186797. if (png_ptr->transformations & PNG_FILLER)
  186798. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  186799. (png_uint_32)png_ptr->filler, png_ptr->flags);
  186800. #endif
  186801. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  186802. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  186803. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186804. #endif
  186805. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  186806. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  186807. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186808. #endif
  186809. #if defined(PNG_READ_SWAP_SUPPORTED)
  186810. if (png_ptr->transformations & PNG_SWAP_BYTES)
  186811. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  186812. #endif
  186813. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  186814. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  186815. {
  186816. if(png_ptr->read_user_transform_fn != NULL)
  186817. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  186818. (png_ptr, /* png_ptr */
  186819. &(png_ptr->row_info), /* row_info: */
  186820. /* png_uint_32 width; width of row */
  186821. /* png_uint_32 rowbytes; number of bytes in row */
  186822. /* png_byte color_type; color type of pixels */
  186823. /* png_byte bit_depth; bit depth of samples */
  186824. /* png_byte channels; number of channels (1-4) */
  186825. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  186826. png_ptr->row_buf + 1); /* start of pixel data for row */
  186827. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  186828. if(png_ptr->user_transform_depth)
  186829. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  186830. if(png_ptr->user_transform_channels)
  186831. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  186832. #endif
  186833. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  186834. png_ptr->row_info.channels);
  186835. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  186836. png_ptr->row_info.width);
  186837. }
  186838. #endif
  186839. }
  186840. #if defined(PNG_READ_PACK_SUPPORTED)
  186841. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  186842. * without changing the actual values. Thus, if you had a row with
  186843. * a bit depth of 1, you would end up with bytes that only contained
  186844. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  186845. * png_do_shift() after this.
  186846. */
  186847. void /* PRIVATE */
  186848. png_do_unpack(png_row_infop row_info, png_bytep row)
  186849. {
  186850. png_debug(1, "in png_do_unpack\n");
  186851. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186852. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  186853. #else
  186854. if (row_info->bit_depth < 8)
  186855. #endif
  186856. {
  186857. png_uint_32 i;
  186858. png_uint_32 row_width=row_info->width;
  186859. switch (row_info->bit_depth)
  186860. {
  186861. case 1:
  186862. {
  186863. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  186864. png_bytep dp = row + (png_size_t)row_width - 1;
  186865. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  186866. for (i = 0; i < row_width; i++)
  186867. {
  186868. *dp = (png_byte)((*sp >> shift) & 0x01);
  186869. if (shift == 7)
  186870. {
  186871. shift = 0;
  186872. sp--;
  186873. }
  186874. else
  186875. shift++;
  186876. dp--;
  186877. }
  186878. break;
  186879. }
  186880. case 2:
  186881. {
  186882. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  186883. png_bytep dp = row + (png_size_t)row_width - 1;
  186884. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186885. for (i = 0; i < row_width; i++)
  186886. {
  186887. *dp = (png_byte)((*sp >> shift) & 0x03);
  186888. if (shift == 6)
  186889. {
  186890. shift = 0;
  186891. sp--;
  186892. }
  186893. else
  186894. shift += 2;
  186895. dp--;
  186896. }
  186897. break;
  186898. }
  186899. case 4:
  186900. {
  186901. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  186902. png_bytep dp = row + (png_size_t)row_width - 1;
  186903. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186904. for (i = 0; i < row_width; i++)
  186905. {
  186906. *dp = (png_byte)((*sp >> shift) & 0x0f);
  186907. if (shift == 4)
  186908. {
  186909. shift = 0;
  186910. sp--;
  186911. }
  186912. else
  186913. shift = 4;
  186914. dp--;
  186915. }
  186916. break;
  186917. }
  186918. }
  186919. row_info->bit_depth = 8;
  186920. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  186921. row_info->rowbytes = row_width * row_info->channels;
  186922. }
  186923. }
  186924. #endif
  186925. #if defined(PNG_READ_SHIFT_SUPPORTED)
  186926. /* Reverse the effects of png_do_shift. This routine merely shifts the
  186927. * pixels back to their significant bits values. Thus, if you have
  186928. * a row of bit depth 8, but only 5 are significant, this will shift
  186929. * the values back to 0 through 31.
  186930. */
  186931. void /* PRIVATE */
  186932. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  186933. {
  186934. png_debug(1, "in png_do_unshift\n");
  186935. if (
  186936. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186937. row != NULL && row_info != NULL && sig_bits != NULL &&
  186938. #endif
  186939. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  186940. {
  186941. int shift[4];
  186942. int channels = 0;
  186943. int c;
  186944. png_uint_16 value = 0;
  186945. png_uint_32 row_width = row_info->width;
  186946. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  186947. {
  186948. shift[channels++] = row_info->bit_depth - sig_bits->red;
  186949. shift[channels++] = row_info->bit_depth - sig_bits->green;
  186950. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  186951. }
  186952. else
  186953. {
  186954. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  186955. }
  186956. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186957. {
  186958. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  186959. }
  186960. for (c = 0; c < channels; c++)
  186961. {
  186962. if (shift[c] <= 0)
  186963. shift[c] = 0;
  186964. else
  186965. value = 1;
  186966. }
  186967. if (!value)
  186968. return;
  186969. switch (row_info->bit_depth)
  186970. {
  186971. case 2:
  186972. {
  186973. png_bytep bp;
  186974. png_uint_32 i;
  186975. png_uint_32 istop = row_info->rowbytes;
  186976. for (bp = row, i = 0; i < istop; i++)
  186977. {
  186978. *bp >>= 1;
  186979. *bp++ &= 0x55;
  186980. }
  186981. break;
  186982. }
  186983. case 4:
  186984. {
  186985. png_bytep bp = row;
  186986. png_uint_32 i;
  186987. png_uint_32 istop = row_info->rowbytes;
  186988. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  186989. (png_byte)((int)0xf >> shift[0]));
  186990. for (i = 0; i < istop; i++)
  186991. {
  186992. *bp >>= shift[0];
  186993. *bp++ &= mask;
  186994. }
  186995. break;
  186996. }
  186997. case 8:
  186998. {
  186999. png_bytep bp = row;
  187000. png_uint_32 i;
  187001. png_uint_32 istop = row_width * channels;
  187002. for (i = 0; i < istop; i++)
  187003. {
  187004. *bp++ >>= shift[i%channels];
  187005. }
  187006. break;
  187007. }
  187008. case 16:
  187009. {
  187010. png_bytep bp = row;
  187011. png_uint_32 i;
  187012. png_uint_32 istop = channels * row_width;
  187013. for (i = 0; i < istop; i++)
  187014. {
  187015. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  187016. value >>= shift[i%channels];
  187017. *bp++ = (png_byte)(value >> 8);
  187018. *bp++ = (png_byte)(value & 0xff);
  187019. }
  187020. break;
  187021. }
  187022. }
  187023. }
  187024. }
  187025. #endif
  187026. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  187027. /* chop rows of bit depth 16 down to 8 */
  187028. void /* PRIVATE */
  187029. png_do_chop(png_row_infop row_info, png_bytep row)
  187030. {
  187031. png_debug(1, "in png_do_chop\n");
  187032. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187033. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  187034. #else
  187035. if (row_info->bit_depth == 16)
  187036. #endif
  187037. {
  187038. png_bytep sp = row;
  187039. png_bytep dp = row;
  187040. png_uint_32 i;
  187041. png_uint_32 istop = row_info->width * row_info->channels;
  187042. for (i = 0; i<istop; i++, sp += 2, dp++)
  187043. {
  187044. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  187045. /* This does a more accurate scaling of the 16-bit color
  187046. * value, rather than a simple low-byte truncation.
  187047. *
  187048. * What the ideal calculation should be:
  187049. * *dp = (((((png_uint_32)(*sp) << 8) |
  187050. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  187051. *
  187052. * GRR: no, I think this is what it really should be:
  187053. * *dp = (((((png_uint_32)(*sp) << 8) |
  187054. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  187055. *
  187056. * GRR: here's the exact calculation with shifts:
  187057. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  187058. * *dp = (temp - (temp >> 8)) >> 8;
  187059. *
  187060. * Approximate calculation with shift/add instead of multiply/divide:
  187061. * *dp = ((((png_uint_32)(*sp) << 8) |
  187062. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  187063. *
  187064. * What we actually do to avoid extra shifting and conversion:
  187065. */
  187066. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  187067. #else
  187068. /* Simply discard the low order byte */
  187069. *dp = *sp;
  187070. #endif
  187071. }
  187072. row_info->bit_depth = 8;
  187073. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  187074. row_info->rowbytes = row_info->width * row_info->channels;
  187075. }
  187076. }
  187077. #endif
  187078. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  187079. void /* PRIVATE */
  187080. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  187081. {
  187082. png_debug(1, "in png_do_read_swap_alpha\n");
  187083. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187084. if (row != NULL && row_info != NULL)
  187085. #endif
  187086. {
  187087. png_uint_32 row_width = row_info->width;
  187088. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187089. {
  187090. /* This converts from RGBA to ARGB */
  187091. if (row_info->bit_depth == 8)
  187092. {
  187093. png_bytep sp = row + row_info->rowbytes;
  187094. png_bytep dp = sp;
  187095. png_byte save;
  187096. png_uint_32 i;
  187097. for (i = 0; i < row_width; i++)
  187098. {
  187099. save = *(--sp);
  187100. *(--dp) = *(--sp);
  187101. *(--dp) = *(--sp);
  187102. *(--dp) = *(--sp);
  187103. *(--dp) = save;
  187104. }
  187105. }
  187106. /* This converts from RRGGBBAA to AARRGGBB */
  187107. else
  187108. {
  187109. png_bytep sp = row + row_info->rowbytes;
  187110. png_bytep dp = sp;
  187111. png_byte save[2];
  187112. png_uint_32 i;
  187113. for (i = 0; i < row_width; i++)
  187114. {
  187115. save[0] = *(--sp);
  187116. save[1] = *(--sp);
  187117. *(--dp) = *(--sp);
  187118. *(--dp) = *(--sp);
  187119. *(--dp) = *(--sp);
  187120. *(--dp) = *(--sp);
  187121. *(--dp) = *(--sp);
  187122. *(--dp) = *(--sp);
  187123. *(--dp) = save[0];
  187124. *(--dp) = save[1];
  187125. }
  187126. }
  187127. }
  187128. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187129. {
  187130. /* This converts from GA to AG */
  187131. if (row_info->bit_depth == 8)
  187132. {
  187133. png_bytep sp = row + row_info->rowbytes;
  187134. png_bytep dp = sp;
  187135. png_byte save;
  187136. png_uint_32 i;
  187137. for (i = 0; i < row_width; i++)
  187138. {
  187139. save = *(--sp);
  187140. *(--dp) = *(--sp);
  187141. *(--dp) = save;
  187142. }
  187143. }
  187144. /* This converts from GGAA to AAGG */
  187145. else
  187146. {
  187147. png_bytep sp = row + row_info->rowbytes;
  187148. png_bytep dp = sp;
  187149. png_byte save[2];
  187150. png_uint_32 i;
  187151. for (i = 0; i < row_width; i++)
  187152. {
  187153. save[0] = *(--sp);
  187154. save[1] = *(--sp);
  187155. *(--dp) = *(--sp);
  187156. *(--dp) = *(--sp);
  187157. *(--dp) = save[0];
  187158. *(--dp) = save[1];
  187159. }
  187160. }
  187161. }
  187162. }
  187163. }
  187164. #endif
  187165. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  187166. void /* PRIVATE */
  187167. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  187168. {
  187169. png_debug(1, "in png_do_read_invert_alpha\n");
  187170. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187171. if (row != NULL && row_info != NULL)
  187172. #endif
  187173. {
  187174. png_uint_32 row_width = row_info->width;
  187175. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187176. {
  187177. /* This inverts the alpha channel in RGBA */
  187178. if (row_info->bit_depth == 8)
  187179. {
  187180. png_bytep sp = row + row_info->rowbytes;
  187181. png_bytep dp = sp;
  187182. png_uint_32 i;
  187183. for (i = 0; i < row_width; i++)
  187184. {
  187185. *(--dp) = (png_byte)(255 - *(--sp));
  187186. /* This does nothing:
  187187. *(--dp) = *(--sp);
  187188. *(--dp) = *(--sp);
  187189. *(--dp) = *(--sp);
  187190. We can replace it with:
  187191. */
  187192. sp-=3;
  187193. dp=sp;
  187194. }
  187195. }
  187196. /* This inverts the alpha channel in RRGGBBAA */
  187197. else
  187198. {
  187199. png_bytep sp = row + row_info->rowbytes;
  187200. png_bytep dp = sp;
  187201. png_uint_32 i;
  187202. for (i = 0; i < row_width; i++)
  187203. {
  187204. *(--dp) = (png_byte)(255 - *(--sp));
  187205. *(--dp) = (png_byte)(255 - *(--sp));
  187206. /* This does nothing:
  187207. *(--dp) = *(--sp);
  187208. *(--dp) = *(--sp);
  187209. *(--dp) = *(--sp);
  187210. *(--dp) = *(--sp);
  187211. *(--dp) = *(--sp);
  187212. *(--dp) = *(--sp);
  187213. We can replace it with:
  187214. */
  187215. sp-=6;
  187216. dp=sp;
  187217. }
  187218. }
  187219. }
  187220. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187221. {
  187222. /* This inverts the alpha channel in GA */
  187223. if (row_info->bit_depth == 8)
  187224. {
  187225. png_bytep sp = row + row_info->rowbytes;
  187226. png_bytep dp = sp;
  187227. png_uint_32 i;
  187228. for (i = 0; i < row_width; i++)
  187229. {
  187230. *(--dp) = (png_byte)(255 - *(--sp));
  187231. *(--dp) = *(--sp);
  187232. }
  187233. }
  187234. /* This inverts the alpha channel in GGAA */
  187235. else
  187236. {
  187237. png_bytep sp = row + row_info->rowbytes;
  187238. png_bytep dp = sp;
  187239. png_uint_32 i;
  187240. for (i = 0; i < row_width; i++)
  187241. {
  187242. *(--dp) = (png_byte)(255 - *(--sp));
  187243. *(--dp) = (png_byte)(255 - *(--sp));
  187244. /*
  187245. *(--dp) = *(--sp);
  187246. *(--dp) = *(--sp);
  187247. */
  187248. sp-=2;
  187249. dp=sp;
  187250. }
  187251. }
  187252. }
  187253. }
  187254. }
  187255. #endif
  187256. #if defined(PNG_READ_FILLER_SUPPORTED)
  187257. /* Add filler channel if we have RGB color */
  187258. void /* PRIVATE */
  187259. png_do_read_filler(png_row_infop row_info, png_bytep row,
  187260. png_uint_32 filler, png_uint_32 flags)
  187261. {
  187262. png_uint_32 i;
  187263. png_uint_32 row_width = row_info->width;
  187264. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  187265. png_byte lo_filler = (png_byte)(filler & 0xff);
  187266. png_debug(1, "in png_do_read_filler\n");
  187267. if (
  187268. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187269. row != NULL && row_info != NULL &&
  187270. #endif
  187271. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187272. {
  187273. if(row_info->bit_depth == 8)
  187274. {
  187275. /* This changes the data from G to GX */
  187276. if (flags & PNG_FLAG_FILLER_AFTER)
  187277. {
  187278. png_bytep sp = row + (png_size_t)row_width;
  187279. png_bytep dp = sp + (png_size_t)row_width;
  187280. for (i = 1; i < row_width; i++)
  187281. {
  187282. *(--dp) = lo_filler;
  187283. *(--dp) = *(--sp);
  187284. }
  187285. *(--dp) = lo_filler;
  187286. row_info->channels = 2;
  187287. row_info->pixel_depth = 16;
  187288. row_info->rowbytes = row_width * 2;
  187289. }
  187290. /* This changes the data from G to XG */
  187291. else
  187292. {
  187293. png_bytep sp = row + (png_size_t)row_width;
  187294. png_bytep dp = sp + (png_size_t)row_width;
  187295. for (i = 0; i < row_width; i++)
  187296. {
  187297. *(--dp) = *(--sp);
  187298. *(--dp) = lo_filler;
  187299. }
  187300. row_info->channels = 2;
  187301. row_info->pixel_depth = 16;
  187302. row_info->rowbytes = row_width * 2;
  187303. }
  187304. }
  187305. else if(row_info->bit_depth == 16)
  187306. {
  187307. /* This changes the data from GG to GGXX */
  187308. if (flags & PNG_FLAG_FILLER_AFTER)
  187309. {
  187310. png_bytep sp = row + (png_size_t)row_width * 2;
  187311. png_bytep dp = sp + (png_size_t)row_width * 2;
  187312. for (i = 1; i < row_width; i++)
  187313. {
  187314. *(--dp) = hi_filler;
  187315. *(--dp) = lo_filler;
  187316. *(--dp) = *(--sp);
  187317. *(--dp) = *(--sp);
  187318. }
  187319. *(--dp) = hi_filler;
  187320. *(--dp) = lo_filler;
  187321. row_info->channels = 2;
  187322. row_info->pixel_depth = 32;
  187323. row_info->rowbytes = row_width * 4;
  187324. }
  187325. /* This changes the data from GG to XXGG */
  187326. else
  187327. {
  187328. png_bytep sp = row + (png_size_t)row_width * 2;
  187329. png_bytep dp = sp + (png_size_t)row_width * 2;
  187330. for (i = 0; i < row_width; i++)
  187331. {
  187332. *(--dp) = *(--sp);
  187333. *(--dp) = *(--sp);
  187334. *(--dp) = hi_filler;
  187335. *(--dp) = lo_filler;
  187336. }
  187337. row_info->channels = 2;
  187338. row_info->pixel_depth = 32;
  187339. row_info->rowbytes = row_width * 4;
  187340. }
  187341. }
  187342. } /* COLOR_TYPE == GRAY */
  187343. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187344. {
  187345. if(row_info->bit_depth == 8)
  187346. {
  187347. /* This changes the data from RGB to RGBX */
  187348. if (flags & PNG_FLAG_FILLER_AFTER)
  187349. {
  187350. png_bytep sp = row + (png_size_t)row_width * 3;
  187351. png_bytep dp = sp + (png_size_t)row_width;
  187352. for (i = 1; i < row_width; i++)
  187353. {
  187354. *(--dp) = lo_filler;
  187355. *(--dp) = *(--sp);
  187356. *(--dp) = *(--sp);
  187357. *(--dp) = *(--sp);
  187358. }
  187359. *(--dp) = lo_filler;
  187360. row_info->channels = 4;
  187361. row_info->pixel_depth = 32;
  187362. row_info->rowbytes = row_width * 4;
  187363. }
  187364. /* This changes the data from RGB to XRGB */
  187365. else
  187366. {
  187367. png_bytep sp = row + (png_size_t)row_width * 3;
  187368. png_bytep dp = sp + (png_size_t)row_width;
  187369. for (i = 0; i < row_width; i++)
  187370. {
  187371. *(--dp) = *(--sp);
  187372. *(--dp) = *(--sp);
  187373. *(--dp) = *(--sp);
  187374. *(--dp) = lo_filler;
  187375. }
  187376. row_info->channels = 4;
  187377. row_info->pixel_depth = 32;
  187378. row_info->rowbytes = row_width * 4;
  187379. }
  187380. }
  187381. else if(row_info->bit_depth == 16)
  187382. {
  187383. /* This changes the data from RRGGBB to RRGGBBXX */
  187384. if (flags & PNG_FLAG_FILLER_AFTER)
  187385. {
  187386. png_bytep sp = row + (png_size_t)row_width * 6;
  187387. png_bytep dp = sp + (png_size_t)row_width * 2;
  187388. for (i = 1; i < row_width; i++)
  187389. {
  187390. *(--dp) = hi_filler;
  187391. *(--dp) = lo_filler;
  187392. *(--dp) = *(--sp);
  187393. *(--dp) = *(--sp);
  187394. *(--dp) = *(--sp);
  187395. *(--dp) = *(--sp);
  187396. *(--dp) = *(--sp);
  187397. *(--dp) = *(--sp);
  187398. }
  187399. *(--dp) = hi_filler;
  187400. *(--dp) = lo_filler;
  187401. row_info->channels = 4;
  187402. row_info->pixel_depth = 64;
  187403. row_info->rowbytes = row_width * 8;
  187404. }
  187405. /* This changes the data from RRGGBB to XXRRGGBB */
  187406. else
  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 = 0; i < row_width; i++)
  187411. {
  187412. *(--dp) = *(--sp);
  187413. *(--dp) = *(--sp);
  187414. *(--dp) = *(--sp);
  187415. *(--dp) = *(--sp);
  187416. *(--dp) = *(--sp);
  187417. *(--dp) = *(--sp);
  187418. *(--dp) = hi_filler;
  187419. *(--dp) = lo_filler;
  187420. }
  187421. row_info->channels = 4;
  187422. row_info->pixel_depth = 64;
  187423. row_info->rowbytes = row_width * 8;
  187424. }
  187425. }
  187426. } /* COLOR_TYPE == RGB */
  187427. }
  187428. #endif
  187429. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  187430. /* expand grayscale files to RGB, with or without alpha */
  187431. void /* PRIVATE */
  187432. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  187433. {
  187434. png_uint_32 i;
  187435. png_uint_32 row_width = row_info->width;
  187436. png_debug(1, "in png_do_gray_to_rgb\n");
  187437. if (row_info->bit_depth >= 8 &&
  187438. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187439. row != NULL && row_info != NULL &&
  187440. #endif
  187441. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  187442. {
  187443. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  187444. {
  187445. if (row_info->bit_depth == 8)
  187446. {
  187447. png_bytep sp = row + (png_size_t)row_width - 1;
  187448. png_bytep dp = sp + (png_size_t)row_width * 2;
  187449. for (i = 0; i < row_width; i++)
  187450. {
  187451. *(dp--) = *sp;
  187452. *(dp--) = *sp;
  187453. *(dp--) = *(sp--);
  187454. }
  187455. }
  187456. else
  187457. {
  187458. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187459. png_bytep dp = sp + (png_size_t)row_width * 4;
  187460. for (i = 0; i < row_width; i++)
  187461. {
  187462. *(dp--) = *sp;
  187463. *(dp--) = *(sp - 1);
  187464. *(dp--) = *sp;
  187465. *(dp--) = *(sp - 1);
  187466. *(dp--) = *(sp--);
  187467. *(dp--) = *(sp--);
  187468. }
  187469. }
  187470. }
  187471. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  187472. {
  187473. if (row_info->bit_depth == 8)
  187474. {
  187475. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  187476. png_bytep dp = sp + (png_size_t)row_width * 2;
  187477. for (i = 0; i < row_width; i++)
  187478. {
  187479. *(dp--) = *(sp--);
  187480. *(dp--) = *sp;
  187481. *(dp--) = *sp;
  187482. *(dp--) = *(sp--);
  187483. }
  187484. }
  187485. else
  187486. {
  187487. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  187488. png_bytep dp = sp + (png_size_t)row_width * 4;
  187489. for (i = 0; i < row_width; i++)
  187490. {
  187491. *(dp--) = *(sp--);
  187492. *(dp--) = *(sp--);
  187493. *(dp--) = *sp;
  187494. *(dp--) = *(sp - 1);
  187495. *(dp--) = *sp;
  187496. *(dp--) = *(sp - 1);
  187497. *(dp--) = *(sp--);
  187498. *(dp--) = *(sp--);
  187499. }
  187500. }
  187501. }
  187502. row_info->channels += (png_byte)2;
  187503. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  187504. row_info->pixel_depth = (png_byte)(row_info->channels *
  187505. row_info->bit_depth);
  187506. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187507. }
  187508. }
  187509. #endif
  187510. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187511. /* reduce RGB files to grayscale, with or without alpha
  187512. * using the equation given in Poynton's ColorFAQ at
  187513. * <http://www.inforamp.net/~poynton/>
  187514. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  187515. *
  187516. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  187517. *
  187518. * We approximate this with
  187519. *
  187520. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  187521. *
  187522. * which can be expressed with integers as
  187523. *
  187524. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  187525. *
  187526. * The calculation is to be done in a linear colorspace.
  187527. *
  187528. * Other integer coefficents can be used via png_set_rgb_to_gray().
  187529. */
  187530. int /* PRIVATE */
  187531. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  187532. {
  187533. png_uint_32 i;
  187534. png_uint_32 row_width = row_info->width;
  187535. int rgb_error = 0;
  187536. png_debug(1, "in png_do_rgb_to_gray\n");
  187537. if (
  187538. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187539. row != NULL && row_info != NULL &&
  187540. #endif
  187541. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187542. {
  187543. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  187544. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  187545. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  187546. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187547. {
  187548. if (row_info->bit_depth == 8)
  187549. {
  187550. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187551. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187552. {
  187553. png_bytep sp = row;
  187554. png_bytep dp = row;
  187555. for (i = 0; i < row_width; i++)
  187556. {
  187557. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187558. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187559. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187560. if(red != green || red != blue)
  187561. {
  187562. rgb_error |= 1;
  187563. *(dp++) = png_ptr->gamma_from_1[
  187564. (rc*red+gc*green+bc*blue)>>15];
  187565. }
  187566. else
  187567. *(dp++) = *(sp-1);
  187568. }
  187569. }
  187570. else
  187571. #endif
  187572. {
  187573. png_bytep sp = row;
  187574. png_bytep dp = row;
  187575. for (i = 0; i < row_width; i++)
  187576. {
  187577. png_byte red = *(sp++);
  187578. png_byte green = *(sp++);
  187579. png_byte blue = *(sp++);
  187580. if(red != green || red != blue)
  187581. {
  187582. rgb_error |= 1;
  187583. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  187584. }
  187585. else
  187586. *(dp++) = *(sp-1);
  187587. }
  187588. }
  187589. }
  187590. else /* RGB bit_depth == 16 */
  187591. {
  187592. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187593. if (png_ptr->gamma_16_to_1 != NULL &&
  187594. png_ptr->gamma_16_from_1 != NULL)
  187595. {
  187596. png_bytep sp = row;
  187597. png_bytep dp = row;
  187598. for (i = 0; i < row_width; i++)
  187599. {
  187600. png_uint_16 red, green, blue, w;
  187601. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187602. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187603. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187604. if(red == green && red == blue)
  187605. w = red;
  187606. else
  187607. {
  187608. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187609. png_ptr->gamma_shift][red>>8];
  187610. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187611. png_ptr->gamma_shift][green>>8];
  187612. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187613. png_ptr->gamma_shift][blue>>8];
  187614. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  187615. + bc*blue_1)>>15);
  187616. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187617. png_ptr->gamma_shift][gray16 >> 8];
  187618. rgb_error |= 1;
  187619. }
  187620. *(dp++) = (png_byte)((w>>8) & 0xff);
  187621. *(dp++) = (png_byte)(w & 0xff);
  187622. }
  187623. }
  187624. else
  187625. #endif
  187626. {
  187627. png_bytep sp = row;
  187628. png_bytep dp = row;
  187629. for (i = 0; i < row_width; i++)
  187630. {
  187631. png_uint_16 red, green, blue, gray16;
  187632. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187633. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187634. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187635. if(red != green || red != blue)
  187636. rgb_error |= 1;
  187637. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187638. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187639. *(dp++) = (png_byte)(gray16 & 0xff);
  187640. }
  187641. }
  187642. }
  187643. }
  187644. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187645. {
  187646. if (row_info->bit_depth == 8)
  187647. {
  187648. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187649. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  187650. {
  187651. png_bytep sp = row;
  187652. png_bytep dp = row;
  187653. for (i = 0; i < row_width; i++)
  187654. {
  187655. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  187656. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  187657. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  187658. if(red != green || red != blue)
  187659. rgb_error |= 1;
  187660. *(dp++) = png_ptr->gamma_from_1
  187661. [(rc*red + gc*green + bc*blue)>>15];
  187662. *(dp++) = *(sp++); /* alpha */
  187663. }
  187664. }
  187665. else
  187666. #endif
  187667. {
  187668. png_bytep sp = row;
  187669. png_bytep dp = row;
  187670. for (i = 0; i < row_width; i++)
  187671. {
  187672. png_byte red = *(sp++);
  187673. png_byte green = *(sp++);
  187674. png_byte blue = *(sp++);
  187675. if(red != green || red != blue)
  187676. rgb_error |= 1;
  187677. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  187678. *(dp++) = *(sp++); /* alpha */
  187679. }
  187680. }
  187681. }
  187682. else /* RGBA bit_depth == 16 */
  187683. {
  187684. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  187685. if (png_ptr->gamma_16_to_1 != NULL &&
  187686. png_ptr->gamma_16_from_1 != NULL)
  187687. {
  187688. png_bytep sp = row;
  187689. png_bytep dp = row;
  187690. for (i = 0; i < row_width; i++)
  187691. {
  187692. png_uint_16 red, green, blue, w;
  187693. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187694. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187695. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  187696. if(red == green && red == blue)
  187697. w = red;
  187698. else
  187699. {
  187700. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  187701. png_ptr->gamma_shift][red>>8];
  187702. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  187703. png_ptr->gamma_shift][green>>8];
  187704. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  187705. png_ptr->gamma_shift][blue>>8];
  187706. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  187707. + gc * green_1 + bc * blue_1)>>15);
  187708. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  187709. png_ptr->gamma_shift][gray16 >> 8];
  187710. rgb_error |= 1;
  187711. }
  187712. *(dp++) = (png_byte)((w>>8) & 0xff);
  187713. *(dp++) = (png_byte)(w & 0xff);
  187714. *(dp++) = *(sp++); /* alpha */
  187715. *(dp++) = *(sp++);
  187716. }
  187717. }
  187718. else
  187719. #endif
  187720. {
  187721. png_bytep sp = row;
  187722. png_bytep dp = row;
  187723. for (i = 0; i < row_width; i++)
  187724. {
  187725. png_uint_16 red, green, blue, gray16;
  187726. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187727. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187728. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  187729. if(red != green || red != blue)
  187730. rgb_error |= 1;
  187731. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  187732. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  187733. *(dp++) = (png_byte)(gray16 & 0xff);
  187734. *(dp++) = *(sp++); /* alpha */
  187735. *(dp++) = *(sp++);
  187736. }
  187737. }
  187738. }
  187739. }
  187740. row_info->channels -= (png_byte)2;
  187741. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  187742. row_info->pixel_depth = (png_byte)(row_info->channels *
  187743. row_info->bit_depth);
  187744. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  187745. }
  187746. return rgb_error;
  187747. }
  187748. #endif
  187749. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  187750. * large of png_color. This lets grayscale images be treated as
  187751. * paletted. Most useful for gamma correction and simplification
  187752. * of code.
  187753. */
  187754. void PNGAPI
  187755. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  187756. {
  187757. int num_palette;
  187758. int color_inc;
  187759. int i;
  187760. int v;
  187761. png_debug(1, "in png_do_build_grayscale_palette\n");
  187762. if (palette == NULL)
  187763. return;
  187764. switch (bit_depth)
  187765. {
  187766. case 1:
  187767. num_palette = 2;
  187768. color_inc = 0xff;
  187769. break;
  187770. case 2:
  187771. num_palette = 4;
  187772. color_inc = 0x55;
  187773. break;
  187774. case 4:
  187775. num_palette = 16;
  187776. color_inc = 0x11;
  187777. break;
  187778. case 8:
  187779. num_palette = 256;
  187780. color_inc = 1;
  187781. break;
  187782. default:
  187783. num_palette = 0;
  187784. color_inc = 0;
  187785. break;
  187786. }
  187787. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  187788. {
  187789. palette[i].red = (png_byte)v;
  187790. palette[i].green = (png_byte)v;
  187791. palette[i].blue = (png_byte)v;
  187792. }
  187793. }
  187794. /* This function is currently unused. Do we really need it? */
  187795. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  187796. void /* PRIVATE */
  187797. png_correct_palette(png_structp png_ptr, png_colorp palette,
  187798. int num_palette)
  187799. {
  187800. png_debug(1, "in png_correct_palette\n");
  187801. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  187802. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  187803. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  187804. {
  187805. png_color back, back_1;
  187806. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  187807. {
  187808. back.red = png_ptr->gamma_table[png_ptr->background.red];
  187809. back.green = png_ptr->gamma_table[png_ptr->background.green];
  187810. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  187811. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  187812. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  187813. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  187814. }
  187815. else
  187816. {
  187817. double g;
  187818. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  187819. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  187820. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  187821. {
  187822. back.red = png_ptr->background.red;
  187823. back.green = png_ptr->background.green;
  187824. back.blue = png_ptr->background.blue;
  187825. }
  187826. else
  187827. {
  187828. back.red =
  187829. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187830. 255.0 + 0.5);
  187831. back.green =
  187832. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187833. 255.0 + 0.5);
  187834. back.blue =
  187835. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187836. 255.0 + 0.5);
  187837. }
  187838. g = 1.0 / png_ptr->background_gamma;
  187839. back_1.red =
  187840. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  187841. 255.0 + 0.5);
  187842. back_1.green =
  187843. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  187844. 255.0 + 0.5);
  187845. back_1.blue =
  187846. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  187847. 255.0 + 0.5);
  187848. }
  187849. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187850. {
  187851. png_uint_32 i;
  187852. for (i = 0; i < (png_uint_32)num_palette; i++)
  187853. {
  187854. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  187855. {
  187856. palette[i] = back;
  187857. }
  187858. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  187859. {
  187860. png_byte v, w;
  187861. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  187862. png_composite(w, v, png_ptr->trans[i], back_1.red);
  187863. palette[i].red = png_ptr->gamma_from_1[w];
  187864. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  187865. png_composite(w, v, png_ptr->trans[i], back_1.green);
  187866. palette[i].green = png_ptr->gamma_from_1[w];
  187867. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  187868. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  187869. palette[i].blue = png_ptr->gamma_from_1[w];
  187870. }
  187871. else
  187872. {
  187873. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187874. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187875. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187876. }
  187877. }
  187878. }
  187879. else
  187880. {
  187881. int i;
  187882. for (i = 0; i < num_palette; i++)
  187883. {
  187884. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  187885. {
  187886. palette[i] = back;
  187887. }
  187888. else
  187889. {
  187890. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187891. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187892. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187893. }
  187894. }
  187895. }
  187896. }
  187897. else
  187898. #endif
  187899. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187900. if (png_ptr->transformations & PNG_GAMMA)
  187901. {
  187902. int i;
  187903. for (i = 0; i < num_palette; i++)
  187904. {
  187905. palette[i].red = png_ptr->gamma_table[palette[i].red];
  187906. palette[i].green = png_ptr->gamma_table[palette[i].green];
  187907. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  187908. }
  187909. }
  187910. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187911. else
  187912. #endif
  187913. #endif
  187914. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187915. if (png_ptr->transformations & PNG_BACKGROUND)
  187916. {
  187917. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187918. {
  187919. png_color back;
  187920. back.red = (png_byte)png_ptr->background.red;
  187921. back.green = (png_byte)png_ptr->background.green;
  187922. back.blue = (png_byte)png_ptr->background.blue;
  187923. for (i = 0; i < (int)png_ptr->num_trans; i++)
  187924. {
  187925. if (png_ptr->trans[i] == 0)
  187926. {
  187927. palette[i].red = back.red;
  187928. palette[i].green = back.green;
  187929. palette[i].blue = back.blue;
  187930. }
  187931. else if (png_ptr->trans[i] != 0xff)
  187932. {
  187933. png_composite(palette[i].red, png_ptr->palette[i].red,
  187934. png_ptr->trans[i], back.red);
  187935. png_composite(palette[i].green, png_ptr->palette[i].green,
  187936. png_ptr->trans[i], back.green);
  187937. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  187938. png_ptr->trans[i], back.blue);
  187939. }
  187940. }
  187941. }
  187942. else /* assume grayscale palette (what else could it be?) */
  187943. {
  187944. int i;
  187945. for (i = 0; i < num_palette; i++)
  187946. {
  187947. if (i == (png_byte)png_ptr->trans_values.gray)
  187948. {
  187949. palette[i].red = (png_byte)png_ptr->background.red;
  187950. palette[i].green = (png_byte)png_ptr->background.green;
  187951. palette[i].blue = (png_byte)png_ptr->background.blue;
  187952. }
  187953. }
  187954. }
  187955. }
  187956. #endif
  187957. }
  187958. #endif
  187959. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  187960. /* Replace any alpha or transparency with the supplied background color.
  187961. * "background" is already in the screen gamma, while "background_1" is
  187962. * at a gamma of 1.0. Paletted files have already been taken care of.
  187963. */
  187964. void /* PRIVATE */
  187965. png_do_background(png_row_infop row_info, png_bytep row,
  187966. png_color_16p trans_values, png_color_16p background
  187967. #if defined(PNG_READ_GAMMA_SUPPORTED)
  187968. , png_color_16p background_1,
  187969. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  187970. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  187971. png_uint_16pp gamma_16_to_1, int gamma_shift
  187972. #endif
  187973. )
  187974. {
  187975. png_bytep sp, dp;
  187976. png_uint_32 i;
  187977. png_uint_32 row_width=row_info->width;
  187978. int shift;
  187979. png_debug(1, "in png_do_background\n");
  187980. if (background != NULL &&
  187981. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187982. row != NULL && row_info != NULL &&
  187983. #endif
  187984. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  187985. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  187986. {
  187987. switch (row_info->color_type)
  187988. {
  187989. case PNG_COLOR_TYPE_GRAY:
  187990. {
  187991. switch (row_info->bit_depth)
  187992. {
  187993. case 1:
  187994. {
  187995. sp = row;
  187996. shift = 7;
  187997. for (i = 0; i < row_width; i++)
  187998. {
  187999. if ((png_uint_16)((*sp >> shift) & 0x01)
  188000. == trans_values->gray)
  188001. {
  188002. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  188003. *sp |= (png_byte)(background->gray << shift);
  188004. }
  188005. if (!shift)
  188006. {
  188007. shift = 7;
  188008. sp++;
  188009. }
  188010. else
  188011. shift--;
  188012. }
  188013. break;
  188014. }
  188015. case 2:
  188016. {
  188017. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188018. if (gamma_table != NULL)
  188019. {
  188020. sp = row;
  188021. shift = 6;
  188022. for (i = 0; i < row_width; i++)
  188023. {
  188024. if ((png_uint_16)((*sp >> shift) & 0x03)
  188025. == trans_values->gray)
  188026. {
  188027. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188028. *sp |= (png_byte)(background->gray << shift);
  188029. }
  188030. else
  188031. {
  188032. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  188033. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  188034. (p << 4) | (p << 6)] >> 6) & 0x03);
  188035. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188036. *sp |= (png_byte)(g << shift);
  188037. }
  188038. if (!shift)
  188039. {
  188040. shift = 6;
  188041. sp++;
  188042. }
  188043. else
  188044. shift -= 2;
  188045. }
  188046. }
  188047. else
  188048. #endif
  188049. {
  188050. sp = row;
  188051. shift = 6;
  188052. for (i = 0; i < row_width; i++)
  188053. {
  188054. if ((png_uint_16)((*sp >> shift) & 0x03)
  188055. == trans_values->gray)
  188056. {
  188057. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  188058. *sp |= (png_byte)(background->gray << shift);
  188059. }
  188060. if (!shift)
  188061. {
  188062. shift = 6;
  188063. sp++;
  188064. }
  188065. else
  188066. shift -= 2;
  188067. }
  188068. }
  188069. break;
  188070. }
  188071. case 4:
  188072. {
  188073. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188074. if (gamma_table != NULL)
  188075. {
  188076. sp = row;
  188077. shift = 4;
  188078. for (i = 0; i < row_width; i++)
  188079. {
  188080. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188081. == trans_values->gray)
  188082. {
  188083. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188084. *sp |= (png_byte)(background->gray << shift);
  188085. }
  188086. else
  188087. {
  188088. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  188089. png_byte g = (png_byte)((gamma_table[p |
  188090. (p << 4)] >> 4) & 0x0f);
  188091. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188092. *sp |= (png_byte)(g << shift);
  188093. }
  188094. if (!shift)
  188095. {
  188096. shift = 4;
  188097. sp++;
  188098. }
  188099. else
  188100. shift -= 4;
  188101. }
  188102. }
  188103. else
  188104. #endif
  188105. {
  188106. sp = row;
  188107. shift = 4;
  188108. for (i = 0; i < row_width; i++)
  188109. {
  188110. if ((png_uint_16)((*sp >> shift) & 0x0f)
  188111. == trans_values->gray)
  188112. {
  188113. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  188114. *sp |= (png_byte)(background->gray << shift);
  188115. }
  188116. if (!shift)
  188117. {
  188118. shift = 4;
  188119. sp++;
  188120. }
  188121. else
  188122. shift -= 4;
  188123. }
  188124. }
  188125. break;
  188126. }
  188127. case 8:
  188128. {
  188129. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188130. if (gamma_table != NULL)
  188131. {
  188132. sp = row;
  188133. for (i = 0; i < row_width; i++, sp++)
  188134. {
  188135. if (*sp == trans_values->gray)
  188136. {
  188137. *sp = (png_byte)background->gray;
  188138. }
  188139. else
  188140. {
  188141. *sp = gamma_table[*sp];
  188142. }
  188143. }
  188144. }
  188145. else
  188146. #endif
  188147. {
  188148. sp = row;
  188149. for (i = 0; i < row_width; i++, sp++)
  188150. {
  188151. if (*sp == trans_values->gray)
  188152. {
  188153. *sp = (png_byte)background->gray;
  188154. }
  188155. }
  188156. }
  188157. break;
  188158. }
  188159. case 16:
  188160. {
  188161. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188162. if (gamma_16 != NULL)
  188163. {
  188164. sp = row;
  188165. for (i = 0; i < row_width; i++, sp += 2)
  188166. {
  188167. png_uint_16 v;
  188168. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188169. if (v == trans_values->gray)
  188170. {
  188171. /* background is already in screen gamma */
  188172. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188173. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188174. }
  188175. else
  188176. {
  188177. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188178. *sp = (png_byte)((v >> 8) & 0xff);
  188179. *(sp + 1) = (png_byte)(v & 0xff);
  188180. }
  188181. }
  188182. }
  188183. else
  188184. #endif
  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. *sp = (png_byte)((background->gray >> 8) & 0xff);
  188194. *(sp + 1) = (png_byte)(background->gray & 0xff);
  188195. }
  188196. }
  188197. }
  188198. break;
  188199. }
  188200. }
  188201. break;
  188202. }
  188203. case PNG_COLOR_TYPE_RGB:
  188204. {
  188205. if (row_info->bit_depth == 8)
  188206. {
  188207. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188208. if (gamma_table != NULL)
  188209. {
  188210. sp = row;
  188211. for (i = 0; i < row_width; i++, sp += 3)
  188212. {
  188213. if (*sp == trans_values->red &&
  188214. *(sp + 1) == trans_values->green &&
  188215. *(sp + 2) == trans_values->blue)
  188216. {
  188217. *sp = (png_byte)background->red;
  188218. *(sp + 1) = (png_byte)background->green;
  188219. *(sp + 2) = (png_byte)background->blue;
  188220. }
  188221. else
  188222. {
  188223. *sp = gamma_table[*sp];
  188224. *(sp + 1) = gamma_table[*(sp + 1)];
  188225. *(sp + 2) = gamma_table[*(sp + 2)];
  188226. }
  188227. }
  188228. }
  188229. else
  188230. #endif
  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. }
  188244. }
  188245. }
  188246. else /* if (row_info->bit_depth == 16) */
  188247. {
  188248. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188249. if (gamma_16 != NULL)
  188250. {
  188251. sp = row;
  188252. for (i = 0; i < row_width; i++, sp += 6)
  188253. {
  188254. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188255. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188256. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188257. if (r == trans_values->red && g == trans_values->green &&
  188258. b == trans_values->blue)
  188259. {
  188260. /* background is already in screen gamma */
  188261. *sp = (png_byte)((background->red >> 8) & 0xff);
  188262. *(sp + 1) = (png_byte)(background->red & 0xff);
  188263. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188264. *(sp + 3) = (png_byte)(background->green & 0xff);
  188265. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188266. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188267. }
  188268. else
  188269. {
  188270. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188271. *sp = (png_byte)((v >> 8) & 0xff);
  188272. *(sp + 1) = (png_byte)(v & 0xff);
  188273. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188274. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  188275. *(sp + 3) = (png_byte)(v & 0xff);
  188276. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188277. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  188278. *(sp + 5) = (png_byte)(v & 0xff);
  188279. }
  188280. }
  188281. }
  188282. else
  188283. #endif
  188284. {
  188285. sp = row;
  188286. for (i = 0; i < row_width; i++, sp += 6)
  188287. {
  188288. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  188289. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188290. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  188291. if (r == trans_values->red && g == trans_values->green &&
  188292. b == trans_values->blue)
  188293. {
  188294. *sp = (png_byte)((background->red >> 8) & 0xff);
  188295. *(sp + 1) = (png_byte)(background->red & 0xff);
  188296. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188297. *(sp + 3) = (png_byte)(background->green & 0xff);
  188298. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188299. *(sp + 5) = (png_byte)(background->blue & 0xff);
  188300. }
  188301. }
  188302. }
  188303. }
  188304. break;
  188305. }
  188306. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188307. {
  188308. if (row_info->bit_depth == 8)
  188309. {
  188310. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188311. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188312. gamma_table != NULL)
  188313. {
  188314. sp = row;
  188315. dp = row;
  188316. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188317. {
  188318. png_uint_16 a = *(sp + 1);
  188319. if (a == 0xff)
  188320. {
  188321. *dp = gamma_table[*sp];
  188322. }
  188323. else if (a == 0)
  188324. {
  188325. /* background is already in screen gamma */
  188326. *dp = (png_byte)background->gray;
  188327. }
  188328. else
  188329. {
  188330. png_byte v, w;
  188331. v = gamma_to_1[*sp];
  188332. png_composite(w, v, a, background_1->gray);
  188333. *dp = gamma_from_1[w];
  188334. }
  188335. }
  188336. }
  188337. else
  188338. #endif
  188339. {
  188340. sp = row;
  188341. dp = row;
  188342. for (i = 0; i < row_width; i++, sp += 2, dp++)
  188343. {
  188344. png_byte a = *(sp + 1);
  188345. if (a == 0xff)
  188346. {
  188347. *dp = *sp;
  188348. }
  188349. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188350. else if (a == 0)
  188351. {
  188352. *dp = (png_byte)background->gray;
  188353. }
  188354. else
  188355. {
  188356. png_composite(*dp, *sp, a, background_1->gray);
  188357. }
  188358. #else
  188359. *dp = (png_byte)background->gray;
  188360. #endif
  188361. }
  188362. }
  188363. }
  188364. else /* if (png_ptr->bit_depth == 16) */
  188365. {
  188366. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188367. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188368. gamma_16_to_1 != NULL)
  188369. {
  188370. sp = row;
  188371. dp = row;
  188372. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188373. {
  188374. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188375. if (a == (png_uint_16)0xffff)
  188376. {
  188377. png_uint_16 v;
  188378. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188379. *dp = (png_byte)((v >> 8) & 0xff);
  188380. *(dp + 1) = (png_byte)(v & 0xff);
  188381. }
  188382. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188383. else if (a == 0)
  188384. #else
  188385. else
  188386. #endif
  188387. {
  188388. /* background is already in screen gamma */
  188389. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188390. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188391. }
  188392. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188393. else
  188394. {
  188395. png_uint_16 g, v, w;
  188396. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188397. png_composite_16(v, g, a, background_1->gray);
  188398. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  188399. *dp = (png_byte)((w >> 8) & 0xff);
  188400. *(dp + 1) = (png_byte)(w & 0xff);
  188401. }
  188402. #endif
  188403. }
  188404. }
  188405. else
  188406. #endif
  188407. {
  188408. sp = row;
  188409. dp = row;
  188410. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  188411. {
  188412. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  188413. if (a == (png_uint_16)0xffff)
  188414. {
  188415. png_memcpy(dp, sp, 2);
  188416. }
  188417. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188418. else if (a == 0)
  188419. #else
  188420. else
  188421. #endif
  188422. {
  188423. *dp = (png_byte)((background->gray >> 8) & 0xff);
  188424. *(dp + 1) = (png_byte)(background->gray & 0xff);
  188425. }
  188426. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188427. else
  188428. {
  188429. png_uint_16 g, v;
  188430. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188431. png_composite_16(v, g, a, background_1->gray);
  188432. *dp = (png_byte)((v >> 8) & 0xff);
  188433. *(dp + 1) = (png_byte)(v & 0xff);
  188434. }
  188435. #endif
  188436. }
  188437. }
  188438. }
  188439. break;
  188440. }
  188441. case PNG_COLOR_TYPE_RGB_ALPHA:
  188442. {
  188443. if (row_info->bit_depth == 8)
  188444. {
  188445. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188446. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  188447. gamma_table != NULL)
  188448. {
  188449. sp = row;
  188450. dp = row;
  188451. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188452. {
  188453. png_byte a = *(sp + 3);
  188454. if (a == 0xff)
  188455. {
  188456. *dp = gamma_table[*sp];
  188457. *(dp + 1) = gamma_table[*(sp + 1)];
  188458. *(dp + 2) = gamma_table[*(sp + 2)];
  188459. }
  188460. else if (a == 0)
  188461. {
  188462. /* background is already in screen gamma */
  188463. *dp = (png_byte)background->red;
  188464. *(dp + 1) = (png_byte)background->green;
  188465. *(dp + 2) = (png_byte)background->blue;
  188466. }
  188467. else
  188468. {
  188469. png_byte v, w;
  188470. v = gamma_to_1[*sp];
  188471. png_composite(w, v, a, background_1->red);
  188472. *dp = gamma_from_1[w];
  188473. v = gamma_to_1[*(sp + 1)];
  188474. png_composite(w, v, a, background_1->green);
  188475. *(dp + 1) = gamma_from_1[w];
  188476. v = gamma_to_1[*(sp + 2)];
  188477. png_composite(w, v, a, background_1->blue);
  188478. *(dp + 2) = gamma_from_1[w];
  188479. }
  188480. }
  188481. }
  188482. else
  188483. #endif
  188484. {
  188485. sp = row;
  188486. dp = row;
  188487. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  188488. {
  188489. png_byte a = *(sp + 3);
  188490. if (a == 0xff)
  188491. {
  188492. *dp = *sp;
  188493. *(dp + 1) = *(sp + 1);
  188494. *(dp + 2) = *(sp + 2);
  188495. }
  188496. else if (a == 0)
  188497. {
  188498. *dp = (png_byte)background->red;
  188499. *(dp + 1) = (png_byte)background->green;
  188500. *(dp + 2) = (png_byte)background->blue;
  188501. }
  188502. else
  188503. {
  188504. png_composite(*dp, *sp, a, background->red);
  188505. png_composite(*(dp + 1), *(sp + 1), a,
  188506. background->green);
  188507. png_composite(*(dp + 2), *(sp + 2), a,
  188508. background->blue);
  188509. }
  188510. }
  188511. }
  188512. }
  188513. else /* if (row_info->bit_depth == 16) */
  188514. {
  188515. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188516. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  188517. gamma_16_to_1 != NULL)
  188518. {
  188519. sp = row;
  188520. dp = row;
  188521. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188522. {
  188523. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188524. << 8) + (png_uint_16)(*(sp + 7)));
  188525. if (a == (png_uint_16)0xffff)
  188526. {
  188527. png_uint_16 v;
  188528. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  188529. *dp = (png_byte)((v >> 8) & 0xff);
  188530. *(dp + 1) = (png_byte)(v & 0xff);
  188531. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188532. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188533. *(dp + 3) = (png_byte)(v & 0xff);
  188534. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188535. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188536. *(dp + 5) = (png_byte)(v & 0xff);
  188537. }
  188538. else if (a == 0)
  188539. {
  188540. /* background is already in screen gamma */
  188541. *dp = (png_byte)((background->red >> 8) & 0xff);
  188542. *(dp + 1) = (png_byte)(background->red & 0xff);
  188543. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188544. *(dp + 3) = (png_byte)(background->green & 0xff);
  188545. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188546. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188547. }
  188548. else
  188549. {
  188550. png_uint_16 v, w, x;
  188551. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  188552. png_composite_16(w, v, a, background_1->red);
  188553. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188554. *dp = (png_byte)((x >> 8) & 0xff);
  188555. *(dp + 1) = (png_byte)(x & 0xff);
  188556. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  188557. png_composite_16(w, v, a, background_1->green);
  188558. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  188559. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  188560. *(dp + 3) = (png_byte)(x & 0xff);
  188561. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  188562. png_composite_16(w, v, a, background_1->blue);
  188563. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  188564. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  188565. *(dp + 5) = (png_byte)(x & 0xff);
  188566. }
  188567. }
  188568. }
  188569. else
  188570. #endif
  188571. {
  188572. sp = row;
  188573. dp = row;
  188574. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  188575. {
  188576. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  188577. << 8) + (png_uint_16)(*(sp + 7)));
  188578. if (a == (png_uint_16)0xffff)
  188579. {
  188580. png_memcpy(dp, sp, 6);
  188581. }
  188582. else if (a == 0)
  188583. {
  188584. *dp = (png_byte)((background->red >> 8) & 0xff);
  188585. *(dp + 1) = (png_byte)(background->red & 0xff);
  188586. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  188587. *(dp + 3) = (png_byte)(background->green & 0xff);
  188588. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  188589. *(dp + 5) = (png_byte)(background->blue & 0xff);
  188590. }
  188591. else
  188592. {
  188593. png_uint_16 v;
  188594. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  188595. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  188596. + *(sp + 3));
  188597. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  188598. + *(sp + 5));
  188599. png_composite_16(v, r, a, background->red);
  188600. *dp = (png_byte)((v >> 8) & 0xff);
  188601. *(dp + 1) = (png_byte)(v & 0xff);
  188602. png_composite_16(v, g, a, background->green);
  188603. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  188604. *(dp + 3) = (png_byte)(v & 0xff);
  188605. png_composite_16(v, b, a, background->blue);
  188606. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  188607. *(dp + 5) = (png_byte)(v & 0xff);
  188608. }
  188609. }
  188610. }
  188611. }
  188612. break;
  188613. }
  188614. }
  188615. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  188616. {
  188617. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  188618. row_info->channels--;
  188619. row_info->pixel_depth = (png_byte)(row_info->channels *
  188620. row_info->bit_depth);
  188621. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  188622. }
  188623. }
  188624. }
  188625. #endif
  188626. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188627. /* Gamma correct the image, avoiding the alpha channel. Make sure
  188628. * you do this after you deal with the transparency issue on grayscale
  188629. * or RGB images. If your bit depth is 8, use gamma_table, if it
  188630. * is 16, use gamma_16_table and gamma_shift. Build these with
  188631. * build_gamma_table().
  188632. */
  188633. void /* PRIVATE */
  188634. png_do_gamma(png_row_infop row_info, png_bytep row,
  188635. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  188636. int gamma_shift)
  188637. {
  188638. png_bytep sp;
  188639. png_uint_32 i;
  188640. png_uint_32 row_width=row_info->width;
  188641. png_debug(1, "in png_do_gamma\n");
  188642. if (
  188643. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188644. row != NULL && row_info != NULL &&
  188645. #endif
  188646. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  188647. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  188648. {
  188649. switch (row_info->color_type)
  188650. {
  188651. case PNG_COLOR_TYPE_RGB:
  188652. {
  188653. if (row_info->bit_depth == 8)
  188654. {
  188655. sp = row;
  188656. for (i = 0; i < row_width; i++)
  188657. {
  188658. *sp = gamma_table[*sp];
  188659. sp++;
  188660. *sp = gamma_table[*sp];
  188661. sp++;
  188662. *sp = gamma_table[*sp];
  188663. sp++;
  188664. }
  188665. }
  188666. else /* if (row_info->bit_depth == 16) */
  188667. {
  188668. sp = row;
  188669. for (i = 0; i < row_width; i++)
  188670. {
  188671. png_uint_16 v;
  188672. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188673. *sp = (png_byte)((v >> 8) & 0xff);
  188674. *(sp + 1) = (png_byte)(v & 0xff);
  188675. sp += 2;
  188676. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188677. *sp = (png_byte)((v >> 8) & 0xff);
  188678. *(sp + 1) = (png_byte)(v & 0xff);
  188679. sp += 2;
  188680. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188681. *sp = (png_byte)((v >> 8) & 0xff);
  188682. *(sp + 1) = (png_byte)(v & 0xff);
  188683. sp += 2;
  188684. }
  188685. }
  188686. break;
  188687. }
  188688. case PNG_COLOR_TYPE_RGB_ALPHA:
  188689. {
  188690. if (row_info->bit_depth == 8)
  188691. {
  188692. sp = row;
  188693. for (i = 0; i < row_width; i++)
  188694. {
  188695. *sp = gamma_table[*sp];
  188696. sp++;
  188697. *sp = gamma_table[*sp];
  188698. sp++;
  188699. *sp = gamma_table[*sp];
  188700. sp++;
  188701. sp++;
  188702. }
  188703. }
  188704. else /* if (row_info->bit_depth == 16) */
  188705. {
  188706. sp = row;
  188707. for (i = 0; i < row_width; i++)
  188708. {
  188709. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188710. *sp = (png_byte)((v >> 8) & 0xff);
  188711. *(sp + 1) = (png_byte)(v & 0xff);
  188712. sp += 2;
  188713. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188714. *sp = (png_byte)((v >> 8) & 0xff);
  188715. *(sp + 1) = (png_byte)(v & 0xff);
  188716. sp += 2;
  188717. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188718. *sp = (png_byte)((v >> 8) & 0xff);
  188719. *(sp + 1) = (png_byte)(v & 0xff);
  188720. sp += 4;
  188721. }
  188722. }
  188723. break;
  188724. }
  188725. case PNG_COLOR_TYPE_GRAY_ALPHA:
  188726. {
  188727. if (row_info->bit_depth == 8)
  188728. {
  188729. sp = row;
  188730. for (i = 0; i < row_width; i++)
  188731. {
  188732. *sp = gamma_table[*sp];
  188733. sp += 2;
  188734. }
  188735. }
  188736. else /* if (row_info->bit_depth == 16) */
  188737. {
  188738. sp = row;
  188739. for (i = 0; i < row_width; i++)
  188740. {
  188741. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188742. *sp = (png_byte)((v >> 8) & 0xff);
  188743. *(sp + 1) = (png_byte)(v & 0xff);
  188744. sp += 4;
  188745. }
  188746. }
  188747. break;
  188748. }
  188749. case PNG_COLOR_TYPE_GRAY:
  188750. {
  188751. if (row_info->bit_depth == 2)
  188752. {
  188753. sp = row;
  188754. for (i = 0; i < row_width; i += 4)
  188755. {
  188756. int a = *sp & 0xc0;
  188757. int b = *sp & 0x30;
  188758. int c = *sp & 0x0c;
  188759. int d = *sp & 0x03;
  188760. *sp = (png_byte)(
  188761. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  188762. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  188763. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  188764. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  188765. sp++;
  188766. }
  188767. }
  188768. if (row_info->bit_depth == 4)
  188769. {
  188770. sp = row;
  188771. for (i = 0; i < row_width; i += 2)
  188772. {
  188773. int msb = *sp & 0xf0;
  188774. int lsb = *sp & 0x0f;
  188775. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  188776. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  188777. sp++;
  188778. }
  188779. }
  188780. else if (row_info->bit_depth == 8)
  188781. {
  188782. sp = row;
  188783. for (i = 0; i < row_width; i++)
  188784. {
  188785. *sp = gamma_table[*sp];
  188786. sp++;
  188787. }
  188788. }
  188789. else if (row_info->bit_depth == 16)
  188790. {
  188791. sp = row;
  188792. for (i = 0; i < row_width; i++)
  188793. {
  188794. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  188795. *sp = (png_byte)((v >> 8) & 0xff);
  188796. *(sp + 1) = (png_byte)(v & 0xff);
  188797. sp += 2;
  188798. }
  188799. }
  188800. break;
  188801. }
  188802. }
  188803. }
  188804. }
  188805. #endif
  188806. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188807. /* Expands a palette row to an RGB or RGBA row depending
  188808. * upon whether you supply trans and num_trans.
  188809. */
  188810. void /* PRIVATE */
  188811. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  188812. png_colorp palette, png_bytep trans, int num_trans)
  188813. {
  188814. int shift, value;
  188815. png_bytep sp, dp;
  188816. png_uint_32 i;
  188817. png_uint_32 row_width=row_info->width;
  188818. png_debug(1, "in png_do_expand_palette\n");
  188819. if (
  188820. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188821. row != NULL && row_info != NULL &&
  188822. #endif
  188823. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  188824. {
  188825. if (row_info->bit_depth < 8)
  188826. {
  188827. switch (row_info->bit_depth)
  188828. {
  188829. case 1:
  188830. {
  188831. sp = row + (png_size_t)((row_width - 1) >> 3);
  188832. dp = row + (png_size_t)row_width - 1;
  188833. shift = 7 - (int)((row_width + 7) & 0x07);
  188834. for (i = 0; i < row_width; i++)
  188835. {
  188836. if ((*sp >> shift) & 0x01)
  188837. *dp = 1;
  188838. else
  188839. *dp = 0;
  188840. if (shift == 7)
  188841. {
  188842. shift = 0;
  188843. sp--;
  188844. }
  188845. else
  188846. shift++;
  188847. dp--;
  188848. }
  188849. break;
  188850. }
  188851. case 2:
  188852. {
  188853. sp = row + (png_size_t)((row_width - 1) >> 2);
  188854. dp = row + (png_size_t)row_width - 1;
  188855. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188856. for (i = 0; i < row_width; i++)
  188857. {
  188858. value = (*sp >> shift) & 0x03;
  188859. *dp = (png_byte)value;
  188860. if (shift == 6)
  188861. {
  188862. shift = 0;
  188863. sp--;
  188864. }
  188865. else
  188866. shift += 2;
  188867. dp--;
  188868. }
  188869. break;
  188870. }
  188871. case 4:
  188872. {
  188873. sp = row + (png_size_t)((row_width - 1) >> 1);
  188874. dp = row + (png_size_t)row_width - 1;
  188875. shift = (int)((row_width & 0x01) << 2);
  188876. for (i = 0; i < row_width; i++)
  188877. {
  188878. value = (*sp >> shift) & 0x0f;
  188879. *dp = (png_byte)value;
  188880. if (shift == 4)
  188881. {
  188882. shift = 0;
  188883. sp--;
  188884. }
  188885. else
  188886. shift += 4;
  188887. dp--;
  188888. }
  188889. break;
  188890. }
  188891. }
  188892. row_info->bit_depth = 8;
  188893. row_info->pixel_depth = 8;
  188894. row_info->rowbytes = row_width;
  188895. }
  188896. switch (row_info->bit_depth)
  188897. {
  188898. case 8:
  188899. {
  188900. if (trans != NULL)
  188901. {
  188902. sp = row + (png_size_t)row_width - 1;
  188903. dp = row + (png_size_t)(row_width << 2) - 1;
  188904. for (i = 0; i < row_width; i++)
  188905. {
  188906. if ((int)(*sp) >= num_trans)
  188907. *dp-- = 0xff;
  188908. else
  188909. *dp-- = trans[*sp];
  188910. *dp-- = palette[*sp].blue;
  188911. *dp-- = palette[*sp].green;
  188912. *dp-- = palette[*sp].red;
  188913. sp--;
  188914. }
  188915. row_info->bit_depth = 8;
  188916. row_info->pixel_depth = 32;
  188917. row_info->rowbytes = row_width * 4;
  188918. row_info->color_type = 6;
  188919. row_info->channels = 4;
  188920. }
  188921. else
  188922. {
  188923. sp = row + (png_size_t)row_width - 1;
  188924. dp = row + (png_size_t)(row_width * 3) - 1;
  188925. for (i = 0; i < row_width; i++)
  188926. {
  188927. *dp-- = palette[*sp].blue;
  188928. *dp-- = palette[*sp].green;
  188929. *dp-- = palette[*sp].red;
  188930. sp--;
  188931. }
  188932. row_info->bit_depth = 8;
  188933. row_info->pixel_depth = 24;
  188934. row_info->rowbytes = row_width * 3;
  188935. row_info->color_type = 2;
  188936. row_info->channels = 3;
  188937. }
  188938. break;
  188939. }
  188940. }
  188941. }
  188942. }
  188943. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  188944. * expanded transparency value is supplied, an alpha channel is built.
  188945. */
  188946. void /* PRIVATE */
  188947. png_do_expand(png_row_infop row_info, png_bytep row,
  188948. png_color_16p trans_value)
  188949. {
  188950. int shift, value;
  188951. png_bytep sp, dp;
  188952. png_uint_32 i;
  188953. png_uint_32 row_width=row_info->width;
  188954. png_debug(1, "in png_do_expand\n");
  188955. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  188956. if (row != NULL && row_info != NULL)
  188957. #endif
  188958. {
  188959. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  188960. {
  188961. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  188962. if (row_info->bit_depth < 8)
  188963. {
  188964. switch (row_info->bit_depth)
  188965. {
  188966. case 1:
  188967. {
  188968. gray = (png_uint_16)((gray&0x01)*0xff);
  188969. sp = row + (png_size_t)((row_width - 1) >> 3);
  188970. dp = row + (png_size_t)row_width - 1;
  188971. shift = 7 - (int)((row_width + 7) & 0x07);
  188972. for (i = 0; i < row_width; i++)
  188973. {
  188974. if ((*sp >> shift) & 0x01)
  188975. *dp = 0xff;
  188976. else
  188977. *dp = 0;
  188978. if (shift == 7)
  188979. {
  188980. shift = 0;
  188981. sp--;
  188982. }
  188983. else
  188984. shift++;
  188985. dp--;
  188986. }
  188987. break;
  188988. }
  188989. case 2:
  188990. {
  188991. gray = (png_uint_16)((gray&0x03)*0x55);
  188992. sp = row + (png_size_t)((row_width - 1) >> 2);
  188993. dp = row + (png_size_t)row_width - 1;
  188994. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  188995. for (i = 0; i < row_width; i++)
  188996. {
  188997. value = (*sp >> shift) & 0x03;
  188998. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  188999. (value << 6));
  189000. if (shift == 6)
  189001. {
  189002. shift = 0;
  189003. sp--;
  189004. }
  189005. else
  189006. shift += 2;
  189007. dp--;
  189008. }
  189009. break;
  189010. }
  189011. case 4:
  189012. {
  189013. gray = (png_uint_16)((gray&0x0f)*0x11);
  189014. sp = row + (png_size_t)((row_width - 1) >> 1);
  189015. dp = row + (png_size_t)row_width - 1;
  189016. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  189017. for (i = 0; i < row_width; i++)
  189018. {
  189019. value = (*sp >> shift) & 0x0f;
  189020. *dp = (png_byte)(value | (value << 4));
  189021. if (shift == 4)
  189022. {
  189023. shift = 0;
  189024. sp--;
  189025. }
  189026. else
  189027. shift = 4;
  189028. dp--;
  189029. }
  189030. break;
  189031. }
  189032. }
  189033. row_info->bit_depth = 8;
  189034. row_info->pixel_depth = 8;
  189035. row_info->rowbytes = row_width;
  189036. }
  189037. if (trans_value != NULL)
  189038. {
  189039. if (row_info->bit_depth == 8)
  189040. {
  189041. gray = gray & 0xff;
  189042. sp = row + (png_size_t)row_width - 1;
  189043. dp = row + (png_size_t)(row_width << 1) - 1;
  189044. for (i = 0; i < row_width; i++)
  189045. {
  189046. if (*sp == gray)
  189047. *dp-- = 0;
  189048. else
  189049. *dp-- = 0xff;
  189050. *dp-- = *sp--;
  189051. }
  189052. }
  189053. else if (row_info->bit_depth == 16)
  189054. {
  189055. png_byte gray_high = (gray >> 8) & 0xff;
  189056. png_byte gray_low = gray & 0xff;
  189057. sp = row + row_info->rowbytes - 1;
  189058. dp = row + (row_info->rowbytes << 1) - 1;
  189059. for (i = 0; i < row_width; i++)
  189060. {
  189061. if (*(sp-1) == gray_high && *(sp) == gray_low)
  189062. {
  189063. *dp-- = 0;
  189064. *dp-- = 0;
  189065. }
  189066. else
  189067. {
  189068. *dp-- = 0xff;
  189069. *dp-- = 0xff;
  189070. }
  189071. *dp-- = *sp--;
  189072. *dp-- = *sp--;
  189073. }
  189074. }
  189075. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  189076. row_info->channels = 2;
  189077. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  189078. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  189079. row_width);
  189080. }
  189081. }
  189082. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  189083. {
  189084. if (row_info->bit_depth == 8)
  189085. {
  189086. png_byte red = trans_value->red & 0xff;
  189087. png_byte green = trans_value->green & 0xff;
  189088. png_byte blue = trans_value->blue & 0xff;
  189089. sp = row + (png_size_t)row_info->rowbytes - 1;
  189090. dp = row + (png_size_t)(row_width << 2) - 1;
  189091. for (i = 0; i < row_width; i++)
  189092. {
  189093. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  189094. *dp-- = 0;
  189095. else
  189096. *dp-- = 0xff;
  189097. *dp-- = *sp--;
  189098. *dp-- = *sp--;
  189099. *dp-- = *sp--;
  189100. }
  189101. }
  189102. else if (row_info->bit_depth == 16)
  189103. {
  189104. png_byte red_high = (trans_value->red >> 8) & 0xff;
  189105. png_byte green_high = (trans_value->green >> 8) & 0xff;
  189106. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  189107. png_byte red_low = trans_value->red & 0xff;
  189108. png_byte green_low = trans_value->green & 0xff;
  189109. png_byte blue_low = trans_value->blue & 0xff;
  189110. sp = row + row_info->rowbytes - 1;
  189111. dp = row + (png_size_t)(row_width << 3) - 1;
  189112. for (i = 0; i < row_width; i++)
  189113. {
  189114. if (*(sp - 5) == red_high &&
  189115. *(sp - 4) == red_low &&
  189116. *(sp - 3) == green_high &&
  189117. *(sp - 2) == green_low &&
  189118. *(sp - 1) == blue_high &&
  189119. *(sp ) == blue_low)
  189120. {
  189121. *dp-- = 0;
  189122. *dp-- = 0;
  189123. }
  189124. else
  189125. {
  189126. *dp-- = 0xff;
  189127. *dp-- = 0xff;
  189128. }
  189129. *dp-- = *sp--;
  189130. *dp-- = *sp--;
  189131. *dp-- = *sp--;
  189132. *dp-- = *sp--;
  189133. *dp-- = *sp--;
  189134. *dp-- = *sp--;
  189135. }
  189136. }
  189137. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  189138. row_info->channels = 4;
  189139. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  189140. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189141. }
  189142. }
  189143. }
  189144. #endif
  189145. #if defined(PNG_READ_DITHER_SUPPORTED)
  189146. void /* PRIVATE */
  189147. png_do_dither(png_row_infop row_info, png_bytep row,
  189148. png_bytep palette_lookup, png_bytep dither_lookup)
  189149. {
  189150. png_bytep sp, dp;
  189151. png_uint_32 i;
  189152. png_uint_32 row_width=row_info->width;
  189153. png_debug(1, "in png_do_dither\n");
  189154. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189155. if (row != NULL && row_info != NULL)
  189156. #endif
  189157. {
  189158. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  189159. palette_lookup && row_info->bit_depth == 8)
  189160. {
  189161. int r, g, b, p;
  189162. sp = row;
  189163. dp = row;
  189164. for (i = 0; i < row_width; i++)
  189165. {
  189166. r = *sp++;
  189167. g = *sp++;
  189168. b = *sp++;
  189169. /* this looks real messy, but the compiler will reduce
  189170. it down to a reasonable formula. For example, with
  189171. 5 bits per color, we get:
  189172. p = (((r >> 3) & 0x1f) << 10) |
  189173. (((g >> 3) & 0x1f) << 5) |
  189174. ((b >> 3) & 0x1f);
  189175. */
  189176. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189177. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189178. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189179. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189180. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189181. (PNG_DITHER_BLUE_BITS)) |
  189182. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189183. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189184. *dp++ = palette_lookup[p];
  189185. }
  189186. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189187. row_info->channels = 1;
  189188. row_info->pixel_depth = row_info->bit_depth;
  189189. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189190. }
  189191. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  189192. palette_lookup != NULL && row_info->bit_depth == 8)
  189193. {
  189194. int r, g, b, p;
  189195. sp = row;
  189196. dp = row;
  189197. for (i = 0; i < row_width; i++)
  189198. {
  189199. r = *sp++;
  189200. g = *sp++;
  189201. b = *sp++;
  189202. sp++;
  189203. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  189204. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  189205. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  189206. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  189207. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  189208. (PNG_DITHER_BLUE_BITS)) |
  189209. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  189210. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  189211. *dp++ = palette_lookup[p];
  189212. }
  189213. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  189214. row_info->channels = 1;
  189215. row_info->pixel_depth = row_info->bit_depth;
  189216. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  189217. }
  189218. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  189219. dither_lookup && row_info->bit_depth == 8)
  189220. {
  189221. sp = row;
  189222. for (i = 0; i < row_width; i++, sp++)
  189223. {
  189224. *sp = dither_lookup[*sp];
  189225. }
  189226. }
  189227. }
  189228. }
  189229. #endif
  189230. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189231. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189232. static PNG_CONST int png_gamma_shift[] =
  189233. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  189234. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  189235. * tables, we don't make a full table if we are reducing to 8-bit in
  189236. * the future. Note also how the gamma_16 tables are segmented so that
  189237. * we don't need to allocate > 64K chunks for a full 16-bit table.
  189238. */
  189239. void /* PRIVATE */
  189240. png_build_gamma_table(png_structp png_ptr)
  189241. {
  189242. png_debug(1, "in png_build_gamma_table\n");
  189243. if (png_ptr->bit_depth <= 8)
  189244. {
  189245. int i;
  189246. double g;
  189247. if (png_ptr->screen_gamma > .000001)
  189248. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189249. else
  189250. g = 1.0;
  189251. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  189252. (png_uint_32)256);
  189253. for (i = 0; i < 256; i++)
  189254. {
  189255. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  189256. g) * 255.0 + .5);
  189257. }
  189258. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189259. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189260. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  189261. {
  189262. g = 1.0 / (png_ptr->gamma);
  189263. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  189264. (png_uint_32)256);
  189265. for (i = 0; i < 256; i++)
  189266. {
  189267. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  189268. g) * 255.0 + .5);
  189269. }
  189270. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  189271. (png_uint_32)256);
  189272. if(png_ptr->screen_gamma > 0.000001)
  189273. g = 1.0 / png_ptr->screen_gamma;
  189274. else
  189275. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189276. for (i = 0; i < 256; i++)
  189277. {
  189278. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  189279. g) * 255.0 + .5);
  189280. }
  189281. }
  189282. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189283. }
  189284. else
  189285. {
  189286. double g;
  189287. int i, j, shift, num;
  189288. int sig_bit;
  189289. png_uint_32 ig;
  189290. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  189291. {
  189292. sig_bit = (int)png_ptr->sig_bit.red;
  189293. if ((int)png_ptr->sig_bit.green > sig_bit)
  189294. sig_bit = png_ptr->sig_bit.green;
  189295. if ((int)png_ptr->sig_bit.blue > sig_bit)
  189296. sig_bit = png_ptr->sig_bit.blue;
  189297. }
  189298. else
  189299. {
  189300. sig_bit = (int)png_ptr->sig_bit.gray;
  189301. }
  189302. if (sig_bit > 0)
  189303. shift = 16 - sig_bit;
  189304. else
  189305. shift = 0;
  189306. if (png_ptr->transformations & PNG_16_TO_8)
  189307. {
  189308. if (shift < (16 - PNG_MAX_GAMMA_8))
  189309. shift = (16 - PNG_MAX_GAMMA_8);
  189310. }
  189311. if (shift > 8)
  189312. shift = 8;
  189313. if (shift < 0)
  189314. shift = 0;
  189315. png_ptr->gamma_shift = (png_byte)shift;
  189316. num = (1 << (8 - shift));
  189317. if (png_ptr->screen_gamma > .000001)
  189318. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  189319. else
  189320. g = 1.0;
  189321. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  189322. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189323. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  189324. {
  189325. double fin, fout;
  189326. png_uint_32 last, max;
  189327. for (i = 0; i < num; i++)
  189328. {
  189329. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189330. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189331. }
  189332. g = 1.0 / g;
  189333. last = 0;
  189334. for (i = 0; i < 256; i++)
  189335. {
  189336. fout = ((double)i + 0.5) / 256.0;
  189337. fin = pow(fout, g);
  189338. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  189339. while (last <= max)
  189340. {
  189341. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189342. [(int)(last >> (8 - shift))] = (png_uint_16)(
  189343. (png_uint_16)i | ((png_uint_16)i << 8));
  189344. last++;
  189345. }
  189346. }
  189347. while (last < ((png_uint_32)num << 8))
  189348. {
  189349. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  189350. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  189351. last++;
  189352. }
  189353. }
  189354. else
  189355. {
  189356. for (i = 0; i < num; i++)
  189357. {
  189358. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  189359. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189360. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  189361. for (j = 0; j < 256; j++)
  189362. {
  189363. png_ptr->gamma_16_table[i][j] =
  189364. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189365. 65535.0, g) * 65535.0 + .5);
  189366. }
  189367. }
  189368. }
  189369. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  189370. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  189371. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  189372. {
  189373. g = 1.0 / (png_ptr->gamma);
  189374. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  189375. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  189376. for (i = 0; i < num; i++)
  189377. {
  189378. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189379. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189380. ig = (((png_uint_32)i *
  189381. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189382. for (j = 0; j < 256; j++)
  189383. {
  189384. png_ptr->gamma_16_to_1[i][j] =
  189385. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189386. 65535.0, g) * 65535.0 + .5);
  189387. }
  189388. }
  189389. if(png_ptr->screen_gamma > 0.000001)
  189390. g = 1.0 / png_ptr->screen_gamma;
  189391. else
  189392. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  189393. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  189394. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  189395. for (i = 0; i < num; i++)
  189396. {
  189397. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  189398. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  189399. ig = (((png_uint_32)i *
  189400. (png_uint_32)png_gamma_shift[shift]) >> 4);
  189401. for (j = 0; j < 256; j++)
  189402. {
  189403. png_ptr->gamma_16_from_1[i][j] =
  189404. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  189405. 65535.0, g) * 65535.0 + .5);
  189406. }
  189407. }
  189408. }
  189409. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  189410. }
  189411. }
  189412. #endif
  189413. /* To do: install integer version of png_build_gamma_table here */
  189414. #endif
  189415. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189416. /* undoes intrapixel differencing */
  189417. void /* PRIVATE */
  189418. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  189419. {
  189420. png_debug(1, "in png_do_read_intrapixel\n");
  189421. if (
  189422. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  189423. row != NULL && row_info != NULL &&
  189424. #endif
  189425. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  189426. {
  189427. int bytes_per_pixel;
  189428. png_uint_32 row_width = row_info->width;
  189429. if (row_info->bit_depth == 8)
  189430. {
  189431. png_bytep rp;
  189432. png_uint_32 i;
  189433. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189434. bytes_per_pixel = 3;
  189435. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189436. bytes_per_pixel = 4;
  189437. else
  189438. return;
  189439. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189440. {
  189441. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  189442. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  189443. }
  189444. }
  189445. else if (row_info->bit_depth == 16)
  189446. {
  189447. png_bytep rp;
  189448. png_uint_32 i;
  189449. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  189450. bytes_per_pixel = 6;
  189451. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189452. bytes_per_pixel = 8;
  189453. else
  189454. return;
  189455. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  189456. {
  189457. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  189458. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  189459. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  189460. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  189461. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  189462. *(rp ) = (png_byte)((red >> 8) & 0xff);
  189463. *(rp+1) = (png_byte)(red & 0xff);
  189464. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  189465. *(rp+5) = (png_byte)(blue & 0xff);
  189466. }
  189467. }
  189468. }
  189469. }
  189470. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  189471. #endif /* PNG_READ_SUPPORTED */
  189472. /********* End of inlined file: pngrtran.c *********/
  189473. /********* Start of inlined file: pngrutil.c *********/
  189474. /* pngrutil.c - utilities to read a PNG file
  189475. *
  189476. * Last changed in libpng 1.2.21 [October 4, 2007]
  189477. * For conditions of distribution and use, see copyright notice in png.h
  189478. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189479. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189480. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189481. *
  189482. * This file contains routines that are only called from within
  189483. * libpng itself during the course of reading an image.
  189484. */
  189485. #define PNG_INTERNAL
  189486. #if defined(PNG_READ_SUPPORTED)
  189487. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  189488. # define WIN32_WCE_OLD
  189489. #endif
  189490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189491. # if defined(WIN32_WCE_OLD)
  189492. /* strtod() function is not supported on WindowsCE */
  189493. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  189494. {
  189495. double result = 0;
  189496. int len;
  189497. wchar_t *str, *end;
  189498. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  189499. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  189500. if ( NULL != str )
  189501. {
  189502. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  189503. result = wcstod(str, &end);
  189504. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  189505. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  189506. png_free(png_ptr, str);
  189507. }
  189508. return result;
  189509. }
  189510. # else
  189511. # define png_strtod(p,a,b) strtod(a,b)
  189512. # endif
  189513. #endif
  189514. png_uint_32 PNGAPI
  189515. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  189516. {
  189517. png_uint_32 i = png_get_uint_32(buf);
  189518. if (i > PNG_UINT_31_MAX)
  189519. png_error(png_ptr, "PNG unsigned integer out of range.");
  189520. return (i);
  189521. }
  189522. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  189523. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  189524. png_uint_32 PNGAPI
  189525. png_get_uint_32(png_bytep buf)
  189526. {
  189527. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  189528. ((png_uint_32)(*(buf + 1)) << 16) +
  189529. ((png_uint_32)(*(buf + 2)) << 8) +
  189530. (png_uint_32)(*(buf + 3));
  189531. return (i);
  189532. }
  189533. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  189534. * data is stored in the PNG file in two's complement format, and it is
  189535. * assumed that the machine format for signed integers is the same. */
  189536. png_int_32 PNGAPI
  189537. png_get_int_32(png_bytep buf)
  189538. {
  189539. png_int_32 i = ((png_int_32)(*buf) << 24) +
  189540. ((png_int_32)(*(buf + 1)) << 16) +
  189541. ((png_int_32)(*(buf + 2)) << 8) +
  189542. (png_int_32)(*(buf + 3));
  189543. return (i);
  189544. }
  189545. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  189546. png_uint_16 PNGAPI
  189547. png_get_uint_16(png_bytep buf)
  189548. {
  189549. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  189550. (png_uint_16)(*(buf + 1)));
  189551. return (i);
  189552. }
  189553. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  189554. /* Read data, and (optionally) run it through the CRC. */
  189555. void /* PRIVATE */
  189556. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  189557. {
  189558. if(png_ptr == NULL) return;
  189559. png_read_data(png_ptr, buf, length);
  189560. png_calculate_crc(png_ptr, buf, length);
  189561. }
  189562. /* Optionally skip data and then check the CRC. Depending on whether we
  189563. are reading a ancillary or critical chunk, and how the program has set
  189564. things up, we may calculate the CRC on the data and print a message.
  189565. Returns '1' if there was a CRC error, '0' otherwise. */
  189566. int /* PRIVATE */
  189567. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  189568. {
  189569. png_size_t i;
  189570. png_size_t istop = png_ptr->zbuf_size;
  189571. for (i = (png_size_t)skip; i > istop; i -= istop)
  189572. {
  189573. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  189574. }
  189575. if (i)
  189576. {
  189577. png_crc_read(png_ptr, png_ptr->zbuf, i);
  189578. }
  189579. if (png_crc_error(png_ptr))
  189580. {
  189581. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  189582. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  189583. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  189584. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  189585. {
  189586. png_chunk_warning(png_ptr, "CRC error");
  189587. }
  189588. else
  189589. {
  189590. png_chunk_error(png_ptr, "CRC error");
  189591. }
  189592. return (1);
  189593. }
  189594. return (0);
  189595. }
  189596. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  189597. the data it has read thus far. */
  189598. int /* PRIVATE */
  189599. png_crc_error(png_structp png_ptr)
  189600. {
  189601. png_byte crc_bytes[4];
  189602. png_uint_32 crc;
  189603. int need_crc = 1;
  189604. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  189605. {
  189606. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  189607. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189608. need_crc = 0;
  189609. }
  189610. else /* critical */
  189611. {
  189612. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  189613. need_crc = 0;
  189614. }
  189615. png_read_data(png_ptr, crc_bytes, 4);
  189616. if (need_crc)
  189617. {
  189618. crc = png_get_uint_32(crc_bytes);
  189619. return ((int)(crc != png_ptr->crc));
  189620. }
  189621. else
  189622. return (0);
  189623. }
  189624. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  189625. defined(PNG_READ_iCCP_SUPPORTED)
  189626. /*
  189627. * Decompress trailing data in a chunk. The assumption is that chunkdata
  189628. * points at an allocated area holding the contents of a chunk with a
  189629. * trailing compressed part. What we get back is an allocated area
  189630. * holding the original prefix part and an uncompressed version of the
  189631. * trailing part (the malloc area passed in is freed).
  189632. */
  189633. png_charp /* PRIVATE */
  189634. png_decompress_chunk(png_structp png_ptr, int comp_type,
  189635. png_charp chunkdata, png_size_t chunklength,
  189636. png_size_t prefix_size, png_size_t *newlength)
  189637. {
  189638. static PNG_CONST char msg[] = "Error decoding compressed text";
  189639. png_charp text;
  189640. png_size_t text_size;
  189641. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  189642. {
  189643. int ret = Z_OK;
  189644. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  189645. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  189646. png_ptr->zstream.next_out = png_ptr->zbuf;
  189647. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189648. text_size = 0;
  189649. text = NULL;
  189650. while (png_ptr->zstream.avail_in)
  189651. {
  189652. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189653. if (ret != Z_OK && ret != Z_STREAM_END)
  189654. {
  189655. if (png_ptr->zstream.msg != NULL)
  189656. png_warning(png_ptr, png_ptr->zstream.msg);
  189657. else
  189658. png_warning(png_ptr, msg);
  189659. inflateReset(&png_ptr->zstream);
  189660. png_ptr->zstream.avail_in = 0;
  189661. if (text == NULL)
  189662. {
  189663. text_size = prefix_size + png_sizeof(msg) + 1;
  189664. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  189665. if (text == NULL)
  189666. {
  189667. png_free(png_ptr,chunkdata);
  189668. png_error(png_ptr,"Not enough memory to decompress chunk");
  189669. }
  189670. png_memcpy(text, chunkdata, prefix_size);
  189671. }
  189672. text[text_size - 1] = 0x00;
  189673. /* Copy what we can of the error message into the text chunk */
  189674. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  189675. text_size = png_sizeof(msg) > text_size ? text_size :
  189676. png_sizeof(msg);
  189677. png_memcpy(text + prefix_size, msg, text_size + 1);
  189678. break;
  189679. }
  189680. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  189681. {
  189682. if (text == NULL)
  189683. {
  189684. text_size = prefix_size +
  189685. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189686. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  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 + prefix_size, png_ptr->zbuf,
  189693. text_size - prefix_size);
  189694. png_memcpy(text, chunkdata, prefix_size);
  189695. *(text + text_size) = 0x00;
  189696. }
  189697. else
  189698. {
  189699. png_charp tmp;
  189700. tmp = text;
  189701. text = (png_charp)png_malloc_warn(png_ptr,
  189702. (png_uint_32)(text_size +
  189703. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  189704. if (text == NULL)
  189705. {
  189706. png_free(png_ptr, tmp);
  189707. png_free(png_ptr, chunkdata);
  189708. png_error(png_ptr,"Not enough memory to decompress chunk..");
  189709. }
  189710. png_memcpy(text, tmp, text_size);
  189711. png_free(png_ptr, tmp);
  189712. png_memcpy(text + text_size, png_ptr->zbuf,
  189713. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  189714. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189715. *(text + text_size) = 0x00;
  189716. }
  189717. if (ret == Z_STREAM_END)
  189718. break;
  189719. else
  189720. {
  189721. png_ptr->zstream.next_out = png_ptr->zbuf;
  189722. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189723. }
  189724. }
  189725. }
  189726. if (ret != Z_STREAM_END)
  189727. {
  189728. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189729. char umsg[52];
  189730. if (ret == Z_BUF_ERROR)
  189731. png_snprintf(umsg, 52,
  189732. "Buffer error in compressed datastream in %s chunk",
  189733. png_ptr->chunk_name);
  189734. else if (ret == Z_DATA_ERROR)
  189735. png_snprintf(umsg, 52,
  189736. "Data error in compressed datastream in %s chunk",
  189737. png_ptr->chunk_name);
  189738. else
  189739. png_snprintf(umsg, 52,
  189740. "Incomplete compressed datastream in %s chunk",
  189741. png_ptr->chunk_name);
  189742. png_warning(png_ptr, umsg);
  189743. #else
  189744. png_warning(png_ptr,
  189745. "Incomplete compressed datastream in chunk other than IDAT");
  189746. #endif
  189747. text_size=prefix_size;
  189748. if (text == NULL)
  189749. {
  189750. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  189751. if (text == NULL)
  189752. {
  189753. png_free(png_ptr, chunkdata);
  189754. png_error(png_ptr,"Not enough memory for text.");
  189755. }
  189756. png_memcpy(text, chunkdata, prefix_size);
  189757. }
  189758. *(text + text_size) = 0x00;
  189759. }
  189760. inflateReset(&png_ptr->zstream);
  189761. png_ptr->zstream.avail_in = 0;
  189762. png_free(png_ptr, chunkdata);
  189763. chunkdata = text;
  189764. *newlength=text_size;
  189765. }
  189766. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  189767. {
  189768. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  189769. char umsg[50];
  189770. png_snprintf(umsg, 50,
  189771. "Unknown zTXt compression type %d", comp_type);
  189772. png_warning(png_ptr, umsg);
  189773. #else
  189774. png_warning(png_ptr, "Unknown zTXt compression type");
  189775. #endif
  189776. *(chunkdata + prefix_size) = 0x00;
  189777. *newlength=prefix_size;
  189778. }
  189779. return chunkdata;
  189780. }
  189781. #endif
  189782. /* read and check the IDHR chunk */
  189783. void /* PRIVATE */
  189784. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189785. {
  189786. png_byte buf[13];
  189787. png_uint_32 width, height;
  189788. int bit_depth, color_type, compression_type, filter_type;
  189789. int interlace_type;
  189790. png_debug(1, "in png_handle_IHDR\n");
  189791. if (png_ptr->mode & PNG_HAVE_IHDR)
  189792. png_error(png_ptr, "Out of place IHDR");
  189793. /* check the length */
  189794. if (length != 13)
  189795. png_error(png_ptr, "Invalid IHDR chunk");
  189796. png_ptr->mode |= PNG_HAVE_IHDR;
  189797. png_crc_read(png_ptr, buf, 13);
  189798. png_crc_finish(png_ptr, 0);
  189799. width = png_get_uint_31(png_ptr, buf);
  189800. height = png_get_uint_31(png_ptr, buf + 4);
  189801. bit_depth = buf[8];
  189802. color_type = buf[9];
  189803. compression_type = buf[10];
  189804. filter_type = buf[11];
  189805. interlace_type = buf[12];
  189806. /* set internal variables */
  189807. png_ptr->width = width;
  189808. png_ptr->height = height;
  189809. png_ptr->bit_depth = (png_byte)bit_depth;
  189810. png_ptr->interlaced = (png_byte)interlace_type;
  189811. png_ptr->color_type = (png_byte)color_type;
  189812. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  189813. png_ptr->filter_type = (png_byte)filter_type;
  189814. #endif
  189815. png_ptr->compression_type = (png_byte)compression_type;
  189816. /* find number of channels */
  189817. switch (png_ptr->color_type)
  189818. {
  189819. case PNG_COLOR_TYPE_GRAY:
  189820. case PNG_COLOR_TYPE_PALETTE:
  189821. png_ptr->channels = 1;
  189822. break;
  189823. case PNG_COLOR_TYPE_RGB:
  189824. png_ptr->channels = 3;
  189825. break;
  189826. case PNG_COLOR_TYPE_GRAY_ALPHA:
  189827. png_ptr->channels = 2;
  189828. break;
  189829. case PNG_COLOR_TYPE_RGB_ALPHA:
  189830. png_ptr->channels = 4;
  189831. break;
  189832. }
  189833. /* set up other useful info */
  189834. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  189835. png_ptr->channels);
  189836. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  189837. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  189838. png_debug1(3,"channels = %d\n", png_ptr->channels);
  189839. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  189840. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  189841. color_type, interlace_type, compression_type, filter_type);
  189842. }
  189843. /* read and check the palette */
  189844. void /* PRIVATE */
  189845. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189846. {
  189847. png_color palette[PNG_MAX_PALETTE_LENGTH];
  189848. int num, i;
  189849. #ifndef PNG_NO_POINTER_INDEXING
  189850. png_colorp pal_ptr;
  189851. #endif
  189852. png_debug(1, "in png_handle_PLTE\n");
  189853. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189854. png_error(png_ptr, "Missing IHDR before PLTE");
  189855. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189856. {
  189857. png_warning(png_ptr, "Invalid PLTE after IDAT");
  189858. png_crc_finish(png_ptr, length);
  189859. return;
  189860. }
  189861. else if (png_ptr->mode & PNG_HAVE_PLTE)
  189862. png_error(png_ptr, "Duplicate PLTE chunk");
  189863. png_ptr->mode |= PNG_HAVE_PLTE;
  189864. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  189865. {
  189866. png_warning(png_ptr,
  189867. "Ignoring PLTE chunk in grayscale PNG");
  189868. png_crc_finish(png_ptr, length);
  189869. return;
  189870. }
  189871. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189872. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189873. {
  189874. png_crc_finish(png_ptr, length);
  189875. return;
  189876. }
  189877. #endif
  189878. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  189879. {
  189880. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  189881. {
  189882. png_warning(png_ptr, "Invalid palette chunk");
  189883. png_crc_finish(png_ptr, length);
  189884. return;
  189885. }
  189886. else
  189887. {
  189888. png_error(png_ptr, "Invalid palette chunk");
  189889. }
  189890. }
  189891. num = (int)length / 3;
  189892. #ifndef PNG_NO_POINTER_INDEXING
  189893. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  189894. {
  189895. png_byte buf[3];
  189896. png_crc_read(png_ptr, buf, 3);
  189897. pal_ptr->red = buf[0];
  189898. pal_ptr->green = buf[1];
  189899. pal_ptr->blue = buf[2];
  189900. }
  189901. #else
  189902. for (i = 0; i < num; i++)
  189903. {
  189904. png_byte buf[3];
  189905. png_crc_read(png_ptr, buf, 3);
  189906. /* don't depend upon png_color being any order */
  189907. palette[i].red = buf[0];
  189908. palette[i].green = buf[1];
  189909. palette[i].blue = buf[2];
  189910. }
  189911. #endif
  189912. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  189913. whatever the normal CRC configuration tells us. However, if we
  189914. have an RGB image, the PLTE can be considered ancillary, so
  189915. we will act as though it is. */
  189916. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189917. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189918. #endif
  189919. {
  189920. png_crc_finish(png_ptr, 0);
  189921. }
  189922. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  189923. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  189924. {
  189925. /* If we don't want to use the data from an ancillary chunk,
  189926. we have two options: an error abort, or a warning and we
  189927. ignore the data in this chunk (which should be OK, since
  189928. it's considered ancillary for a RGB or RGBA image). */
  189929. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  189930. {
  189931. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  189932. {
  189933. png_chunk_error(png_ptr, "CRC error");
  189934. }
  189935. else
  189936. {
  189937. png_chunk_warning(png_ptr, "CRC error");
  189938. return;
  189939. }
  189940. }
  189941. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  189942. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  189943. {
  189944. png_chunk_warning(png_ptr, "CRC error");
  189945. }
  189946. }
  189947. #endif
  189948. png_set_PLTE(png_ptr, info_ptr, palette, num);
  189949. #if defined(PNG_READ_tRNS_SUPPORTED)
  189950. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189951. {
  189952. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  189953. {
  189954. if (png_ptr->num_trans > (png_uint_16)num)
  189955. {
  189956. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  189957. png_ptr->num_trans = (png_uint_16)num;
  189958. }
  189959. if (info_ptr->num_trans > (png_uint_16)num)
  189960. {
  189961. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  189962. info_ptr->num_trans = (png_uint_16)num;
  189963. }
  189964. }
  189965. }
  189966. #endif
  189967. }
  189968. void /* PRIVATE */
  189969. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189970. {
  189971. png_debug(1, "in png_handle_IEND\n");
  189972. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  189973. {
  189974. png_error(png_ptr, "No image in file");
  189975. }
  189976. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  189977. if (length != 0)
  189978. {
  189979. png_warning(png_ptr, "Incorrect IEND chunk length");
  189980. }
  189981. png_crc_finish(png_ptr, length);
  189982. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  189983. }
  189984. #if defined(PNG_READ_gAMA_SUPPORTED)
  189985. void /* PRIVATE */
  189986. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189987. {
  189988. png_fixed_point igamma;
  189989. #ifdef PNG_FLOATING_POINT_SUPPORTED
  189990. float file_gamma;
  189991. #endif
  189992. png_byte buf[4];
  189993. png_debug(1, "in png_handle_gAMA\n");
  189994. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189995. png_error(png_ptr, "Missing IHDR before gAMA");
  189996. else if (png_ptr->mode & PNG_HAVE_IDAT)
  189997. {
  189998. png_warning(png_ptr, "Invalid gAMA after IDAT");
  189999. png_crc_finish(png_ptr, length);
  190000. return;
  190001. }
  190002. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190003. /* Should be an error, but we can cope with it */
  190004. png_warning(png_ptr, "Out of place gAMA chunk");
  190005. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  190006. #if defined(PNG_READ_sRGB_SUPPORTED)
  190007. && !(info_ptr->valid & PNG_INFO_sRGB)
  190008. #endif
  190009. )
  190010. {
  190011. png_warning(png_ptr, "Duplicate gAMA chunk");
  190012. png_crc_finish(png_ptr, length);
  190013. return;
  190014. }
  190015. if (length != 4)
  190016. {
  190017. png_warning(png_ptr, "Incorrect gAMA chunk length");
  190018. png_crc_finish(png_ptr, length);
  190019. return;
  190020. }
  190021. png_crc_read(png_ptr, buf, 4);
  190022. if (png_crc_finish(png_ptr, 0))
  190023. return;
  190024. igamma = (png_fixed_point)png_get_uint_32(buf);
  190025. /* check for zero gamma */
  190026. if (igamma == 0)
  190027. {
  190028. png_warning(png_ptr,
  190029. "Ignoring gAMA chunk with gamma=0");
  190030. return;
  190031. }
  190032. #if defined(PNG_READ_sRGB_SUPPORTED)
  190033. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190034. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190035. {
  190036. png_warning(png_ptr,
  190037. "Ignoring incorrect gAMA value when sRGB is also present");
  190038. #ifndef PNG_NO_CONSOLE_IO
  190039. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  190040. #endif
  190041. return;
  190042. }
  190043. #endif /* PNG_READ_sRGB_SUPPORTED */
  190044. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190045. file_gamma = (float)igamma / (float)100000.0;
  190046. # ifdef PNG_READ_GAMMA_SUPPORTED
  190047. png_ptr->gamma = file_gamma;
  190048. # endif
  190049. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190050. #endif
  190051. #ifdef PNG_FIXED_POINT_SUPPORTED
  190052. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  190053. #endif
  190054. }
  190055. #endif
  190056. #if defined(PNG_READ_sBIT_SUPPORTED)
  190057. void /* PRIVATE */
  190058. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190059. {
  190060. png_size_t truelen;
  190061. png_byte buf[4];
  190062. png_debug(1, "in png_handle_sBIT\n");
  190063. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  190064. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190065. png_error(png_ptr, "Missing IHDR before sBIT");
  190066. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190067. {
  190068. png_warning(png_ptr, "Invalid sBIT after IDAT");
  190069. png_crc_finish(png_ptr, length);
  190070. return;
  190071. }
  190072. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190073. {
  190074. /* Should be an error, but we can cope with it */
  190075. png_warning(png_ptr, "Out of place sBIT chunk");
  190076. }
  190077. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  190078. {
  190079. png_warning(png_ptr, "Duplicate sBIT chunk");
  190080. png_crc_finish(png_ptr, length);
  190081. return;
  190082. }
  190083. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190084. truelen = 3;
  190085. else
  190086. truelen = (png_size_t)png_ptr->channels;
  190087. if (length != truelen || length > 4)
  190088. {
  190089. png_warning(png_ptr, "Incorrect sBIT chunk length");
  190090. png_crc_finish(png_ptr, length);
  190091. return;
  190092. }
  190093. png_crc_read(png_ptr, buf, truelen);
  190094. if (png_crc_finish(png_ptr, 0))
  190095. return;
  190096. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190097. {
  190098. png_ptr->sig_bit.red = buf[0];
  190099. png_ptr->sig_bit.green = buf[1];
  190100. png_ptr->sig_bit.blue = buf[2];
  190101. png_ptr->sig_bit.alpha = buf[3];
  190102. }
  190103. else
  190104. {
  190105. png_ptr->sig_bit.gray = buf[0];
  190106. png_ptr->sig_bit.red = buf[0];
  190107. png_ptr->sig_bit.green = buf[0];
  190108. png_ptr->sig_bit.blue = buf[0];
  190109. png_ptr->sig_bit.alpha = buf[1];
  190110. }
  190111. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  190112. }
  190113. #endif
  190114. #if defined(PNG_READ_cHRM_SUPPORTED)
  190115. void /* PRIVATE */
  190116. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190117. {
  190118. png_byte buf[4];
  190119. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190120. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190121. #endif
  190122. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190123. int_y_green, int_x_blue, int_y_blue;
  190124. png_uint_32 uint_x, uint_y;
  190125. png_debug(1, "in png_handle_cHRM\n");
  190126. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190127. png_error(png_ptr, "Missing IHDR before cHRM");
  190128. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190129. {
  190130. png_warning(png_ptr, "Invalid cHRM after IDAT");
  190131. png_crc_finish(png_ptr, length);
  190132. return;
  190133. }
  190134. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190135. /* Should be an error, but we can cope with it */
  190136. png_warning(png_ptr, "Missing PLTE before cHRM");
  190137. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  190138. #if defined(PNG_READ_sRGB_SUPPORTED)
  190139. && !(info_ptr->valid & PNG_INFO_sRGB)
  190140. #endif
  190141. )
  190142. {
  190143. png_warning(png_ptr, "Duplicate cHRM chunk");
  190144. png_crc_finish(png_ptr, length);
  190145. return;
  190146. }
  190147. if (length != 32)
  190148. {
  190149. png_warning(png_ptr, "Incorrect cHRM chunk length");
  190150. png_crc_finish(png_ptr, length);
  190151. return;
  190152. }
  190153. png_crc_read(png_ptr, buf, 4);
  190154. uint_x = png_get_uint_32(buf);
  190155. png_crc_read(png_ptr, buf, 4);
  190156. uint_y = png_get_uint_32(buf);
  190157. if (uint_x > 80000L || uint_y > 80000L ||
  190158. uint_x + uint_y > 100000L)
  190159. {
  190160. png_warning(png_ptr, "Invalid cHRM white point");
  190161. png_crc_finish(png_ptr, 24);
  190162. return;
  190163. }
  190164. int_x_white = (png_fixed_point)uint_x;
  190165. int_y_white = (png_fixed_point)uint_y;
  190166. png_crc_read(png_ptr, buf, 4);
  190167. uint_x = png_get_uint_32(buf);
  190168. png_crc_read(png_ptr, buf, 4);
  190169. uint_y = png_get_uint_32(buf);
  190170. if (uint_x + uint_y > 100000L)
  190171. {
  190172. png_warning(png_ptr, "Invalid cHRM red point");
  190173. png_crc_finish(png_ptr, 16);
  190174. return;
  190175. }
  190176. int_x_red = (png_fixed_point)uint_x;
  190177. int_y_red = (png_fixed_point)uint_y;
  190178. png_crc_read(png_ptr, buf, 4);
  190179. uint_x = png_get_uint_32(buf);
  190180. png_crc_read(png_ptr, buf, 4);
  190181. uint_y = png_get_uint_32(buf);
  190182. if (uint_x + uint_y > 100000L)
  190183. {
  190184. png_warning(png_ptr, "Invalid cHRM green point");
  190185. png_crc_finish(png_ptr, 8);
  190186. return;
  190187. }
  190188. int_x_green = (png_fixed_point)uint_x;
  190189. int_y_green = (png_fixed_point)uint_y;
  190190. png_crc_read(png_ptr, buf, 4);
  190191. uint_x = png_get_uint_32(buf);
  190192. png_crc_read(png_ptr, buf, 4);
  190193. uint_y = png_get_uint_32(buf);
  190194. if (uint_x + uint_y > 100000L)
  190195. {
  190196. png_warning(png_ptr, "Invalid cHRM blue point");
  190197. png_crc_finish(png_ptr, 0);
  190198. return;
  190199. }
  190200. int_x_blue = (png_fixed_point)uint_x;
  190201. int_y_blue = (png_fixed_point)uint_y;
  190202. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190203. white_x = (float)int_x_white / (float)100000.0;
  190204. white_y = (float)int_y_white / (float)100000.0;
  190205. red_x = (float)int_x_red / (float)100000.0;
  190206. red_y = (float)int_y_red / (float)100000.0;
  190207. green_x = (float)int_x_green / (float)100000.0;
  190208. green_y = (float)int_y_green / (float)100000.0;
  190209. blue_x = (float)int_x_blue / (float)100000.0;
  190210. blue_y = (float)int_y_blue / (float)100000.0;
  190211. #endif
  190212. #if defined(PNG_READ_sRGB_SUPPORTED)
  190213. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  190214. {
  190215. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  190216. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  190217. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  190218. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  190219. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  190220. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  190221. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  190222. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  190223. {
  190224. png_warning(png_ptr,
  190225. "Ignoring incorrect cHRM value when sRGB is also present");
  190226. #ifndef PNG_NO_CONSOLE_IO
  190227. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190228. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  190229. white_x, white_y, red_x, red_y);
  190230. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  190231. green_x, green_y, blue_x, blue_y);
  190232. #else
  190233. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  190234. int_x_white, int_y_white, int_x_red, int_y_red);
  190235. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  190236. int_x_green, int_y_green, int_x_blue, int_y_blue);
  190237. #endif
  190238. #endif /* PNG_NO_CONSOLE_IO */
  190239. }
  190240. png_crc_finish(png_ptr, 0);
  190241. return;
  190242. }
  190243. #endif /* PNG_READ_sRGB_SUPPORTED */
  190244. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190245. png_set_cHRM(png_ptr, info_ptr,
  190246. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190247. #endif
  190248. #ifdef PNG_FIXED_POINT_SUPPORTED
  190249. png_set_cHRM_fixed(png_ptr, info_ptr,
  190250. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  190251. int_y_green, int_x_blue, int_y_blue);
  190252. #endif
  190253. if (png_crc_finish(png_ptr, 0))
  190254. return;
  190255. }
  190256. #endif
  190257. #if defined(PNG_READ_sRGB_SUPPORTED)
  190258. void /* PRIVATE */
  190259. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190260. {
  190261. int intent;
  190262. png_byte buf[1];
  190263. png_debug(1, "in png_handle_sRGB\n");
  190264. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190265. png_error(png_ptr, "Missing IHDR before sRGB");
  190266. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190267. {
  190268. png_warning(png_ptr, "Invalid sRGB after IDAT");
  190269. png_crc_finish(png_ptr, length);
  190270. return;
  190271. }
  190272. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190273. /* Should be an error, but we can cope with it */
  190274. png_warning(png_ptr, "Out of place sRGB chunk");
  190275. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  190276. {
  190277. png_warning(png_ptr, "Duplicate sRGB chunk");
  190278. png_crc_finish(png_ptr, length);
  190279. return;
  190280. }
  190281. if (length != 1)
  190282. {
  190283. png_warning(png_ptr, "Incorrect sRGB chunk length");
  190284. png_crc_finish(png_ptr, length);
  190285. return;
  190286. }
  190287. png_crc_read(png_ptr, buf, 1);
  190288. if (png_crc_finish(png_ptr, 0))
  190289. return;
  190290. intent = buf[0];
  190291. /* check for bad intent */
  190292. if (intent >= PNG_sRGB_INTENT_LAST)
  190293. {
  190294. png_warning(png_ptr, "Unknown sRGB intent");
  190295. return;
  190296. }
  190297. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190298. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  190299. {
  190300. png_fixed_point igamma;
  190301. #ifdef PNG_FIXED_POINT_SUPPORTED
  190302. igamma=info_ptr->int_gamma;
  190303. #else
  190304. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190305. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  190306. # endif
  190307. #endif
  190308. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  190309. {
  190310. png_warning(png_ptr,
  190311. "Ignoring incorrect gAMA value when sRGB is also present");
  190312. #ifndef PNG_NO_CONSOLE_IO
  190313. # ifdef PNG_FIXED_POINT_SUPPORTED
  190314. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  190315. # else
  190316. # ifdef PNG_FLOATING_POINT_SUPPORTED
  190317. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  190318. # endif
  190319. # endif
  190320. #endif
  190321. }
  190322. }
  190323. #endif /* PNG_READ_gAMA_SUPPORTED */
  190324. #ifdef PNG_READ_cHRM_SUPPORTED
  190325. #ifdef PNG_FIXED_POINT_SUPPORTED
  190326. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  190327. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  190328. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  190329. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  190330. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  190331. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  190332. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  190333. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  190334. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  190335. {
  190336. png_warning(png_ptr,
  190337. "Ignoring incorrect cHRM value when sRGB is also present");
  190338. }
  190339. #endif /* PNG_FIXED_POINT_SUPPORTED */
  190340. #endif /* PNG_READ_cHRM_SUPPORTED */
  190341. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  190342. }
  190343. #endif /* PNG_READ_sRGB_SUPPORTED */
  190344. #if defined(PNG_READ_iCCP_SUPPORTED)
  190345. void /* PRIVATE */
  190346. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190347. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190348. {
  190349. png_charp chunkdata;
  190350. png_byte compression_type;
  190351. png_bytep pC;
  190352. png_charp profile;
  190353. png_uint_32 skip = 0;
  190354. png_uint_32 profile_size, profile_length;
  190355. png_size_t slength, prefix_length, data_length;
  190356. png_debug(1, "in png_handle_iCCP\n");
  190357. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190358. png_error(png_ptr, "Missing IHDR before iCCP");
  190359. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190360. {
  190361. png_warning(png_ptr, "Invalid iCCP after IDAT");
  190362. png_crc_finish(png_ptr, length);
  190363. return;
  190364. }
  190365. else if (png_ptr->mode & PNG_HAVE_PLTE)
  190366. /* Should be an error, but we can cope with it */
  190367. png_warning(png_ptr, "Out of place iCCP chunk");
  190368. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  190369. {
  190370. png_warning(png_ptr, "Duplicate iCCP chunk");
  190371. png_crc_finish(png_ptr, length);
  190372. return;
  190373. }
  190374. #ifdef PNG_MAX_MALLOC_64K
  190375. if (length > (png_uint_32)65535L)
  190376. {
  190377. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  190378. skip = length - (png_uint_32)65535L;
  190379. length = (png_uint_32)65535L;
  190380. }
  190381. #endif
  190382. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  190383. slength = (png_size_t)length;
  190384. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190385. if (png_crc_finish(png_ptr, skip))
  190386. {
  190387. png_free(png_ptr, chunkdata);
  190388. return;
  190389. }
  190390. chunkdata[slength] = 0x00;
  190391. for (profile = chunkdata; *profile; profile++)
  190392. /* empty loop to find end of name */ ;
  190393. ++profile;
  190394. /* there should be at least one zero (the compression type byte)
  190395. following the separator, and we should be on it */
  190396. if ( profile >= chunkdata + slength - 1)
  190397. {
  190398. png_free(png_ptr, chunkdata);
  190399. png_warning(png_ptr, "Malformed iCCP chunk");
  190400. return;
  190401. }
  190402. /* compression_type should always be zero */
  190403. compression_type = *profile++;
  190404. if (compression_type)
  190405. {
  190406. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  190407. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  190408. wrote nonzero) */
  190409. }
  190410. prefix_length = profile - chunkdata;
  190411. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  190412. slength, prefix_length, &data_length);
  190413. profile_length = data_length - prefix_length;
  190414. if ( prefix_length > data_length || profile_length < 4)
  190415. {
  190416. png_free(png_ptr, chunkdata);
  190417. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  190418. return;
  190419. }
  190420. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  190421. pC = (png_bytep)(chunkdata+prefix_length);
  190422. profile_size = ((*(pC ))<<24) |
  190423. ((*(pC+1))<<16) |
  190424. ((*(pC+2))<< 8) |
  190425. ((*(pC+3)) );
  190426. if(profile_size < profile_length)
  190427. profile_length = profile_size;
  190428. if(profile_size > profile_length)
  190429. {
  190430. png_free(png_ptr, chunkdata);
  190431. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  190432. return;
  190433. }
  190434. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  190435. chunkdata + prefix_length, profile_length);
  190436. png_free(png_ptr, chunkdata);
  190437. }
  190438. #endif /* PNG_READ_iCCP_SUPPORTED */
  190439. #if defined(PNG_READ_sPLT_SUPPORTED)
  190440. void /* PRIVATE */
  190441. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190442. /* Note: this does not properly handle chunks that are > 64K under DOS */
  190443. {
  190444. png_bytep chunkdata;
  190445. png_bytep entry_start;
  190446. png_sPLT_t new_palette;
  190447. #ifdef PNG_NO_POINTER_INDEXING
  190448. png_sPLT_entryp pp;
  190449. #endif
  190450. int data_length, entry_size, i;
  190451. png_uint_32 skip = 0;
  190452. png_size_t slength;
  190453. png_debug(1, "in png_handle_sPLT\n");
  190454. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190455. png_error(png_ptr, "Missing IHDR before sPLT");
  190456. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190457. {
  190458. png_warning(png_ptr, "Invalid sPLT after IDAT");
  190459. png_crc_finish(png_ptr, length);
  190460. return;
  190461. }
  190462. #ifdef PNG_MAX_MALLOC_64K
  190463. if (length > (png_uint_32)65535L)
  190464. {
  190465. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  190466. skip = length - (png_uint_32)65535L;
  190467. length = (png_uint_32)65535L;
  190468. }
  190469. #endif
  190470. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  190471. slength = (png_size_t)length;
  190472. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  190473. if (png_crc_finish(png_ptr, skip))
  190474. {
  190475. png_free(png_ptr, chunkdata);
  190476. return;
  190477. }
  190478. chunkdata[slength] = 0x00;
  190479. for (entry_start = chunkdata; *entry_start; entry_start++)
  190480. /* empty loop to find end of name */ ;
  190481. ++entry_start;
  190482. /* a sample depth should follow the separator, and we should be on it */
  190483. if (entry_start > chunkdata + slength - 2)
  190484. {
  190485. png_free(png_ptr, chunkdata);
  190486. png_warning(png_ptr, "malformed sPLT chunk");
  190487. return;
  190488. }
  190489. new_palette.depth = *entry_start++;
  190490. entry_size = (new_palette.depth == 8 ? 6 : 10);
  190491. data_length = (slength - (entry_start - chunkdata));
  190492. /* integrity-check the data length */
  190493. if (data_length % entry_size)
  190494. {
  190495. png_free(png_ptr, chunkdata);
  190496. png_warning(png_ptr, "sPLT chunk has bad length");
  190497. return;
  190498. }
  190499. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  190500. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  190501. png_sizeof(png_sPLT_entry)))
  190502. {
  190503. png_warning(png_ptr, "sPLT chunk too long");
  190504. return;
  190505. }
  190506. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  190507. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  190508. if (new_palette.entries == NULL)
  190509. {
  190510. png_warning(png_ptr, "sPLT chunk requires too much memory");
  190511. return;
  190512. }
  190513. #ifndef PNG_NO_POINTER_INDEXING
  190514. for (i = 0; i < new_palette.nentries; i++)
  190515. {
  190516. png_sPLT_entryp pp = new_palette.entries + i;
  190517. if (new_palette.depth == 8)
  190518. {
  190519. pp->red = *entry_start++;
  190520. pp->green = *entry_start++;
  190521. pp->blue = *entry_start++;
  190522. pp->alpha = *entry_start++;
  190523. }
  190524. else
  190525. {
  190526. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  190527. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  190528. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  190529. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  190530. }
  190531. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190532. }
  190533. #else
  190534. pp = new_palette.entries;
  190535. for (i = 0; i < new_palette.nentries; i++)
  190536. {
  190537. if (new_palette.depth == 8)
  190538. {
  190539. pp[i].red = *entry_start++;
  190540. pp[i].green = *entry_start++;
  190541. pp[i].blue = *entry_start++;
  190542. pp[i].alpha = *entry_start++;
  190543. }
  190544. else
  190545. {
  190546. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  190547. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  190548. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  190549. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  190550. }
  190551. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  190552. }
  190553. #endif
  190554. /* discard all chunk data except the name and stash that */
  190555. new_palette.name = (png_charp)chunkdata;
  190556. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  190557. png_free(png_ptr, chunkdata);
  190558. png_free(png_ptr, new_palette.entries);
  190559. }
  190560. #endif /* PNG_READ_sPLT_SUPPORTED */
  190561. #if defined(PNG_READ_tRNS_SUPPORTED)
  190562. void /* PRIVATE */
  190563. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190564. {
  190565. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  190566. int bit_mask;
  190567. png_debug(1, "in png_handle_tRNS\n");
  190568. /* For non-indexed color, mask off any bits in the tRNS value that
  190569. * exceed the bit depth. Some creators were writing extra bits there.
  190570. * This is not needed for indexed color. */
  190571. bit_mask = (1 << png_ptr->bit_depth) - 1;
  190572. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190573. png_error(png_ptr, "Missing IHDR before tRNS");
  190574. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190575. {
  190576. png_warning(png_ptr, "Invalid tRNS after IDAT");
  190577. png_crc_finish(png_ptr, length);
  190578. return;
  190579. }
  190580. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  190581. {
  190582. png_warning(png_ptr, "Duplicate tRNS chunk");
  190583. png_crc_finish(png_ptr, length);
  190584. return;
  190585. }
  190586. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  190587. {
  190588. png_byte buf[2];
  190589. if (length != 2)
  190590. {
  190591. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190592. png_crc_finish(png_ptr, length);
  190593. return;
  190594. }
  190595. png_crc_read(png_ptr, buf, 2);
  190596. png_ptr->num_trans = 1;
  190597. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  190598. }
  190599. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  190600. {
  190601. png_byte buf[6];
  190602. if (length != 6)
  190603. {
  190604. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190605. png_crc_finish(png_ptr, length);
  190606. return;
  190607. }
  190608. png_crc_read(png_ptr, buf, (png_size_t)length);
  190609. png_ptr->num_trans = 1;
  190610. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  190611. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  190612. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  190613. }
  190614. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190615. {
  190616. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190617. {
  190618. /* Should be an error, but we can cope with it. */
  190619. png_warning(png_ptr, "Missing PLTE before tRNS");
  190620. }
  190621. if (length > (png_uint_32)png_ptr->num_palette ||
  190622. length > PNG_MAX_PALETTE_LENGTH)
  190623. {
  190624. png_warning(png_ptr, "Incorrect tRNS chunk length");
  190625. png_crc_finish(png_ptr, length);
  190626. return;
  190627. }
  190628. if (length == 0)
  190629. {
  190630. png_warning(png_ptr, "Zero length tRNS chunk");
  190631. png_crc_finish(png_ptr, length);
  190632. return;
  190633. }
  190634. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  190635. png_ptr->num_trans = (png_uint_16)length;
  190636. }
  190637. else
  190638. {
  190639. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  190640. png_crc_finish(png_ptr, length);
  190641. return;
  190642. }
  190643. if (png_crc_finish(png_ptr, 0))
  190644. {
  190645. png_ptr->num_trans = 0;
  190646. return;
  190647. }
  190648. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  190649. &(png_ptr->trans_values));
  190650. }
  190651. #endif
  190652. #if defined(PNG_READ_bKGD_SUPPORTED)
  190653. void /* PRIVATE */
  190654. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190655. {
  190656. png_size_t truelen;
  190657. png_byte buf[6];
  190658. png_debug(1, "in png_handle_bKGD\n");
  190659. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190660. png_error(png_ptr, "Missing IHDR before bKGD");
  190661. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190662. {
  190663. png_warning(png_ptr, "Invalid bKGD after IDAT");
  190664. png_crc_finish(png_ptr, length);
  190665. return;
  190666. }
  190667. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  190668. !(png_ptr->mode & PNG_HAVE_PLTE))
  190669. {
  190670. png_warning(png_ptr, "Missing PLTE before bKGD");
  190671. png_crc_finish(png_ptr, length);
  190672. return;
  190673. }
  190674. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  190675. {
  190676. png_warning(png_ptr, "Duplicate bKGD chunk");
  190677. png_crc_finish(png_ptr, length);
  190678. return;
  190679. }
  190680. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190681. truelen = 1;
  190682. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190683. truelen = 6;
  190684. else
  190685. truelen = 2;
  190686. if (length != truelen)
  190687. {
  190688. png_warning(png_ptr, "Incorrect bKGD chunk length");
  190689. png_crc_finish(png_ptr, length);
  190690. return;
  190691. }
  190692. png_crc_read(png_ptr, buf, truelen);
  190693. if (png_crc_finish(png_ptr, 0))
  190694. return;
  190695. /* We convert the index value into RGB components so that we can allow
  190696. * arbitrary RGB values for background when we have transparency, and
  190697. * so it is easy to determine the RGB values of the background color
  190698. * from the info_ptr struct. */
  190699. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190700. {
  190701. png_ptr->background.index = buf[0];
  190702. if(info_ptr->num_palette)
  190703. {
  190704. if(buf[0] > info_ptr->num_palette)
  190705. {
  190706. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  190707. return;
  190708. }
  190709. png_ptr->background.red =
  190710. (png_uint_16)png_ptr->palette[buf[0]].red;
  190711. png_ptr->background.green =
  190712. (png_uint_16)png_ptr->palette[buf[0]].green;
  190713. png_ptr->background.blue =
  190714. (png_uint_16)png_ptr->palette[buf[0]].blue;
  190715. }
  190716. }
  190717. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  190718. {
  190719. png_ptr->background.red =
  190720. png_ptr->background.green =
  190721. png_ptr->background.blue =
  190722. png_ptr->background.gray = png_get_uint_16(buf);
  190723. }
  190724. else
  190725. {
  190726. png_ptr->background.red = png_get_uint_16(buf);
  190727. png_ptr->background.green = png_get_uint_16(buf + 2);
  190728. png_ptr->background.blue = png_get_uint_16(buf + 4);
  190729. }
  190730. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  190731. }
  190732. #endif
  190733. #if defined(PNG_READ_hIST_SUPPORTED)
  190734. void /* PRIVATE */
  190735. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190736. {
  190737. unsigned int num, i;
  190738. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  190739. png_debug(1, "in png_handle_hIST\n");
  190740. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190741. png_error(png_ptr, "Missing IHDR before hIST");
  190742. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190743. {
  190744. png_warning(png_ptr, "Invalid hIST after IDAT");
  190745. png_crc_finish(png_ptr, length);
  190746. return;
  190747. }
  190748. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  190749. {
  190750. png_warning(png_ptr, "Missing PLTE before hIST");
  190751. png_crc_finish(png_ptr, length);
  190752. return;
  190753. }
  190754. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  190755. {
  190756. png_warning(png_ptr, "Duplicate hIST chunk");
  190757. png_crc_finish(png_ptr, length);
  190758. return;
  190759. }
  190760. num = length / 2 ;
  190761. if (num != (unsigned int) png_ptr->num_palette || num >
  190762. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  190763. {
  190764. png_warning(png_ptr, "Incorrect hIST chunk length");
  190765. png_crc_finish(png_ptr, length);
  190766. return;
  190767. }
  190768. for (i = 0; i < num; i++)
  190769. {
  190770. png_byte buf[2];
  190771. png_crc_read(png_ptr, buf, 2);
  190772. readbuf[i] = png_get_uint_16(buf);
  190773. }
  190774. if (png_crc_finish(png_ptr, 0))
  190775. return;
  190776. png_set_hIST(png_ptr, info_ptr, readbuf);
  190777. }
  190778. #endif
  190779. #if defined(PNG_READ_pHYs_SUPPORTED)
  190780. void /* PRIVATE */
  190781. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190782. {
  190783. png_byte buf[9];
  190784. png_uint_32 res_x, res_y;
  190785. int unit_type;
  190786. png_debug(1, "in png_handle_pHYs\n");
  190787. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190788. png_error(png_ptr, "Missing IHDR before pHYs");
  190789. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190790. {
  190791. png_warning(png_ptr, "Invalid pHYs after IDAT");
  190792. png_crc_finish(png_ptr, length);
  190793. return;
  190794. }
  190795. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  190796. {
  190797. png_warning(png_ptr, "Duplicate pHYs chunk");
  190798. png_crc_finish(png_ptr, length);
  190799. return;
  190800. }
  190801. if (length != 9)
  190802. {
  190803. png_warning(png_ptr, "Incorrect pHYs chunk length");
  190804. png_crc_finish(png_ptr, length);
  190805. return;
  190806. }
  190807. png_crc_read(png_ptr, buf, 9);
  190808. if (png_crc_finish(png_ptr, 0))
  190809. return;
  190810. res_x = png_get_uint_32(buf);
  190811. res_y = png_get_uint_32(buf + 4);
  190812. unit_type = buf[8];
  190813. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  190814. }
  190815. #endif
  190816. #if defined(PNG_READ_oFFs_SUPPORTED)
  190817. void /* PRIVATE */
  190818. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190819. {
  190820. png_byte buf[9];
  190821. png_int_32 offset_x, offset_y;
  190822. int unit_type;
  190823. png_debug(1, "in png_handle_oFFs\n");
  190824. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190825. png_error(png_ptr, "Missing IHDR before oFFs");
  190826. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190827. {
  190828. png_warning(png_ptr, "Invalid oFFs after IDAT");
  190829. png_crc_finish(png_ptr, length);
  190830. return;
  190831. }
  190832. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  190833. {
  190834. png_warning(png_ptr, "Duplicate oFFs chunk");
  190835. png_crc_finish(png_ptr, length);
  190836. return;
  190837. }
  190838. if (length != 9)
  190839. {
  190840. png_warning(png_ptr, "Incorrect oFFs chunk length");
  190841. png_crc_finish(png_ptr, length);
  190842. return;
  190843. }
  190844. png_crc_read(png_ptr, buf, 9);
  190845. if (png_crc_finish(png_ptr, 0))
  190846. return;
  190847. offset_x = png_get_int_32(buf);
  190848. offset_y = png_get_int_32(buf + 4);
  190849. unit_type = buf[8];
  190850. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  190851. }
  190852. #endif
  190853. #if defined(PNG_READ_pCAL_SUPPORTED)
  190854. /* read the pCAL chunk (described in the PNG Extensions document) */
  190855. void /* PRIVATE */
  190856. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190857. {
  190858. png_charp purpose;
  190859. png_int_32 X0, X1;
  190860. png_byte type, nparams;
  190861. png_charp buf, units, endptr;
  190862. png_charpp params;
  190863. png_size_t slength;
  190864. int i;
  190865. png_debug(1, "in png_handle_pCAL\n");
  190866. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190867. png_error(png_ptr, "Missing IHDR before pCAL");
  190868. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190869. {
  190870. png_warning(png_ptr, "Invalid pCAL after IDAT");
  190871. png_crc_finish(png_ptr, length);
  190872. return;
  190873. }
  190874. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  190875. {
  190876. png_warning(png_ptr, "Duplicate pCAL chunk");
  190877. png_crc_finish(png_ptr, length);
  190878. return;
  190879. }
  190880. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  190881. length + 1);
  190882. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190883. if (purpose == NULL)
  190884. {
  190885. png_warning(png_ptr, "No memory for pCAL purpose.");
  190886. return;
  190887. }
  190888. slength = (png_size_t)length;
  190889. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  190890. if (png_crc_finish(png_ptr, 0))
  190891. {
  190892. png_free(png_ptr, purpose);
  190893. return;
  190894. }
  190895. purpose[slength] = 0x00; /* null terminate the last string */
  190896. png_debug(3, "Finding end of pCAL purpose string\n");
  190897. for (buf = purpose; *buf; buf++)
  190898. /* empty loop */ ;
  190899. endptr = purpose + slength;
  190900. /* We need to have at least 12 bytes after the purpose string
  190901. in order to get the parameter information. */
  190902. if (endptr <= buf + 12)
  190903. {
  190904. png_warning(png_ptr, "Invalid pCAL data");
  190905. png_free(png_ptr, purpose);
  190906. return;
  190907. }
  190908. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  190909. X0 = png_get_int_32((png_bytep)buf+1);
  190910. X1 = png_get_int_32((png_bytep)buf+5);
  190911. type = buf[9];
  190912. nparams = buf[10];
  190913. units = buf + 11;
  190914. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  190915. /* Check that we have the right number of parameters for known
  190916. equation types. */
  190917. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  190918. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  190919. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  190920. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  190921. {
  190922. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  190923. png_free(png_ptr, purpose);
  190924. return;
  190925. }
  190926. else if (type >= PNG_EQUATION_LAST)
  190927. {
  190928. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  190929. }
  190930. for (buf = units; *buf; buf++)
  190931. /* Empty loop to move past the units string. */ ;
  190932. png_debug(3, "Allocating pCAL parameters array\n");
  190933. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  190934. *png_sizeof(png_charp))) ;
  190935. if (params == NULL)
  190936. {
  190937. png_free(png_ptr, purpose);
  190938. png_warning(png_ptr, "No memory for pCAL params.");
  190939. return;
  190940. }
  190941. /* Get pointers to the start of each parameter string. */
  190942. for (i = 0; i < (int)nparams; i++)
  190943. {
  190944. buf++; /* Skip the null string terminator from previous parameter. */
  190945. png_debug1(3, "Reading pCAL parameter %d\n", i);
  190946. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  190947. /* Empty loop to move past each parameter string */ ;
  190948. /* Make sure we haven't run out of data yet */
  190949. if (buf > endptr)
  190950. {
  190951. png_warning(png_ptr, "Invalid pCAL data");
  190952. png_free(png_ptr, purpose);
  190953. png_free(png_ptr, params);
  190954. return;
  190955. }
  190956. }
  190957. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  190958. units, params);
  190959. png_free(png_ptr, purpose);
  190960. png_free(png_ptr, params);
  190961. }
  190962. #endif
  190963. #if defined(PNG_READ_sCAL_SUPPORTED)
  190964. /* read the sCAL chunk */
  190965. void /* PRIVATE */
  190966. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  190967. {
  190968. png_charp buffer, ep;
  190969. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190970. double width, height;
  190971. png_charp vp;
  190972. #else
  190973. #ifdef PNG_FIXED_POINT_SUPPORTED
  190974. png_charp swidth, sheight;
  190975. #endif
  190976. #endif
  190977. png_size_t slength;
  190978. png_debug(1, "in png_handle_sCAL\n");
  190979. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  190980. png_error(png_ptr, "Missing IHDR before sCAL");
  190981. else if (png_ptr->mode & PNG_HAVE_IDAT)
  190982. {
  190983. png_warning(png_ptr, "Invalid sCAL after IDAT");
  190984. png_crc_finish(png_ptr, length);
  190985. return;
  190986. }
  190987. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  190988. {
  190989. png_warning(png_ptr, "Duplicate sCAL chunk");
  190990. png_crc_finish(png_ptr, length);
  190991. return;
  190992. }
  190993. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  190994. length + 1);
  190995. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  190996. if (buffer == NULL)
  190997. {
  190998. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  190999. return;
  191000. }
  191001. slength = (png_size_t)length;
  191002. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  191003. if (png_crc_finish(png_ptr, 0))
  191004. {
  191005. png_free(png_ptr, buffer);
  191006. return;
  191007. }
  191008. buffer[slength] = 0x00; /* null terminate the last string */
  191009. ep = buffer + 1; /* skip unit byte */
  191010. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191011. width = png_strtod(png_ptr, ep, &vp);
  191012. if (*vp)
  191013. {
  191014. png_warning(png_ptr, "malformed width string in sCAL chunk");
  191015. return;
  191016. }
  191017. #else
  191018. #ifdef PNG_FIXED_POINT_SUPPORTED
  191019. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191020. if (swidth == NULL)
  191021. {
  191022. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  191023. return;
  191024. }
  191025. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  191026. #endif
  191027. #endif
  191028. for (ep = buffer; *ep; ep++)
  191029. /* empty loop */ ;
  191030. ep++;
  191031. if (buffer + slength < ep)
  191032. {
  191033. png_warning(png_ptr, "Truncated sCAL chunk");
  191034. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  191035. !defined(PNG_FLOATING_POINT_SUPPORTED)
  191036. png_free(png_ptr, swidth);
  191037. #endif
  191038. png_free(png_ptr, buffer);
  191039. return;
  191040. }
  191041. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191042. height = png_strtod(png_ptr, ep, &vp);
  191043. if (*vp)
  191044. {
  191045. png_warning(png_ptr, "malformed height string in sCAL chunk");
  191046. return;
  191047. }
  191048. #else
  191049. #ifdef PNG_FIXED_POINT_SUPPORTED
  191050. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  191051. if (swidth == NULL)
  191052. {
  191053. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  191054. return;
  191055. }
  191056. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  191057. #endif
  191058. #endif
  191059. if (buffer + slength < ep
  191060. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191061. || width <= 0. || height <= 0.
  191062. #endif
  191063. )
  191064. {
  191065. png_warning(png_ptr, "Invalid sCAL data");
  191066. png_free(png_ptr, buffer);
  191067. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191068. png_free(png_ptr, swidth);
  191069. png_free(png_ptr, sheight);
  191070. #endif
  191071. return;
  191072. }
  191073. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191074. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  191075. #else
  191076. #ifdef PNG_FIXED_POINT_SUPPORTED
  191077. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  191078. #endif
  191079. #endif
  191080. png_free(png_ptr, buffer);
  191081. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  191082. png_free(png_ptr, swidth);
  191083. png_free(png_ptr, sheight);
  191084. #endif
  191085. }
  191086. #endif
  191087. #if defined(PNG_READ_tIME_SUPPORTED)
  191088. void /* PRIVATE */
  191089. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191090. {
  191091. png_byte buf[7];
  191092. png_time mod_time;
  191093. png_debug(1, "in png_handle_tIME\n");
  191094. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191095. png_error(png_ptr, "Out of place tIME chunk");
  191096. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  191097. {
  191098. png_warning(png_ptr, "Duplicate tIME chunk");
  191099. png_crc_finish(png_ptr, length);
  191100. return;
  191101. }
  191102. if (png_ptr->mode & PNG_HAVE_IDAT)
  191103. png_ptr->mode |= PNG_AFTER_IDAT;
  191104. if (length != 7)
  191105. {
  191106. png_warning(png_ptr, "Incorrect tIME chunk length");
  191107. png_crc_finish(png_ptr, length);
  191108. return;
  191109. }
  191110. png_crc_read(png_ptr, buf, 7);
  191111. if (png_crc_finish(png_ptr, 0))
  191112. return;
  191113. mod_time.second = buf[6];
  191114. mod_time.minute = buf[5];
  191115. mod_time.hour = buf[4];
  191116. mod_time.day = buf[3];
  191117. mod_time.month = buf[2];
  191118. mod_time.year = png_get_uint_16(buf);
  191119. png_set_tIME(png_ptr, info_ptr, &mod_time);
  191120. }
  191121. #endif
  191122. #if defined(PNG_READ_tEXt_SUPPORTED)
  191123. /* Note: this does not properly handle chunks that are > 64K under DOS */
  191124. void /* PRIVATE */
  191125. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191126. {
  191127. png_textp text_ptr;
  191128. png_charp key;
  191129. png_charp text;
  191130. png_uint_32 skip = 0;
  191131. png_size_t slength;
  191132. int ret;
  191133. png_debug(1, "in png_handle_tEXt\n");
  191134. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191135. png_error(png_ptr, "Missing IHDR before tEXt");
  191136. if (png_ptr->mode & PNG_HAVE_IDAT)
  191137. png_ptr->mode |= PNG_AFTER_IDAT;
  191138. #ifdef PNG_MAX_MALLOC_64K
  191139. if (length > (png_uint_32)65535L)
  191140. {
  191141. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  191142. skip = length - (png_uint_32)65535L;
  191143. length = (png_uint_32)65535L;
  191144. }
  191145. #endif
  191146. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191147. if (key == NULL)
  191148. {
  191149. png_warning(png_ptr, "No memory to process text chunk.");
  191150. return;
  191151. }
  191152. slength = (png_size_t)length;
  191153. png_crc_read(png_ptr, (png_bytep)key, slength);
  191154. if (png_crc_finish(png_ptr, skip))
  191155. {
  191156. png_free(png_ptr, key);
  191157. return;
  191158. }
  191159. key[slength] = 0x00;
  191160. for (text = key; *text; text++)
  191161. /* empty loop to find end of key */ ;
  191162. if (text != key + slength)
  191163. text++;
  191164. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191165. (png_uint_32)png_sizeof(png_text));
  191166. if (text_ptr == NULL)
  191167. {
  191168. png_warning(png_ptr, "Not enough memory to process text chunk.");
  191169. png_free(png_ptr, key);
  191170. return;
  191171. }
  191172. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  191173. text_ptr->key = key;
  191174. #ifdef PNG_iTXt_SUPPORTED
  191175. text_ptr->lang = NULL;
  191176. text_ptr->lang_key = NULL;
  191177. text_ptr->itxt_length = 0;
  191178. #endif
  191179. text_ptr->text = text;
  191180. text_ptr->text_length = png_strlen(text);
  191181. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191182. png_free(png_ptr, key);
  191183. png_free(png_ptr, text_ptr);
  191184. if (ret)
  191185. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  191186. }
  191187. #endif
  191188. #if defined(PNG_READ_zTXt_SUPPORTED)
  191189. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191190. void /* PRIVATE */
  191191. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191192. {
  191193. png_textp text_ptr;
  191194. png_charp chunkdata;
  191195. png_charp text;
  191196. int comp_type;
  191197. int ret;
  191198. png_size_t slength, prefix_len, data_len;
  191199. png_debug(1, "in png_handle_zTXt\n");
  191200. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191201. png_error(png_ptr, "Missing IHDR before zTXt");
  191202. if (png_ptr->mode & PNG_HAVE_IDAT)
  191203. png_ptr->mode |= PNG_AFTER_IDAT;
  191204. #ifdef PNG_MAX_MALLOC_64K
  191205. /* We will no doubt have problems with chunks even half this size, but
  191206. there is no hard and fast rule to tell us where to stop. */
  191207. if (length > (png_uint_32)65535L)
  191208. {
  191209. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  191210. png_crc_finish(png_ptr, length);
  191211. return;
  191212. }
  191213. #endif
  191214. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191215. if (chunkdata == NULL)
  191216. {
  191217. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  191218. return;
  191219. }
  191220. slength = (png_size_t)length;
  191221. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191222. if (png_crc_finish(png_ptr, 0))
  191223. {
  191224. png_free(png_ptr, chunkdata);
  191225. return;
  191226. }
  191227. chunkdata[slength] = 0x00;
  191228. for (text = chunkdata; *text; text++)
  191229. /* empty loop */ ;
  191230. /* zTXt must have some text after the chunkdataword */
  191231. if (text >= chunkdata + slength - 2)
  191232. {
  191233. png_warning(png_ptr, "Truncated zTXt chunk");
  191234. png_free(png_ptr, chunkdata);
  191235. return;
  191236. }
  191237. else
  191238. {
  191239. comp_type = *(++text);
  191240. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  191241. {
  191242. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  191243. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  191244. }
  191245. text++; /* skip the compression_method byte */
  191246. }
  191247. prefix_len = text - chunkdata;
  191248. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191249. (png_size_t)length, prefix_len, &data_len);
  191250. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191251. (png_uint_32)png_sizeof(png_text));
  191252. if (text_ptr == NULL)
  191253. {
  191254. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  191255. png_free(png_ptr, chunkdata);
  191256. return;
  191257. }
  191258. text_ptr->compression = comp_type;
  191259. text_ptr->key = chunkdata;
  191260. #ifdef PNG_iTXt_SUPPORTED
  191261. text_ptr->lang = NULL;
  191262. text_ptr->lang_key = NULL;
  191263. text_ptr->itxt_length = 0;
  191264. #endif
  191265. text_ptr->text = chunkdata + prefix_len;
  191266. text_ptr->text_length = data_len;
  191267. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191268. png_free(png_ptr, text_ptr);
  191269. png_free(png_ptr, chunkdata);
  191270. if (ret)
  191271. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  191272. }
  191273. #endif
  191274. #if defined(PNG_READ_iTXt_SUPPORTED)
  191275. /* note: this does not correctly handle chunks that are > 64K under DOS */
  191276. void /* PRIVATE */
  191277. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191278. {
  191279. png_textp text_ptr;
  191280. png_charp chunkdata;
  191281. png_charp key, lang, text, lang_key;
  191282. int comp_flag;
  191283. int comp_type = 0;
  191284. int ret;
  191285. png_size_t slength, prefix_len, data_len;
  191286. png_debug(1, "in png_handle_iTXt\n");
  191287. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  191288. png_error(png_ptr, "Missing IHDR before iTXt");
  191289. if (png_ptr->mode & PNG_HAVE_IDAT)
  191290. png_ptr->mode |= PNG_AFTER_IDAT;
  191291. #ifdef PNG_MAX_MALLOC_64K
  191292. /* We will no doubt have problems with chunks even half this size, but
  191293. there is no hard and fast rule to tell us where to stop. */
  191294. if (length > (png_uint_32)65535L)
  191295. {
  191296. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  191297. png_crc_finish(png_ptr, length);
  191298. return;
  191299. }
  191300. #endif
  191301. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  191302. if (chunkdata == NULL)
  191303. {
  191304. png_warning(png_ptr, "No memory to process iTXt chunk.");
  191305. return;
  191306. }
  191307. slength = (png_size_t)length;
  191308. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  191309. if (png_crc_finish(png_ptr, 0))
  191310. {
  191311. png_free(png_ptr, chunkdata);
  191312. return;
  191313. }
  191314. chunkdata[slength] = 0x00;
  191315. for (lang = chunkdata; *lang; lang++)
  191316. /* empty loop */ ;
  191317. lang++; /* skip NUL separator */
  191318. /* iTXt must have a language tag (possibly empty), two compression bytes,
  191319. translated keyword (possibly empty), and possibly some text after the
  191320. keyword */
  191321. if (lang >= chunkdata + slength - 3)
  191322. {
  191323. png_warning(png_ptr, "Truncated iTXt chunk");
  191324. png_free(png_ptr, chunkdata);
  191325. return;
  191326. }
  191327. else
  191328. {
  191329. comp_flag = *lang++;
  191330. comp_type = *lang++;
  191331. }
  191332. for (lang_key = lang; *lang_key; lang_key++)
  191333. /* empty loop */ ;
  191334. lang_key++; /* skip NUL separator */
  191335. if (lang_key >= chunkdata + slength)
  191336. {
  191337. png_warning(png_ptr, "Truncated iTXt chunk");
  191338. png_free(png_ptr, chunkdata);
  191339. return;
  191340. }
  191341. for (text = lang_key; *text; text++)
  191342. /* empty loop */ ;
  191343. text++; /* skip NUL separator */
  191344. if (text >= chunkdata + slength)
  191345. {
  191346. png_warning(png_ptr, "Malformed iTXt chunk");
  191347. png_free(png_ptr, chunkdata);
  191348. return;
  191349. }
  191350. prefix_len = text - chunkdata;
  191351. key=chunkdata;
  191352. if (comp_flag)
  191353. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  191354. (size_t)length, prefix_len, &data_len);
  191355. else
  191356. data_len=png_strlen(chunkdata + prefix_len);
  191357. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  191358. (png_uint_32)png_sizeof(png_text));
  191359. if (text_ptr == NULL)
  191360. {
  191361. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  191362. png_free(png_ptr, chunkdata);
  191363. return;
  191364. }
  191365. text_ptr->compression = (int)comp_flag + 1;
  191366. text_ptr->lang_key = chunkdata+(lang_key-key);
  191367. text_ptr->lang = chunkdata+(lang-key);
  191368. text_ptr->itxt_length = data_len;
  191369. text_ptr->text_length = 0;
  191370. text_ptr->key = chunkdata;
  191371. text_ptr->text = chunkdata + prefix_len;
  191372. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  191373. png_free(png_ptr, text_ptr);
  191374. png_free(png_ptr, chunkdata);
  191375. if (ret)
  191376. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  191377. }
  191378. #endif
  191379. /* This function is called when we haven't found a handler for a
  191380. chunk. If there isn't a problem with the chunk itself (ie bad
  191381. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  191382. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  191383. case it will be saved away to be written out later. */
  191384. void /* PRIVATE */
  191385. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  191386. {
  191387. png_uint_32 skip = 0;
  191388. png_debug(1, "in png_handle_unknown\n");
  191389. if (png_ptr->mode & PNG_HAVE_IDAT)
  191390. {
  191391. #ifdef PNG_USE_LOCAL_ARRAYS
  191392. PNG_CONST PNG_IDAT;
  191393. #endif
  191394. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  191395. png_ptr->mode |= PNG_AFTER_IDAT;
  191396. }
  191397. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  191398. if (!(png_ptr->chunk_name[0] & 0x20))
  191399. {
  191400. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191401. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191402. PNG_HANDLE_CHUNK_ALWAYS
  191403. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191404. && png_ptr->read_user_chunk_fn == NULL
  191405. #endif
  191406. )
  191407. #endif
  191408. png_chunk_error(png_ptr, "unknown critical chunk");
  191409. }
  191410. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  191411. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  191412. (png_ptr->read_user_chunk_fn != NULL))
  191413. {
  191414. #ifdef PNG_MAX_MALLOC_64K
  191415. if (length > (png_uint_32)65535L)
  191416. {
  191417. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  191418. skip = length - (png_uint_32)65535L;
  191419. length = (png_uint_32)65535L;
  191420. }
  191421. #endif
  191422. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  191423. (png_charp)png_ptr->chunk_name, 5);
  191424. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  191425. png_ptr->unknown_chunk.size = (png_size_t)length;
  191426. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  191427. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191428. if(png_ptr->read_user_chunk_fn != NULL)
  191429. {
  191430. /* callback to user unknown chunk handler */
  191431. int ret;
  191432. ret = (*(png_ptr->read_user_chunk_fn))
  191433. (png_ptr, &png_ptr->unknown_chunk);
  191434. if (ret < 0)
  191435. png_chunk_error(png_ptr, "error in user chunk");
  191436. if (ret == 0)
  191437. {
  191438. if (!(png_ptr->chunk_name[0] & 0x20))
  191439. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  191440. PNG_HANDLE_CHUNK_ALWAYS)
  191441. png_chunk_error(png_ptr, "unknown critical chunk");
  191442. png_set_unknown_chunks(png_ptr, info_ptr,
  191443. &png_ptr->unknown_chunk, 1);
  191444. }
  191445. }
  191446. #else
  191447. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  191448. #endif
  191449. png_free(png_ptr, png_ptr->unknown_chunk.data);
  191450. png_ptr->unknown_chunk.data = NULL;
  191451. }
  191452. else
  191453. #endif
  191454. skip = length;
  191455. png_crc_finish(png_ptr, skip);
  191456. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191457. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  191458. #endif
  191459. }
  191460. /* This function is called to verify that a chunk name is valid.
  191461. This function can't have the "critical chunk check" incorporated
  191462. into it, since in the future we will need to be able to call user
  191463. functions to handle unknown critical chunks after we check that
  191464. the chunk name itself is valid. */
  191465. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  191466. void /* PRIVATE */
  191467. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  191468. {
  191469. png_debug(1, "in png_check_chunk_name\n");
  191470. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  191471. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  191472. {
  191473. png_chunk_error(png_ptr, "invalid chunk type");
  191474. }
  191475. }
  191476. /* Combines the row recently read in with the existing pixels in the
  191477. row. This routine takes care of alpha and transparency if requested.
  191478. This routine also handles the two methods of progressive display
  191479. of interlaced images, depending on the mask value.
  191480. The mask value describes which pixels are to be combined with
  191481. the row. The pattern always repeats every 8 pixels, so just 8
  191482. bits are needed. A one indicates the pixel is to be combined,
  191483. a zero indicates the pixel is to be skipped. This is in addition
  191484. to any alpha or transparency value associated with the pixel. If
  191485. you want all pixels to be combined, pass 0xff (255) in mask. */
  191486. void /* PRIVATE */
  191487. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  191488. {
  191489. png_debug(1,"in png_combine_row\n");
  191490. if (mask == 0xff)
  191491. {
  191492. png_memcpy(row, png_ptr->row_buf + 1,
  191493. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  191494. }
  191495. else
  191496. {
  191497. switch (png_ptr->row_info.pixel_depth)
  191498. {
  191499. case 1:
  191500. {
  191501. png_bytep sp = png_ptr->row_buf + 1;
  191502. png_bytep dp = row;
  191503. int s_inc, s_start, s_end;
  191504. int m = 0x80;
  191505. int shift;
  191506. png_uint_32 i;
  191507. png_uint_32 row_width = png_ptr->width;
  191508. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191509. if (png_ptr->transformations & PNG_PACKSWAP)
  191510. {
  191511. s_start = 0;
  191512. s_end = 7;
  191513. s_inc = 1;
  191514. }
  191515. else
  191516. #endif
  191517. {
  191518. s_start = 7;
  191519. s_end = 0;
  191520. s_inc = -1;
  191521. }
  191522. shift = s_start;
  191523. for (i = 0; i < row_width; i++)
  191524. {
  191525. if (m & mask)
  191526. {
  191527. int value;
  191528. value = (*sp >> shift) & 0x01;
  191529. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  191530. *dp |= (png_byte)(value << shift);
  191531. }
  191532. if (shift == s_end)
  191533. {
  191534. shift = s_start;
  191535. sp++;
  191536. dp++;
  191537. }
  191538. else
  191539. shift += s_inc;
  191540. if (m == 1)
  191541. m = 0x80;
  191542. else
  191543. m >>= 1;
  191544. }
  191545. break;
  191546. }
  191547. case 2:
  191548. {
  191549. png_bytep sp = png_ptr->row_buf + 1;
  191550. png_bytep dp = row;
  191551. int s_start, s_end, s_inc;
  191552. int m = 0x80;
  191553. int shift;
  191554. png_uint_32 i;
  191555. png_uint_32 row_width = png_ptr->width;
  191556. int value;
  191557. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191558. if (png_ptr->transformations & PNG_PACKSWAP)
  191559. {
  191560. s_start = 0;
  191561. s_end = 6;
  191562. s_inc = 2;
  191563. }
  191564. else
  191565. #endif
  191566. {
  191567. s_start = 6;
  191568. s_end = 0;
  191569. s_inc = -2;
  191570. }
  191571. shift = s_start;
  191572. for (i = 0; i < row_width; i++)
  191573. {
  191574. if (m & mask)
  191575. {
  191576. value = (*sp >> shift) & 0x03;
  191577. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  191578. *dp |= (png_byte)(value << shift);
  191579. }
  191580. if (shift == s_end)
  191581. {
  191582. shift = s_start;
  191583. sp++;
  191584. dp++;
  191585. }
  191586. else
  191587. shift += s_inc;
  191588. if (m == 1)
  191589. m = 0x80;
  191590. else
  191591. m >>= 1;
  191592. }
  191593. break;
  191594. }
  191595. case 4:
  191596. {
  191597. png_bytep sp = png_ptr->row_buf + 1;
  191598. png_bytep dp = row;
  191599. int s_start, s_end, s_inc;
  191600. int m = 0x80;
  191601. int shift;
  191602. png_uint_32 i;
  191603. png_uint_32 row_width = png_ptr->width;
  191604. int value;
  191605. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191606. if (png_ptr->transformations & PNG_PACKSWAP)
  191607. {
  191608. s_start = 0;
  191609. s_end = 4;
  191610. s_inc = 4;
  191611. }
  191612. else
  191613. #endif
  191614. {
  191615. s_start = 4;
  191616. s_end = 0;
  191617. s_inc = -4;
  191618. }
  191619. shift = s_start;
  191620. for (i = 0; i < row_width; i++)
  191621. {
  191622. if (m & mask)
  191623. {
  191624. value = (*sp >> shift) & 0xf;
  191625. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  191626. *dp |= (png_byte)(value << shift);
  191627. }
  191628. if (shift == s_end)
  191629. {
  191630. shift = s_start;
  191631. sp++;
  191632. dp++;
  191633. }
  191634. else
  191635. shift += s_inc;
  191636. if (m == 1)
  191637. m = 0x80;
  191638. else
  191639. m >>= 1;
  191640. }
  191641. break;
  191642. }
  191643. default:
  191644. {
  191645. png_bytep sp = png_ptr->row_buf + 1;
  191646. png_bytep dp = row;
  191647. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  191648. png_uint_32 i;
  191649. png_uint_32 row_width = png_ptr->width;
  191650. png_byte m = 0x80;
  191651. for (i = 0; i < row_width; i++)
  191652. {
  191653. if (m & mask)
  191654. {
  191655. png_memcpy(dp, sp, pixel_bytes);
  191656. }
  191657. sp += pixel_bytes;
  191658. dp += pixel_bytes;
  191659. if (m == 1)
  191660. m = 0x80;
  191661. else
  191662. m >>= 1;
  191663. }
  191664. break;
  191665. }
  191666. }
  191667. }
  191668. }
  191669. #ifdef PNG_READ_INTERLACING_SUPPORTED
  191670. /* OLD pre-1.0.9 interface:
  191671. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  191672. png_uint_32 transformations)
  191673. */
  191674. void /* PRIVATE */
  191675. png_do_read_interlace(png_structp png_ptr)
  191676. {
  191677. png_row_infop row_info = &(png_ptr->row_info);
  191678. png_bytep row = png_ptr->row_buf + 1;
  191679. int pass = png_ptr->pass;
  191680. png_uint_32 transformations = png_ptr->transformations;
  191681. #ifdef PNG_USE_LOCAL_ARRAYS
  191682. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191683. /* offset to next interlace block */
  191684. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  191685. #endif
  191686. png_debug(1,"in png_do_read_interlace\n");
  191687. if (row != NULL && row_info != NULL)
  191688. {
  191689. png_uint_32 final_width;
  191690. final_width = row_info->width * png_pass_inc[pass];
  191691. switch (row_info->pixel_depth)
  191692. {
  191693. case 1:
  191694. {
  191695. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  191696. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  191697. int sshift, dshift;
  191698. int s_start, s_end, s_inc;
  191699. int jstop = png_pass_inc[pass];
  191700. png_byte v;
  191701. png_uint_32 i;
  191702. int j;
  191703. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191704. if (transformations & PNG_PACKSWAP)
  191705. {
  191706. sshift = (int)((row_info->width + 7) & 0x07);
  191707. dshift = (int)((final_width + 7) & 0x07);
  191708. s_start = 7;
  191709. s_end = 0;
  191710. s_inc = -1;
  191711. }
  191712. else
  191713. #endif
  191714. {
  191715. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  191716. dshift = 7 - (int)((final_width + 7) & 0x07);
  191717. s_start = 0;
  191718. s_end = 7;
  191719. s_inc = 1;
  191720. }
  191721. for (i = 0; i < row_info->width; i++)
  191722. {
  191723. v = (png_byte)((*sp >> sshift) & 0x01);
  191724. for (j = 0; j < jstop; j++)
  191725. {
  191726. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  191727. *dp |= (png_byte)(v << dshift);
  191728. if (dshift == s_end)
  191729. {
  191730. dshift = s_start;
  191731. dp--;
  191732. }
  191733. else
  191734. dshift += s_inc;
  191735. }
  191736. if (sshift == s_end)
  191737. {
  191738. sshift = s_start;
  191739. sp--;
  191740. }
  191741. else
  191742. sshift += s_inc;
  191743. }
  191744. break;
  191745. }
  191746. case 2:
  191747. {
  191748. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  191749. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  191750. int sshift, dshift;
  191751. int s_start, s_end, s_inc;
  191752. int jstop = png_pass_inc[pass];
  191753. png_uint_32 i;
  191754. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191755. if (transformations & PNG_PACKSWAP)
  191756. {
  191757. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  191758. dshift = (int)(((final_width + 3) & 0x03) << 1);
  191759. s_start = 6;
  191760. s_end = 0;
  191761. s_inc = -2;
  191762. }
  191763. else
  191764. #endif
  191765. {
  191766. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  191767. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  191768. s_start = 0;
  191769. s_end = 6;
  191770. s_inc = 2;
  191771. }
  191772. for (i = 0; i < row_info->width; i++)
  191773. {
  191774. png_byte v;
  191775. int j;
  191776. v = (png_byte)((*sp >> sshift) & 0x03);
  191777. for (j = 0; j < jstop; j++)
  191778. {
  191779. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  191780. *dp |= (png_byte)(v << dshift);
  191781. if (dshift == s_end)
  191782. {
  191783. dshift = s_start;
  191784. dp--;
  191785. }
  191786. else
  191787. dshift += s_inc;
  191788. }
  191789. if (sshift == s_end)
  191790. {
  191791. sshift = s_start;
  191792. sp--;
  191793. }
  191794. else
  191795. sshift += s_inc;
  191796. }
  191797. break;
  191798. }
  191799. case 4:
  191800. {
  191801. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  191802. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  191803. int sshift, dshift;
  191804. int s_start, s_end, s_inc;
  191805. png_uint_32 i;
  191806. int jstop = png_pass_inc[pass];
  191807. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191808. if (transformations & PNG_PACKSWAP)
  191809. {
  191810. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  191811. dshift = (int)(((final_width + 1) & 0x01) << 2);
  191812. s_start = 4;
  191813. s_end = 0;
  191814. s_inc = -4;
  191815. }
  191816. else
  191817. #endif
  191818. {
  191819. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  191820. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  191821. s_start = 0;
  191822. s_end = 4;
  191823. s_inc = 4;
  191824. }
  191825. for (i = 0; i < row_info->width; i++)
  191826. {
  191827. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  191828. int j;
  191829. for (j = 0; j < jstop; j++)
  191830. {
  191831. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  191832. *dp |= (png_byte)(v << dshift);
  191833. if (dshift == s_end)
  191834. {
  191835. dshift = s_start;
  191836. dp--;
  191837. }
  191838. else
  191839. dshift += s_inc;
  191840. }
  191841. if (sshift == s_end)
  191842. {
  191843. sshift = s_start;
  191844. sp--;
  191845. }
  191846. else
  191847. sshift += s_inc;
  191848. }
  191849. break;
  191850. }
  191851. default:
  191852. {
  191853. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  191854. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  191855. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  191856. int jstop = png_pass_inc[pass];
  191857. png_uint_32 i;
  191858. for (i = 0; i < row_info->width; i++)
  191859. {
  191860. png_byte v[8];
  191861. int j;
  191862. png_memcpy(v, sp, pixel_bytes);
  191863. for (j = 0; j < jstop; j++)
  191864. {
  191865. png_memcpy(dp, v, pixel_bytes);
  191866. dp -= pixel_bytes;
  191867. }
  191868. sp -= pixel_bytes;
  191869. }
  191870. break;
  191871. }
  191872. }
  191873. row_info->width = final_width;
  191874. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  191875. }
  191876. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  191877. transformations = transformations; /* silence compiler warning */
  191878. #endif
  191879. }
  191880. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  191881. void /* PRIVATE */
  191882. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  191883. png_bytep prev_row, int filter)
  191884. {
  191885. png_debug(1, "in png_read_filter_row\n");
  191886. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  191887. switch (filter)
  191888. {
  191889. case PNG_FILTER_VALUE_NONE:
  191890. break;
  191891. case PNG_FILTER_VALUE_SUB:
  191892. {
  191893. png_uint_32 i;
  191894. png_uint_32 istop = row_info->rowbytes;
  191895. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191896. png_bytep rp = row + bpp;
  191897. png_bytep lp = row;
  191898. for (i = bpp; i < istop; i++)
  191899. {
  191900. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  191901. rp++;
  191902. }
  191903. break;
  191904. }
  191905. case PNG_FILTER_VALUE_UP:
  191906. {
  191907. png_uint_32 i;
  191908. png_uint_32 istop = row_info->rowbytes;
  191909. png_bytep rp = row;
  191910. png_bytep pp = prev_row;
  191911. for (i = 0; i < istop; i++)
  191912. {
  191913. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191914. rp++;
  191915. }
  191916. break;
  191917. }
  191918. case PNG_FILTER_VALUE_AVG:
  191919. {
  191920. png_uint_32 i;
  191921. png_bytep rp = row;
  191922. png_bytep pp = prev_row;
  191923. png_bytep lp = row;
  191924. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191925. png_uint_32 istop = row_info->rowbytes - bpp;
  191926. for (i = 0; i < bpp; i++)
  191927. {
  191928. *rp = (png_byte)(((int)(*rp) +
  191929. ((int)(*pp++) / 2 )) & 0xff);
  191930. rp++;
  191931. }
  191932. for (i = 0; i < istop; i++)
  191933. {
  191934. *rp = (png_byte)(((int)(*rp) +
  191935. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  191936. rp++;
  191937. }
  191938. break;
  191939. }
  191940. case PNG_FILTER_VALUE_PAETH:
  191941. {
  191942. png_uint_32 i;
  191943. png_bytep rp = row;
  191944. png_bytep pp = prev_row;
  191945. png_bytep lp = row;
  191946. png_bytep cp = prev_row;
  191947. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  191948. png_uint_32 istop=row_info->rowbytes - bpp;
  191949. for (i = 0; i < bpp; i++)
  191950. {
  191951. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  191952. rp++;
  191953. }
  191954. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  191955. {
  191956. int a, b, c, pa, pb, pc, p;
  191957. a = *lp++;
  191958. b = *pp++;
  191959. c = *cp++;
  191960. p = b - c;
  191961. pc = a - c;
  191962. #ifdef PNG_USE_ABS
  191963. pa = abs(p);
  191964. pb = abs(pc);
  191965. pc = abs(p + pc);
  191966. #else
  191967. pa = p < 0 ? -p : p;
  191968. pb = pc < 0 ? -pc : pc;
  191969. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  191970. #endif
  191971. /*
  191972. if (pa <= pb && pa <= pc)
  191973. p = a;
  191974. else if (pb <= pc)
  191975. p = b;
  191976. else
  191977. p = c;
  191978. */
  191979. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  191980. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  191981. rp++;
  191982. }
  191983. break;
  191984. }
  191985. default:
  191986. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  191987. *row=0;
  191988. break;
  191989. }
  191990. }
  191991. void /* PRIVATE */
  191992. png_read_finish_row(png_structp png_ptr)
  191993. {
  191994. #ifdef PNG_USE_LOCAL_ARRAYS
  191995. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  191996. /* start of interlace block */
  191997. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  191998. /* offset to next interlace block */
  191999. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192000. /* start of interlace block in the y direction */
  192001. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192002. /* offset to next interlace block in the y direction */
  192003. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192004. #endif
  192005. png_debug(1, "in png_read_finish_row\n");
  192006. png_ptr->row_number++;
  192007. if (png_ptr->row_number < png_ptr->num_rows)
  192008. return;
  192009. if (png_ptr->interlaced)
  192010. {
  192011. png_ptr->row_number = 0;
  192012. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  192013. png_ptr->rowbytes + 1);
  192014. do
  192015. {
  192016. png_ptr->pass++;
  192017. if (png_ptr->pass >= 7)
  192018. break;
  192019. png_ptr->iwidth = (png_ptr->width +
  192020. png_pass_inc[png_ptr->pass] - 1 -
  192021. png_pass_start[png_ptr->pass]) /
  192022. png_pass_inc[png_ptr->pass];
  192023. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  192024. png_ptr->iwidth) + 1;
  192025. if (!(png_ptr->transformations & PNG_INTERLACE))
  192026. {
  192027. png_ptr->num_rows = (png_ptr->height +
  192028. png_pass_yinc[png_ptr->pass] - 1 -
  192029. png_pass_ystart[png_ptr->pass]) /
  192030. png_pass_yinc[png_ptr->pass];
  192031. if (!(png_ptr->num_rows))
  192032. continue;
  192033. }
  192034. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  192035. break;
  192036. } while (png_ptr->iwidth == 0);
  192037. if (png_ptr->pass < 7)
  192038. return;
  192039. }
  192040. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  192041. {
  192042. #ifdef PNG_USE_LOCAL_ARRAYS
  192043. PNG_CONST PNG_IDAT;
  192044. #endif
  192045. char extra;
  192046. int ret;
  192047. png_ptr->zstream.next_out = (Bytef *)&extra;
  192048. png_ptr->zstream.avail_out = (uInt)1;
  192049. for(;;)
  192050. {
  192051. if (!(png_ptr->zstream.avail_in))
  192052. {
  192053. while (!png_ptr->idat_size)
  192054. {
  192055. png_byte chunk_length[4];
  192056. png_crc_finish(png_ptr, 0);
  192057. png_read_data(png_ptr, chunk_length, 4);
  192058. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  192059. png_reset_crc(png_ptr);
  192060. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  192061. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  192062. png_error(png_ptr, "Not enough image data");
  192063. }
  192064. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  192065. png_ptr->zstream.next_in = png_ptr->zbuf;
  192066. if (png_ptr->zbuf_size > png_ptr->idat_size)
  192067. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  192068. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  192069. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  192070. }
  192071. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  192072. if (ret == Z_STREAM_END)
  192073. {
  192074. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  192075. png_ptr->idat_size)
  192076. png_warning(png_ptr, "Extra compressed data");
  192077. png_ptr->mode |= PNG_AFTER_IDAT;
  192078. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192079. break;
  192080. }
  192081. if (ret != Z_OK)
  192082. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  192083. "Decompression Error");
  192084. if (!(png_ptr->zstream.avail_out))
  192085. {
  192086. png_warning(png_ptr, "Extra compressed data.");
  192087. png_ptr->mode |= PNG_AFTER_IDAT;
  192088. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  192089. break;
  192090. }
  192091. }
  192092. png_ptr->zstream.avail_out = 0;
  192093. }
  192094. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  192095. png_warning(png_ptr, "Extra compression data");
  192096. inflateReset(&png_ptr->zstream);
  192097. png_ptr->mode |= PNG_AFTER_IDAT;
  192098. }
  192099. void /* PRIVATE */
  192100. png_read_start_row(png_structp png_ptr)
  192101. {
  192102. #ifdef PNG_USE_LOCAL_ARRAYS
  192103. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  192104. /* start of interlace block */
  192105. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  192106. /* offset to next interlace block */
  192107. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  192108. /* start of interlace block in the y direction */
  192109. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  192110. /* offset to next interlace block in the y direction */
  192111. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  192112. #endif
  192113. int max_pixel_depth;
  192114. png_uint_32 row_bytes;
  192115. png_debug(1, "in png_read_start_row\n");
  192116. png_ptr->zstream.avail_in = 0;
  192117. png_init_read_transformations(png_ptr);
  192118. if (png_ptr->interlaced)
  192119. {
  192120. if (!(png_ptr->transformations & PNG_INTERLACE))
  192121. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  192122. png_pass_ystart[0]) / png_pass_yinc[0];
  192123. else
  192124. png_ptr->num_rows = png_ptr->height;
  192125. png_ptr->iwidth = (png_ptr->width +
  192126. png_pass_inc[png_ptr->pass] - 1 -
  192127. png_pass_start[png_ptr->pass]) /
  192128. png_pass_inc[png_ptr->pass];
  192129. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  192130. png_ptr->irowbytes = (png_size_t)row_bytes;
  192131. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  192132. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  192133. }
  192134. else
  192135. {
  192136. png_ptr->num_rows = png_ptr->height;
  192137. png_ptr->iwidth = png_ptr->width;
  192138. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  192139. }
  192140. max_pixel_depth = png_ptr->pixel_depth;
  192141. #if defined(PNG_READ_PACK_SUPPORTED)
  192142. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  192143. max_pixel_depth = 8;
  192144. #endif
  192145. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192146. if (png_ptr->transformations & PNG_EXPAND)
  192147. {
  192148. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192149. {
  192150. if (png_ptr->num_trans)
  192151. max_pixel_depth = 32;
  192152. else
  192153. max_pixel_depth = 24;
  192154. }
  192155. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192156. {
  192157. if (max_pixel_depth < 8)
  192158. max_pixel_depth = 8;
  192159. if (png_ptr->num_trans)
  192160. max_pixel_depth *= 2;
  192161. }
  192162. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192163. {
  192164. if (png_ptr->num_trans)
  192165. {
  192166. max_pixel_depth *= 4;
  192167. max_pixel_depth /= 3;
  192168. }
  192169. }
  192170. }
  192171. #endif
  192172. #if defined(PNG_READ_FILLER_SUPPORTED)
  192173. if (png_ptr->transformations & (PNG_FILLER))
  192174. {
  192175. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192176. max_pixel_depth = 32;
  192177. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  192178. {
  192179. if (max_pixel_depth <= 8)
  192180. max_pixel_depth = 16;
  192181. else
  192182. max_pixel_depth = 32;
  192183. }
  192184. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  192185. {
  192186. if (max_pixel_depth <= 32)
  192187. max_pixel_depth = 32;
  192188. else
  192189. max_pixel_depth = 64;
  192190. }
  192191. }
  192192. #endif
  192193. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192194. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  192195. {
  192196. if (
  192197. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192198. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  192199. #endif
  192200. #if defined(PNG_READ_FILLER_SUPPORTED)
  192201. (png_ptr->transformations & (PNG_FILLER)) ||
  192202. #endif
  192203. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192204. {
  192205. if (max_pixel_depth <= 16)
  192206. max_pixel_depth = 32;
  192207. else
  192208. max_pixel_depth = 64;
  192209. }
  192210. else
  192211. {
  192212. if (max_pixel_depth <= 8)
  192213. {
  192214. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192215. max_pixel_depth = 32;
  192216. else
  192217. max_pixel_depth = 24;
  192218. }
  192219. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192220. max_pixel_depth = 64;
  192221. else
  192222. max_pixel_depth = 48;
  192223. }
  192224. }
  192225. #endif
  192226. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  192227. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192228. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  192229. {
  192230. int user_pixel_depth=png_ptr->user_transform_depth*
  192231. png_ptr->user_transform_channels;
  192232. if(user_pixel_depth > max_pixel_depth)
  192233. max_pixel_depth=user_pixel_depth;
  192234. }
  192235. #endif
  192236. /* align the width on the next larger 8 pixels. Mainly used
  192237. for interlacing */
  192238. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  192239. /* calculate the maximum bytes needed, adding a byte and a pixel
  192240. for safety's sake */
  192241. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  192242. 1 + ((max_pixel_depth + 7) >> 3);
  192243. #ifdef PNG_MAX_MALLOC_64K
  192244. if (row_bytes > (png_uint_32)65536L)
  192245. png_error(png_ptr, "This image requires a row greater than 64KB");
  192246. #endif
  192247. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  192248. png_ptr->row_buf = png_ptr->big_row_buf+32;
  192249. #ifdef PNG_MAX_MALLOC_64K
  192250. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  192251. png_error(png_ptr, "This image requires a row greater than 64KB");
  192252. #endif
  192253. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  192254. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  192255. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  192256. png_ptr->rowbytes + 1));
  192257. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  192258. png_debug1(3, "width = %lu,\n", png_ptr->width);
  192259. png_debug1(3, "height = %lu,\n", png_ptr->height);
  192260. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  192261. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  192262. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  192263. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  192264. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  192265. }
  192266. #endif /* PNG_READ_SUPPORTED */
  192267. /********* End of inlined file: pngrutil.c *********/
  192268. /********* Start of inlined file: pngset.c *********/
  192269. /* pngset.c - storage of image information into info struct
  192270. *
  192271. * Last changed in libpng 1.2.21 [October 4, 2007]
  192272. * For conditions of distribution and use, see copyright notice in png.h
  192273. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  192274. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192275. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192276. *
  192277. * The functions here are used during reads to store data from the file
  192278. * into the info struct, and during writes to store application data
  192279. * into the info struct for writing into the file. This abstracts the
  192280. * info struct and allows us to change the structure in the future.
  192281. */
  192282. #define PNG_INTERNAL
  192283. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  192284. #if defined(PNG_bKGD_SUPPORTED)
  192285. void PNGAPI
  192286. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  192287. {
  192288. png_debug1(1, "in %s storage function\n", "bKGD");
  192289. if (png_ptr == NULL || info_ptr == NULL)
  192290. return;
  192291. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  192292. info_ptr->valid |= PNG_INFO_bKGD;
  192293. }
  192294. #endif
  192295. #if defined(PNG_cHRM_SUPPORTED)
  192296. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192297. void PNGAPI
  192298. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  192299. double white_x, double white_y, double red_x, double red_y,
  192300. double green_x, double green_y, double blue_x, double blue_y)
  192301. {
  192302. png_debug1(1, "in %s storage function\n", "cHRM");
  192303. if (png_ptr == NULL || info_ptr == NULL)
  192304. return;
  192305. if (white_x < 0.0 || white_y < 0.0 ||
  192306. red_x < 0.0 || red_y < 0.0 ||
  192307. green_x < 0.0 || green_y < 0.0 ||
  192308. blue_x < 0.0 || blue_y < 0.0)
  192309. {
  192310. png_warning(png_ptr,
  192311. "Ignoring attempt to set negative chromaticity value");
  192312. return;
  192313. }
  192314. if (white_x > 21474.83 || white_y > 21474.83 ||
  192315. red_x > 21474.83 || red_y > 21474.83 ||
  192316. green_x > 21474.83 || green_y > 21474.83 ||
  192317. blue_x > 21474.83 || blue_y > 21474.83)
  192318. {
  192319. png_warning(png_ptr,
  192320. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192321. return;
  192322. }
  192323. info_ptr->x_white = (float)white_x;
  192324. info_ptr->y_white = (float)white_y;
  192325. info_ptr->x_red = (float)red_x;
  192326. info_ptr->y_red = (float)red_y;
  192327. info_ptr->x_green = (float)green_x;
  192328. info_ptr->y_green = (float)green_y;
  192329. info_ptr->x_blue = (float)blue_x;
  192330. info_ptr->y_blue = (float)blue_y;
  192331. #ifdef PNG_FIXED_POINT_SUPPORTED
  192332. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  192333. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  192334. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  192335. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  192336. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  192337. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  192338. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  192339. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  192340. #endif
  192341. info_ptr->valid |= PNG_INFO_cHRM;
  192342. }
  192343. #endif
  192344. #ifdef PNG_FIXED_POINT_SUPPORTED
  192345. void PNGAPI
  192346. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  192347. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  192348. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  192349. png_fixed_point blue_x, png_fixed_point blue_y)
  192350. {
  192351. png_debug1(1, "in %s storage function\n", "cHRM");
  192352. if (png_ptr == NULL || info_ptr == NULL)
  192353. return;
  192354. if (white_x < 0 || white_y < 0 ||
  192355. red_x < 0 || red_y < 0 ||
  192356. green_x < 0 || green_y < 0 ||
  192357. blue_x < 0 || blue_y < 0)
  192358. {
  192359. png_warning(png_ptr,
  192360. "Ignoring attempt to set negative chromaticity value");
  192361. return;
  192362. }
  192363. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192364. if (white_x > (double) PNG_UINT_31_MAX ||
  192365. white_y > (double) PNG_UINT_31_MAX ||
  192366. red_x > (double) PNG_UINT_31_MAX ||
  192367. red_y > (double) PNG_UINT_31_MAX ||
  192368. green_x > (double) PNG_UINT_31_MAX ||
  192369. green_y > (double) PNG_UINT_31_MAX ||
  192370. blue_x > (double) PNG_UINT_31_MAX ||
  192371. blue_y > (double) PNG_UINT_31_MAX)
  192372. #else
  192373. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192374. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192375. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192376. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192377. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192378. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192379. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  192380. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  192381. #endif
  192382. {
  192383. png_warning(png_ptr,
  192384. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  192385. return;
  192386. }
  192387. info_ptr->int_x_white = white_x;
  192388. info_ptr->int_y_white = white_y;
  192389. info_ptr->int_x_red = red_x;
  192390. info_ptr->int_y_red = red_y;
  192391. info_ptr->int_x_green = green_x;
  192392. info_ptr->int_y_green = green_y;
  192393. info_ptr->int_x_blue = blue_x;
  192394. info_ptr->int_y_blue = blue_y;
  192395. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192396. info_ptr->x_white = (float)(white_x/100000.);
  192397. info_ptr->y_white = (float)(white_y/100000.);
  192398. info_ptr->x_red = (float)( red_x/100000.);
  192399. info_ptr->y_red = (float)( red_y/100000.);
  192400. info_ptr->x_green = (float)(green_x/100000.);
  192401. info_ptr->y_green = (float)(green_y/100000.);
  192402. info_ptr->x_blue = (float)( blue_x/100000.);
  192403. info_ptr->y_blue = (float)( blue_y/100000.);
  192404. #endif
  192405. info_ptr->valid |= PNG_INFO_cHRM;
  192406. }
  192407. #endif
  192408. #endif
  192409. #if defined(PNG_gAMA_SUPPORTED)
  192410. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192411. void PNGAPI
  192412. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  192413. {
  192414. double gamma;
  192415. png_debug1(1, "in %s storage function\n", "gAMA");
  192416. if (png_ptr == NULL || info_ptr == NULL)
  192417. return;
  192418. /* Check for overflow */
  192419. if (file_gamma > 21474.83)
  192420. {
  192421. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192422. gamma=21474.83;
  192423. }
  192424. else
  192425. gamma=file_gamma;
  192426. info_ptr->gamma = (float)gamma;
  192427. #ifdef PNG_FIXED_POINT_SUPPORTED
  192428. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  192429. #endif
  192430. info_ptr->valid |= PNG_INFO_gAMA;
  192431. if(gamma == 0.0)
  192432. png_warning(png_ptr, "Setting gamma=0");
  192433. }
  192434. #endif
  192435. void PNGAPI
  192436. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  192437. int_gamma)
  192438. {
  192439. png_fixed_point gamma;
  192440. png_debug1(1, "in %s storage function\n", "gAMA");
  192441. if (png_ptr == NULL || info_ptr == NULL)
  192442. return;
  192443. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  192444. {
  192445. png_warning(png_ptr, "Limiting gamma to 21474.83");
  192446. gamma=PNG_UINT_31_MAX;
  192447. }
  192448. else
  192449. {
  192450. if (int_gamma < 0)
  192451. {
  192452. png_warning(png_ptr, "Setting negative gamma to zero");
  192453. gamma=0;
  192454. }
  192455. else
  192456. gamma=int_gamma;
  192457. }
  192458. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192459. info_ptr->gamma = (float)(gamma/100000.);
  192460. #endif
  192461. #ifdef PNG_FIXED_POINT_SUPPORTED
  192462. info_ptr->int_gamma = gamma;
  192463. #endif
  192464. info_ptr->valid |= PNG_INFO_gAMA;
  192465. if(gamma == 0)
  192466. png_warning(png_ptr, "Setting gamma=0");
  192467. }
  192468. #endif
  192469. #if defined(PNG_hIST_SUPPORTED)
  192470. void PNGAPI
  192471. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  192472. {
  192473. int i;
  192474. png_debug1(1, "in %s storage function\n", "hIST");
  192475. if (png_ptr == NULL || info_ptr == NULL)
  192476. return;
  192477. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  192478. > PNG_MAX_PALETTE_LENGTH)
  192479. {
  192480. png_warning(png_ptr,
  192481. "Invalid palette size, hIST allocation skipped.");
  192482. return;
  192483. }
  192484. #ifdef PNG_FREE_ME_SUPPORTED
  192485. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  192486. #endif
  192487. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  192488. 1.2.1 */
  192489. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  192490. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  192491. if (png_ptr->hist == NULL)
  192492. {
  192493. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  192494. return;
  192495. }
  192496. for (i = 0; i < info_ptr->num_palette; i++)
  192497. png_ptr->hist[i] = hist[i];
  192498. info_ptr->hist = png_ptr->hist;
  192499. info_ptr->valid |= PNG_INFO_hIST;
  192500. #ifdef PNG_FREE_ME_SUPPORTED
  192501. info_ptr->free_me |= PNG_FREE_HIST;
  192502. #else
  192503. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  192504. #endif
  192505. }
  192506. #endif
  192507. void PNGAPI
  192508. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  192509. png_uint_32 width, png_uint_32 height, int bit_depth,
  192510. int color_type, int interlace_type, int compression_type,
  192511. int filter_type)
  192512. {
  192513. png_debug1(1, "in %s storage function\n", "IHDR");
  192514. if (png_ptr == NULL || info_ptr == NULL)
  192515. return;
  192516. /* check for width and height valid values */
  192517. if (width == 0 || height == 0)
  192518. png_error(png_ptr, "Image width or height is zero in IHDR");
  192519. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192520. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  192521. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192522. #else
  192523. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  192524. png_error(png_ptr, "image size exceeds user limits in IHDR");
  192525. #endif
  192526. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  192527. png_error(png_ptr, "Invalid image size in IHDR");
  192528. if ( width > (PNG_UINT_32_MAX
  192529. >> 3) /* 8-byte RGBA pixels */
  192530. - 64 /* bigrowbuf hack */
  192531. - 1 /* filter byte */
  192532. - 7*8 /* rounding of width to multiple of 8 pixels */
  192533. - 8) /* extra max_pixel_depth pad */
  192534. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  192535. /* check other values */
  192536. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  192537. bit_depth != 8 && bit_depth != 16)
  192538. png_error(png_ptr, "Invalid bit depth in IHDR");
  192539. if (color_type < 0 || color_type == 1 ||
  192540. color_type == 5 || color_type > 6)
  192541. png_error(png_ptr, "Invalid color type in IHDR");
  192542. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  192543. ((color_type == PNG_COLOR_TYPE_RGB ||
  192544. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  192545. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  192546. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  192547. if (interlace_type >= PNG_INTERLACE_LAST)
  192548. png_error(png_ptr, "Unknown interlace method in IHDR");
  192549. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  192550. png_error(png_ptr, "Unknown compression method in IHDR");
  192551. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192552. /* Accept filter_method 64 (intrapixel differencing) only if
  192553. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192554. * 2. Libpng did not read a PNG signature (this filter_method is only
  192555. * used in PNG datastreams that are embedded in MNG datastreams) and
  192556. * 3. The application called png_permit_mng_features with a mask that
  192557. * included PNG_FLAG_MNG_FILTER_64 and
  192558. * 4. The filter_method is 64 and
  192559. * 5. The color_type is RGB or RGBA
  192560. */
  192561. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  192562. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192563. if(filter_type != PNG_FILTER_TYPE_BASE)
  192564. {
  192565. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192566. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  192567. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  192568. (color_type == PNG_COLOR_TYPE_RGB ||
  192569. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  192570. png_error(png_ptr, "Unknown filter method in IHDR");
  192571. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  192572. png_warning(png_ptr, "Invalid filter method in IHDR");
  192573. }
  192574. #else
  192575. if(filter_type != PNG_FILTER_TYPE_BASE)
  192576. png_error(png_ptr, "Unknown filter method in IHDR");
  192577. #endif
  192578. info_ptr->width = width;
  192579. info_ptr->height = height;
  192580. info_ptr->bit_depth = (png_byte)bit_depth;
  192581. info_ptr->color_type =(png_byte) color_type;
  192582. info_ptr->compression_type = (png_byte)compression_type;
  192583. info_ptr->filter_type = (png_byte)filter_type;
  192584. info_ptr->interlace_type = (png_byte)interlace_type;
  192585. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192586. info_ptr->channels = 1;
  192587. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192588. info_ptr->channels = 3;
  192589. else
  192590. info_ptr->channels = 1;
  192591. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192592. info_ptr->channels++;
  192593. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  192594. /* check for potential overflow */
  192595. if (width > (PNG_UINT_32_MAX
  192596. >> 3) /* 8-byte RGBA pixels */
  192597. - 64 /* bigrowbuf hack */
  192598. - 1 /* filter byte */
  192599. - 7*8 /* rounding of width to multiple of 8 pixels */
  192600. - 8) /* extra max_pixel_depth pad */
  192601. info_ptr->rowbytes = (png_size_t)0;
  192602. else
  192603. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  192604. }
  192605. #if defined(PNG_oFFs_SUPPORTED)
  192606. void PNGAPI
  192607. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  192608. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  192609. {
  192610. png_debug1(1, "in %s storage function\n", "oFFs");
  192611. if (png_ptr == NULL || info_ptr == NULL)
  192612. return;
  192613. info_ptr->x_offset = offset_x;
  192614. info_ptr->y_offset = offset_y;
  192615. info_ptr->offset_unit_type = (png_byte)unit_type;
  192616. info_ptr->valid |= PNG_INFO_oFFs;
  192617. }
  192618. #endif
  192619. #if defined(PNG_pCAL_SUPPORTED)
  192620. void PNGAPI
  192621. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  192622. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  192623. png_charp units, png_charpp params)
  192624. {
  192625. png_uint_32 length;
  192626. int i;
  192627. png_debug1(1, "in %s storage function\n", "pCAL");
  192628. if (png_ptr == NULL || info_ptr == NULL)
  192629. return;
  192630. length = png_strlen(purpose) + 1;
  192631. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  192632. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  192633. if (info_ptr->pcal_purpose == NULL)
  192634. {
  192635. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  192636. return;
  192637. }
  192638. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  192639. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  192640. info_ptr->pcal_X0 = X0;
  192641. info_ptr->pcal_X1 = X1;
  192642. info_ptr->pcal_type = (png_byte)type;
  192643. info_ptr->pcal_nparams = (png_byte)nparams;
  192644. length = png_strlen(units) + 1;
  192645. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  192646. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  192647. if (info_ptr->pcal_units == NULL)
  192648. {
  192649. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  192650. return;
  192651. }
  192652. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  192653. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  192654. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  192655. if (info_ptr->pcal_params == NULL)
  192656. {
  192657. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  192658. return;
  192659. }
  192660. info_ptr->pcal_params[nparams] = NULL;
  192661. for (i = 0; i < nparams; i++)
  192662. {
  192663. length = png_strlen(params[i]) + 1;
  192664. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  192665. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  192666. if (info_ptr->pcal_params[i] == NULL)
  192667. {
  192668. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  192669. return;
  192670. }
  192671. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  192672. }
  192673. info_ptr->valid |= PNG_INFO_pCAL;
  192674. #ifdef PNG_FREE_ME_SUPPORTED
  192675. info_ptr->free_me |= PNG_FREE_PCAL;
  192676. #endif
  192677. }
  192678. #endif
  192679. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  192680. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192681. void PNGAPI
  192682. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  192683. int unit, double width, double height)
  192684. {
  192685. png_debug1(1, "in %s storage function\n", "sCAL");
  192686. if (png_ptr == NULL || info_ptr == NULL)
  192687. return;
  192688. info_ptr->scal_unit = (png_byte)unit;
  192689. info_ptr->scal_pixel_width = width;
  192690. info_ptr->scal_pixel_height = height;
  192691. info_ptr->valid |= PNG_INFO_sCAL;
  192692. }
  192693. #else
  192694. #ifdef PNG_FIXED_POINT_SUPPORTED
  192695. void PNGAPI
  192696. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  192697. int unit, png_charp swidth, png_charp sheight)
  192698. {
  192699. png_uint_32 length;
  192700. png_debug1(1, "in %s storage function\n", "sCAL");
  192701. if (png_ptr == NULL || info_ptr == NULL)
  192702. return;
  192703. info_ptr->scal_unit = (png_byte)unit;
  192704. length = png_strlen(swidth) + 1;
  192705. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192706. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  192707. if (info_ptr->scal_s_width == NULL)
  192708. {
  192709. png_warning(png_ptr,
  192710. "Memory allocation failed while processing sCAL.");
  192711. }
  192712. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  192713. length = png_strlen(sheight) + 1;
  192714. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  192715. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  192716. if (info_ptr->scal_s_height == NULL)
  192717. {
  192718. png_free (png_ptr, info_ptr->scal_s_width);
  192719. png_warning(png_ptr,
  192720. "Memory allocation failed while processing sCAL.");
  192721. }
  192722. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  192723. info_ptr->valid |= PNG_INFO_sCAL;
  192724. #ifdef PNG_FREE_ME_SUPPORTED
  192725. info_ptr->free_me |= PNG_FREE_SCAL;
  192726. #endif
  192727. }
  192728. #endif
  192729. #endif
  192730. #endif
  192731. #if defined(PNG_pHYs_SUPPORTED)
  192732. void PNGAPI
  192733. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  192734. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  192735. {
  192736. png_debug1(1, "in %s storage function\n", "pHYs");
  192737. if (png_ptr == NULL || info_ptr == NULL)
  192738. return;
  192739. info_ptr->x_pixels_per_unit = res_x;
  192740. info_ptr->y_pixels_per_unit = res_y;
  192741. info_ptr->phys_unit_type = (png_byte)unit_type;
  192742. info_ptr->valid |= PNG_INFO_pHYs;
  192743. }
  192744. #endif
  192745. void PNGAPI
  192746. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  192747. png_colorp palette, int num_palette)
  192748. {
  192749. png_debug1(1, "in %s storage function\n", "PLTE");
  192750. if (png_ptr == NULL || info_ptr == NULL)
  192751. return;
  192752. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  192753. {
  192754. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192755. png_error(png_ptr, "Invalid palette length");
  192756. else
  192757. {
  192758. png_warning(png_ptr, "Invalid palette length");
  192759. return;
  192760. }
  192761. }
  192762. /*
  192763. * It may not actually be necessary to set png_ptr->palette here;
  192764. * we do it for backward compatibility with the way the png_handle_tRNS
  192765. * function used to do the allocation.
  192766. */
  192767. #ifdef PNG_FREE_ME_SUPPORTED
  192768. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  192769. #endif
  192770. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  192771. of num_palette entries,
  192772. in case of an invalid PNG file that has too-large sample values. */
  192773. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  192774. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  192775. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  192776. png_sizeof(png_color));
  192777. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  192778. info_ptr->palette = png_ptr->palette;
  192779. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  192780. #ifdef PNG_FREE_ME_SUPPORTED
  192781. info_ptr->free_me |= PNG_FREE_PLTE;
  192782. #else
  192783. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  192784. #endif
  192785. info_ptr->valid |= PNG_INFO_PLTE;
  192786. }
  192787. #if defined(PNG_sBIT_SUPPORTED)
  192788. void PNGAPI
  192789. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  192790. png_color_8p sig_bit)
  192791. {
  192792. png_debug1(1, "in %s storage function\n", "sBIT");
  192793. if (png_ptr == NULL || info_ptr == NULL)
  192794. return;
  192795. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  192796. info_ptr->valid |= PNG_INFO_sBIT;
  192797. }
  192798. #endif
  192799. #if defined(PNG_sRGB_SUPPORTED)
  192800. void PNGAPI
  192801. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  192802. {
  192803. png_debug1(1, "in %s storage function\n", "sRGB");
  192804. if (png_ptr == NULL || info_ptr == NULL)
  192805. return;
  192806. info_ptr->srgb_intent = (png_byte)intent;
  192807. info_ptr->valid |= PNG_INFO_sRGB;
  192808. }
  192809. void PNGAPI
  192810. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  192811. int intent)
  192812. {
  192813. #if defined(PNG_gAMA_SUPPORTED)
  192814. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192815. float file_gamma;
  192816. #endif
  192817. #ifdef PNG_FIXED_POINT_SUPPORTED
  192818. png_fixed_point int_file_gamma;
  192819. #endif
  192820. #endif
  192821. #if defined(PNG_cHRM_SUPPORTED)
  192822. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192823. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  192824. #endif
  192825. #ifdef PNG_FIXED_POINT_SUPPORTED
  192826. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  192827. int_green_y, int_blue_x, int_blue_y;
  192828. #endif
  192829. #endif
  192830. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  192831. if (png_ptr == NULL || info_ptr == NULL)
  192832. return;
  192833. png_set_sRGB(png_ptr, info_ptr, intent);
  192834. #if defined(PNG_gAMA_SUPPORTED)
  192835. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192836. file_gamma = (float).45455;
  192837. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  192838. #endif
  192839. #ifdef PNG_FIXED_POINT_SUPPORTED
  192840. int_file_gamma = 45455L;
  192841. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  192842. #endif
  192843. #endif
  192844. #if defined(PNG_cHRM_SUPPORTED)
  192845. #ifdef PNG_FIXED_POINT_SUPPORTED
  192846. int_white_x = 31270L;
  192847. int_white_y = 32900L;
  192848. int_red_x = 64000L;
  192849. int_red_y = 33000L;
  192850. int_green_x = 30000L;
  192851. int_green_y = 60000L;
  192852. int_blue_x = 15000L;
  192853. int_blue_y = 6000L;
  192854. png_set_cHRM_fixed(png_ptr, info_ptr,
  192855. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  192856. int_blue_x, int_blue_y);
  192857. #endif
  192858. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192859. white_x = (float).3127;
  192860. white_y = (float).3290;
  192861. red_x = (float).64;
  192862. red_y = (float).33;
  192863. green_x = (float).30;
  192864. green_y = (float).60;
  192865. blue_x = (float).15;
  192866. blue_y = (float).06;
  192867. png_set_cHRM(png_ptr, info_ptr,
  192868. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  192869. #endif
  192870. #endif
  192871. }
  192872. #endif
  192873. #if defined(PNG_iCCP_SUPPORTED)
  192874. void PNGAPI
  192875. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  192876. png_charp name, int compression_type,
  192877. png_charp profile, png_uint_32 proflen)
  192878. {
  192879. png_charp new_iccp_name;
  192880. png_charp new_iccp_profile;
  192881. png_debug1(1, "in %s storage function\n", "iCCP");
  192882. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  192883. return;
  192884. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  192885. if (new_iccp_name == NULL)
  192886. {
  192887. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  192888. return;
  192889. }
  192890. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  192891. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  192892. if (new_iccp_profile == NULL)
  192893. {
  192894. png_free (png_ptr, new_iccp_name);
  192895. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  192896. return;
  192897. }
  192898. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  192899. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  192900. info_ptr->iccp_proflen = proflen;
  192901. info_ptr->iccp_name = new_iccp_name;
  192902. info_ptr->iccp_profile = new_iccp_profile;
  192903. /* Compression is always zero but is here so the API and info structure
  192904. * does not have to change if we introduce multiple compression types */
  192905. info_ptr->iccp_compression = (png_byte)compression_type;
  192906. #ifdef PNG_FREE_ME_SUPPORTED
  192907. info_ptr->free_me |= PNG_FREE_ICCP;
  192908. #endif
  192909. info_ptr->valid |= PNG_INFO_iCCP;
  192910. }
  192911. #endif
  192912. #if defined(PNG_TEXT_SUPPORTED)
  192913. void PNGAPI
  192914. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192915. int num_text)
  192916. {
  192917. int ret;
  192918. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  192919. if (ret)
  192920. png_error(png_ptr, "Insufficient memory to store text");
  192921. }
  192922. int /* PRIVATE */
  192923. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  192924. int num_text)
  192925. {
  192926. int i;
  192927. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  192928. "text" : (png_const_charp)png_ptr->chunk_name));
  192929. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  192930. return(0);
  192931. /* Make sure we have enough space in the "text" array in info_struct
  192932. * to hold all of the incoming text_ptr objects.
  192933. */
  192934. if (info_ptr->num_text + num_text > info_ptr->max_text)
  192935. {
  192936. if (info_ptr->text != NULL)
  192937. {
  192938. png_textp old_text;
  192939. int old_max;
  192940. old_max = info_ptr->max_text;
  192941. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  192942. old_text = info_ptr->text;
  192943. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192944. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192945. if (info_ptr->text == NULL)
  192946. {
  192947. png_free(png_ptr, old_text);
  192948. return(1);
  192949. }
  192950. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  192951. png_sizeof(png_text)));
  192952. png_free(png_ptr, old_text);
  192953. }
  192954. else
  192955. {
  192956. info_ptr->max_text = num_text + 8;
  192957. info_ptr->num_text = 0;
  192958. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  192959. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  192960. if (info_ptr->text == NULL)
  192961. return(1);
  192962. #ifdef PNG_FREE_ME_SUPPORTED
  192963. info_ptr->free_me |= PNG_FREE_TEXT;
  192964. #endif
  192965. }
  192966. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  192967. info_ptr->max_text);
  192968. }
  192969. for (i = 0; i < num_text; i++)
  192970. {
  192971. png_size_t text_length,key_len;
  192972. png_size_t lang_len,lang_key_len;
  192973. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  192974. if (text_ptr[i].key == NULL)
  192975. continue;
  192976. key_len = png_strlen(text_ptr[i].key);
  192977. if(text_ptr[i].compression <= 0)
  192978. {
  192979. lang_len = 0;
  192980. lang_key_len = 0;
  192981. }
  192982. else
  192983. #ifdef PNG_iTXt_SUPPORTED
  192984. {
  192985. /* set iTXt data */
  192986. if (text_ptr[i].lang != NULL)
  192987. lang_len = png_strlen(text_ptr[i].lang);
  192988. else
  192989. lang_len = 0;
  192990. if (text_ptr[i].lang_key != NULL)
  192991. lang_key_len = png_strlen(text_ptr[i].lang_key);
  192992. else
  192993. lang_key_len = 0;
  192994. }
  192995. #else
  192996. {
  192997. png_warning(png_ptr, "iTXt chunk not supported.");
  192998. continue;
  192999. }
  193000. #endif
  193001. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  193002. {
  193003. text_length = 0;
  193004. #ifdef PNG_iTXt_SUPPORTED
  193005. if(text_ptr[i].compression > 0)
  193006. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  193007. else
  193008. #endif
  193009. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  193010. }
  193011. else
  193012. {
  193013. text_length = png_strlen(text_ptr[i].text);
  193014. textp->compression = text_ptr[i].compression;
  193015. }
  193016. textp->key = (png_charp)png_malloc_warn(png_ptr,
  193017. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  193018. if (textp->key == NULL)
  193019. return(1);
  193020. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  193021. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  193022. (int)textp->key);
  193023. png_memcpy(textp->key, text_ptr[i].key,
  193024. (png_size_t)(key_len));
  193025. *(textp->key+key_len) = '\0';
  193026. #ifdef PNG_iTXt_SUPPORTED
  193027. if (text_ptr[i].compression > 0)
  193028. {
  193029. textp->lang=textp->key + key_len + 1;
  193030. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  193031. *(textp->lang+lang_len) = '\0';
  193032. textp->lang_key=textp->lang + lang_len + 1;
  193033. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  193034. *(textp->lang_key+lang_key_len) = '\0';
  193035. textp->text=textp->lang_key + lang_key_len + 1;
  193036. }
  193037. else
  193038. #endif
  193039. {
  193040. #ifdef PNG_iTXt_SUPPORTED
  193041. textp->lang=NULL;
  193042. textp->lang_key=NULL;
  193043. #endif
  193044. textp->text=textp->key + key_len + 1;
  193045. }
  193046. if(text_length)
  193047. png_memcpy(textp->text, text_ptr[i].text,
  193048. (png_size_t)(text_length));
  193049. *(textp->text+text_length) = '\0';
  193050. #ifdef PNG_iTXt_SUPPORTED
  193051. if(textp->compression > 0)
  193052. {
  193053. textp->text_length = 0;
  193054. textp->itxt_length = text_length;
  193055. }
  193056. else
  193057. #endif
  193058. {
  193059. textp->text_length = text_length;
  193060. #ifdef PNG_iTXt_SUPPORTED
  193061. textp->itxt_length = 0;
  193062. #endif
  193063. }
  193064. info_ptr->num_text++;
  193065. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  193066. }
  193067. return(0);
  193068. }
  193069. #endif
  193070. #if defined(PNG_tIME_SUPPORTED)
  193071. void PNGAPI
  193072. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  193073. {
  193074. png_debug1(1, "in %s storage function\n", "tIME");
  193075. if (png_ptr == NULL || info_ptr == NULL ||
  193076. (png_ptr->mode & PNG_WROTE_tIME))
  193077. return;
  193078. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  193079. info_ptr->valid |= PNG_INFO_tIME;
  193080. }
  193081. #endif
  193082. #if defined(PNG_tRNS_SUPPORTED)
  193083. void PNGAPI
  193084. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  193085. png_bytep trans, int num_trans, png_color_16p trans_values)
  193086. {
  193087. png_debug1(1, "in %s storage function\n", "tRNS");
  193088. if (png_ptr == NULL || info_ptr == NULL)
  193089. return;
  193090. if (trans != NULL)
  193091. {
  193092. /*
  193093. * It may not actually be necessary to set png_ptr->trans here;
  193094. * we do it for backward compatibility with the way the png_handle_tRNS
  193095. * function used to do the allocation.
  193096. */
  193097. #ifdef PNG_FREE_ME_SUPPORTED
  193098. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  193099. #endif
  193100. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  193101. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  193102. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  193103. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  193104. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  193105. #ifdef PNG_FREE_ME_SUPPORTED
  193106. info_ptr->free_me |= PNG_FREE_TRNS;
  193107. #else
  193108. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  193109. #endif
  193110. }
  193111. if (trans_values != NULL)
  193112. {
  193113. png_memcpy(&(info_ptr->trans_values), trans_values,
  193114. png_sizeof(png_color_16));
  193115. if (num_trans == 0)
  193116. num_trans = 1;
  193117. }
  193118. info_ptr->num_trans = (png_uint_16)num_trans;
  193119. info_ptr->valid |= PNG_INFO_tRNS;
  193120. }
  193121. #endif
  193122. #if defined(PNG_sPLT_SUPPORTED)
  193123. void PNGAPI
  193124. png_set_sPLT(png_structp png_ptr,
  193125. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  193126. {
  193127. png_sPLT_tp np;
  193128. int i;
  193129. if (png_ptr == NULL || info_ptr == NULL)
  193130. return;
  193131. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  193132. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  193133. if (np == NULL)
  193134. {
  193135. png_warning(png_ptr, "No memory for sPLT palettes.");
  193136. return;
  193137. }
  193138. png_memcpy(np, info_ptr->splt_palettes,
  193139. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  193140. png_free(png_ptr, info_ptr->splt_palettes);
  193141. info_ptr->splt_palettes=NULL;
  193142. for (i = 0; i < nentries; i++)
  193143. {
  193144. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  193145. png_sPLT_tp from = entries + i;
  193146. to->name = (png_charp)png_malloc_warn(png_ptr,
  193147. png_strlen(from->name) + 1);
  193148. if (to->name == NULL)
  193149. {
  193150. png_warning(png_ptr,
  193151. "Out of memory while processing sPLT chunk");
  193152. }
  193153. /* TODO: use png_malloc_warn */
  193154. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  193155. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  193156. from->nentries * png_sizeof(png_sPLT_entry));
  193157. /* TODO: use png_malloc_warn */
  193158. png_memcpy(to->entries, from->entries,
  193159. from->nentries * png_sizeof(png_sPLT_entry));
  193160. if (to->entries == NULL)
  193161. {
  193162. png_warning(png_ptr,
  193163. "Out of memory while processing sPLT chunk");
  193164. png_free(png_ptr,to->name);
  193165. to->name = NULL;
  193166. }
  193167. to->nentries = from->nentries;
  193168. to->depth = from->depth;
  193169. }
  193170. info_ptr->splt_palettes = np;
  193171. info_ptr->splt_palettes_num += nentries;
  193172. info_ptr->valid |= PNG_INFO_sPLT;
  193173. #ifdef PNG_FREE_ME_SUPPORTED
  193174. info_ptr->free_me |= PNG_FREE_SPLT;
  193175. #endif
  193176. }
  193177. #endif /* PNG_sPLT_SUPPORTED */
  193178. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193179. void PNGAPI
  193180. png_set_unknown_chunks(png_structp png_ptr,
  193181. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  193182. {
  193183. png_unknown_chunkp np;
  193184. int i;
  193185. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  193186. return;
  193187. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  193188. (info_ptr->unknown_chunks_num + num_unknowns) *
  193189. png_sizeof(png_unknown_chunk));
  193190. if (np == NULL)
  193191. {
  193192. png_warning(png_ptr,
  193193. "Out of memory while processing unknown chunk.");
  193194. return;
  193195. }
  193196. png_memcpy(np, info_ptr->unknown_chunks,
  193197. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  193198. png_free(png_ptr, info_ptr->unknown_chunks);
  193199. info_ptr->unknown_chunks=NULL;
  193200. for (i = 0; i < num_unknowns; i++)
  193201. {
  193202. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  193203. png_unknown_chunkp from = unknowns + i;
  193204. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  193205. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  193206. if (to->data == NULL)
  193207. {
  193208. png_warning(png_ptr,
  193209. "Out of memory while processing unknown chunk.");
  193210. }
  193211. else
  193212. {
  193213. png_memcpy(to->data, from->data, from->size);
  193214. to->size = from->size;
  193215. /* note our location in the read or write sequence */
  193216. to->location = (png_byte)(png_ptr->mode & 0xff);
  193217. }
  193218. }
  193219. info_ptr->unknown_chunks = np;
  193220. info_ptr->unknown_chunks_num += num_unknowns;
  193221. #ifdef PNG_FREE_ME_SUPPORTED
  193222. info_ptr->free_me |= PNG_FREE_UNKN;
  193223. #endif
  193224. }
  193225. void PNGAPI
  193226. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  193227. int chunk, int location)
  193228. {
  193229. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  193230. (int)info_ptr->unknown_chunks_num)
  193231. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  193232. }
  193233. #endif
  193234. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  193235. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  193236. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  193237. void PNGAPI
  193238. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  193239. {
  193240. /* This function is deprecated in favor of png_permit_mng_features()
  193241. and will be removed from libpng-1.3.0 */
  193242. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  193243. if (png_ptr == NULL)
  193244. return;
  193245. png_ptr->mng_features_permitted = (png_byte)
  193246. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  193247. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  193248. }
  193249. #endif
  193250. #endif
  193251. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193252. png_uint_32 PNGAPI
  193253. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  193254. {
  193255. png_debug(1, "in png_permit_mng_features\n");
  193256. if (png_ptr == NULL)
  193257. return (png_uint_32)0;
  193258. png_ptr->mng_features_permitted =
  193259. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  193260. return (png_uint_32)png_ptr->mng_features_permitted;
  193261. }
  193262. #endif
  193263. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  193264. void PNGAPI
  193265. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  193266. chunk_list, int num_chunks)
  193267. {
  193268. png_bytep new_list, p;
  193269. int i, old_num_chunks;
  193270. if (png_ptr == NULL)
  193271. return;
  193272. if (num_chunks == 0)
  193273. {
  193274. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  193275. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193276. else
  193277. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  193278. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  193279. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193280. else
  193281. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  193282. return;
  193283. }
  193284. if (chunk_list == NULL)
  193285. return;
  193286. old_num_chunks=png_ptr->num_chunk_list;
  193287. new_list=(png_bytep)png_malloc(png_ptr,
  193288. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  193289. if(png_ptr->chunk_list != NULL)
  193290. {
  193291. png_memcpy(new_list, png_ptr->chunk_list,
  193292. (png_size_t)(5*old_num_chunks));
  193293. png_free(png_ptr, png_ptr->chunk_list);
  193294. png_ptr->chunk_list=NULL;
  193295. }
  193296. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  193297. (png_size_t)(5*num_chunks));
  193298. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  193299. *p=(png_byte)keep;
  193300. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  193301. png_ptr->chunk_list=new_list;
  193302. #ifdef PNG_FREE_ME_SUPPORTED
  193303. png_ptr->free_me |= PNG_FREE_LIST;
  193304. #endif
  193305. }
  193306. #endif
  193307. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  193308. void PNGAPI
  193309. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  193310. png_user_chunk_ptr read_user_chunk_fn)
  193311. {
  193312. png_debug(1, "in png_set_read_user_chunk_fn\n");
  193313. if (png_ptr == NULL)
  193314. return;
  193315. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  193316. png_ptr->user_chunk_ptr = user_chunk_ptr;
  193317. }
  193318. #endif
  193319. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193320. void PNGAPI
  193321. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  193322. {
  193323. png_debug1(1, "in %s storage function\n", "rows");
  193324. if (png_ptr == NULL || info_ptr == NULL)
  193325. return;
  193326. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  193327. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  193328. info_ptr->row_pointers = row_pointers;
  193329. if(row_pointers)
  193330. info_ptr->valid |= PNG_INFO_IDAT;
  193331. }
  193332. #endif
  193333. #ifdef PNG_WRITE_SUPPORTED
  193334. void PNGAPI
  193335. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  193336. {
  193337. if (png_ptr == NULL)
  193338. return;
  193339. if(png_ptr->zbuf)
  193340. png_free(png_ptr, png_ptr->zbuf);
  193341. png_ptr->zbuf_size = (png_size_t)size;
  193342. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  193343. png_ptr->zstream.next_out = png_ptr->zbuf;
  193344. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  193345. }
  193346. #endif
  193347. void PNGAPI
  193348. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  193349. {
  193350. if (png_ptr && info_ptr)
  193351. info_ptr->valid &= ~(mask);
  193352. }
  193353. #ifndef PNG_1_0_X
  193354. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  193355. /* function was added to libpng 1.2.0 and should always exist by default */
  193356. void PNGAPI
  193357. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  193358. {
  193359. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193360. if (png_ptr != NULL)
  193361. png_ptr->asm_flags = 0;
  193362. }
  193363. /* this function was added to libpng 1.2.0 */
  193364. void PNGAPI
  193365. png_set_mmx_thresholds (png_structp png_ptr,
  193366. png_byte mmx_bitdepth_threshold,
  193367. png_uint_32 mmx_rowbytes_threshold)
  193368. {
  193369. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  193370. if (png_ptr == NULL)
  193371. return;
  193372. }
  193373. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  193374. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  193375. /* this function was added to libpng 1.2.6 */
  193376. void PNGAPI
  193377. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  193378. png_uint_32 user_height_max)
  193379. {
  193380. /* Images with dimensions larger than these limits will be
  193381. * rejected by png_set_IHDR(). To accept any PNG datastream
  193382. * regardless of dimensions, set both limits to 0x7ffffffL.
  193383. */
  193384. if(png_ptr == NULL) return;
  193385. png_ptr->user_width_max = user_width_max;
  193386. png_ptr->user_height_max = user_height_max;
  193387. }
  193388. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  193389. #endif /* ?PNG_1_0_X */
  193390. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  193391. /********* End of inlined file: pngset.c *********/
  193392. /********* Start of inlined file: pngtrans.c *********/
  193393. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  193394. *
  193395. * Last changed in libpng 1.2.17 May 15, 2007
  193396. * For conditions of distribution and use, see copyright notice in png.h
  193397. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193398. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193399. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193400. */
  193401. #define PNG_INTERNAL
  193402. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  193403. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193404. /* turn on BGR-to-RGB mapping */
  193405. void PNGAPI
  193406. png_set_bgr(png_structp png_ptr)
  193407. {
  193408. png_debug(1, "in png_set_bgr\n");
  193409. if(png_ptr == NULL) return;
  193410. png_ptr->transformations |= PNG_BGR;
  193411. }
  193412. #endif
  193413. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193414. /* turn on 16 bit byte swapping */
  193415. void PNGAPI
  193416. png_set_swap(png_structp png_ptr)
  193417. {
  193418. png_debug(1, "in png_set_swap\n");
  193419. if(png_ptr == NULL) return;
  193420. if (png_ptr->bit_depth == 16)
  193421. png_ptr->transformations |= PNG_SWAP_BYTES;
  193422. }
  193423. #endif
  193424. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  193425. /* turn on pixel packing */
  193426. void PNGAPI
  193427. png_set_packing(png_structp png_ptr)
  193428. {
  193429. png_debug(1, "in png_set_packing\n");
  193430. if(png_ptr == NULL) return;
  193431. if (png_ptr->bit_depth < 8)
  193432. {
  193433. png_ptr->transformations |= PNG_PACK;
  193434. png_ptr->usr_bit_depth = 8;
  193435. }
  193436. }
  193437. #endif
  193438. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193439. /* turn on packed pixel swapping */
  193440. void PNGAPI
  193441. png_set_packswap(png_structp png_ptr)
  193442. {
  193443. png_debug(1, "in png_set_packswap\n");
  193444. if(png_ptr == NULL) return;
  193445. if (png_ptr->bit_depth < 8)
  193446. png_ptr->transformations |= PNG_PACKSWAP;
  193447. }
  193448. #endif
  193449. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  193450. void PNGAPI
  193451. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  193452. {
  193453. png_debug(1, "in png_set_shift\n");
  193454. if(png_ptr == NULL) return;
  193455. png_ptr->transformations |= PNG_SHIFT;
  193456. png_ptr->shift = *true_bits;
  193457. }
  193458. #endif
  193459. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  193460. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  193461. int PNGAPI
  193462. png_set_interlace_handling(png_structp png_ptr)
  193463. {
  193464. png_debug(1, "in png_set_interlace handling\n");
  193465. if (png_ptr && png_ptr->interlaced)
  193466. {
  193467. png_ptr->transformations |= PNG_INTERLACE;
  193468. return (7);
  193469. }
  193470. return (1);
  193471. }
  193472. #endif
  193473. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  193474. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  193475. * The filler type has changed in v0.95 to allow future 2-byte fillers
  193476. * for 48-bit input data, as well as to avoid problems with some compilers
  193477. * that don't like bytes as parameters.
  193478. */
  193479. void PNGAPI
  193480. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193481. {
  193482. png_debug(1, "in png_set_filler\n");
  193483. if(png_ptr == NULL) return;
  193484. png_ptr->transformations |= PNG_FILLER;
  193485. png_ptr->filler = (png_byte)filler;
  193486. if (filler_loc == PNG_FILLER_AFTER)
  193487. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  193488. else
  193489. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  193490. /* This should probably go in the "do_read_filler" routine.
  193491. * I attempted to do that in libpng-1.0.1a but that caused problems
  193492. * so I restored it in libpng-1.0.2a
  193493. */
  193494. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  193495. {
  193496. png_ptr->usr_channels = 4;
  193497. }
  193498. /* Also I added this in libpng-1.0.2a (what happens when we expand
  193499. * a less-than-8-bit grayscale to GA? */
  193500. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  193501. {
  193502. png_ptr->usr_channels = 2;
  193503. }
  193504. }
  193505. #if !defined(PNG_1_0_X)
  193506. /* Added to libpng-1.2.7 */
  193507. void PNGAPI
  193508. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  193509. {
  193510. png_debug(1, "in png_set_add_alpha\n");
  193511. if(png_ptr == NULL) return;
  193512. png_set_filler(png_ptr, filler, filler_loc);
  193513. png_ptr->transformations |= PNG_ADD_ALPHA;
  193514. }
  193515. #endif
  193516. #endif
  193517. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  193518. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193519. void PNGAPI
  193520. png_set_swap_alpha(png_structp png_ptr)
  193521. {
  193522. png_debug(1, "in png_set_swap_alpha\n");
  193523. if(png_ptr == NULL) return;
  193524. png_ptr->transformations |= PNG_SWAP_ALPHA;
  193525. }
  193526. #endif
  193527. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  193528. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193529. void PNGAPI
  193530. png_set_invert_alpha(png_structp png_ptr)
  193531. {
  193532. png_debug(1, "in png_set_invert_alpha\n");
  193533. if(png_ptr == NULL) return;
  193534. png_ptr->transformations |= PNG_INVERT_ALPHA;
  193535. }
  193536. #endif
  193537. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  193538. void PNGAPI
  193539. png_set_invert_mono(png_structp png_ptr)
  193540. {
  193541. png_debug(1, "in png_set_invert_mono\n");
  193542. if(png_ptr == NULL) return;
  193543. png_ptr->transformations |= PNG_INVERT_MONO;
  193544. }
  193545. /* invert monochrome grayscale data */
  193546. void /* PRIVATE */
  193547. png_do_invert(png_row_infop row_info, png_bytep row)
  193548. {
  193549. png_debug(1, "in png_do_invert\n");
  193550. /* This test removed from libpng version 1.0.13 and 1.2.0:
  193551. * if (row_info->bit_depth == 1 &&
  193552. */
  193553. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193554. if (row == NULL || row_info == NULL)
  193555. return;
  193556. #endif
  193557. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193558. {
  193559. png_bytep rp = row;
  193560. png_uint_32 i;
  193561. png_uint_32 istop = row_info->rowbytes;
  193562. for (i = 0; i < istop; i++)
  193563. {
  193564. *rp = (png_byte)(~(*rp));
  193565. rp++;
  193566. }
  193567. }
  193568. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193569. row_info->bit_depth == 8)
  193570. {
  193571. png_bytep rp = row;
  193572. png_uint_32 i;
  193573. png_uint_32 istop = row_info->rowbytes;
  193574. for (i = 0; i < istop; i+=2)
  193575. {
  193576. *rp = (png_byte)(~(*rp));
  193577. rp+=2;
  193578. }
  193579. }
  193580. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193581. row_info->bit_depth == 16)
  193582. {
  193583. png_bytep rp = row;
  193584. png_uint_32 i;
  193585. png_uint_32 istop = row_info->rowbytes;
  193586. for (i = 0; i < istop; i+=4)
  193587. {
  193588. *rp = (png_byte)(~(*rp));
  193589. *(rp+1) = (png_byte)(~(*(rp+1)));
  193590. rp+=4;
  193591. }
  193592. }
  193593. }
  193594. #endif
  193595. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  193596. /* swaps byte order on 16 bit depth images */
  193597. void /* PRIVATE */
  193598. png_do_swap(png_row_infop row_info, png_bytep row)
  193599. {
  193600. png_debug(1, "in png_do_swap\n");
  193601. if (
  193602. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193603. row != NULL && row_info != NULL &&
  193604. #endif
  193605. row_info->bit_depth == 16)
  193606. {
  193607. png_bytep rp = row;
  193608. png_uint_32 i;
  193609. png_uint_32 istop= row_info->width * row_info->channels;
  193610. for (i = 0; i < istop; i++, rp += 2)
  193611. {
  193612. png_byte t = *rp;
  193613. *rp = *(rp + 1);
  193614. *(rp + 1) = t;
  193615. }
  193616. }
  193617. }
  193618. #endif
  193619. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193620. static PNG_CONST png_byte onebppswaptable[256] = {
  193621. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  193622. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  193623. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  193624. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  193625. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  193626. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  193627. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  193628. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  193629. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  193630. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  193631. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  193632. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  193633. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  193634. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  193635. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  193636. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  193637. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  193638. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  193639. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  193640. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  193641. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  193642. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  193643. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  193644. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  193645. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  193646. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  193647. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  193648. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  193649. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  193650. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  193651. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  193652. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  193653. };
  193654. static PNG_CONST png_byte twobppswaptable[256] = {
  193655. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  193656. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  193657. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  193658. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  193659. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  193660. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  193661. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  193662. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  193663. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  193664. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  193665. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  193666. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  193667. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  193668. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  193669. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  193670. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  193671. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  193672. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  193673. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  193674. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  193675. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  193676. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  193677. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  193678. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  193679. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  193680. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  193681. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  193682. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  193683. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  193684. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  193685. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  193686. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  193687. };
  193688. static PNG_CONST png_byte fourbppswaptable[256] = {
  193689. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  193690. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  193691. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  193692. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  193693. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  193694. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  193695. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  193696. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  193697. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  193698. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  193699. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  193700. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  193701. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  193702. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  193703. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  193704. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  193705. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  193706. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  193707. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  193708. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  193709. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  193710. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  193711. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  193712. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  193713. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  193714. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  193715. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  193716. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  193717. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  193718. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  193719. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  193720. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  193721. };
  193722. /* swaps pixel packing order within bytes */
  193723. void /* PRIVATE */
  193724. png_do_packswap(png_row_infop row_info, png_bytep row)
  193725. {
  193726. png_debug(1, "in png_do_packswap\n");
  193727. if (
  193728. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193729. row != NULL && row_info != NULL &&
  193730. #endif
  193731. row_info->bit_depth < 8)
  193732. {
  193733. png_bytep rp, end, table;
  193734. end = row + row_info->rowbytes;
  193735. if (row_info->bit_depth == 1)
  193736. table = (png_bytep)onebppswaptable;
  193737. else if (row_info->bit_depth == 2)
  193738. table = (png_bytep)twobppswaptable;
  193739. else if (row_info->bit_depth == 4)
  193740. table = (png_bytep)fourbppswaptable;
  193741. else
  193742. return;
  193743. for (rp = row; rp < end; rp++)
  193744. *rp = table[*rp];
  193745. }
  193746. }
  193747. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  193748. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  193749. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  193750. /* remove filler or alpha byte(s) */
  193751. void /* PRIVATE */
  193752. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  193753. {
  193754. png_debug(1, "in png_do_strip_filler\n");
  193755. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193756. if (row != NULL && row_info != NULL)
  193757. #endif
  193758. {
  193759. png_bytep sp=row;
  193760. png_bytep dp=row;
  193761. png_uint_32 row_width=row_info->width;
  193762. png_uint_32 i;
  193763. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  193764. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193765. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193766. row_info->channels == 4)
  193767. {
  193768. if (row_info->bit_depth == 8)
  193769. {
  193770. /* This converts from RGBX or RGBA to RGB */
  193771. if (flags & PNG_FLAG_FILLER_AFTER)
  193772. {
  193773. dp+=3; sp+=4;
  193774. for (i = 1; i < row_width; i++)
  193775. {
  193776. *dp++ = *sp++;
  193777. *dp++ = *sp++;
  193778. *dp++ = *sp++;
  193779. sp++;
  193780. }
  193781. }
  193782. /* This converts from XRGB or ARGB to RGB */
  193783. else
  193784. {
  193785. for (i = 0; i < row_width; i++)
  193786. {
  193787. sp++;
  193788. *dp++ = *sp++;
  193789. *dp++ = *sp++;
  193790. *dp++ = *sp++;
  193791. }
  193792. }
  193793. row_info->pixel_depth = 24;
  193794. row_info->rowbytes = row_width * 3;
  193795. }
  193796. else /* if (row_info->bit_depth == 16) */
  193797. {
  193798. if (flags & PNG_FLAG_FILLER_AFTER)
  193799. {
  193800. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  193801. sp += 8; dp += 6;
  193802. for (i = 1; i < row_width; i++)
  193803. {
  193804. /* This could be (although png_memcpy is probably slower):
  193805. png_memcpy(dp, sp, 6);
  193806. sp += 8;
  193807. dp += 6;
  193808. */
  193809. *dp++ = *sp++;
  193810. *dp++ = *sp++;
  193811. *dp++ = *sp++;
  193812. *dp++ = *sp++;
  193813. *dp++ = *sp++;
  193814. *dp++ = *sp++;
  193815. sp += 2;
  193816. }
  193817. }
  193818. else
  193819. {
  193820. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  193821. for (i = 0; i < row_width; i++)
  193822. {
  193823. /* This could be (although png_memcpy is probably slower):
  193824. png_memcpy(dp, sp, 6);
  193825. sp += 8;
  193826. dp += 6;
  193827. */
  193828. sp+=2;
  193829. *dp++ = *sp++;
  193830. *dp++ = *sp++;
  193831. *dp++ = *sp++;
  193832. *dp++ = *sp++;
  193833. *dp++ = *sp++;
  193834. *dp++ = *sp++;
  193835. }
  193836. }
  193837. row_info->pixel_depth = 48;
  193838. row_info->rowbytes = row_width * 6;
  193839. }
  193840. row_info->channels = 3;
  193841. }
  193842. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  193843. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  193844. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  193845. row_info->channels == 2)
  193846. {
  193847. if (row_info->bit_depth == 8)
  193848. {
  193849. /* This converts from GX or GA to G */
  193850. if (flags & PNG_FLAG_FILLER_AFTER)
  193851. {
  193852. for (i = 0; i < row_width; i++)
  193853. {
  193854. *dp++ = *sp++;
  193855. sp++;
  193856. }
  193857. }
  193858. /* This converts from XG or AG to G */
  193859. else
  193860. {
  193861. for (i = 0; i < row_width; i++)
  193862. {
  193863. sp++;
  193864. *dp++ = *sp++;
  193865. }
  193866. }
  193867. row_info->pixel_depth = 8;
  193868. row_info->rowbytes = row_width;
  193869. }
  193870. else /* if (row_info->bit_depth == 16) */
  193871. {
  193872. if (flags & PNG_FLAG_FILLER_AFTER)
  193873. {
  193874. /* This converts from GGXX or GGAA to GG */
  193875. sp += 4; dp += 2;
  193876. for (i = 1; i < row_width; i++)
  193877. {
  193878. *dp++ = *sp++;
  193879. *dp++ = *sp++;
  193880. sp += 2;
  193881. }
  193882. }
  193883. else
  193884. {
  193885. /* This converts from XXGG or AAGG to GG */
  193886. for (i = 0; i < row_width; i++)
  193887. {
  193888. sp += 2;
  193889. *dp++ = *sp++;
  193890. *dp++ = *sp++;
  193891. }
  193892. }
  193893. row_info->pixel_depth = 16;
  193894. row_info->rowbytes = row_width * 2;
  193895. }
  193896. row_info->channels = 1;
  193897. }
  193898. if (flags & PNG_FLAG_STRIP_ALPHA)
  193899. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193900. }
  193901. }
  193902. #endif
  193903. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  193904. /* swaps red and blue bytes within a pixel */
  193905. void /* PRIVATE */
  193906. png_do_bgr(png_row_infop row_info, png_bytep row)
  193907. {
  193908. png_debug(1, "in png_do_bgr\n");
  193909. if (
  193910. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193911. row != NULL && row_info != NULL &&
  193912. #endif
  193913. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193914. {
  193915. png_uint_32 row_width = row_info->width;
  193916. if (row_info->bit_depth == 8)
  193917. {
  193918. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193919. {
  193920. png_bytep rp;
  193921. png_uint_32 i;
  193922. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  193923. {
  193924. png_byte save = *rp;
  193925. *rp = *(rp + 2);
  193926. *(rp + 2) = save;
  193927. }
  193928. }
  193929. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193930. {
  193931. png_bytep rp;
  193932. png_uint_32 i;
  193933. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  193934. {
  193935. png_byte save = *rp;
  193936. *rp = *(rp + 2);
  193937. *(rp + 2) = save;
  193938. }
  193939. }
  193940. }
  193941. else if (row_info->bit_depth == 16)
  193942. {
  193943. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193944. {
  193945. png_bytep rp;
  193946. png_uint_32 i;
  193947. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  193948. {
  193949. png_byte save = *rp;
  193950. *rp = *(rp + 4);
  193951. *(rp + 4) = save;
  193952. save = *(rp + 1);
  193953. *(rp + 1) = *(rp + 5);
  193954. *(rp + 5) = save;
  193955. }
  193956. }
  193957. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193958. {
  193959. png_bytep rp;
  193960. png_uint_32 i;
  193961. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  193962. {
  193963. png_byte save = *rp;
  193964. *rp = *(rp + 4);
  193965. *(rp + 4) = save;
  193966. save = *(rp + 1);
  193967. *(rp + 1) = *(rp + 5);
  193968. *(rp + 5) = save;
  193969. }
  193970. }
  193971. }
  193972. }
  193973. }
  193974. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  193975. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  193976. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  193977. defined(PNG_LEGACY_SUPPORTED)
  193978. void PNGAPI
  193979. png_set_user_transform_info(png_structp png_ptr, png_voidp
  193980. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  193981. {
  193982. png_debug(1, "in png_set_user_transform_info\n");
  193983. if(png_ptr == NULL) return;
  193984. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  193985. png_ptr->user_transform_ptr = user_transform_ptr;
  193986. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  193987. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  193988. #else
  193989. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  193990. png_warning(png_ptr,
  193991. "This version of libpng does not support user transform info");
  193992. #endif
  193993. }
  193994. #endif
  193995. /* This function returns a pointer to the user_transform_ptr associated with
  193996. * the user transform functions. The application should free any memory
  193997. * associated with this pointer before png_write_destroy and png_read_destroy
  193998. * are called.
  193999. */
  194000. png_voidp PNGAPI
  194001. png_get_user_transform_ptr(png_structp png_ptr)
  194002. {
  194003. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  194004. if (png_ptr == NULL) return (NULL);
  194005. return ((png_voidp)png_ptr->user_transform_ptr);
  194006. #else
  194007. return (NULL);
  194008. #endif
  194009. }
  194010. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  194011. /********* End of inlined file: pngtrans.c *********/
  194012. /********* Start of inlined file: pngwio.c *********/
  194013. /* pngwio.c - functions for data output
  194014. *
  194015. * Last changed in libpng 1.2.13 November 13, 2006
  194016. * For conditions of distribution and use, see copyright notice in png.h
  194017. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  194018. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194019. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194020. *
  194021. * This file provides a location for all output. Users who need
  194022. * special handling are expected to write functions that have the same
  194023. * arguments as these and perform similar functions, but that possibly
  194024. * use different output methods. Note that you shouldn't change these
  194025. * functions, but rather write replacement functions and then change
  194026. * them at run time with png_set_write_fn(...).
  194027. */
  194028. #define PNG_INTERNAL
  194029. #ifdef PNG_WRITE_SUPPORTED
  194030. /* Write the data to whatever output you are using. The default routine
  194031. writes to a file pointer. Note that this routine sometimes gets called
  194032. with very small lengths, so you should implement some kind of simple
  194033. buffering if you are using unbuffered writes. This should never be asked
  194034. to write more than 64K on a 16 bit machine. */
  194035. void /* PRIVATE */
  194036. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194037. {
  194038. if (png_ptr->write_data_fn != NULL )
  194039. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  194040. else
  194041. png_error(png_ptr, "Call to NULL write function");
  194042. }
  194043. #if !defined(PNG_NO_STDIO)
  194044. /* This is the function that does the actual writing of data. If you are
  194045. not writing to a standard C stream, you should create a replacement
  194046. write_data function and use it at run time with png_set_write_fn(), rather
  194047. than changing the library. */
  194048. #ifndef USE_FAR_KEYWORD
  194049. void PNGAPI
  194050. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194051. {
  194052. png_uint_32 check;
  194053. if(png_ptr == NULL) return;
  194054. #if defined(_WIN32_WCE)
  194055. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  194056. check = 0;
  194057. #else
  194058. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  194059. #endif
  194060. if (check != length)
  194061. png_error(png_ptr, "Write Error");
  194062. }
  194063. #else
  194064. /* this is the model-independent version. Since the standard I/O library
  194065. can't handle far buffers in the medium and small models, we have to copy
  194066. the data.
  194067. */
  194068. #define NEAR_BUF_SIZE 1024
  194069. #define MIN(a,b) (a <= b ? a : b)
  194070. void PNGAPI
  194071. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  194072. {
  194073. png_uint_32 check;
  194074. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  194075. png_FILE_p io_ptr;
  194076. if(png_ptr == NULL) return;
  194077. /* Check if data really is near. If so, use usual code. */
  194078. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  194079. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  194080. if ((png_bytep)near_data == data)
  194081. {
  194082. #if defined(_WIN32_WCE)
  194083. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  194084. check = 0;
  194085. #else
  194086. check = fwrite(near_data, 1, length, io_ptr);
  194087. #endif
  194088. }
  194089. else
  194090. {
  194091. png_byte buf[NEAR_BUF_SIZE];
  194092. png_size_t written, remaining, err;
  194093. check = 0;
  194094. remaining = length;
  194095. do
  194096. {
  194097. written = MIN(NEAR_BUF_SIZE, remaining);
  194098. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  194099. #if defined(_WIN32_WCE)
  194100. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  194101. err = 0;
  194102. #else
  194103. err = fwrite(buf, 1, written, io_ptr);
  194104. #endif
  194105. if (err != written)
  194106. break;
  194107. else
  194108. check += err;
  194109. data += written;
  194110. remaining -= written;
  194111. }
  194112. while (remaining != 0);
  194113. }
  194114. if (check != length)
  194115. png_error(png_ptr, "Write Error");
  194116. }
  194117. #endif
  194118. #endif
  194119. /* This function is called to output any data pending writing (normally
  194120. to disk). After png_flush is called, there should be no data pending
  194121. writing in any buffers. */
  194122. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194123. void /* PRIVATE */
  194124. png_flush(png_structp png_ptr)
  194125. {
  194126. if (png_ptr->output_flush_fn != NULL)
  194127. (*(png_ptr->output_flush_fn))(png_ptr);
  194128. }
  194129. #if !defined(PNG_NO_STDIO)
  194130. void PNGAPI
  194131. png_default_flush(png_structp png_ptr)
  194132. {
  194133. #if !defined(_WIN32_WCE)
  194134. png_FILE_p io_ptr;
  194135. #endif
  194136. if(png_ptr == NULL) return;
  194137. #if !defined(_WIN32_WCE)
  194138. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  194139. if (io_ptr != NULL)
  194140. fflush(io_ptr);
  194141. #endif
  194142. }
  194143. #endif
  194144. #endif
  194145. /* This function allows the application to supply new output functions for
  194146. libpng if standard C streams aren't being used.
  194147. This function takes as its arguments:
  194148. png_ptr - pointer to a png output data structure
  194149. io_ptr - pointer to user supplied structure containing info about
  194150. the output functions. May be NULL.
  194151. write_data_fn - pointer to a new output function that takes as its
  194152. arguments a pointer to a png_struct, a pointer to
  194153. data to be written, and a 32-bit unsigned int that is
  194154. the number of bytes to be written. The new write
  194155. function should call png_error(png_ptr, "Error msg")
  194156. to exit and output any fatal error messages.
  194157. flush_data_fn - pointer to a new flush function that takes as its
  194158. arguments a pointer to a png_struct. After a call to
  194159. the flush function, there should be no data in any buffers
  194160. or pending transmission. If the output method doesn't do
  194161. any buffering of ouput, a function prototype must still be
  194162. supplied although it doesn't have to do anything. If
  194163. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  194164. time, output_flush_fn will be ignored, although it must be
  194165. supplied for compatibility. */
  194166. void PNGAPI
  194167. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  194168. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  194169. {
  194170. if(png_ptr == NULL) return;
  194171. png_ptr->io_ptr = io_ptr;
  194172. #if !defined(PNG_NO_STDIO)
  194173. if (write_data_fn != NULL)
  194174. png_ptr->write_data_fn = write_data_fn;
  194175. else
  194176. png_ptr->write_data_fn = png_default_write_data;
  194177. #else
  194178. png_ptr->write_data_fn = write_data_fn;
  194179. #endif
  194180. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  194181. #if !defined(PNG_NO_STDIO)
  194182. if (output_flush_fn != NULL)
  194183. png_ptr->output_flush_fn = output_flush_fn;
  194184. else
  194185. png_ptr->output_flush_fn = png_default_flush;
  194186. #else
  194187. png_ptr->output_flush_fn = output_flush_fn;
  194188. #endif
  194189. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  194190. /* It is an error to read while writing a png file */
  194191. if (png_ptr->read_data_fn != NULL)
  194192. {
  194193. png_ptr->read_data_fn = NULL;
  194194. png_warning(png_ptr,
  194195. "Attempted to set both read_data_fn and write_data_fn in");
  194196. png_warning(png_ptr,
  194197. "the same structure. Resetting read_data_fn to NULL.");
  194198. }
  194199. }
  194200. #if defined(USE_FAR_KEYWORD)
  194201. #if defined(_MSC_VER)
  194202. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194203. {
  194204. void *near_ptr;
  194205. void FAR *far_ptr;
  194206. FP_OFF(near_ptr) = FP_OFF(ptr);
  194207. far_ptr = (void FAR *)near_ptr;
  194208. if(check != 0)
  194209. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  194210. png_error(png_ptr,"segment lost in conversion");
  194211. return(near_ptr);
  194212. }
  194213. # else
  194214. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  194215. {
  194216. void *near_ptr;
  194217. void FAR *far_ptr;
  194218. near_ptr = (void FAR *)ptr;
  194219. far_ptr = (void FAR *)near_ptr;
  194220. if(check != 0)
  194221. if(far_ptr != ptr)
  194222. png_error(png_ptr,"segment lost in conversion");
  194223. return(near_ptr);
  194224. }
  194225. # endif
  194226. # endif
  194227. #endif /* PNG_WRITE_SUPPORTED */
  194228. /********* End of inlined file: pngwio.c *********/
  194229. /********* Start of inlined file: pngwrite.c *********/
  194230. /* pngwrite.c - general routines to write a PNG file
  194231. *
  194232. * Last changed in libpng 1.2.15 January 5, 2007
  194233. * For conditions of distribution and use, see copyright notice in png.h
  194234. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194235. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194236. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194237. */
  194238. /* get internal access to png.h */
  194239. #define PNG_INTERNAL
  194240. #ifdef PNG_WRITE_SUPPORTED
  194241. /* Writes all the PNG information. This is the suggested way to use the
  194242. * library. If you have a new chunk to add, make a function to write it,
  194243. * and put it in the correct location here. If you want the chunk written
  194244. * after the image data, put it in png_write_end(). I strongly encourage
  194245. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  194246. * the chunk, as that will keep the code from breaking if you want to just
  194247. * write a plain PNG file. If you have long comments, I suggest writing
  194248. * them in png_write_end(), and compressing them.
  194249. */
  194250. void PNGAPI
  194251. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  194252. {
  194253. png_debug(1, "in png_write_info_before_PLTE\n");
  194254. if (png_ptr == NULL || info_ptr == NULL)
  194255. return;
  194256. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194257. {
  194258. png_write_sig(png_ptr); /* write PNG signature */
  194259. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194260. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  194261. {
  194262. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  194263. png_ptr->mng_features_permitted=0;
  194264. }
  194265. #endif
  194266. /* write IHDR information. */
  194267. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  194268. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  194269. info_ptr->filter_type,
  194270. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194271. info_ptr->interlace_type);
  194272. #else
  194273. 0);
  194274. #endif
  194275. /* the rest of these check to see if the valid field has the appropriate
  194276. flag set, and if it does, writes the chunk. */
  194277. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194278. if (info_ptr->valid & PNG_INFO_gAMA)
  194279. {
  194280. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194281. png_write_gAMA(png_ptr, info_ptr->gamma);
  194282. #else
  194283. #ifdef PNG_FIXED_POINT_SUPPORTED
  194284. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  194285. # endif
  194286. #endif
  194287. }
  194288. #endif
  194289. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194290. if (info_ptr->valid & PNG_INFO_sRGB)
  194291. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  194292. #endif
  194293. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194294. if (info_ptr->valid & PNG_INFO_iCCP)
  194295. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  194296. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  194297. #endif
  194298. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194299. if (info_ptr->valid & PNG_INFO_sBIT)
  194300. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  194301. #endif
  194302. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194303. if (info_ptr->valid & PNG_INFO_cHRM)
  194304. {
  194305. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194306. png_write_cHRM(png_ptr,
  194307. info_ptr->x_white, info_ptr->y_white,
  194308. info_ptr->x_red, info_ptr->y_red,
  194309. info_ptr->x_green, info_ptr->y_green,
  194310. info_ptr->x_blue, info_ptr->y_blue);
  194311. #else
  194312. # ifdef PNG_FIXED_POINT_SUPPORTED
  194313. png_write_cHRM_fixed(png_ptr,
  194314. info_ptr->int_x_white, info_ptr->int_y_white,
  194315. info_ptr->int_x_red, info_ptr->int_y_red,
  194316. info_ptr->int_x_green, info_ptr->int_y_green,
  194317. info_ptr->int_x_blue, info_ptr->int_y_blue);
  194318. # endif
  194319. #endif
  194320. }
  194321. #endif
  194322. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194323. if (info_ptr->unknown_chunks_num)
  194324. {
  194325. png_unknown_chunk *up;
  194326. png_debug(5, "writing extra chunks\n");
  194327. for (up = info_ptr->unknown_chunks;
  194328. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194329. up++)
  194330. {
  194331. int keep=png_handle_as_unknown(png_ptr, up->name);
  194332. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194333. up->location && !(up->location & PNG_HAVE_PLTE) &&
  194334. !(up->location & PNG_HAVE_IDAT) &&
  194335. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194336. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194337. {
  194338. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194339. }
  194340. }
  194341. }
  194342. #endif
  194343. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  194344. }
  194345. }
  194346. void PNGAPI
  194347. png_write_info(png_structp png_ptr, png_infop info_ptr)
  194348. {
  194349. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194350. int i;
  194351. #endif
  194352. png_debug(1, "in png_write_info\n");
  194353. if (png_ptr == NULL || info_ptr == NULL)
  194354. return;
  194355. png_write_info_before_PLTE(png_ptr, info_ptr);
  194356. if (info_ptr->valid & PNG_INFO_PLTE)
  194357. png_write_PLTE(png_ptr, info_ptr->palette,
  194358. (png_uint_32)info_ptr->num_palette);
  194359. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194360. png_error(png_ptr, "Valid palette required for paletted images");
  194361. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194362. if (info_ptr->valid & PNG_INFO_tRNS)
  194363. {
  194364. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  194365. /* invert the alpha channel (in tRNS) */
  194366. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  194367. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194368. {
  194369. int j;
  194370. for (j=0; j<(int)info_ptr->num_trans; j++)
  194371. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  194372. }
  194373. #endif
  194374. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  194375. info_ptr->num_trans, info_ptr->color_type);
  194376. }
  194377. #endif
  194378. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194379. if (info_ptr->valid & PNG_INFO_bKGD)
  194380. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  194381. #endif
  194382. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194383. if (info_ptr->valid & PNG_INFO_hIST)
  194384. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  194385. #endif
  194386. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  194387. if (info_ptr->valid & PNG_INFO_oFFs)
  194388. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  194389. info_ptr->offset_unit_type);
  194390. #endif
  194391. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  194392. if (info_ptr->valid & PNG_INFO_pCAL)
  194393. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  194394. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  194395. info_ptr->pcal_units, info_ptr->pcal_params);
  194396. #endif
  194397. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  194398. if (info_ptr->valid & PNG_INFO_sCAL)
  194399. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  194400. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  194401. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  194402. #else
  194403. #ifdef PNG_FIXED_POINT_SUPPORTED
  194404. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  194405. info_ptr->scal_s_width, info_ptr->scal_s_height);
  194406. #else
  194407. png_warning(png_ptr,
  194408. "png_write_sCAL not supported; sCAL chunk not written.");
  194409. #endif
  194410. #endif
  194411. #endif
  194412. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  194413. if (info_ptr->valid & PNG_INFO_pHYs)
  194414. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  194415. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  194416. #endif
  194417. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194418. if (info_ptr->valid & PNG_INFO_tIME)
  194419. {
  194420. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194421. png_ptr->mode |= PNG_WROTE_tIME;
  194422. }
  194423. #endif
  194424. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194425. if (info_ptr->valid & PNG_INFO_sPLT)
  194426. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  194427. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  194428. #endif
  194429. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194430. /* Check to see if we need to write text chunks */
  194431. for (i = 0; i < info_ptr->num_text; i++)
  194432. {
  194433. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  194434. info_ptr->text[i].compression);
  194435. /* an internationalized chunk? */
  194436. if (info_ptr->text[i].compression > 0)
  194437. {
  194438. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194439. /* write international chunk */
  194440. png_write_iTXt(png_ptr,
  194441. info_ptr->text[i].compression,
  194442. info_ptr->text[i].key,
  194443. info_ptr->text[i].lang,
  194444. info_ptr->text[i].lang_key,
  194445. info_ptr->text[i].text);
  194446. #else
  194447. png_warning(png_ptr, "Unable to write international text");
  194448. #endif
  194449. /* Mark this chunk as written */
  194450. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194451. }
  194452. /* If we want a compressed text chunk */
  194453. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  194454. {
  194455. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194456. /* write compressed chunk */
  194457. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194458. info_ptr->text[i].text, 0,
  194459. info_ptr->text[i].compression);
  194460. #else
  194461. png_warning(png_ptr, "Unable to write compressed text");
  194462. #endif
  194463. /* Mark this chunk as written */
  194464. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194465. }
  194466. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194467. {
  194468. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194469. /* write uncompressed chunk */
  194470. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194471. info_ptr->text[i].text,
  194472. 0);
  194473. #else
  194474. png_warning(png_ptr, "Unable to write uncompressed text");
  194475. #endif
  194476. /* Mark this chunk as written */
  194477. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194478. }
  194479. }
  194480. #endif
  194481. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194482. if (info_ptr->unknown_chunks_num)
  194483. {
  194484. png_unknown_chunk *up;
  194485. png_debug(5, "writing extra chunks\n");
  194486. for (up = info_ptr->unknown_chunks;
  194487. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194488. up++)
  194489. {
  194490. int keep=png_handle_as_unknown(png_ptr, up->name);
  194491. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194492. up->location && (up->location & PNG_HAVE_PLTE) &&
  194493. !(up->location & PNG_HAVE_IDAT) &&
  194494. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194495. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194496. {
  194497. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194498. }
  194499. }
  194500. }
  194501. #endif
  194502. }
  194503. /* Writes the end of the PNG file. If you don't want to write comments or
  194504. * time information, you can pass NULL for info. If you already wrote these
  194505. * in png_write_info(), do not write them again here. If you have long
  194506. * comments, I suggest writing them here, and compressing them.
  194507. */
  194508. void PNGAPI
  194509. png_write_end(png_structp png_ptr, png_infop info_ptr)
  194510. {
  194511. png_debug(1, "in png_write_end\n");
  194512. if (png_ptr == NULL)
  194513. return;
  194514. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  194515. png_error(png_ptr, "No IDATs written into file");
  194516. /* see if user wants us to write information chunks */
  194517. if (info_ptr != NULL)
  194518. {
  194519. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194520. int i; /* local index variable */
  194521. #endif
  194522. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194523. /* check to see if user has supplied a time chunk */
  194524. if ((info_ptr->valid & PNG_INFO_tIME) &&
  194525. !(png_ptr->mode & PNG_WROTE_tIME))
  194526. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  194527. #endif
  194528. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  194529. /* loop through comment chunks */
  194530. for (i = 0; i < info_ptr->num_text; i++)
  194531. {
  194532. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  194533. info_ptr->text[i].compression);
  194534. /* an internationalized chunk? */
  194535. if (info_ptr->text[i].compression > 0)
  194536. {
  194537. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  194538. /* write international chunk */
  194539. png_write_iTXt(png_ptr,
  194540. info_ptr->text[i].compression,
  194541. info_ptr->text[i].key,
  194542. info_ptr->text[i].lang,
  194543. info_ptr->text[i].lang_key,
  194544. info_ptr->text[i].text);
  194545. #else
  194546. png_warning(png_ptr, "Unable to write international text");
  194547. #endif
  194548. /* Mark this chunk as written */
  194549. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194550. }
  194551. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  194552. {
  194553. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  194554. /* write compressed chunk */
  194555. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  194556. info_ptr->text[i].text, 0,
  194557. info_ptr->text[i].compression);
  194558. #else
  194559. png_warning(png_ptr, "Unable to write compressed text");
  194560. #endif
  194561. /* Mark this chunk as written */
  194562. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  194563. }
  194564. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  194565. {
  194566. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  194567. /* write uncompressed chunk */
  194568. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  194569. info_ptr->text[i].text, 0);
  194570. #else
  194571. png_warning(png_ptr, "Unable to write uncompressed text");
  194572. #endif
  194573. /* Mark this chunk as written */
  194574. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  194575. }
  194576. }
  194577. #endif
  194578. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  194579. if (info_ptr->unknown_chunks_num)
  194580. {
  194581. png_unknown_chunk *up;
  194582. png_debug(5, "writing extra chunks\n");
  194583. for (up = info_ptr->unknown_chunks;
  194584. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  194585. up++)
  194586. {
  194587. int keep=png_handle_as_unknown(png_ptr, up->name);
  194588. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  194589. up->location && (up->location & PNG_AFTER_IDAT) &&
  194590. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  194591. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  194592. {
  194593. png_write_chunk(png_ptr, up->name, up->data, up->size);
  194594. }
  194595. }
  194596. }
  194597. #endif
  194598. }
  194599. png_ptr->mode |= PNG_AFTER_IDAT;
  194600. /* write end of PNG file */
  194601. png_write_IEND(png_ptr);
  194602. }
  194603. #if defined(PNG_WRITE_tIME_SUPPORTED)
  194604. #if !defined(_WIN32_WCE)
  194605. /* "time.h" functions are not supported on WindowsCE */
  194606. void PNGAPI
  194607. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  194608. {
  194609. png_debug(1, "in png_convert_from_struct_tm\n");
  194610. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  194611. ptime->month = (png_byte)(ttime->tm_mon + 1);
  194612. ptime->day = (png_byte)ttime->tm_mday;
  194613. ptime->hour = (png_byte)ttime->tm_hour;
  194614. ptime->minute = (png_byte)ttime->tm_min;
  194615. ptime->second = (png_byte)ttime->tm_sec;
  194616. }
  194617. void PNGAPI
  194618. png_convert_from_time_t(png_timep ptime, time_t ttime)
  194619. {
  194620. struct tm *tbuf;
  194621. png_debug(1, "in png_convert_from_time_t\n");
  194622. tbuf = gmtime(&ttime);
  194623. png_convert_from_struct_tm(ptime, tbuf);
  194624. }
  194625. #endif
  194626. #endif
  194627. /* Initialize png_ptr structure, and allocate any memory needed */
  194628. png_structp PNGAPI
  194629. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  194630. png_error_ptr error_fn, png_error_ptr warn_fn)
  194631. {
  194632. #ifdef PNG_USER_MEM_SUPPORTED
  194633. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  194634. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  194635. }
  194636. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  194637. png_structp PNGAPI
  194638. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  194639. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  194640. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  194641. {
  194642. #endif /* PNG_USER_MEM_SUPPORTED */
  194643. png_structp png_ptr;
  194644. #ifdef PNG_SETJMP_SUPPORTED
  194645. #ifdef USE_FAR_KEYWORD
  194646. jmp_buf jmpbuf;
  194647. #endif
  194648. #endif
  194649. int i;
  194650. png_debug(1, "in png_create_write_struct\n");
  194651. #ifdef PNG_USER_MEM_SUPPORTED
  194652. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  194653. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  194654. #else
  194655. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194656. #endif /* PNG_USER_MEM_SUPPORTED */
  194657. if (png_ptr == NULL)
  194658. return (NULL);
  194659. /* added at libpng-1.2.6 */
  194660. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194661. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194662. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194663. #endif
  194664. #ifdef PNG_SETJMP_SUPPORTED
  194665. #ifdef USE_FAR_KEYWORD
  194666. if (setjmp(jmpbuf))
  194667. #else
  194668. if (setjmp(png_ptr->jmpbuf))
  194669. #endif
  194670. {
  194671. png_free(png_ptr, png_ptr->zbuf);
  194672. png_ptr->zbuf=NULL;
  194673. png_destroy_struct(png_ptr);
  194674. return (NULL);
  194675. }
  194676. #ifdef USE_FAR_KEYWORD
  194677. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194678. #endif
  194679. #endif
  194680. #ifdef PNG_USER_MEM_SUPPORTED
  194681. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  194682. #endif /* PNG_USER_MEM_SUPPORTED */
  194683. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  194684. i=0;
  194685. do
  194686. {
  194687. if(user_png_ver[i] != png_libpng_ver[i])
  194688. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194689. } while (png_libpng_ver[i++]);
  194690. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  194691. {
  194692. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  194693. * we must recompile any applications that use any older library version.
  194694. * For versions after libpng 1.0, we will be compatible, so we need
  194695. * only check the first digit.
  194696. */
  194697. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  194698. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  194699. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  194700. {
  194701. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194702. char msg[80];
  194703. if (user_png_ver)
  194704. {
  194705. png_snprintf(msg, 80,
  194706. "Application was compiled with png.h from libpng-%.20s",
  194707. user_png_ver);
  194708. png_warning(png_ptr, msg);
  194709. }
  194710. png_snprintf(msg, 80,
  194711. "Application is running with png.c from libpng-%.20s",
  194712. png_libpng_ver);
  194713. png_warning(png_ptr, msg);
  194714. #endif
  194715. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194716. png_ptr->flags=0;
  194717. #endif
  194718. png_error(png_ptr,
  194719. "Incompatible libpng version in application and library");
  194720. }
  194721. }
  194722. /* initialize zbuf - compression buffer */
  194723. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194724. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194725. (png_uint_32)png_ptr->zbuf_size);
  194726. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194727. png_flush_ptr_NULL);
  194728. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194729. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194730. 1, png_doublep_NULL, png_doublep_NULL);
  194731. #endif
  194732. #ifdef PNG_SETJMP_SUPPORTED
  194733. /* Applications that neglect to set up their own setjmp() and then encounter
  194734. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  194735. abort instead of returning. */
  194736. #ifdef USE_FAR_KEYWORD
  194737. if (setjmp(jmpbuf))
  194738. PNG_ABORT();
  194739. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  194740. #else
  194741. if (setjmp(png_ptr->jmpbuf))
  194742. PNG_ABORT();
  194743. #endif
  194744. #endif
  194745. return (png_ptr);
  194746. }
  194747. /* Initialize png_ptr structure, and allocate any memory needed */
  194748. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  194749. /* Deprecated. */
  194750. #undef png_write_init
  194751. void PNGAPI
  194752. png_write_init(png_structp png_ptr)
  194753. {
  194754. /* We only come here via pre-1.0.7-compiled applications */
  194755. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  194756. }
  194757. void PNGAPI
  194758. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  194759. png_size_t png_struct_size, png_size_t png_info_size)
  194760. {
  194761. /* We only come here via pre-1.0.12-compiled applications */
  194762. if(png_ptr == NULL) return;
  194763. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194764. if(png_sizeof(png_struct) > png_struct_size ||
  194765. png_sizeof(png_info) > png_info_size)
  194766. {
  194767. char msg[80];
  194768. png_ptr->warning_fn=NULL;
  194769. if (user_png_ver)
  194770. {
  194771. png_snprintf(msg, 80,
  194772. "Application was compiled with png.h from libpng-%.20s",
  194773. user_png_ver);
  194774. png_warning(png_ptr, msg);
  194775. }
  194776. png_snprintf(msg, 80,
  194777. "Application is running with png.c from libpng-%.20s",
  194778. png_libpng_ver);
  194779. png_warning(png_ptr, msg);
  194780. }
  194781. #endif
  194782. if(png_sizeof(png_struct) > png_struct_size)
  194783. {
  194784. png_ptr->error_fn=NULL;
  194785. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194786. png_ptr->flags=0;
  194787. #endif
  194788. png_error(png_ptr,
  194789. "The png struct allocated by the application for writing is too small.");
  194790. }
  194791. if(png_sizeof(png_info) > png_info_size)
  194792. {
  194793. png_ptr->error_fn=NULL;
  194794. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  194795. png_ptr->flags=0;
  194796. #endif
  194797. png_error(png_ptr,
  194798. "The info struct allocated by the application for writing is too small.");
  194799. }
  194800. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  194801. }
  194802. #endif /* PNG_1_0_X || PNG_1_2_X */
  194803. void PNGAPI
  194804. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  194805. png_size_t png_struct_size)
  194806. {
  194807. png_structp png_ptr=*ptr_ptr;
  194808. #ifdef PNG_SETJMP_SUPPORTED
  194809. jmp_buf tmp_jmp; /* to save current jump buffer */
  194810. #endif
  194811. int i = 0;
  194812. if (png_ptr == NULL)
  194813. return;
  194814. do
  194815. {
  194816. if (user_png_ver[i] != png_libpng_ver[i])
  194817. {
  194818. #ifdef PNG_LEGACY_SUPPORTED
  194819. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  194820. #else
  194821. png_ptr->warning_fn=NULL;
  194822. png_warning(png_ptr,
  194823. "Application uses deprecated png_write_init() and should be recompiled.");
  194824. break;
  194825. #endif
  194826. }
  194827. } while (png_libpng_ver[i++]);
  194828. png_debug(1, "in png_write_init_3\n");
  194829. #ifdef PNG_SETJMP_SUPPORTED
  194830. /* save jump buffer and error functions */
  194831. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  194832. #endif
  194833. if (png_sizeof(png_struct) > png_struct_size)
  194834. {
  194835. png_destroy_struct(png_ptr);
  194836. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  194837. *ptr_ptr = png_ptr;
  194838. }
  194839. /* reset all variables to 0 */
  194840. png_memset(png_ptr, 0, png_sizeof (png_struct));
  194841. /* added at libpng-1.2.6 */
  194842. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  194843. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  194844. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  194845. #endif
  194846. #ifdef PNG_SETJMP_SUPPORTED
  194847. /* restore jump buffer */
  194848. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  194849. #endif
  194850. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  194851. png_flush_ptr_NULL);
  194852. /* initialize zbuf - compression buffer */
  194853. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  194854. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  194855. (png_uint_32)png_ptr->zbuf_size);
  194856. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  194857. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  194858. 1, png_doublep_NULL, png_doublep_NULL);
  194859. #endif
  194860. }
  194861. /* Write a few rows of image data. If the image is interlaced,
  194862. * either you will have to write the 7 sub images, or, if you
  194863. * have called png_set_interlace_handling(), you will have to
  194864. * "write" the image seven times.
  194865. */
  194866. void PNGAPI
  194867. png_write_rows(png_structp png_ptr, png_bytepp row,
  194868. png_uint_32 num_rows)
  194869. {
  194870. png_uint_32 i; /* row counter */
  194871. png_bytepp rp; /* row pointer */
  194872. png_debug(1, "in png_write_rows\n");
  194873. if (png_ptr == NULL)
  194874. return;
  194875. /* loop through the rows */
  194876. for (i = 0, rp = row; i < num_rows; i++, rp++)
  194877. {
  194878. png_write_row(png_ptr, *rp);
  194879. }
  194880. }
  194881. /* Write the image. You only need to call this function once, even
  194882. * if you are writing an interlaced image.
  194883. */
  194884. void PNGAPI
  194885. png_write_image(png_structp png_ptr, png_bytepp image)
  194886. {
  194887. png_uint_32 i; /* row index */
  194888. int pass, num_pass; /* pass variables */
  194889. png_bytepp rp; /* points to current row */
  194890. if (png_ptr == NULL)
  194891. return;
  194892. png_debug(1, "in png_write_image\n");
  194893. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194894. /* intialize interlace handling. If image is not interlaced,
  194895. this will set pass to 1 */
  194896. num_pass = png_set_interlace_handling(png_ptr);
  194897. #else
  194898. num_pass = 1;
  194899. #endif
  194900. /* loop through passes */
  194901. for (pass = 0; pass < num_pass; pass++)
  194902. {
  194903. /* loop through image */
  194904. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  194905. {
  194906. png_write_row(png_ptr, *rp);
  194907. }
  194908. }
  194909. }
  194910. /* called by user to write a row of image data */
  194911. void PNGAPI
  194912. png_write_row(png_structp png_ptr, png_bytep row)
  194913. {
  194914. if (png_ptr == NULL)
  194915. return;
  194916. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  194917. png_ptr->row_number, png_ptr->pass);
  194918. /* initialize transformations and other stuff if first time */
  194919. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  194920. {
  194921. /* make sure we wrote the header info */
  194922. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  194923. png_error(png_ptr,
  194924. "png_write_info was never called before png_write_row.");
  194925. /* check for transforms that have been set but were defined out */
  194926. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  194927. if (png_ptr->transformations & PNG_INVERT_MONO)
  194928. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  194929. #endif
  194930. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  194931. if (png_ptr->transformations & PNG_FILLER)
  194932. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  194933. #endif
  194934. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  194935. if (png_ptr->transformations & PNG_PACKSWAP)
  194936. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  194937. #endif
  194938. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  194939. if (png_ptr->transformations & PNG_PACK)
  194940. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  194941. #endif
  194942. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  194943. if (png_ptr->transformations & PNG_SHIFT)
  194944. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  194945. #endif
  194946. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  194947. if (png_ptr->transformations & PNG_BGR)
  194948. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  194949. #endif
  194950. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  194951. if (png_ptr->transformations & PNG_SWAP_BYTES)
  194952. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  194953. #endif
  194954. png_write_start_row(png_ptr);
  194955. }
  194956. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  194957. /* if interlaced and not interested in row, return */
  194958. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  194959. {
  194960. switch (png_ptr->pass)
  194961. {
  194962. case 0:
  194963. if (png_ptr->row_number & 0x07)
  194964. {
  194965. png_write_finish_row(png_ptr);
  194966. return;
  194967. }
  194968. break;
  194969. case 1:
  194970. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  194971. {
  194972. png_write_finish_row(png_ptr);
  194973. return;
  194974. }
  194975. break;
  194976. case 2:
  194977. if ((png_ptr->row_number & 0x07) != 4)
  194978. {
  194979. png_write_finish_row(png_ptr);
  194980. return;
  194981. }
  194982. break;
  194983. case 3:
  194984. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  194985. {
  194986. png_write_finish_row(png_ptr);
  194987. return;
  194988. }
  194989. break;
  194990. case 4:
  194991. if ((png_ptr->row_number & 0x03) != 2)
  194992. {
  194993. png_write_finish_row(png_ptr);
  194994. return;
  194995. }
  194996. break;
  194997. case 5:
  194998. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  194999. {
  195000. png_write_finish_row(png_ptr);
  195001. return;
  195002. }
  195003. break;
  195004. case 6:
  195005. if (!(png_ptr->row_number & 0x01))
  195006. {
  195007. png_write_finish_row(png_ptr);
  195008. return;
  195009. }
  195010. break;
  195011. }
  195012. }
  195013. #endif
  195014. /* set up row info for transformations */
  195015. png_ptr->row_info.color_type = png_ptr->color_type;
  195016. png_ptr->row_info.width = png_ptr->usr_width;
  195017. png_ptr->row_info.channels = png_ptr->usr_channels;
  195018. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  195019. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  195020. png_ptr->row_info.channels);
  195021. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  195022. png_ptr->row_info.width);
  195023. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  195024. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  195025. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  195026. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  195027. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  195028. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  195029. /* Copy user's row into buffer, leaving room for filter byte. */
  195030. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  195031. png_ptr->row_info.rowbytes);
  195032. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195033. /* handle interlacing */
  195034. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  195035. (png_ptr->transformations & PNG_INTERLACE))
  195036. {
  195037. png_do_write_interlace(&(png_ptr->row_info),
  195038. png_ptr->row_buf + 1, png_ptr->pass);
  195039. /* this should always get caught above, but still ... */
  195040. if (!(png_ptr->row_info.width))
  195041. {
  195042. png_write_finish_row(png_ptr);
  195043. return;
  195044. }
  195045. }
  195046. #endif
  195047. /* handle other transformations */
  195048. if (png_ptr->transformations)
  195049. png_do_write_transformations(png_ptr);
  195050. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195051. /* Write filter_method 64 (intrapixel differencing) only if
  195052. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  195053. * 2. Libpng did not write a PNG signature (this filter_method is only
  195054. * used in PNG datastreams that are embedded in MNG datastreams) and
  195055. * 3. The application called png_permit_mng_features with a mask that
  195056. * included PNG_FLAG_MNG_FILTER_64 and
  195057. * 4. The filter_method is 64 and
  195058. * 5. The color_type is RGB or RGBA
  195059. */
  195060. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195061. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  195062. {
  195063. /* Intrapixel differencing */
  195064. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195065. }
  195066. #endif
  195067. /* Find a filter if necessary, filter the row and write it out. */
  195068. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  195069. if (png_ptr->write_row_fn != NULL)
  195070. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  195071. }
  195072. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  195073. /* Set the automatic flush interval or 0 to turn flushing off */
  195074. void PNGAPI
  195075. png_set_flush(png_structp png_ptr, int nrows)
  195076. {
  195077. png_debug(1, "in png_set_flush\n");
  195078. if (png_ptr == NULL)
  195079. return;
  195080. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  195081. }
  195082. /* flush the current output buffers now */
  195083. void PNGAPI
  195084. png_write_flush(png_structp png_ptr)
  195085. {
  195086. int wrote_IDAT;
  195087. png_debug(1, "in png_write_flush\n");
  195088. if (png_ptr == NULL)
  195089. return;
  195090. /* We have already written out all of the data */
  195091. if (png_ptr->row_number >= png_ptr->num_rows)
  195092. return;
  195093. do
  195094. {
  195095. int ret;
  195096. /* compress the data */
  195097. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  195098. wrote_IDAT = 0;
  195099. /* check for compression errors */
  195100. if (ret != Z_OK)
  195101. {
  195102. if (png_ptr->zstream.msg != NULL)
  195103. png_error(png_ptr, png_ptr->zstream.msg);
  195104. else
  195105. png_error(png_ptr, "zlib error");
  195106. }
  195107. if (!(png_ptr->zstream.avail_out))
  195108. {
  195109. /* write the IDAT and reset the zlib output buffer */
  195110. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195111. png_ptr->zbuf_size);
  195112. png_ptr->zstream.next_out = png_ptr->zbuf;
  195113. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195114. wrote_IDAT = 1;
  195115. }
  195116. } while(wrote_IDAT == 1);
  195117. /* If there is any data left to be output, write it into a new IDAT */
  195118. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  195119. {
  195120. /* write the IDAT and reset the zlib output buffer */
  195121. png_write_IDAT(png_ptr, png_ptr->zbuf,
  195122. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  195123. png_ptr->zstream.next_out = png_ptr->zbuf;
  195124. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195125. }
  195126. png_ptr->flush_rows = 0;
  195127. png_flush(png_ptr);
  195128. }
  195129. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  195130. /* free all memory used by the write */
  195131. void PNGAPI
  195132. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  195133. {
  195134. png_structp png_ptr = NULL;
  195135. png_infop info_ptr = NULL;
  195136. #ifdef PNG_USER_MEM_SUPPORTED
  195137. png_free_ptr free_fn = NULL;
  195138. png_voidp mem_ptr = NULL;
  195139. #endif
  195140. png_debug(1, "in png_destroy_write_struct\n");
  195141. if (png_ptr_ptr != NULL)
  195142. {
  195143. png_ptr = *png_ptr_ptr;
  195144. #ifdef PNG_USER_MEM_SUPPORTED
  195145. free_fn = png_ptr->free_fn;
  195146. mem_ptr = png_ptr->mem_ptr;
  195147. #endif
  195148. }
  195149. if (info_ptr_ptr != NULL)
  195150. info_ptr = *info_ptr_ptr;
  195151. if (info_ptr != NULL)
  195152. {
  195153. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  195154. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  195155. if (png_ptr->num_chunk_list)
  195156. {
  195157. png_free(png_ptr, png_ptr->chunk_list);
  195158. png_ptr->chunk_list=NULL;
  195159. png_ptr->num_chunk_list=0;
  195160. }
  195161. #endif
  195162. #ifdef PNG_USER_MEM_SUPPORTED
  195163. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  195164. (png_voidp)mem_ptr);
  195165. #else
  195166. png_destroy_struct((png_voidp)info_ptr);
  195167. #endif
  195168. *info_ptr_ptr = NULL;
  195169. }
  195170. if (png_ptr != NULL)
  195171. {
  195172. png_write_destroy(png_ptr);
  195173. #ifdef PNG_USER_MEM_SUPPORTED
  195174. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  195175. (png_voidp)mem_ptr);
  195176. #else
  195177. png_destroy_struct((png_voidp)png_ptr);
  195178. #endif
  195179. *png_ptr_ptr = NULL;
  195180. }
  195181. }
  195182. /* Free any memory used in png_ptr struct (old method) */
  195183. void /* PRIVATE */
  195184. png_write_destroy(png_structp png_ptr)
  195185. {
  195186. #ifdef PNG_SETJMP_SUPPORTED
  195187. jmp_buf tmp_jmp; /* save jump buffer */
  195188. #endif
  195189. png_error_ptr error_fn;
  195190. png_error_ptr warning_fn;
  195191. png_voidp error_ptr;
  195192. #ifdef PNG_USER_MEM_SUPPORTED
  195193. png_free_ptr free_fn;
  195194. #endif
  195195. png_debug(1, "in png_write_destroy\n");
  195196. /* free any memory zlib uses */
  195197. deflateEnd(&png_ptr->zstream);
  195198. /* free our memory. png_free checks NULL for us. */
  195199. png_free(png_ptr, png_ptr->zbuf);
  195200. png_free(png_ptr, png_ptr->row_buf);
  195201. png_free(png_ptr, png_ptr->prev_row);
  195202. png_free(png_ptr, png_ptr->sub_row);
  195203. png_free(png_ptr, png_ptr->up_row);
  195204. png_free(png_ptr, png_ptr->avg_row);
  195205. png_free(png_ptr, png_ptr->paeth_row);
  195206. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  195207. png_free(png_ptr, png_ptr->time_buffer);
  195208. #endif
  195209. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195210. png_free(png_ptr, png_ptr->prev_filters);
  195211. png_free(png_ptr, png_ptr->filter_weights);
  195212. png_free(png_ptr, png_ptr->inv_filter_weights);
  195213. png_free(png_ptr, png_ptr->filter_costs);
  195214. png_free(png_ptr, png_ptr->inv_filter_costs);
  195215. #endif
  195216. #ifdef PNG_SETJMP_SUPPORTED
  195217. /* reset structure */
  195218. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  195219. #endif
  195220. error_fn = png_ptr->error_fn;
  195221. warning_fn = png_ptr->warning_fn;
  195222. error_ptr = png_ptr->error_ptr;
  195223. #ifdef PNG_USER_MEM_SUPPORTED
  195224. free_fn = png_ptr->free_fn;
  195225. #endif
  195226. png_memset(png_ptr, 0, png_sizeof (png_struct));
  195227. png_ptr->error_fn = error_fn;
  195228. png_ptr->warning_fn = warning_fn;
  195229. png_ptr->error_ptr = error_ptr;
  195230. #ifdef PNG_USER_MEM_SUPPORTED
  195231. png_ptr->free_fn = free_fn;
  195232. #endif
  195233. #ifdef PNG_SETJMP_SUPPORTED
  195234. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  195235. #endif
  195236. }
  195237. /* Allow the application to select one or more row filters to use. */
  195238. void PNGAPI
  195239. png_set_filter(png_structp png_ptr, int method, int filters)
  195240. {
  195241. png_debug(1, "in png_set_filter\n");
  195242. if (png_ptr == NULL)
  195243. return;
  195244. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195245. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  195246. (method == PNG_INTRAPIXEL_DIFFERENCING))
  195247. method = PNG_FILTER_TYPE_BASE;
  195248. #endif
  195249. if (method == PNG_FILTER_TYPE_BASE)
  195250. {
  195251. switch (filters & (PNG_ALL_FILTERS | 0x07))
  195252. {
  195253. #ifndef PNG_NO_WRITE_FILTER
  195254. case 5:
  195255. case 6:
  195256. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  195257. #endif /* PNG_NO_WRITE_FILTER */
  195258. case PNG_FILTER_VALUE_NONE:
  195259. png_ptr->do_filter=PNG_FILTER_NONE; break;
  195260. #ifndef PNG_NO_WRITE_FILTER
  195261. case PNG_FILTER_VALUE_SUB:
  195262. png_ptr->do_filter=PNG_FILTER_SUB; break;
  195263. case PNG_FILTER_VALUE_UP:
  195264. png_ptr->do_filter=PNG_FILTER_UP; break;
  195265. case PNG_FILTER_VALUE_AVG:
  195266. png_ptr->do_filter=PNG_FILTER_AVG; break;
  195267. case PNG_FILTER_VALUE_PAETH:
  195268. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  195269. default: png_ptr->do_filter = (png_byte)filters; break;
  195270. #else
  195271. default: png_warning(png_ptr, "Unknown row filter for method 0");
  195272. #endif /* PNG_NO_WRITE_FILTER */
  195273. }
  195274. /* If we have allocated the row_buf, this means we have already started
  195275. * with the image and we should have allocated all of the filter buffers
  195276. * that have been selected. If prev_row isn't already allocated, then
  195277. * it is too late to start using the filters that need it, since we
  195278. * will be missing the data in the previous row. If an application
  195279. * wants to start and stop using particular filters during compression,
  195280. * it should start out with all of the filters, and then add and
  195281. * remove them after the start of compression.
  195282. */
  195283. if (png_ptr->row_buf != NULL)
  195284. {
  195285. #ifndef PNG_NO_WRITE_FILTER
  195286. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  195287. {
  195288. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195289. (png_ptr->rowbytes + 1));
  195290. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195291. }
  195292. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  195293. {
  195294. if (png_ptr->prev_row == NULL)
  195295. {
  195296. png_warning(png_ptr, "Can't add Up filter after starting");
  195297. png_ptr->do_filter &= ~PNG_FILTER_UP;
  195298. }
  195299. else
  195300. {
  195301. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195302. (png_ptr->rowbytes + 1));
  195303. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195304. }
  195305. }
  195306. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  195307. {
  195308. if (png_ptr->prev_row == NULL)
  195309. {
  195310. png_warning(png_ptr, "Can't add Average filter after starting");
  195311. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  195312. }
  195313. else
  195314. {
  195315. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195316. (png_ptr->rowbytes + 1));
  195317. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195318. }
  195319. }
  195320. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  195321. png_ptr->paeth_row == NULL)
  195322. {
  195323. if (png_ptr->prev_row == NULL)
  195324. {
  195325. png_warning(png_ptr, "Can't add Paeth filter after starting");
  195326. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  195327. }
  195328. else
  195329. {
  195330. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195331. (png_ptr->rowbytes + 1));
  195332. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195333. }
  195334. }
  195335. if (png_ptr->do_filter == PNG_NO_FILTERS)
  195336. #endif /* PNG_NO_WRITE_FILTER */
  195337. png_ptr->do_filter = PNG_FILTER_NONE;
  195338. }
  195339. }
  195340. else
  195341. png_error(png_ptr, "Unknown custom filter method");
  195342. }
  195343. /* This allows us to influence the way in which libpng chooses the "best"
  195344. * filter for the current scanline. While the "minimum-sum-of-absolute-
  195345. * differences metric is relatively fast and effective, there is some
  195346. * question as to whether it can be improved upon by trying to keep the
  195347. * filtered data going to zlib more consistent, hopefully resulting in
  195348. * better compression.
  195349. */
  195350. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  195351. void PNGAPI
  195352. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  195353. int num_weights, png_doublep filter_weights,
  195354. png_doublep filter_costs)
  195355. {
  195356. int i;
  195357. png_debug(1, "in png_set_filter_heuristics\n");
  195358. if (png_ptr == NULL)
  195359. return;
  195360. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  195361. {
  195362. png_warning(png_ptr, "Unknown filter heuristic method");
  195363. return;
  195364. }
  195365. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  195366. {
  195367. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  195368. }
  195369. if (num_weights < 0 || filter_weights == NULL ||
  195370. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  195371. {
  195372. num_weights = 0;
  195373. }
  195374. png_ptr->num_prev_filters = (png_byte)num_weights;
  195375. png_ptr->heuristic_method = (png_byte)heuristic_method;
  195376. if (num_weights > 0)
  195377. {
  195378. if (png_ptr->prev_filters == NULL)
  195379. {
  195380. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  195381. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  195382. /* To make sure that the weighting starts out fairly */
  195383. for (i = 0; i < num_weights; i++)
  195384. {
  195385. png_ptr->prev_filters[i] = 255;
  195386. }
  195387. }
  195388. if (png_ptr->filter_weights == NULL)
  195389. {
  195390. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195391. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195392. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  195393. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  195394. for (i = 0; i < num_weights; i++)
  195395. {
  195396. png_ptr->inv_filter_weights[i] =
  195397. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195398. }
  195399. }
  195400. for (i = 0; i < num_weights; i++)
  195401. {
  195402. if (filter_weights[i] < 0.0)
  195403. {
  195404. png_ptr->inv_filter_weights[i] =
  195405. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  195406. }
  195407. else
  195408. {
  195409. png_ptr->inv_filter_weights[i] =
  195410. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  195411. png_ptr->filter_weights[i] =
  195412. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  195413. }
  195414. }
  195415. }
  195416. /* If, in the future, there are other filter methods, this would
  195417. * need to be based on png_ptr->filter.
  195418. */
  195419. if (png_ptr->filter_costs == NULL)
  195420. {
  195421. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195422. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195423. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  195424. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  195425. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195426. {
  195427. png_ptr->inv_filter_costs[i] =
  195428. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195429. }
  195430. }
  195431. /* Here is where we set the relative costs of the different filters. We
  195432. * should take the desired compression level into account when setting
  195433. * the costs, so that Paeth, for instance, has a high relative cost at low
  195434. * compression levels, while it has a lower relative cost at higher
  195435. * compression settings. The filter types are in order of increasing
  195436. * relative cost, so it would be possible to do this with an algorithm.
  195437. */
  195438. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  195439. {
  195440. if (filter_costs == NULL || filter_costs[i] < 0.0)
  195441. {
  195442. png_ptr->inv_filter_costs[i] =
  195443. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  195444. }
  195445. else if (filter_costs[i] >= 1.0)
  195446. {
  195447. png_ptr->inv_filter_costs[i] =
  195448. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  195449. png_ptr->filter_costs[i] =
  195450. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  195451. }
  195452. }
  195453. }
  195454. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  195455. void PNGAPI
  195456. png_set_compression_level(png_structp png_ptr, int level)
  195457. {
  195458. png_debug(1, "in png_set_compression_level\n");
  195459. if (png_ptr == NULL)
  195460. return;
  195461. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  195462. png_ptr->zlib_level = level;
  195463. }
  195464. void PNGAPI
  195465. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  195466. {
  195467. png_debug(1, "in png_set_compression_mem_level\n");
  195468. if (png_ptr == NULL)
  195469. return;
  195470. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  195471. png_ptr->zlib_mem_level = mem_level;
  195472. }
  195473. void PNGAPI
  195474. png_set_compression_strategy(png_structp png_ptr, int strategy)
  195475. {
  195476. png_debug(1, "in png_set_compression_strategy\n");
  195477. if (png_ptr == NULL)
  195478. return;
  195479. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  195480. png_ptr->zlib_strategy = strategy;
  195481. }
  195482. void PNGAPI
  195483. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  195484. {
  195485. if (png_ptr == NULL)
  195486. return;
  195487. if (window_bits > 15)
  195488. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  195489. else if (window_bits < 8)
  195490. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  195491. #ifndef WBITS_8_OK
  195492. /* avoid libpng bug with 256-byte windows */
  195493. if (window_bits == 8)
  195494. {
  195495. png_warning(png_ptr, "Compression window is being reset to 512");
  195496. window_bits=9;
  195497. }
  195498. #endif
  195499. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  195500. png_ptr->zlib_window_bits = window_bits;
  195501. }
  195502. void PNGAPI
  195503. png_set_compression_method(png_structp png_ptr, int method)
  195504. {
  195505. png_debug(1, "in png_set_compression_method\n");
  195506. if (png_ptr == NULL)
  195507. return;
  195508. if (method != 8)
  195509. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  195510. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  195511. png_ptr->zlib_method = method;
  195512. }
  195513. void PNGAPI
  195514. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  195515. {
  195516. if (png_ptr == NULL)
  195517. return;
  195518. png_ptr->write_row_fn = write_row_fn;
  195519. }
  195520. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195521. void PNGAPI
  195522. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  195523. write_user_transform_fn)
  195524. {
  195525. png_debug(1, "in png_set_write_user_transform_fn\n");
  195526. if (png_ptr == NULL)
  195527. return;
  195528. png_ptr->transformations |= PNG_USER_TRANSFORM;
  195529. png_ptr->write_user_transform_fn = write_user_transform_fn;
  195530. }
  195531. #endif
  195532. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  195533. void PNGAPI
  195534. png_write_png(png_structp png_ptr, png_infop info_ptr,
  195535. int transforms, voidp params)
  195536. {
  195537. if (png_ptr == NULL || info_ptr == NULL)
  195538. return;
  195539. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195540. /* invert the alpha channel from opacity to transparency */
  195541. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  195542. png_set_invert_alpha(png_ptr);
  195543. #endif
  195544. /* Write the file header information. */
  195545. png_write_info(png_ptr, info_ptr);
  195546. /* ------ these transformations don't touch the info structure ------- */
  195547. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195548. /* invert monochrome pixels */
  195549. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  195550. png_set_invert_mono(png_ptr);
  195551. #endif
  195552. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195553. /* Shift the pixels up to a legal bit depth and fill in
  195554. * as appropriate to correctly scale the image.
  195555. */
  195556. if ((transforms & PNG_TRANSFORM_SHIFT)
  195557. && (info_ptr->valid & PNG_INFO_sBIT))
  195558. png_set_shift(png_ptr, &info_ptr->sig_bit);
  195559. #endif
  195560. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195561. /* pack pixels into bytes */
  195562. if (transforms & PNG_TRANSFORM_PACKING)
  195563. png_set_packing(png_ptr);
  195564. #endif
  195565. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195566. /* swap location of alpha bytes from ARGB to RGBA */
  195567. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  195568. png_set_swap_alpha(png_ptr);
  195569. #endif
  195570. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195571. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  195572. * RGB (4 channels -> 3 channels). The second parameter is not used.
  195573. */
  195574. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  195575. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  195576. #endif
  195577. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195578. /* flip BGR pixels to RGB */
  195579. if (transforms & PNG_TRANSFORM_BGR)
  195580. png_set_bgr(png_ptr);
  195581. #endif
  195582. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195583. /* swap bytes of 16-bit files to most significant byte first */
  195584. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  195585. png_set_swap(png_ptr);
  195586. #endif
  195587. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195588. /* swap bits of 1, 2, 4 bit packed pixel formats */
  195589. if (transforms & PNG_TRANSFORM_PACKSWAP)
  195590. png_set_packswap(png_ptr);
  195591. #endif
  195592. /* ----------------------- end of transformations ------------------- */
  195593. /* write the bits */
  195594. if (info_ptr->valid & PNG_INFO_IDAT)
  195595. png_write_image(png_ptr, info_ptr->row_pointers);
  195596. /* It is REQUIRED to call this to finish writing the rest of the file */
  195597. png_write_end(png_ptr, info_ptr);
  195598. transforms = transforms; /* quiet compiler warnings */
  195599. params = params;
  195600. }
  195601. #endif
  195602. #endif /* PNG_WRITE_SUPPORTED */
  195603. /********* End of inlined file: pngwrite.c *********/
  195604. /********* Start of inlined file: pngwtran.c *********/
  195605. /* pngwtran.c - transforms the data in a row for PNG writers
  195606. *
  195607. * Last changed in libpng 1.2.9 April 14, 2006
  195608. * For conditions of distribution and use, see copyright notice in png.h
  195609. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  195610. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  195611. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  195612. */
  195613. #define PNG_INTERNAL
  195614. #ifdef PNG_WRITE_SUPPORTED
  195615. /* Transform the data according to the user's wishes. The order of
  195616. * transformations is significant.
  195617. */
  195618. void /* PRIVATE */
  195619. png_do_write_transformations(png_structp png_ptr)
  195620. {
  195621. png_debug(1, "in png_do_write_transformations\n");
  195622. if (png_ptr == NULL)
  195623. return;
  195624. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  195625. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  195626. if(png_ptr->write_user_transform_fn != NULL)
  195627. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  195628. (png_ptr, /* png_ptr */
  195629. &(png_ptr->row_info), /* row_info: */
  195630. /* png_uint_32 width; width of row */
  195631. /* png_uint_32 rowbytes; number of bytes in row */
  195632. /* png_byte color_type; color type of pixels */
  195633. /* png_byte bit_depth; bit depth of samples */
  195634. /* png_byte channels; number of channels (1-4) */
  195635. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  195636. png_ptr->row_buf + 1); /* start of pixel data for row */
  195637. #endif
  195638. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  195639. if (png_ptr->transformations & PNG_FILLER)
  195640. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195641. png_ptr->flags);
  195642. #endif
  195643. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  195644. if (png_ptr->transformations & PNG_PACKSWAP)
  195645. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195646. #endif
  195647. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195648. if (png_ptr->transformations & PNG_PACK)
  195649. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195650. (png_uint_32)png_ptr->bit_depth);
  195651. #endif
  195652. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  195653. if (png_ptr->transformations & PNG_SWAP_BYTES)
  195654. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195655. #endif
  195656. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195657. if (png_ptr->transformations & PNG_SHIFT)
  195658. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  195659. &(png_ptr->shift));
  195660. #endif
  195661. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195662. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  195663. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195664. #endif
  195665. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195666. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  195667. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195668. #endif
  195669. #if defined(PNG_WRITE_BGR_SUPPORTED)
  195670. if (png_ptr->transformations & PNG_BGR)
  195671. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195672. #endif
  195673. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  195674. if (png_ptr->transformations & PNG_INVERT_MONO)
  195675. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  195676. #endif
  195677. }
  195678. #if defined(PNG_WRITE_PACK_SUPPORTED)
  195679. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  195680. * row_info bit depth should be 8 (one pixel per byte). The channels
  195681. * should be 1 (this only happens on grayscale and paletted images).
  195682. */
  195683. void /* PRIVATE */
  195684. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  195685. {
  195686. png_debug(1, "in png_do_pack\n");
  195687. if (row_info->bit_depth == 8 &&
  195688. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195689. row != NULL && row_info != NULL &&
  195690. #endif
  195691. row_info->channels == 1)
  195692. {
  195693. switch ((int)bit_depth)
  195694. {
  195695. case 1:
  195696. {
  195697. png_bytep sp, dp;
  195698. int mask, v;
  195699. png_uint_32 i;
  195700. png_uint_32 row_width = row_info->width;
  195701. sp = row;
  195702. dp = row;
  195703. mask = 0x80;
  195704. v = 0;
  195705. for (i = 0; i < row_width; i++)
  195706. {
  195707. if (*sp != 0)
  195708. v |= mask;
  195709. sp++;
  195710. if (mask > 1)
  195711. mask >>= 1;
  195712. else
  195713. {
  195714. mask = 0x80;
  195715. *dp = (png_byte)v;
  195716. dp++;
  195717. v = 0;
  195718. }
  195719. }
  195720. if (mask != 0x80)
  195721. *dp = (png_byte)v;
  195722. break;
  195723. }
  195724. case 2:
  195725. {
  195726. png_bytep sp, dp;
  195727. int shift, v;
  195728. png_uint_32 i;
  195729. png_uint_32 row_width = row_info->width;
  195730. sp = row;
  195731. dp = row;
  195732. shift = 6;
  195733. v = 0;
  195734. for (i = 0; i < row_width; i++)
  195735. {
  195736. png_byte value;
  195737. value = (png_byte)(*sp & 0x03);
  195738. v |= (value << shift);
  195739. if (shift == 0)
  195740. {
  195741. shift = 6;
  195742. *dp = (png_byte)v;
  195743. dp++;
  195744. v = 0;
  195745. }
  195746. else
  195747. shift -= 2;
  195748. sp++;
  195749. }
  195750. if (shift != 6)
  195751. *dp = (png_byte)v;
  195752. break;
  195753. }
  195754. case 4:
  195755. {
  195756. png_bytep sp, dp;
  195757. int shift, v;
  195758. png_uint_32 i;
  195759. png_uint_32 row_width = row_info->width;
  195760. sp = row;
  195761. dp = row;
  195762. shift = 4;
  195763. v = 0;
  195764. for (i = 0; i < row_width; i++)
  195765. {
  195766. png_byte value;
  195767. value = (png_byte)(*sp & 0x0f);
  195768. v |= (value << shift);
  195769. if (shift == 0)
  195770. {
  195771. shift = 4;
  195772. *dp = (png_byte)v;
  195773. dp++;
  195774. v = 0;
  195775. }
  195776. else
  195777. shift -= 4;
  195778. sp++;
  195779. }
  195780. if (shift != 4)
  195781. *dp = (png_byte)v;
  195782. break;
  195783. }
  195784. }
  195785. row_info->bit_depth = (png_byte)bit_depth;
  195786. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  195787. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195788. row_info->width);
  195789. }
  195790. }
  195791. #endif
  195792. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  195793. /* Shift pixel values to take advantage of whole range. Pass the
  195794. * true number of bits in bit_depth. The row should be packed
  195795. * according to row_info->bit_depth. Thus, if you had a row of
  195796. * bit depth 4, but the pixels only had values from 0 to 7, you
  195797. * would pass 3 as bit_depth, and this routine would translate the
  195798. * data to 0 to 15.
  195799. */
  195800. void /* PRIVATE */
  195801. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  195802. {
  195803. png_debug(1, "in png_do_shift\n");
  195804. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195805. if (row != NULL && row_info != NULL &&
  195806. #else
  195807. if (
  195808. #endif
  195809. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  195810. {
  195811. int shift_start[4], shift_dec[4];
  195812. int channels = 0;
  195813. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  195814. {
  195815. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  195816. shift_dec[channels] = bit_depth->red;
  195817. channels++;
  195818. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  195819. shift_dec[channels] = bit_depth->green;
  195820. channels++;
  195821. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  195822. shift_dec[channels] = bit_depth->blue;
  195823. channels++;
  195824. }
  195825. else
  195826. {
  195827. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  195828. shift_dec[channels] = bit_depth->gray;
  195829. channels++;
  195830. }
  195831. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  195832. {
  195833. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  195834. shift_dec[channels] = bit_depth->alpha;
  195835. channels++;
  195836. }
  195837. /* with low row depths, could only be grayscale, so one channel */
  195838. if (row_info->bit_depth < 8)
  195839. {
  195840. png_bytep bp = row;
  195841. png_uint_32 i;
  195842. png_byte mask;
  195843. png_uint_32 row_bytes = row_info->rowbytes;
  195844. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  195845. mask = 0x55;
  195846. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  195847. mask = 0x11;
  195848. else
  195849. mask = 0xff;
  195850. for (i = 0; i < row_bytes; i++, bp++)
  195851. {
  195852. png_uint_16 v;
  195853. int j;
  195854. v = *bp;
  195855. *bp = 0;
  195856. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  195857. {
  195858. if (j > 0)
  195859. *bp |= (png_byte)((v << j) & 0xff);
  195860. else
  195861. *bp |= (png_byte)((v >> (-j)) & mask);
  195862. }
  195863. }
  195864. }
  195865. else if (row_info->bit_depth == 8)
  195866. {
  195867. png_bytep bp = row;
  195868. png_uint_32 i;
  195869. png_uint_32 istop = channels * row_info->width;
  195870. for (i = 0; i < istop; i++, bp++)
  195871. {
  195872. png_uint_16 v;
  195873. int j;
  195874. int c = (int)(i%channels);
  195875. v = *bp;
  195876. *bp = 0;
  195877. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195878. {
  195879. if (j > 0)
  195880. *bp |= (png_byte)((v << j) & 0xff);
  195881. else
  195882. *bp |= (png_byte)((v >> (-j)) & 0xff);
  195883. }
  195884. }
  195885. }
  195886. else
  195887. {
  195888. png_bytep bp;
  195889. png_uint_32 i;
  195890. png_uint_32 istop = channels * row_info->width;
  195891. for (bp = row, i = 0; i < istop; i++)
  195892. {
  195893. int c = (int)(i%channels);
  195894. png_uint_16 value, v;
  195895. int j;
  195896. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  195897. value = 0;
  195898. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  195899. {
  195900. if (j > 0)
  195901. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  195902. else
  195903. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  195904. }
  195905. *bp++ = (png_byte)(value >> 8);
  195906. *bp++ = (png_byte)(value & 0xff);
  195907. }
  195908. }
  195909. }
  195910. }
  195911. #endif
  195912. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  195913. void /* PRIVATE */
  195914. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  195915. {
  195916. png_debug(1, "in png_do_write_swap_alpha\n");
  195917. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195918. if (row != NULL && row_info != NULL)
  195919. #endif
  195920. {
  195921. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  195922. {
  195923. /* This converts from ARGB to RGBA */
  195924. if (row_info->bit_depth == 8)
  195925. {
  195926. png_bytep sp, dp;
  195927. png_uint_32 i;
  195928. png_uint_32 row_width = row_info->width;
  195929. for (i = 0, sp = dp = row; i < row_width; i++)
  195930. {
  195931. png_byte save = *(sp++);
  195932. *(dp++) = *(sp++);
  195933. *(dp++) = *(sp++);
  195934. *(dp++) = *(sp++);
  195935. *(dp++) = save;
  195936. }
  195937. }
  195938. /* This converts from AARRGGBB to RRGGBBAA */
  195939. else
  195940. {
  195941. png_bytep sp, dp;
  195942. png_uint_32 i;
  195943. png_uint_32 row_width = row_info->width;
  195944. for (i = 0, sp = dp = row; i < row_width; i++)
  195945. {
  195946. png_byte save[2];
  195947. save[0] = *(sp++);
  195948. save[1] = *(sp++);
  195949. *(dp++) = *(sp++);
  195950. *(dp++) = *(sp++);
  195951. *(dp++) = *(sp++);
  195952. *(dp++) = *(sp++);
  195953. *(dp++) = *(sp++);
  195954. *(dp++) = *(sp++);
  195955. *(dp++) = save[0];
  195956. *(dp++) = save[1];
  195957. }
  195958. }
  195959. }
  195960. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  195961. {
  195962. /* This converts from AG to GA */
  195963. if (row_info->bit_depth == 8)
  195964. {
  195965. png_bytep sp, dp;
  195966. png_uint_32 i;
  195967. png_uint_32 row_width = row_info->width;
  195968. for (i = 0, sp = dp = row; i < row_width; i++)
  195969. {
  195970. png_byte save = *(sp++);
  195971. *(dp++) = *(sp++);
  195972. *(dp++) = save;
  195973. }
  195974. }
  195975. /* This converts from AAGG to GGAA */
  195976. else
  195977. {
  195978. png_bytep sp, dp;
  195979. png_uint_32 i;
  195980. png_uint_32 row_width = row_info->width;
  195981. for (i = 0, sp = dp = row; i < row_width; i++)
  195982. {
  195983. png_byte save[2];
  195984. save[0] = *(sp++);
  195985. save[1] = *(sp++);
  195986. *(dp++) = *(sp++);
  195987. *(dp++) = *(sp++);
  195988. *(dp++) = save[0];
  195989. *(dp++) = save[1];
  195990. }
  195991. }
  195992. }
  195993. }
  195994. }
  195995. #endif
  195996. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  195997. void /* PRIVATE */
  195998. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  195999. {
  196000. png_debug(1, "in png_do_write_invert_alpha\n");
  196001. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196002. if (row != NULL && row_info != NULL)
  196003. #endif
  196004. {
  196005. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196006. {
  196007. /* This inverts the alpha channel in RGBA */
  196008. if (row_info->bit_depth == 8)
  196009. {
  196010. png_bytep sp, dp;
  196011. png_uint_32 i;
  196012. png_uint_32 row_width = row_info->width;
  196013. for (i = 0, sp = dp = row; i < row_width; i++)
  196014. {
  196015. /* does nothing
  196016. *(dp++) = *(sp++);
  196017. *(dp++) = *(sp++);
  196018. *(dp++) = *(sp++);
  196019. */
  196020. sp+=3; dp = sp;
  196021. *(dp++) = (png_byte)(255 - *(sp++));
  196022. }
  196023. }
  196024. /* This inverts the alpha channel in RRGGBBAA */
  196025. else
  196026. {
  196027. png_bytep sp, dp;
  196028. png_uint_32 i;
  196029. png_uint_32 row_width = row_info->width;
  196030. for (i = 0, sp = dp = row; i < row_width; i++)
  196031. {
  196032. /* does nothing
  196033. *(dp++) = *(sp++);
  196034. *(dp++) = *(sp++);
  196035. *(dp++) = *(sp++);
  196036. *(dp++) = *(sp++);
  196037. *(dp++) = *(sp++);
  196038. *(dp++) = *(sp++);
  196039. */
  196040. sp+=6; dp = sp;
  196041. *(dp++) = (png_byte)(255 - *(sp++));
  196042. *(dp++) = (png_byte)(255 - *(sp++));
  196043. }
  196044. }
  196045. }
  196046. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196047. {
  196048. /* This inverts the alpha channel in GA */
  196049. if (row_info->bit_depth == 8)
  196050. {
  196051. png_bytep sp, dp;
  196052. png_uint_32 i;
  196053. png_uint_32 row_width = row_info->width;
  196054. for (i = 0, sp = dp = row; i < row_width; i++)
  196055. {
  196056. *(dp++) = *(sp++);
  196057. *(dp++) = (png_byte)(255 - *(sp++));
  196058. }
  196059. }
  196060. /* This inverts the alpha channel in GGAA */
  196061. else
  196062. {
  196063. png_bytep sp, dp;
  196064. png_uint_32 i;
  196065. png_uint_32 row_width = row_info->width;
  196066. for (i = 0, sp = dp = row; i < row_width; i++)
  196067. {
  196068. /* does nothing
  196069. *(dp++) = *(sp++);
  196070. *(dp++) = *(sp++);
  196071. */
  196072. sp+=2; dp = sp;
  196073. *(dp++) = (png_byte)(255 - *(sp++));
  196074. *(dp++) = (png_byte)(255 - *(sp++));
  196075. }
  196076. }
  196077. }
  196078. }
  196079. }
  196080. #endif
  196081. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196082. /* undoes intrapixel differencing */
  196083. void /* PRIVATE */
  196084. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  196085. {
  196086. png_debug(1, "in png_do_write_intrapixel\n");
  196087. if (
  196088. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  196089. row != NULL && row_info != NULL &&
  196090. #endif
  196091. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  196092. {
  196093. int bytes_per_pixel;
  196094. png_uint_32 row_width = row_info->width;
  196095. if (row_info->bit_depth == 8)
  196096. {
  196097. png_bytep rp;
  196098. png_uint_32 i;
  196099. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196100. bytes_per_pixel = 3;
  196101. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196102. bytes_per_pixel = 4;
  196103. else
  196104. return;
  196105. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196106. {
  196107. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  196108. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  196109. }
  196110. }
  196111. else if (row_info->bit_depth == 16)
  196112. {
  196113. png_bytep rp;
  196114. png_uint_32 i;
  196115. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  196116. bytes_per_pixel = 6;
  196117. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196118. bytes_per_pixel = 8;
  196119. else
  196120. return;
  196121. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  196122. {
  196123. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  196124. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  196125. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  196126. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  196127. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  196128. *(rp ) = (png_byte)((red >> 8) & 0xff);
  196129. *(rp+1) = (png_byte)(red & 0xff);
  196130. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  196131. *(rp+5) = (png_byte)(blue & 0xff);
  196132. }
  196133. }
  196134. }
  196135. }
  196136. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  196137. #endif /* PNG_WRITE_SUPPORTED */
  196138. /********* End of inlined file: pngwtran.c *********/
  196139. /********* Start of inlined file: pngwutil.c *********/
  196140. /* pngwutil.c - utilities to write a PNG file
  196141. *
  196142. * Last changed in libpng 1.2.20 Septhember 3, 2007
  196143. * For conditions of distribution and use, see copyright notice in png.h
  196144. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196145. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196146. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196147. */
  196148. #define PNG_INTERNAL
  196149. #ifdef PNG_WRITE_SUPPORTED
  196150. /* Place a 32-bit number into a buffer in PNG byte order. We work
  196151. * with unsigned numbers for convenience, although one supported
  196152. * ancillary chunk uses signed (two's complement) numbers.
  196153. */
  196154. void PNGAPI
  196155. png_save_uint_32(png_bytep buf, png_uint_32 i)
  196156. {
  196157. buf[0] = (png_byte)((i >> 24) & 0xff);
  196158. buf[1] = (png_byte)((i >> 16) & 0xff);
  196159. buf[2] = (png_byte)((i >> 8) & 0xff);
  196160. buf[3] = (png_byte)(i & 0xff);
  196161. }
  196162. /* The png_save_int_32 function assumes integers are stored in two's
  196163. * complement format. If this isn't the case, then this routine needs to
  196164. * be modified to write data in two's complement format.
  196165. */
  196166. void PNGAPI
  196167. png_save_int_32(png_bytep buf, png_int_32 i)
  196168. {
  196169. buf[0] = (png_byte)((i >> 24) & 0xff);
  196170. buf[1] = (png_byte)((i >> 16) & 0xff);
  196171. buf[2] = (png_byte)((i >> 8) & 0xff);
  196172. buf[3] = (png_byte)(i & 0xff);
  196173. }
  196174. /* Place a 16-bit number into a buffer in PNG byte order.
  196175. * The parameter is declared unsigned int, not png_uint_16,
  196176. * just to avoid potential problems on pre-ANSI C compilers.
  196177. */
  196178. void PNGAPI
  196179. png_save_uint_16(png_bytep buf, unsigned int i)
  196180. {
  196181. buf[0] = (png_byte)((i >> 8) & 0xff);
  196182. buf[1] = (png_byte)(i & 0xff);
  196183. }
  196184. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  196185. * representing the chunk name. The array must be at least 4 bytes in
  196186. * length, and does not need to be null terminated. To be safe, pass the
  196187. * pre-defined chunk names here, and if you need a new one, define it
  196188. * where the others are defined. The length is the length of the data.
  196189. * All the data must be present. If that is not possible, use the
  196190. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  196191. * functions instead.
  196192. */
  196193. void PNGAPI
  196194. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  196195. png_bytep data, png_size_t length)
  196196. {
  196197. if(png_ptr == NULL) return;
  196198. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  196199. png_write_chunk_data(png_ptr, data, length);
  196200. png_write_chunk_end(png_ptr);
  196201. }
  196202. /* Write the start of a PNG chunk. The type is the chunk type.
  196203. * The total_length is the sum of the lengths of all the data you will be
  196204. * passing in png_write_chunk_data().
  196205. */
  196206. void PNGAPI
  196207. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  196208. png_uint_32 length)
  196209. {
  196210. png_byte buf[4];
  196211. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  196212. if(png_ptr == NULL) return;
  196213. /* write the length */
  196214. png_save_uint_32(buf, length);
  196215. png_write_data(png_ptr, buf, (png_size_t)4);
  196216. /* write the chunk name */
  196217. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  196218. /* reset the crc and run it over the chunk name */
  196219. png_reset_crc(png_ptr);
  196220. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  196221. }
  196222. /* Write the data of a PNG chunk started with png_write_chunk_start().
  196223. * Note that multiple calls to this function are allowed, and that the
  196224. * sum of the lengths from these calls *must* add up to the total_length
  196225. * given to png_write_chunk_start().
  196226. */
  196227. void PNGAPI
  196228. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  196229. {
  196230. /* write the data, and run the CRC over it */
  196231. if(png_ptr == NULL) return;
  196232. if (data != NULL && length > 0)
  196233. {
  196234. png_calculate_crc(png_ptr, data, length);
  196235. png_write_data(png_ptr, data, length);
  196236. }
  196237. }
  196238. /* Finish a chunk started with png_write_chunk_start(). */
  196239. void PNGAPI
  196240. png_write_chunk_end(png_structp png_ptr)
  196241. {
  196242. png_byte buf[4];
  196243. if(png_ptr == NULL) return;
  196244. /* write the crc */
  196245. png_save_uint_32(buf, png_ptr->crc);
  196246. png_write_data(png_ptr, buf, (png_size_t)4);
  196247. }
  196248. /* Simple function to write the signature. If we have already written
  196249. * the magic bytes of the signature, or more likely, the PNG stream is
  196250. * being embedded into another stream and doesn't need its own signature,
  196251. * we should call png_set_sig_bytes() to tell libpng how many of the
  196252. * bytes have already been written.
  196253. */
  196254. void /* PRIVATE */
  196255. png_write_sig(png_structp png_ptr)
  196256. {
  196257. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  196258. /* write the rest of the 8 byte signature */
  196259. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  196260. (png_size_t)8 - png_ptr->sig_bytes);
  196261. if(png_ptr->sig_bytes < 3)
  196262. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  196263. }
  196264. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  196265. /*
  196266. * This pair of functions encapsulates the operation of (a) compressing a
  196267. * text string, and (b) issuing it later as a series of chunk data writes.
  196268. * The compression_state structure is shared context for these functions
  196269. * set up by the caller in order to make the whole mess thread-safe.
  196270. */
  196271. typedef struct
  196272. {
  196273. char *input; /* the uncompressed input data */
  196274. int input_len; /* its length */
  196275. int num_output_ptr; /* number of output pointers used */
  196276. int max_output_ptr; /* size of output_ptr */
  196277. png_charpp output_ptr; /* array of pointers to output */
  196278. } compression_state;
  196279. /* compress given text into storage in the png_ptr structure */
  196280. static int /* PRIVATE */
  196281. png_text_compress(png_structp png_ptr,
  196282. png_charp text, png_size_t text_len, int compression,
  196283. compression_state *comp)
  196284. {
  196285. int ret;
  196286. comp->num_output_ptr = 0;
  196287. comp->max_output_ptr = 0;
  196288. comp->output_ptr = NULL;
  196289. comp->input = NULL;
  196290. comp->input_len = 0;
  196291. /* we may just want to pass the text right through */
  196292. if (compression == PNG_TEXT_COMPRESSION_NONE)
  196293. {
  196294. comp->input = text;
  196295. comp->input_len = text_len;
  196296. return((int)text_len);
  196297. }
  196298. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  196299. {
  196300. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  196301. char msg[50];
  196302. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  196303. png_warning(png_ptr, msg);
  196304. #else
  196305. png_warning(png_ptr, "Unknown compression type");
  196306. #endif
  196307. }
  196308. /* We can't write the chunk until we find out how much data we have,
  196309. * which means we need to run the compressor first and save the
  196310. * output. This shouldn't be a problem, as the vast majority of
  196311. * comments should be reasonable, but we will set up an array of
  196312. * malloc'd pointers to be sure.
  196313. *
  196314. * If we knew the application was well behaved, we could simplify this
  196315. * greatly by assuming we can always malloc an output buffer large
  196316. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  196317. * and malloc this directly. The only time this would be a bad idea is
  196318. * if we can't malloc more than 64K and we have 64K of random input
  196319. * data, or if the input string is incredibly large (although this
  196320. * wouldn't cause a failure, just a slowdown due to swapping).
  196321. */
  196322. /* set up the compression buffers */
  196323. png_ptr->zstream.avail_in = (uInt)text_len;
  196324. png_ptr->zstream.next_in = (Bytef *)text;
  196325. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196326. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  196327. /* this is the same compression loop as in png_write_row() */
  196328. do
  196329. {
  196330. /* compress the data */
  196331. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196332. if (ret != Z_OK)
  196333. {
  196334. /* error */
  196335. if (png_ptr->zstream.msg != NULL)
  196336. png_error(png_ptr, png_ptr->zstream.msg);
  196337. else
  196338. png_error(png_ptr, "zlib error");
  196339. }
  196340. /* check to see if we need more room */
  196341. if (!(png_ptr->zstream.avail_out))
  196342. {
  196343. /* make sure the output array has room */
  196344. if (comp->num_output_ptr >= comp->max_output_ptr)
  196345. {
  196346. int old_max;
  196347. old_max = comp->max_output_ptr;
  196348. comp->max_output_ptr = comp->num_output_ptr + 4;
  196349. if (comp->output_ptr != NULL)
  196350. {
  196351. png_charpp old_ptr;
  196352. old_ptr = comp->output_ptr;
  196353. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196354. (png_uint_32)(comp->max_output_ptr *
  196355. png_sizeof (png_charpp)));
  196356. png_memcpy(comp->output_ptr, old_ptr, old_max
  196357. * png_sizeof (png_charp));
  196358. png_free(png_ptr, old_ptr);
  196359. }
  196360. else
  196361. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196362. (png_uint_32)(comp->max_output_ptr *
  196363. png_sizeof (png_charp)));
  196364. }
  196365. /* save the data */
  196366. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  196367. (png_uint_32)png_ptr->zbuf_size);
  196368. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196369. png_ptr->zbuf_size);
  196370. comp->num_output_ptr++;
  196371. /* and reset the buffer */
  196372. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196373. png_ptr->zstream.next_out = png_ptr->zbuf;
  196374. }
  196375. /* continue until we don't have any more to compress */
  196376. } while (png_ptr->zstream.avail_in);
  196377. /* finish the compression */
  196378. do
  196379. {
  196380. /* tell zlib we are finished */
  196381. ret = deflate(&png_ptr->zstream, Z_FINISH);
  196382. if (ret == Z_OK)
  196383. {
  196384. /* check to see if we need more room */
  196385. if (!(png_ptr->zstream.avail_out))
  196386. {
  196387. /* check to make sure our output array has room */
  196388. if (comp->num_output_ptr >= comp->max_output_ptr)
  196389. {
  196390. int old_max;
  196391. old_max = comp->max_output_ptr;
  196392. comp->max_output_ptr = comp->num_output_ptr + 4;
  196393. if (comp->output_ptr != NULL)
  196394. {
  196395. png_charpp old_ptr;
  196396. old_ptr = comp->output_ptr;
  196397. /* This could be optimized to realloc() */
  196398. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196399. (png_uint_32)(comp->max_output_ptr *
  196400. png_sizeof (png_charpp)));
  196401. png_memcpy(comp->output_ptr, old_ptr,
  196402. old_max * png_sizeof (png_charp));
  196403. png_free(png_ptr, old_ptr);
  196404. }
  196405. else
  196406. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  196407. (png_uint_32)(comp->max_output_ptr *
  196408. png_sizeof (png_charp)));
  196409. }
  196410. /* save off the data */
  196411. comp->output_ptr[comp->num_output_ptr] =
  196412. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  196413. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  196414. png_ptr->zbuf_size);
  196415. comp->num_output_ptr++;
  196416. /* and reset the buffer pointers */
  196417. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196418. png_ptr->zstream.next_out = png_ptr->zbuf;
  196419. }
  196420. }
  196421. else if (ret != Z_STREAM_END)
  196422. {
  196423. /* we got an error */
  196424. if (png_ptr->zstream.msg != NULL)
  196425. png_error(png_ptr, png_ptr->zstream.msg);
  196426. else
  196427. png_error(png_ptr, "zlib error");
  196428. }
  196429. } while (ret != Z_STREAM_END);
  196430. /* text length is number of buffers plus last buffer */
  196431. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  196432. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  196433. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  196434. return((int)text_len);
  196435. }
  196436. /* ship the compressed text out via chunk writes */
  196437. static void /* PRIVATE */
  196438. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  196439. {
  196440. int i;
  196441. /* handle the no-compression case */
  196442. if (comp->input)
  196443. {
  196444. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  196445. (png_size_t)comp->input_len);
  196446. return;
  196447. }
  196448. /* write saved output buffers, if any */
  196449. for (i = 0; i < comp->num_output_ptr; i++)
  196450. {
  196451. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  196452. png_ptr->zbuf_size);
  196453. png_free(png_ptr, comp->output_ptr[i]);
  196454. comp->output_ptr[i]=NULL;
  196455. }
  196456. if (comp->max_output_ptr != 0)
  196457. png_free(png_ptr, comp->output_ptr);
  196458. comp->output_ptr=NULL;
  196459. /* write anything left in zbuf */
  196460. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  196461. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  196462. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  196463. /* reset zlib for another zTXt/iTXt or image data */
  196464. deflateReset(&png_ptr->zstream);
  196465. png_ptr->zstream.data_type = Z_BINARY;
  196466. }
  196467. #endif
  196468. /* Write the IHDR chunk, and update the png_struct with the necessary
  196469. * information. Note that the rest of this code depends upon this
  196470. * information being correct.
  196471. */
  196472. void /* PRIVATE */
  196473. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  196474. int bit_depth, int color_type, int compression_type, int filter_type,
  196475. int interlace_type)
  196476. {
  196477. #ifdef PNG_USE_LOCAL_ARRAYS
  196478. PNG_IHDR;
  196479. #endif
  196480. png_byte buf[13]; /* buffer to store the IHDR info */
  196481. png_debug(1, "in png_write_IHDR\n");
  196482. /* Check that we have valid input data from the application info */
  196483. switch (color_type)
  196484. {
  196485. case PNG_COLOR_TYPE_GRAY:
  196486. switch (bit_depth)
  196487. {
  196488. case 1:
  196489. case 2:
  196490. case 4:
  196491. case 8:
  196492. case 16: png_ptr->channels = 1; break;
  196493. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  196494. }
  196495. break;
  196496. case PNG_COLOR_TYPE_RGB:
  196497. if (bit_depth != 8 && bit_depth != 16)
  196498. png_error(png_ptr, "Invalid bit depth for RGB image");
  196499. png_ptr->channels = 3;
  196500. break;
  196501. case PNG_COLOR_TYPE_PALETTE:
  196502. switch (bit_depth)
  196503. {
  196504. case 1:
  196505. case 2:
  196506. case 4:
  196507. case 8: png_ptr->channels = 1; break;
  196508. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  196509. }
  196510. break;
  196511. case PNG_COLOR_TYPE_GRAY_ALPHA:
  196512. if (bit_depth != 8 && bit_depth != 16)
  196513. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  196514. png_ptr->channels = 2;
  196515. break;
  196516. case PNG_COLOR_TYPE_RGB_ALPHA:
  196517. if (bit_depth != 8 && bit_depth != 16)
  196518. png_error(png_ptr, "Invalid bit depth for RGBA image");
  196519. png_ptr->channels = 4;
  196520. break;
  196521. default:
  196522. png_error(png_ptr, "Invalid image color type specified");
  196523. }
  196524. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196525. {
  196526. png_warning(png_ptr, "Invalid compression type specified");
  196527. compression_type = PNG_COMPRESSION_TYPE_BASE;
  196528. }
  196529. /* Write filter_method 64 (intrapixel differencing) only if
  196530. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  196531. * 2. Libpng did not write a PNG signature (this filter_method is only
  196532. * used in PNG datastreams that are embedded in MNG datastreams) and
  196533. * 3. The application called png_permit_mng_features with a mask that
  196534. * included PNG_FLAG_MNG_FILTER_64 and
  196535. * 4. The filter_method is 64 and
  196536. * 5. The color_type is RGB or RGBA
  196537. */
  196538. if (
  196539. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196540. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  196541. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  196542. (color_type == PNG_COLOR_TYPE_RGB ||
  196543. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  196544. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  196545. #endif
  196546. filter_type != PNG_FILTER_TYPE_BASE)
  196547. {
  196548. png_warning(png_ptr, "Invalid filter type specified");
  196549. filter_type = PNG_FILTER_TYPE_BASE;
  196550. }
  196551. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  196552. if (interlace_type != PNG_INTERLACE_NONE &&
  196553. interlace_type != PNG_INTERLACE_ADAM7)
  196554. {
  196555. png_warning(png_ptr, "Invalid interlace type specified");
  196556. interlace_type = PNG_INTERLACE_ADAM7;
  196557. }
  196558. #else
  196559. interlace_type=PNG_INTERLACE_NONE;
  196560. #endif
  196561. /* save off the relevent information */
  196562. png_ptr->bit_depth = (png_byte)bit_depth;
  196563. png_ptr->color_type = (png_byte)color_type;
  196564. png_ptr->interlaced = (png_byte)interlace_type;
  196565. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196566. png_ptr->filter_type = (png_byte)filter_type;
  196567. #endif
  196568. png_ptr->compression_type = (png_byte)compression_type;
  196569. png_ptr->width = width;
  196570. png_ptr->height = height;
  196571. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  196572. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  196573. /* set the usr info, so any transformations can modify it */
  196574. png_ptr->usr_width = png_ptr->width;
  196575. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  196576. png_ptr->usr_channels = png_ptr->channels;
  196577. /* pack the header information into the buffer */
  196578. png_save_uint_32(buf, width);
  196579. png_save_uint_32(buf + 4, height);
  196580. buf[8] = (png_byte)bit_depth;
  196581. buf[9] = (png_byte)color_type;
  196582. buf[10] = (png_byte)compression_type;
  196583. buf[11] = (png_byte)filter_type;
  196584. buf[12] = (png_byte)interlace_type;
  196585. /* write the chunk */
  196586. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  196587. /* initialize zlib with PNG info */
  196588. png_ptr->zstream.zalloc = png_zalloc;
  196589. png_ptr->zstream.zfree = png_zfree;
  196590. png_ptr->zstream.opaque = (voidpf)png_ptr;
  196591. if (!(png_ptr->do_filter))
  196592. {
  196593. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  196594. png_ptr->bit_depth < 8)
  196595. png_ptr->do_filter = PNG_FILTER_NONE;
  196596. else
  196597. png_ptr->do_filter = PNG_ALL_FILTERS;
  196598. }
  196599. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  196600. {
  196601. if (png_ptr->do_filter != PNG_FILTER_NONE)
  196602. png_ptr->zlib_strategy = Z_FILTERED;
  196603. else
  196604. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  196605. }
  196606. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  196607. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  196608. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  196609. png_ptr->zlib_mem_level = 8;
  196610. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  196611. png_ptr->zlib_window_bits = 15;
  196612. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  196613. png_ptr->zlib_method = 8;
  196614. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  196615. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  196616. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  196617. png_error(png_ptr, "zlib failed to initialize compressor");
  196618. png_ptr->zstream.next_out = png_ptr->zbuf;
  196619. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196620. /* libpng is not interested in zstream.data_type */
  196621. /* set it to a predefined value, to avoid its evaluation inside zlib */
  196622. png_ptr->zstream.data_type = Z_BINARY;
  196623. png_ptr->mode = PNG_HAVE_IHDR;
  196624. }
  196625. /* write the palette. We are careful not to trust png_color to be in the
  196626. * correct order for PNG, so people can redefine it to any convenient
  196627. * structure.
  196628. */
  196629. void /* PRIVATE */
  196630. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  196631. {
  196632. #ifdef PNG_USE_LOCAL_ARRAYS
  196633. PNG_PLTE;
  196634. #endif
  196635. png_uint_32 i;
  196636. png_colorp pal_ptr;
  196637. png_byte buf[3];
  196638. png_debug(1, "in png_write_PLTE\n");
  196639. if ((
  196640. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  196641. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  196642. #endif
  196643. num_pal == 0) || num_pal > 256)
  196644. {
  196645. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196646. {
  196647. png_error(png_ptr, "Invalid number of colors in palette");
  196648. }
  196649. else
  196650. {
  196651. png_warning(png_ptr, "Invalid number of colors in palette");
  196652. return;
  196653. }
  196654. }
  196655. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  196656. {
  196657. png_warning(png_ptr,
  196658. "Ignoring request to write a PLTE chunk in grayscale PNG");
  196659. return;
  196660. }
  196661. png_ptr->num_palette = (png_uint_16)num_pal;
  196662. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  196663. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  196664. #ifndef PNG_NO_POINTER_INDEXING
  196665. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  196666. {
  196667. buf[0] = pal_ptr->red;
  196668. buf[1] = pal_ptr->green;
  196669. buf[2] = pal_ptr->blue;
  196670. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196671. }
  196672. #else
  196673. /* This is a little slower but some buggy compilers need to do this instead */
  196674. pal_ptr=palette;
  196675. for (i = 0; i < num_pal; i++)
  196676. {
  196677. buf[0] = pal_ptr[i].red;
  196678. buf[1] = pal_ptr[i].green;
  196679. buf[2] = pal_ptr[i].blue;
  196680. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  196681. }
  196682. #endif
  196683. png_write_chunk_end(png_ptr);
  196684. png_ptr->mode |= PNG_HAVE_PLTE;
  196685. }
  196686. /* write an IDAT chunk */
  196687. void /* PRIVATE */
  196688. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  196689. {
  196690. #ifdef PNG_USE_LOCAL_ARRAYS
  196691. PNG_IDAT;
  196692. #endif
  196693. png_debug(1, "in png_write_IDAT\n");
  196694. /* Optimize the CMF field in the zlib stream. */
  196695. /* This hack of the zlib stream is compliant to the stream specification. */
  196696. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  196697. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  196698. {
  196699. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  196700. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  196701. {
  196702. /* Avoid memory underflows and multiplication overflows. */
  196703. /* The conditions below are practically always satisfied;
  196704. however, they still must be checked. */
  196705. if (length >= 2 &&
  196706. png_ptr->height < 16384 && png_ptr->width < 16384)
  196707. {
  196708. png_uint_32 uncompressed_idat_size = png_ptr->height *
  196709. ((png_ptr->width *
  196710. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  196711. unsigned int z_cinfo = z_cmf >> 4;
  196712. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  196713. while (uncompressed_idat_size <= half_z_window_size &&
  196714. half_z_window_size >= 256)
  196715. {
  196716. z_cinfo--;
  196717. half_z_window_size >>= 1;
  196718. }
  196719. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  196720. if (data[0] != (png_byte)z_cmf)
  196721. {
  196722. data[0] = (png_byte)z_cmf;
  196723. data[1] &= 0xe0;
  196724. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  196725. }
  196726. }
  196727. }
  196728. else
  196729. png_error(png_ptr,
  196730. "Invalid zlib compression method or flags in IDAT");
  196731. }
  196732. png_write_chunk(png_ptr, png_IDAT, data, length);
  196733. png_ptr->mode |= PNG_HAVE_IDAT;
  196734. }
  196735. /* write an IEND chunk */
  196736. void /* PRIVATE */
  196737. png_write_IEND(png_structp png_ptr)
  196738. {
  196739. #ifdef PNG_USE_LOCAL_ARRAYS
  196740. PNG_IEND;
  196741. #endif
  196742. png_debug(1, "in png_write_IEND\n");
  196743. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  196744. (png_size_t)0);
  196745. png_ptr->mode |= PNG_HAVE_IEND;
  196746. }
  196747. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  196748. /* write a gAMA chunk */
  196749. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196750. void /* PRIVATE */
  196751. png_write_gAMA(png_structp png_ptr, double file_gamma)
  196752. {
  196753. #ifdef PNG_USE_LOCAL_ARRAYS
  196754. PNG_gAMA;
  196755. #endif
  196756. png_uint_32 igamma;
  196757. png_byte buf[4];
  196758. png_debug(1, "in png_write_gAMA\n");
  196759. /* file_gamma is saved in 1/100,000ths */
  196760. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  196761. png_save_uint_32(buf, igamma);
  196762. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196763. }
  196764. #endif
  196765. #ifdef PNG_FIXED_POINT_SUPPORTED
  196766. void /* PRIVATE */
  196767. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  196768. {
  196769. #ifdef PNG_USE_LOCAL_ARRAYS
  196770. PNG_gAMA;
  196771. #endif
  196772. png_byte buf[4];
  196773. png_debug(1, "in png_write_gAMA\n");
  196774. /* file_gamma is saved in 1/100,000ths */
  196775. png_save_uint_32(buf, (png_uint_32)file_gamma);
  196776. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  196777. }
  196778. #endif
  196779. #endif
  196780. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  196781. /* write a sRGB chunk */
  196782. void /* PRIVATE */
  196783. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  196784. {
  196785. #ifdef PNG_USE_LOCAL_ARRAYS
  196786. PNG_sRGB;
  196787. #endif
  196788. png_byte buf[1];
  196789. png_debug(1, "in png_write_sRGB\n");
  196790. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  196791. png_warning(png_ptr,
  196792. "Invalid sRGB rendering intent specified");
  196793. buf[0]=(png_byte)srgb_intent;
  196794. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  196795. }
  196796. #endif
  196797. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  196798. /* write an iCCP chunk */
  196799. void /* PRIVATE */
  196800. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  196801. png_charp profile, int profile_len)
  196802. {
  196803. #ifdef PNG_USE_LOCAL_ARRAYS
  196804. PNG_iCCP;
  196805. #endif
  196806. png_size_t name_len;
  196807. png_charp new_name;
  196808. compression_state comp;
  196809. int embedded_profile_len = 0;
  196810. png_debug(1, "in png_write_iCCP\n");
  196811. comp.num_output_ptr = 0;
  196812. comp.max_output_ptr = 0;
  196813. comp.output_ptr = NULL;
  196814. comp.input = NULL;
  196815. comp.input_len = 0;
  196816. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  196817. &new_name)) == 0)
  196818. {
  196819. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  196820. return;
  196821. }
  196822. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  196823. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  196824. if (profile == NULL)
  196825. profile_len = 0;
  196826. if (profile_len > 3)
  196827. embedded_profile_len =
  196828. ((*( (png_bytep)profile ))<<24) |
  196829. ((*( (png_bytep)profile+1))<<16) |
  196830. ((*( (png_bytep)profile+2))<< 8) |
  196831. ((*( (png_bytep)profile+3)) );
  196832. if (profile_len < embedded_profile_len)
  196833. {
  196834. png_warning(png_ptr,
  196835. "Embedded profile length too large in iCCP chunk");
  196836. return;
  196837. }
  196838. if (profile_len > embedded_profile_len)
  196839. {
  196840. png_warning(png_ptr,
  196841. "Truncating profile to actual length in iCCP chunk");
  196842. profile_len = embedded_profile_len;
  196843. }
  196844. if (profile_len)
  196845. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  196846. PNG_COMPRESSION_TYPE_BASE, &comp);
  196847. /* make sure we include the NULL after the name and the compression type */
  196848. png_write_chunk_start(png_ptr, png_iCCP,
  196849. (png_uint_32)name_len+profile_len+2);
  196850. new_name[name_len+1]=0x00;
  196851. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  196852. if (profile_len)
  196853. png_write_compressed_data_out(png_ptr, &comp);
  196854. png_write_chunk_end(png_ptr);
  196855. png_free(png_ptr, new_name);
  196856. }
  196857. #endif
  196858. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  196859. /* write a sPLT chunk */
  196860. void /* PRIVATE */
  196861. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  196862. {
  196863. #ifdef PNG_USE_LOCAL_ARRAYS
  196864. PNG_sPLT;
  196865. #endif
  196866. png_size_t name_len;
  196867. png_charp new_name;
  196868. png_byte entrybuf[10];
  196869. int entry_size = (spalette->depth == 8 ? 6 : 10);
  196870. int palette_size = entry_size * spalette->nentries;
  196871. png_sPLT_entryp ep;
  196872. #ifdef PNG_NO_POINTER_INDEXING
  196873. int i;
  196874. #endif
  196875. png_debug(1, "in png_write_sPLT\n");
  196876. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  196877. spalette->name, &new_name))==0)
  196878. {
  196879. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  196880. return;
  196881. }
  196882. /* make sure we include the NULL after the name */
  196883. png_write_chunk_start(png_ptr, png_sPLT,
  196884. (png_uint_32)(name_len + 2 + palette_size));
  196885. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  196886. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  196887. /* loop through each palette entry, writing appropriately */
  196888. #ifndef PNG_NO_POINTER_INDEXING
  196889. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  196890. {
  196891. if (spalette->depth == 8)
  196892. {
  196893. entrybuf[0] = (png_byte)ep->red;
  196894. entrybuf[1] = (png_byte)ep->green;
  196895. entrybuf[2] = (png_byte)ep->blue;
  196896. entrybuf[3] = (png_byte)ep->alpha;
  196897. png_save_uint_16(entrybuf + 4, ep->frequency);
  196898. }
  196899. else
  196900. {
  196901. png_save_uint_16(entrybuf + 0, ep->red);
  196902. png_save_uint_16(entrybuf + 2, ep->green);
  196903. png_save_uint_16(entrybuf + 4, ep->blue);
  196904. png_save_uint_16(entrybuf + 6, ep->alpha);
  196905. png_save_uint_16(entrybuf + 8, ep->frequency);
  196906. }
  196907. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  196908. }
  196909. #else
  196910. ep=spalette->entries;
  196911. for (i=0; i>spalette->nentries; i++)
  196912. {
  196913. if (spalette->depth == 8)
  196914. {
  196915. entrybuf[0] = (png_byte)ep[i].red;
  196916. entrybuf[1] = (png_byte)ep[i].green;
  196917. entrybuf[2] = (png_byte)ep[i].blue;
  196918. entrybuf[3] = (png_byte)ep[i].alpha;
  196919. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  196920. }
  196921. else
  196922. {
  196923. png_save_uint_16(entrybuf + 0, ep[i].red);
  196924. png_save_uint_16(entrybuf + 2, ep[i].green);
  196925. png_save_uint_16(entrybuf + 4, ep[i].blue);
  196926. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  196927. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  196928. }
  196929. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  196930. }
  196931. #endif
  196932. png_write_chunk_end(png_ptr);
  196933. png_free(png_ptr, new_name);
  196934. }
  196935. #endif
  196936. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  196937. /* write the sBIT chunk */
  196938. void /* PRIVATE */
  196939. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  196940. {
  196941. #ifdef PNG_USE_LOCAL_ARRAYS
  196942. PNG_sBIT;
  196943. #endif
  196944. png_byte buf[4];
  196945. png_size_t size;
  196946. png_debug(1, "in png_write_sBIT\n");
  196947. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  196948. if (color_type & PNG_COLOR_MASK_COLOR)
  196949. {
  196950. png_byte maxbits;
  196951. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  196952. png_ptr->usr_bit_depth);
  196953. if (sbit->red == 0 || sbit->red > maxbits ||
  196954. sbit->green == 0 || sbit->green > maxbits ||
  196955. sbit->blue == 0 || sbit->blue > maxbits)
  196956. {
  196957. png_warning(png_ptr, "Invalid sBIT depth specified");
  196958. return;
  196959. }
  196960. buf[0] = sbit->red;
  196961. buf[1] = sbit->green;
  196962. buf[2] = sbit->blue;
  196963. size = 3;
  196964. }
  196965. else
  196966. {
  196967. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  196968. {
  196969. png_warning(png_ptr, "Invalid sBIT depth specified");
  196970. return;
  196971. }
  196972. buf[0] = sbit->gray;
  196973. size = 1;
  196974. }
  196975. if (color_type & PNG_COLOR_MASK_ALPHA)
  196976. {
  196977. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  196978. {
  196979. png_warning(png_ptr, "Invalid sBIT depth specified");
  196980. return;
  196981. }
  196982. buf[size++] = sbit->alpha;
  196983. }
  196984. png_write_chunk(png_ptr, png_sBIT, buf, size);
  196985. }
  196986. #endif
  196987. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  196988. /* write the cHRM chunk */
  196989. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196990. void /* PRIVATE */
  196991. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  196992. double red_x, double red_y, double green_x, double green_y,
  196993. double blue_x, double blue_y)
  196994. {
  196995. #ifdef PNG_USE_LOCAL_ARRAYS
  196996. PNG_cHRM;
  196997. #endif
  196998. png_byte buf[32];
  196999. png_uint_32 itemp;
  197000. png_debug(1, "in png_write_cHRM\n");
  197001. /* each value is saved in 1/100,000ths */
  197002. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  197003. white_x + white_y > 1.0)
  197004. {
  197005. png_warning(png_ptr, "Invalid cHRM white point specified");
  197006. #if !defined(PNG_NO_CONSOLE_IO)
  197007. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  197008. #endif
  197009. return;
  197010. }
  197011. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  197012. png_save_uint_32(buf, itemp);
  197013. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  197014. png_save_uint_32(buf + 4, itemp);
  197015. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  197016. {
  197017. png_warning(png_ptr, "Invalid cHRM red point specified");
  197018. return;
  197019. }
  197020. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  197021. png_save_uint_32(buf + 8, itemp);
  197022. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  197023. png_save_uint_32(buf + 12, itemp);
  197024. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  197025. {
  197026. png_warning(png_ptr, "Invalid cHRM green point specified");
  197027. return;
  197028. }
  197029. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  197030. png_save_uint_32(buf + 16, itemp);
  197031. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  197032. png_save_uint_32(buf + 20, itemp);
  197033. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  197034. {
  197035. png_warning(png_ptr, "Invalid cHRM blue point specified");
  197036. return;
  197037. }
  197038. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  197039. png_save_uint_32(buf + 24, itemp);
  197040. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  197041. png_save_uint_32(buf + 28, itemp);
  197042. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197043. }
  197044. #endif
  197045. #ifdef PNG_FIXED_POINT_SUPPORTED
  197046. void /* PRIVATE */
  197047. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  197048. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  197049. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  197050. png_fixed_point blue_y)
  197051. {
  197052. #ifdef PNG_USE_LOCAL_ARRAYS
  197053. PNG_cHRM;
  197054. #endif
  197055. png_byte buf[32];
  197056. png_debug(1, "in png_write_cHRM\n");
  197057. /* each value is saved in 1/100,000ths */
  197058. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  197059. {
  197060. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  197061. #if !defined(PNG_NO_CONSOLE_IO)
  197062. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  197063. #endif
  197064. return;
  197065. }
  197066. png_save_uint_32(buf, (png_uint_32)white_x);
  197067. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  197068. if (red_x + red_y > 100000L)
  197069. {
  197070. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  197071. return;
  197072. }
  197073. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  197074. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  197075. if (green_x + green_y > 100000L)
  197076. {
  197077. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  197078. return;
  197079. }
  197080. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  197081. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  197082. if (blue_x + blue_y > 100000L)
  197083. {
  197084. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  197085. return;
  197086. }
  197087. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  197088. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  197089. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  197090. }
  197091. #endif
  197092. #endif
  197093. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  197094. /* write the tRNS chunk */
  197095. void /* PRIVATE */
  197096. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  197097. int num_trans, int color_type)
  197098. {
  197099. #ifdef PNG_USE_LOCAL_ARRAYS
  197100. PNG_tRNS;
  197101. #endif
  197102. png_byte buf[6];
  197103. png_debug(1, "in png_write_tRNS\n");
  197104. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197105. {
  197106. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  197107. {
  197108. png_warning(png_ptr,"Invalid number of transparent colors specified");
  197109. return;
  197110. }
  197111. /* write the chunk out as it is */
  197112. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  197113. }
  197114. else if (color_type == PNG_COLOR_TYPE_GRAY)
  197115. {
  197116. /* one 16 bit value */
  197117. if(tran->gray >= (1 << png_ptr->bit_depth))
  197118. {
  197119. png_warning(png_ptr,
  197120. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  197121. return;
  197122. }
  197123. png_save_uint_16(buf, tran->gray);
  197124. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  197125. }
  197126. else if (color_type == PNG_COLOR_TYPE_RGB)
  197127. {
  197128. /* three 16 bit values */
  197129. png_save_uint_16(buf, tran->red);
  197130. png_save_uint_16(buf + 2, tran->green);
  197131. png_save_uint_16(buf + 4, tran->blue);
  197132. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197133. {
  197134. png_warning(png_ptr,
  197135. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  197136. return;
  197137. }
  197138. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  197139. }
  197140. else
  197141. {
  197142. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  197143. }
  197144. }
  197145. #endif
  197146. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  197147. /* write the background chunk */
  197148. void /* PRIVATE */
  197149. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  197150. {
  197151. #ifdef PNG_USE_LOCAL_ARRAYS
  197152. PNG_bKGD;
  197153. #endif
  197154. png_byte buf[6];
  197155. png_debug(1, "in png_write_bKGD\n");
  197156. if (color_type == PNG_COLOR_TYPE_PALETTE)
  197157. {
  197158. if (
  197159. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197160. (png_ptr->num_palette ||
  197161. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  197162. #endif
  197163. back->index > png_ptr->num_palette)
  197164. {
  197165. png_warning(png_ptr, "Invalid background palette index");
  197166. return;
  197167. }
  197168. buf[0] = back->index;
  197169. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  197170. }
  197171. else if (color_type & PNG_COLOR_MASK_COLOR)
  197172. {
  197173. png_save_uint_16(buf, back->red);
  197174. png_save_uint_16(buf + 2, back->green);
  197175. png_save_uint_16(buf + 4, back->blue);
  197176. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  197177. {
  197178. png_warning(png_ptr,
  197179. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  197180. return;
  197181. }
  197182. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  197183. }
  197184. else
  197185. {
  197186. if(back->gray >= (1 << png_ptr->bit_depth))
  197187. {
  197188. png_warning(png_ptr,
  197189. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  197190. return;
  197191. }
  197192. png_save_uint_16(buf, back->gray);
  197193. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  197194. }
  197195. }
  197196. #endif
  197197. #if defined(PNG_WRITE_hIST_SUPPORTED)
  197198. /* write the histogram */
  197199. void /* PRIVATE */
  197200. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  197201. {
  197202. #ifdef PNG_USE_LOCAL_ARRAYS
  197203. PNG_hIST;
  197204. #endif
  197205. int i;
  197206. png_byte buf[3];
  197207. png_debug(1, "in png_write_hIST\n");
  197208. if (num_hist > (int)png_ptr->num_palette)
  197209. {
  197210. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  197211. png_ptr->num_palette);
  197212. png_warning(png_ptr, "Invalid number of histogram entries specified");
  197213. return;
  197214. }
  197215. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  197216. for (i = 0; i < num_hist; i++)
  197217. {
  197218. png_save_uint_16(buf, hist[i]);
  197219. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  197220. }
  197221. png_write_chunk_end(png_ptr);
  197222. }
  197223. #endif
  197224. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  197225. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  197226. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  197227. * and if invalid, correct the keyword rather than discarding the entire
  197228. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  197229. * length, forbids leading or trailing whitespace, multiple internal spaces,
  197230. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  197231. *
  197232. * The new_key is allocated to hold the corrected keyword and must be freed
  197233. * by the calling routine. This avoids problems with trying to write to
  197234. * static keywords without having to have duplicate copies of the strings.
  197235. */
  197236. png_size_t /* PRIVATE */
  197237. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  197238. {
  197239. png_size_t key_len;
  197240. png_charp kp, dp;
  197241. int kflag;
  197242. int kwarn=0;
  197243. png_debug(1, "in png_check_keyword\n");
  197244. *new_key = NULL;
  197245. if (key == NULL || (key_len = png_strlen(key)) == 0)
  197246. {
  197247. png_warning(png_ptr, "zero length keyword");
  197248. return ((png_size_t)0);
  197249. }
  197250. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  197251. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  197252. if (*new_key == NULL)
  197253. {
  197254. png_warning(png_ptr, "Out of memory while procesing keyword");
  197255. return ((png_size_t)0);
  197256. }
  197257. /* Replace non-printing characters with a blank and print a warning */
  197258. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  197259. {
  197260. if ((png_byte)*kp < 0x20 ||
  197261. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  197262. {
  197263. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  197264. char msg[40];
  197265. png_snprintf(msg, 40,
  197266. "invalid keyword character 0x%02X", (png_byte)*kp);
  197267. png_warning(png_ptr, msg);
  197268. #else
  197269. png_warning(png_ptr, "invalid character in keyword");
  197270. #endif
  197271. *dp = ' ';
  197272. }
  197273. else
  197274. {
  197275. *dp = *kp;
  197276. }
  197277. }
  197278. *dp = '\0';
  197279. /* Remove any trailing white space. */
  197280. kp = *new_key + key_len - 1;
  197281. if (*kp == ' ')
  197282. {
  197283. png_warning(png_ptr, "trailing spaces removed from keyword");
  197284. while (*kp == ' ')
  197285. {
  197286. *(kp--) = '\0';
  197287. key_len--;
  197288. }
  197289. }
  197290. /* Remove any leading white space. */
  197291. kp = *new_key;
  197292. if (*kp == ' ')
  197293. {
  197294. png_warning(png_ptr, "leading spaces removed from keyword");
  197295. while (*kp == ' ')
  197296. {
  197297. kp++;
  197298. key_len--;
  197299. }
  197300. }
  197301. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  197302. /* Remove multiple internal spaces. */
  197303. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  197304. {
  197305. if (*kp == ' ' && kflag == 0)
  197306. {
  197307. *(dp++) = *kp;
  197308. kflag = 1;
  197309. }
  197310. else if (*kp == ' ')
  197311. {
  197312. key_len--;
  197313. kwarn=1;
  197314. }
  197315. else
  197316. {
  197317. *(dp++) = *kp;
  197318. kflag = 0;
  197319. }
  197320. }
  197321. *dp = '\0';
  197322. if(kwarn)
  197323. png_warning(png_ptr, "extra interior spaces removed from keyword");
  197324. if (key_len == 0)
  197325. {
  197326. png_free(png_ptr, *new_key);
  197327. *new_key=NULL;
  197328. png_warning(png_ptr, "Zero length keyword");
  197329. }
  197330. if (key_len > 79)
  197331. {
  197332. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  197333. new_key[79] = '\0';
  197334. key_len = 79;
  197335. }
  197336. return (key_len);
  197337. }
  197338. #endif
  197339. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  197340. /* write a tEXt chunk */
  197341. void /* PRIVATE */
  197342. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  197343. png_size_t text_len)
  197344. {
  197345. #ifdef PNG_USE_LOCAL_ARRAYS
  197346. PNG_tEXt;
  197347. #endif
  197348. png_size_t key_len;
  197349. png_charp new_key;
  197350. png_debug(1, "in png_write_tEXt\n");
  197351. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197352. {
  197353. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  197354. return;
  197355. }
  197356. if (text == NULL || *text == '\0')
  197357. text_len = 0;
  197358. else
  197359. text_len = png_strlen(text);
  197360. /* make sure we include the 0 after the key */
  197361. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  197362. /*
  197363. * We leave it to the application to meet PNG-1.0 requirements on the
  197364. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197365. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197366. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197367. */
  197368. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197369. if (text_len)
  197370. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  197371. png_write_chunk_end(png_ptr);
  197372. png_free(png_ptr, new_key);
  197373. }
  197374. #endif
  197375. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  197376. /* write a compressed text chunk */
  197377. void /* PRIVATE */
  197378. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  197379. png_size_t text_len, int compression)
  197380. {
  197381. #ifdef PNG_USE_LOCAL_ARRAYS
  197382. PNG_zTXt;
  197383. #endif
  197384. png_size_t key_len;
  197385. char buf[1];
  197386. png_charp new_key;
  197387. compression_state comp;
  197388. png_debug(1, "in png_write_zTXt\n");
  197389. comp.num_output_ptr = 0;
  197390. comp.max_output_ptr = 0;
  197391. comp.output_ptr = NULL;
  197392. comp.input = NULL;
  197393. comp.input_len = 0;
  197394. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197395. {
  197396. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  197397. return;
  197398. }
  197399. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  197400. {
  197401. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  197402. png_free(png_ptr, new_key);
  197403. return;
  197404. }
  197405. text_len = png_strlen(text);
  197406. /* compute the compressed data; do it now for the length */
  197407. text_len = png_text_compress(png_ptr, text, text_len, compression,
  197408. &comp);
  197409. /* write start of chunk */
  197410. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  197411. (key_len+text_len+2));
  197412. /* write key */
  197413. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197414. png_free(png_ptr, new_key);
  197415. buf[0] = (png_byte)compression;
  197416. /* write compression */
  197417. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  197418. /* write the compressed data */
  197419. png_write_compressed_data_out(png_ptr, &comp);
  197420. /* close the chunk */
  197421. png_write_chunk_end(png_ptr);
  197422. }
  197423. #endif
  197424. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  197425. /* write an iTXt chunk */
  197426. void /* PRIVATE */
  197427. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  197428. png_charp lang, png_charp lang_key, png_charp text)
  197429. {
  197430. #ifdef PNG_USE_LOCAL_ARRAYS
  197431. PNG_iTXt;
  197432. #endif
  197433. png_size_t lang_len, key_len, lang_key_len, text_len;
  197434. png_charp new_lang, new_key;
  197435. png_byte cbuf[2];
  197436. compression_state comp;
  197437. png_debug(1, "in png_write_iTXt\n");
  197438. comp.num_output_ptr = 0;
  197439. comp.max_output_ptr = 0;
  197440. comp.output_ptr = NULL;
  197441. comp.input = NULL;
  197442. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  197443. {
  197444. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  197445. return;
  197446. }
  197447. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  197448. {
  197449. png_warning(png_ptr, "Empty language field in iTXt chunk");
  197450. new_lang = NULL;
  197451. lang_len = 0;
  197452. }
  197453. if (lang_key == NULL)
  197454. lang_key_len = 0;
  197455. else
  197456. lang_key_len = png_strlen(lang_key);
  197457. if (text == NULL)
  197458. text_len = 0;
  197459. else
  197460. text_len = png_strlen(text);
  197461. /* compute the compressed data; do it now for the length */
  197462. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  197463. &comp);
  197464. /* make sure we include the compression flag, the compression byte,
  197465. * and the NULs after the key, lang, and lang_key parts */
  197466. png_write_chunk_start(png_ptr, png_iTXt,
  197467. (png_uint_32)(
  197468. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  197469. + key_len
  197470. + lang_len
  197471. + lang_key_len
  197472. + text_len));
  197473. /*
  197474. * We leave it to the application to meet PNG-1.0 requirements on the
  197475. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  197476. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  197477. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  197478. */
  197479. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  197480. /* set the compression flag */
  197481. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  197482. compression == PNG_TEXT_COMPRESSION_NONE)
  197483. cbuf[0] = 0;
  197484. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  197485. cbuf[0] = 1;
  197486. /* set the compression method */
  197487. cbuf[1] = 0;
  197488. png_write_chunk_data(png_ptr, cbuf, 2);
  197489. cbuf[0] = 0;
  197490. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  197491. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  197492. png_write_compressed_data_out(png_ptr, &comp);
  197493. png_write_chunk_end(png_ptr);
  197494. png_free(png_ptr, new_key);
  197495. if (new_lang)
  197496. png_free(png_ptr, new_lang);
  197497. }
  197498. #endif
  197499. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  197500. /* write the oFFs chunk */
  197501. void /* PRIVATE */
  197502. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  197503. int unit_type)
  197504. {
  197505. #ifdef PNG_USE_LOCAL_ARRAYS
  197506. PNG_oFFs;
  197507. #endif
  197508. png_byte buf[9];
  197509. png_debug(1, "in png_write_oFFs\n");
  197510. if (unit_type >= PNG_OFFSET_LAST)
  197511. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  197512. png_save_int_32(buf, x_offset);
  197513. png_save_int_32(buf + 4, y_offset);
  197514. buf[8] = (png_byte)unit_type;
  197515. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  197516. }
  197517. #endif
  197518. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  197519. /* write the pCAL chunk (described in the PNG extensions document) */
  197520. void /* PRIVATE */
  197521. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  197522. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  197523. {
  197524. #ifdef PNG_USE_LOCAL_ARRAYS
  197525. PNG_pCAL;
  197526. #endif
  197527. png_size_t purpose_len, units_len, total_len;
  197528. png_uint_32p params_len;
  197529. png_byte buf[10];
  197530. png_charp new_purpose;
  197531. int i;
  197532. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  197533. if (type >= PNG_EQUATION_LAST)
  197534. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  197535. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  197536. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  197537. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  197538. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  197539. total_len = purpose_len + units_len + 10;
  197540. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  197541. *png_sizeof(png_uint_32)));
  197542. /* Find the length of each parameter, making sure we don't count the
  197543. null terminator for the last parameter. */
  197544. for (i = 0; i < nparams; i++)
  197545. {
  197546. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  197547. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  197548. total_len += (png_size_t)params_len[i];
  197549. }
  197550. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  197551. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  197552. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  197553. png_save_int_32(buf, X0);
  197554. png_save_int_32(buf + 4, X1);
  197555. buf[8] = (png_byte)type;
  197556. buf[9] = (png_byte)nparams;
  197557. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  197558. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  197559. png_free(png_ptr, new_purpose);
  197560. for (i = 0; i < nparams; i++)
  197561. {
  197562. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  197563. (png_size_t)params_len[i]);
  197564. }
  197565. png_free(png_ptr, params_len);
  197566. png_write_chunk_end(png_ptr);
  197567. }
  197568. #endif
  197569. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  197570. /* write the sCAL chunk */
  197571. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  197572. void /* PRIVATE */
  197573. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  197574. {
  197575. #ifdef PNG_USE_LOCAL_ARRAYS
  197576. PNG_sCAL;
  197577. #endif
  197578. char buf[64];
  197579. png_size_t total_len;
  197580. png_debug(1, "in png_write_sCAL\n");
  197581. buf[0] = (char)unit;
  197582. #if defined(_WIN32_WCE)
  197583. /* sprintf() function is not supported on WindowsCE */
  197584. {
  197585. wchar_t wc_buf[32];
  197586. size_t wc_len;
  197587. swprintf(wc_buf, TEXT("%12.12e"), width);
  197588. wc_len = wcslen(wc_buf);
  197589. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  197590. total_len = wc_len + 2;
  197591. swprintf(wc_buf, TEXT("%12.12e"), height);
  197592. wc_len = wcslen(wc_buf);
  197593. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  197594. NULL, NULL);
  197595. total_len += wc_len;
  197596. }
  197597. #else
  197598. png_snprintf(buf + 1, 63, "%12.12e", width);
  197599. total_len = 1 + png_strlen(buf + 1) + 1;
  197600. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  197601. total_len += png_strlen(buf + total_len);
  197602. #endif
  197603. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197604. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  197605. }
  197606. #else
  197607. #ifdef PNG_FIXED_POINT_SUPPORTED
  197608. void /* PRIVATE */
  197609. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  197610. png_charp height)
  197611. {
  197612. #ifdef PNG_USE_LOCAL_ARRAYS
  197613. PNG_sCAL;
  197614. #endif
  197615. png_byte buf[64];
  197616. png_size_t wlen, hlen, total_len;
  197617. png_debug(1, "in png_write_sCAL_s\n");
  197618. wlen = png_strlen(width);
  197619. hlen = png_strlen(height);
  197620. total_len = wlen + hlen + 2;
  197621. if (total_len > 64)
  197622. {
  197623. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  197624. return;
  197625. }
  197626. buf[0] = (png_byte)unit;
  197627. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  197628. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  197629. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  197630. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  197631. }
  197632. #endif
  197633. #endif
  197634. #endif
  197635. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  197636. /* write the pHYs chunk */
  197637. void /* PRIVATE */
  197638. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  197639. png_uint_32 y_pixels_per_unit,
  197640. int unit_type)
  197641. {
  197642. #ifdef PNG_USE_LOCAL_ARRAYS
  197643. PNG_pHYs;
  197644. #endif
  197645. png_byte buf[9];
  197646. png_debug(1, "in png_write_pHYs\n");
  197647. if (unit_type >= PNG_RESOLUTION_LAST)
  197648. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  197649. png_save_uint_32(buf, x_pixels_per_unit);
  197650. png_save_uint_32(buf + 4, y_pixels_per_unit);
  197651. buf[8] = (png_byte)unit_type;
  197652. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  197653. }
  197654. #endif
  197655. #if defined(PNG_WRITE_tIME_SUPPORTED)
  197656. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  197657. * or png_convert_from_time_t(), or fill in the structure yourself.
  197658. */
  197659. void /* PRIVATE */
  197660. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  197661. {
  197662. #ifdef PNG_USE_LOCAL_ARRAYS
  197663. PNG_tIME;
  197664. #endif
  197665. png_byte buf[7];
  197666. png_debug(1, "in png_write_tIME\n");
  197667. if (mod_time->month > 12 || mod_time->month < 1 ||
  197668. mod_time->day > 31 || mod_time->day < 1 ||
  197669. mod_time->hour > 23 || mod_time->second > 60)
  197670. {
  197671. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  197672. return;
  197673. }
  197674. png_save_uint_16(buf, mod_time->year);
  197675. buf[2] = mod_time->month;
  197676. buf[3] = mod_time->day;
  197677. buf[4] = mod_time->hour;
  197678. buf[5] = mod_time->minute;
  197679. buf[6] = mod_time->second;
  197680. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  197681. }
  197682. #endif
  197683. /* initializes the row writing capability of libpng */
  197684. void /* PRIVATE */
  197685. png_write_start_row(png_structp png_ptr)
  197686. {
  197687. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197688. #ifdef PNG_USE_LOCAL_ARRAYS
  197689. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197690. /* start of interlace block */
  197691. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197692. /* offset to next interlace block */
  197693. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197694. /* start of interlace block in the y direction */
  197695. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197696. /* offset to next interlace block in the y direction */
  197697. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197698. #endif
  197699. #endif
  197700. png_size_t buf_size;
  197701. png_debug(1, "in png_write_start_row\n");
  197702. buf_size = (png_size_t)(PNG_ROWBYTES(
  197703. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  197704. /* set up row buffer */
  197705. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197706. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  197707. #ifndef PNG_NO_WRITE_FILTERING
  197708. /* set up filtering buffer, if using this filter */
  197709. if (png_ptr->do_filter & PNG_FILTER_SUB)
  197710. {
  197711. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  197712. (png_ptr->rowbytes + 1));
  197713. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  197714. }
  197715. /* We only need to keep the previous row if we are using one of these. */
  197716. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  197717. {
  197718. /* set up previous row buffer */
  197719. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  197720. png_memset(png_ptr->prev_row, 0, buf_size);
  197721. if (png_ptr->do_filter & PNG_FILTER_UP)
  197722. {
  197723. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  197724. (png_ptr->rowbytes + 1));
  197725. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  197726. }
  197727. if (png_ptr->do_filter & PNG_FILTER_AVG)
  197728. {
  197729. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  197730. (png_ptr->rowbytes + 1));
  197731. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  197732. }
  197733. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  197734. {
  197735. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  197736. (png_ptr->rowbytes + 1));
  197737. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  197738. }
  197739. #endif /* PNG_NO_WRITE_FILTERING */
  197740. }
  197741. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197742. /* if interlaced, we need to set up width and height of pass */
  197743. if (png_ptr->interlaced)
  197744. {
  197745. if (!(png_ptr->transformations & PNG_INTERLACE))
  197746. {
  197747. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197748. png_pass_ystart[0]) / png_pass_yinc[0];
  197749. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  197750. png_pass_start[0]) / png_pass_inc[0];
  197751. }
  197752. else
  197753. {
  197754. png_ptr->num_rows = png_ptr->height;
  197755. png_ptr->usr_width = png_ptr->width;
  197756. }
  197757. }
  197758. else
  197759. #endif
  197760. {
  197761. png_ptr->num_rows = png_ptr->height;
  197762. png_ptr->usr_width = png_ptr->width;
  197763. }
  197764. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197765. png_ptr->zstream.next_out = png_ptr->zbuf;
  197766. }
  197767. /* Internal use only. Called when finished processing a row of data. */
  197768. void /* PRIVATE */
  197769. png_write_finish_row(png_structp png_ptr)
  197770. {
  197771. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197772. #ifdef PNG_USE_LOCAL_ARRAYS
  197773. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197774. /* start of interlace block */
  197775. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197776. /* offset to next interlace block */
  197777. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197778. /* start of interlace block in the y direction */
  197779. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197780. /* offset to next interlace block in the y direction */
  197781. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197782. #endif
  197783. #endif
  197784. int ret;
  197785. png_debug(1, "in png_write_finish_row\n");
  197786. /* next row */
  197787. png_ptr->row_number++;
  197788. /* see if we are done */
  197789. if (png_ptr->row_number < png_ptr->num_rows)
  197790. return;
  197791. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  197792. /* if interlaced, go to next pass */
  197793. if (png_ptr->interlaced)
  197794. {
  197795. png_ptr->row_number = 0;
  197796. if (png_ptr->transformations & PNG_INTERLACE)
  197797. {
  197798. png_ptr->pass++;
  197799. }
  197800. else
  197801. {
  197802. /* loop until we find a non-zero width or height pass */
  197803. do
  197804. {
  197805. png_ptr->pass++;
  197806. if (png_ptr->pass >= 7)
  197807. break;
  197808. png_ptr->usr_width = (png_ptr->width +
  197809. png_pass_inc[png_ptr->pass] - 1 -
  197810. png_pass_start[png_ptr->pass]) /
  197811. png_pass_inc[png_ptr->pass];
  197812. png_ptr->num_rows = (png_ptr->height +
  197813. png_pass_yinc[png_ptr->pass] - 1 -
  197814. png_pass_ystart[png_ptr->pass]) /
  197815. png_pass_yinc[png_ptr->pass];
  197816. if (png_ptr->transformations & PNG_INTERLACE)
  197817. break;
  197818. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  197819. }
  197820. /* reset the row above the image for the next pass */
  197821. if (png_ptr->pass < 7)
  197822. {
  197823. if (png_ptr->prev_row != NULL)
  197824. png_memset(png_ptr->prev_row, 0,
  197825. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  197826. png_ptr->usr_bit_depth,png_ptr->width))+1);
  197827. return;
  197828. }
  197829. }
  197830. #endif
  197831. /* if we get here, we've just written the last row, so we need
  197832. to flush the compressor */
  197833. do
  197834. {
  197835. /* tell the compressor we are done */
  197836. ret = deflate(&png_ptr->zstream, Z_FINISH);
  197837. /* check for an error */
  197838. if (ret == Z_OK)
  197839. {
  197840. /* check to see if we need more room */
  197841. if (!(png_ptr->zstream.avail_out))
  197842. {
  197843. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  197844. png_ptr->zstream.next_out = png_ptr->zbuf;
  197845. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197846. }
  197847. }
  197848. else if (ret != Z_STREAM_END)
  197849. {
  197850. if (png_ptr->zstream.msg != NULL)
  197851. png_error(png_ptr, png_ptr->zstream.msg);
  197852. else
  197853. png_error(png_ptr, "zlib error");
  197854. }
  197855. } while (ret != Z_STREAM_END);
  197856. /* write any extra space */
  197857. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  197858. {
  197859. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  197860. png_ptr->zstream.avail_out);
  197861. }
  197862. deflateReset(&png_ptr->zstream);
  197863. png_ptr->zstream.data_type = Z_BINARY;
  197864. }
  197865. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197866. /* Pick out the correct pixels for the interlace pass.
  197867. * The basic idea here is to go through the row with a source
  197868. * pointer and a destination pointer (sp and dp), and copy the
  197869. * correct pixels for the pass. As the row gets compacted,
  197870. * sp will always be >= dp, so we should never overwrite anything.
  197871. * See the default: case for the easiest code to understand.
  197872. */
  197873. void /* PRIVATE */
  197874. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  197875. {
  197876. #ifdef PNG_USE_LOCAL_ARRAYS
  197877. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197878. /* start of interlace block */
  197879. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197880. /* offset to next interlace block */
  197881. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197882. #endif
  197883. png_debug(1, "in png_do_write_interlace\n");
  197884. /* we don't have to do anything on the last pass (6) */
  197885. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  197886. if (row != NULL && row_info != NULL && pass < 6)
  197887. #else
  197888. if (pass < 6)
  197889. #endif
  197890. {
  197891. /* each pixel depth is handled separately */
  197892. switch (row_info->pixel_depth)
  197893. {
  197894. case 1:
  197895. {
  197896. png_bytep sp;
  197897. png_bytep dp;
  197898. int shift;
  197899. int d;
  197900. int value;
  197901. png_uint_32 i;
  197902. png_uint_32 row_width = row_info->width;
  197903. dp = row;
  197904. d = 0;
  197905. shift = 7;
  197906. for (i = png_pass_start[pass]; i < row_width;
  197907. i += png_pass_inc[pass])
  197908. {
  197909. sp = row + (png_size_t)(i >> 3);
  197910. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  197911. d |= (value << shift);
  197912. if (shift == 0)
  197913. {
  197914. shift = 7;
  197915. *dp++ = (png_byte)d;
  197916. d = 0;
  197917. }
  197918. else
  197919. shift--;
  197920. }
  197921. if (shift != 7)
  197922. *dp = (png_byte)d;
  197923. break;
  197924. }
  197925. case 2:
  197926. {
  197927. png_bytep sp;
  197928. png_bytep dp;
  197929. int shift;
  197930. int d;
  197931. int value;
  197932. png_uint_32 i;
  197933. png_uint_32 row_width = row_info->width;
  197934. dp = row;
  197935. shift = 6;
  197936. d = 0;
  197937. for (i = png_pass_start[pass]; i < row_width;
  197938. i += png_pass_inc[pass])
  197939. {
  197940. sp = row + (png_size_t)(i >> 2);
  197941. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  197942. d |= (value << shift);
  197943. if (shift == 0)
  197944. {
  197945. shift = 6;
  197946. *dp++ = (png_byte)d;
  197947. d = 0;
  197948. }
  197949. else
  197950. shift -= 2;
  197951. }
  197952. if (shift != 6)
  197953. *dp = (png_byte)d;
  197954. break;
  197955. }
  197956. case 4:
  197957. {
  197958. png_bytep sp;
  197959. png_bytep dp;
  197960. int shift;
  197961. int d;
  197962. int value;
  197963. png_uint_32 i;
  197964. png_uint_32 row_width = row_info->width;
  197965. dp = row;
  197966. shift = 4;
  197967. d = 0;
  197968. for (i = png_pass_start[pass]; i < row_width;
  197969. i += png_pass_inc[pass])
  197970. {
  197971. sp = row + (png_size_t)(i >> 1);
  197972. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  197973. d |= (value << shift);
  197974. if (shift == 0)
  197975. {
  197976. shift = 4;
  197977. *dp++ = (png_byte)d;
  197978. d = 0;
  197979. }
  197980. else
  197981. shift -= 4;
  197982. }
  197983. if (shift != 4)
  197984. *dp = (png_byte)d;
  197985. break;
  197986. }
  197987. default:
  197988. {
  197989. png_bytep sp;
  197990. png_bytep dp;
  197991. png_uint_32 i;
  197992. png_uint_32 row_width = row_info->width;
  197993. png_size_t pixel_bytes;
  197994. /* start at the beginning */
  197995. dp = row;
  197996. /* find out how many bytes each pixel takes up */
  197997. pixel_bytes = (row_info->pixel_depth >> 3);
  197998. /* loop through the row, only looking at the pixels that
  197999. matter */
  198000. for (i = png_pass_start[pass]; i < row_width;
  198001. i += png_pass_inc[pass])
  198002. {
  198003. /* find out where the original pixel is */
  198004. sp = row + (png_size_t)i * pixel_bytes;
  198005. /* move the pixel */
  198006. if (dp != sp)
  198007. png_memcpy(dp, sp, pixel_bytes);
  198008. /* next pixel */
  198009. dp += pixel_bytes;
  198010. }
  198011. break;
  198012. }
  198013. }
  198014. /* set new row width */
  198015. row_info->width = (row_info->width +
  198016. png_pass_inc[pass] - 1 -
  198017. png_pass_start[pass]) /
  198018. png_pass_inc[pass];
  198019. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  198020. row_info->width);
  198021. }
  198022. }
  198023. #endif
  198024. /* This filters the row, chooses which filter to use, if it has not already
  198025. * been specified by the application, and then writes the row out with the
  198026. * chosen filter.
  198027. */
  198028. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  198029. #define PNG_HISHIFT 10
  198030. #define PNG_LOMASK ((png_uint_32)0xffffL)
  198031. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  198032. void /* PRIVATE */
  198033. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  198034. {
  198035. png_bytep best_row;
  198036. #ifndef PNG_NO_WRITE_FILTER
  198037. png_bytep prev_row, row_buf;
  198038. png_uint_32 mins, bpp;
  198039. png_byte filter_to_do = png_ptr->do_filter;
  198040. png_uint_32 row_bytes = row_info->rowbytes;
  198041. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198042. int num_p_filters = (int)png_ptr->num_prev_filters;
  198043. #endif
  198044. png_debug(1, "in png_write_find_filter\n");
  198045. /* find out how many bytes offset each pixel is */
  198046. bpp = (row_info->pixel_depth + 7) >> 3;
  198047. prev_row = png_ptr->prev_row;
  198048. #endif
  198049. best_row = png_ptr->row_buf;
  198050. #ifndef PNG_NO_WRITE_FILTER
  198051. row_buf = best_row;
  198052. mins = PNG_MAXSUM;
  198053. /* The prediction method we use is to find which method provides the
  198054. * smallest value when summing the absolute values of the distances
  198055. * from zero, using anything >= 128 as negative numbers. This is known
  198056. * as the "minimum sum of absolute differences" heuristic. Other
  198057. * heuristics are the "weighted minimum sum of absolute differences"
  198058. * (experimental and can in theory improve compression), and the "zlib
  198059. * predictive" method (not implemented yet), which does test compressions
  198060. * of lines using different filter methods, and then chooses the
  198061. * (series of) filter(s) that give minimum compressed data size (VERY
  198062. * computationally expensive).
  198063. *
  198064. * GRR 980525: consider also
  198065. * (1) minimum sum of absolute differences from running average (i.e.,
  198066. * keep running sum of non-absolute differences & count of bytes)
  198067. * [track dispersion, too? restart average if dispersion too large?]
  198068. * (1b) minimum sum of absolute differences from sliding average, probably
  198069. * with window size <= deflate window (usually 32K)
  198070. * (2) minimum sum of squared differences from zero or running average
  198071. * (i.e., ~ root-mean-square approach)
  198072. */
  198073. /* We don't need to test the 'no filter' case if this is the only filter
  198074. * that has been chosen, as it doesn't actually do anything to the data.
  198075. */
  198076. if ((filter_to_do & PNG_FILTER_NONE) &&
  198077. filter_to_do != PNG_FILTER_NONE)
  198078. {
  198079. png_bytep rp;
  198080. png_uint_32 sum = 0;
  198081. png_uint_32 i;
  198082. int v;
  198083. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  198084. {
  198085. v = *rp;
  198086. sum += (v < 128) ? v : 256 - v;
  198087. }
  198088. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198089. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198090. {
  198091. png_uint_32 sumhi, sumlo;
  198092. int j;
  198093. sumlo = sum & PNG_LOMASK;
  198094. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  198095. /* Reduce the sum if we match any of the previous rows */
  198096. for (j = 0; j < num_p_filters; j++)
  198097. {
  198098. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198099. {
  198100. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198101. PNG_WEIGHT_SHIFT;
  198102. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198103. PNG_WEIGHT_SHIFT;
  198104. }
  198105. }
  198106. /* Factor in the cost of this filter (this is here for completeness,
  198107. * but it makes no sense to have a "cost" for the NONE filter, as
  198108. * it has the minimum possible computational cost - none).
  198109. */
  198110. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198111. PNG_COST_SHIFT;
  198112. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  198113. PNG_COST_SHIFT;
  198114. if (sumhi > PNG_HIMASK)
  198115. sum = PNG_MAXSUM;
  198116. else
  198117. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198118. }
  198119. #endif
  198120. mins = sum;
  198121. }
  198122. /* sub filter */
  198123. if (filter_to_do == PNG_FILTER_SUB)
  198124. /* it's the only filter so no testing is needed */
  198125. {
  198126. png_bytep rp, lp, dp;
  198127. png_uint_32 i;
  198128. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198129. i++, rp++, dp++)
  198130. {
  198131. *dp = *rp;
  198132. }
  198133. for (lp = row_buf + 1; i < row_bytes;
  198134. i++, rp++, lp++, dp++)
  198135. {
  198136. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198137. }
  198138. best_row = png_ptr->sub_row;
  198139. }
  198140. else if (filter_to_do & PNG_FILTER_SUB)
  198141. {
  198142. png_bytep rp, dp, lp;
  198143. png_uint_32 sum = 0, lmins = mins;
  198144. png_uint_32 i;
  198145. int v;
  198146. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198147. /* We temporarily increase the "minimum sum" by the factor we
  198148. * would reduce the sum of this filter, so that we can do the
  198149. * early exit comparison without scaling the sum each time.
  198150. */
  198151. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198152. {
  198153. int j;
  198154. png_uint_32 lmhi, lmlo;
  198155. lmlo = lmins & PNG_LOMASK;
  198156. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198157. for (j = 0; j < num_p_filters; j++)
  198158. {
  198159. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198160. {
  198161. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198162. PNG_WEIGHT_SHIFT;
  198163. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198164. PNG_WEIGHT_SHIFT;
  198165. }
  198166. }
  198167. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198168. PNG_COST_SHIFT;
  198169. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198170. PNG_COST_SHIFT;
  198171. if (lmhi > PNG_HIMASK)
  198172. lmins = PNG_MAXSUM;
  198173. else
  198174. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198175. }
  198176. #endif
  198177. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  198178. i++, rp++, dp++)
  198179. {
  198180. v = *dp = *rp;
  198181. sum += (v < 128) ? v : 256 - v;
  198182. }
  198183. for (lp = row_buf + 1; i < row_bytes;
  198184. i++, rp++, lp++, dp++)
  198185. {
  198186. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  198187. sum += (v < 128) ? v : 256 - v;
  198188. if (sum > lmins) /* We are already worse, don't continue. */
  198189. break;
  198190. }
  198191. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198192. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198193. {
  198194. int j;
  198195. png_uint_32 sumhi, sumlo;
  198196. sumlo = sum & PNG_LOMASK;
  198197. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198198. for (j = 0; j < num_p_filters; j++)
  198199. {
  198200. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  198201. {
  198202. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  198203. PNG_WEIGHT_SHIFT;
  198204. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  198205. PNG_WEIGHT_SHIFT;
  198206. }
  198207. }
  198208. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198209. PNG_COST_SHIFT;
  198210. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  198211. PNG_COST_SHIFT;
  198212. if (sumhi > PNG_HIMASK)
  198213. sum = PNG_MAXSUM;
  198214. else
  198215. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198216. }
  198217. #endif
  198218. if (sum < mins)
  198219. {
  198220. mins = sum;
  198221. best_row = png_ptr->sub_row;
  198222. }
  198223. }
  198224. /* up filter */
  198225. if (filter_to_do == PNG_FILTER_UP)
  198226. {
  198227. png_bytep rp, dp, pp;
  198228. png_uint_32 i;
  198229. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198230. pp = prev_row + 1; i < row_bytes;
  198231. i++, rp++, pp++, dp++)
  198232. {
  198233. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  198234. }
  198235. best_row = png_ptr->up_row;
  198236. }
  198237. else if (filter_to_do & PNG_FILTER_UP)
  198238. {
  198239. png_bytep rp, dp, pp;
  198240. png_uint_32 sum = 0, lmins = mins;
  198241. png_uint_32 i;
  198242. int v;
  198243. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198244. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198245. {
  198246. int j;
  198247. png_uint_32 lmhi, lmlo;
  198248. lmlo = lmins & PNG_LOMASK;
  198249. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198250. for (j = 0; j < num_p_filters; j++)
  198251. {
  198252. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198253. {
  198254. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198255. PNG_WEIGHT_SHIFT;
  198256. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198257. PNG_WEIGHT_SHIFT;
  198258. }
  198259. }
  198260. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198261. PNG_COST_SHIFT;
  198262. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  198263. PNG_COST_SHIFT;
  198264. if (lmhi > PNG_HIMASK)
  198265. lmins = PNG_MAXSUM;
  198266. else
  198267. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198268. }
  198269. #endif
  198270. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  198271. pp = prev_row + 1; i < row_bytes; i++)
  198272. {
  198273. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198274. sum += (v < 128) ? v : 256 - v;
  198275. if (sum > lmins) /* We are already worse, don't continue. */
  198276. break;
  198277. }
  198278. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198279. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198280. {
  198281. int j;
  198282. png_uint_32 sumhi, sumlo;
  198283. sumlo = sum & PNG_LOMASK;
  198284. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198285. for (j = 0; j < num_p_filters; j++)
  198286. {
  198287. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  198288. {
  198289. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198290. PNG_WEIGHT_SHIFT;
  198291. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198292. PNG_WEIGHT_SHIFT;
  198293. }
  198294. }
  198295. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198296. PNG_COST_SHIFT;
  198297. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  198298. PNG_COST_SHIFT;
  198299. if (sumhi > PNG_HIMASK)
  198300. sum = PNG_MAXSUM;
  198301. else
  198302. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198303. }
  198304. #endif
  198305. if (sum < mins)
  198306. {
  198307. mins = sum;
  198308. best_row = png_ptr->up_row;
  198309. }
  198310. }
  198311. /* avg filter */
  198312. if (filter_to_do == PNG_FILTER_AVG)
  198313. {
  198314. png_bytep rp, dp, pp, lp;
  198315. png_uint_32 i;
  198316. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198317. pp = prev_row + 1; i < bpp; i++)
  198318. {
  198319. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198320. }
  198321. for (lp = row_buf + 1; i < row_bytes; i++)
  198322. {
  198323. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  198324. & 0xff);
  198325. }
  198326. best_row = png_ptr->avg_row;
  198327. }
  198328. else if (filter_to_do & PNG_FILTER_AVG)
  198329. {
  198330. png_bytep rp, dp, pp, lp;
  198331. png_uint_32 sum = 0, lmins = mins;
  198332. png_uint_32 i;
  198333. int v;
  198334. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198335. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198336. {
  198337. int j;
  198338. png_uint_32 lmhi, lmlo;
  198339. lmlo = lmins & PNG_LOMASK;
  198340. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198341. for (j = 0; j < num_p_filters; j++)
  198342. {
  198343. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  198344. {
  198345. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198346. PNG_WEIGHT_SHIFT;
  198347. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198348. PNG_WEIGHT_SHIFT;
  198349. }
  198350. }
  198351. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198352. PNG_COST_SHIFT;
  198353. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198354. PNG_COST_SHIFT;
  198355. if (lmhi > PNG_HIMASK)
  198356. lmins = PNG_MAXSUM;
  198357. else
  198358. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198359. }
  198360. #endif
  198361. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  198362. pp = prev_row + 1; i < bpp; i++)
  198363. {
  198364. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  198365. sum += (v < 128) ? v : 256 - v;
  198366. }
  198367. for (lp = row_buf + 1; i < row_bytes; i++)
  198368. {
  198369. v = *dp++ =
  198370. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  198371. sum += (v < 128) ? v : 256 - v;
  198372. if (sum > lmins) /* We are already worse, don't continue. */
  198373. break;
  198374. }
  198375. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198376. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198377. {
  198378. int j;
  198379. png_uint_32 sumhi, sumlo;
  198380. sumlo = sum & PNG_LOMASK;
  198381. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198382. for (j = 0; j < num_p_filters; j++)
  198383. {
  198384. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  198385. {
  198386. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198387. PNG_WEIGHT_SHIFT;
  198388. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198389. PNG_WEIGHT_SHIFT;
  198390. }
  198391. }
  198392. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198393. PNG_COST_SHIFT;
  198394. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  198395. PNG_COST_SHIFT;
  198396. if (sumhi > PNG_HIMASK)
  198397. sum = PNG_MAXSUM;
  198398. else
  198399. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198400. }
  198401. #endif
  198402. if (sum < mins)
  198403. {
  198404. mins = sum;
  198405. best_row = png_ptr->avg_row;
  198406. }
  198407. }
  198408. /* Paeth filter */
  198409. if (filter_to_do == PNG_FILTER_PAETH)
  198410. {
  198411. png_bytep rp, dp, pp, cp, lp;
  198412. png_uint_32 i;
  198413. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198414. pp = prev_row + 1; i < bpp; i++)
  198415. {
  198416. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198417. }
  198418. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198419. {
  198420. int a, b, c, pa, pb, pc, p;
  198421. b = *pp++;
  198422. c = *cp++;
  198423. a = *lp++;
  198424. p = b - c;
  198425. pc = a - c;
  198426. #ifdef PNG_USE_ABS
  198427. pa = abs(p);
  198428. pb = abs(pc);
  198429. pc = abs(p + pc);
  198430. #else
  198431. pa = p < 0 ? -p : p;
  198432. pb = pc < 0 ? -pc : pc;
  198433. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198434. #endif
  198435. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198436. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198437. }
  198438. best_row = png_ptr->paeth_row;
  198439. }
  198440. else if (filter_to_do & PNG_FILTER_PAETH)
  198441. {
  198442. png_bytep rp, dp, pp, cp, lp;
  198443. png_uint_32 sum = 0, lmins = mins;
  198444. png_uint_32 i;
  198445. int v;
  198446. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198447. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198448. {
  198449. int j;
  198450. png_uint_32 lmhi, lmlo;
  198451. lmlo = lmins & PNG_LOMASK;
  198452. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  198453. for (j = 0; j < num_p_filters; j++)
  198454. {
  198455. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198456. {
  198457. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  198458. PNG_WEIGHT_SHIFT;
  198459. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  198460. PNG_WEIGHT_SHIFT;
  198461. }
  198462. }
  198463. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198464. PNG_COST_SHIFT;
  198465. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198466. PNG_COST_SHIFT;
  198467. if (lmhi > PNG_HIMASK)
  198468. lmins = PNG_MAXSUM;
  198469. else
  198470. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  198471. }
  198472. #endif
  198473. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  198474. pp = prev_row + 1; i < bpp; i++)
  198475. {
  198476. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  198477. sum += (v < 128) ? v : 256 - v;
  198478. }
  198479. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  198480. {
  198481. int a, b, c, pa, pb, pc, p;
  198482. b = *pp++;
  198483. c = *cp++;
  198484. a = *lp++;
  198485. #ifndef PNG_SLOW_PAETH
  198486. p = b - c;
  198487. pc = a - c;
  198488. #ifdef PNG_USE_ABS
  198489. pa = abs(p);
  198490. pb = abs(pc);
  198491. pc = abs(p + pc);
  198492. #else
  198493. pa = p < 0 ? -p : p;
  198494. pb = pc < 0 ? -pc : pc;
  198495. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  198496. #endif
  198497. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  198498. #else /* PNG_SLOW_PAETH */
  198499. p = a + b - c;
  198500. pa = abs(p - a);
  198501. pb = abs(p - b);
  198502. pc = abs(p - c);
  198503. if (pa <= pb && pa <= pc)
  198504. p = a;
  198505. else if (pb <= pc)
  198506. p = b;
  198507. else
  198508. p = c;
  198509. #endif /* PNG_SLOW_PAETH */
  198510. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  198511. sum += (v < 128) ? v : 256 - v;
  198512. if (sum > lmins) /* We are already worse, don't continue. */
  198513. break;
  198514. }
  198515. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198516. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  198517. {
  198518. int j;
  198519. png_uint_32 sumhi, sumlo;
  198520. sumlo = sum & PNG_LOMASK;
  198521. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  198522. for (j = 0; j < num_p_filters; j++)
  198523. {
  198524. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  198525. {
  198526. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  198527. PNG_WEIGHT_SHIFT;
  198528. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  198529. PNG_WEIGHT_SHIFT;
  198530. }
  198531. }
  198532. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198533. PNG_COST_SHIFT;
  198534. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  198535. PNG_COST_SHIFT;
  198536. if (sumhi > PNG_HIMASK)
  198537. sum = PNG_MAXSUM;
  198538. else
  198539. sum = (sumhi << PNG_HISHIFT) + sumlo;
  198540. }
  198541. #endif
  198542. if (sum < mins)
  198543. {
  198544. best_row = png_ptr->paeth_row;
  198545. }
  198546. }
  198547. #endif /* PNG_NO_WRITE_FILTER */
  198548. /* Do the actual writing of the filtered row data from the chosen filter. */
  198549. png_write_filtered_row(png_ptr, best_row);
  198550. #ifndef PNG_NO_WRITE_FILTER
  198551. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  198552. /* Save the type of filter we picked this time for future calculations */
  198553. if (png_ptr->num_prev_filters > 0)
  198554. {
  198555. int j;
  198556. for (j = 1; j < num_p_filters; j++)
  198557. {
  198558. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  198559. }
  198560. png_ptr->prev_filters[j] = best_row[0];
  198561. }
  198562. #endif
  198563. #endif /* PNG_NO_WRITE_FILTER */
  198564. }
  198565. /* Do the actual writing of a previously filtered row. */
  198566. void /* PRIVATE */
  198567. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  198568. {
  198569. png_debug(1, "in png_write_filtered_row\n");
  198570. png_debug1(2, "filter = %d\n", filtered_row[0]);
  198571. /* set up the zlib input buffer */
  198572. png_ptr->zstream.next_in = filtered_row;
  198573. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  198574. /* repeat until we have compressed all the data */
  198575. do
  198576. {
  198577. int ret; /* return of zlib */
  198578. /* compress the data */
  198579. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  198580. /* check for compression errors */
  198581. if (ret != Z_OK)
  198582. {
  198583. if (png_ptr->zstream.msg != NULL)
  198584. png_error(png_ptr, png_ptr->zstream.msg);
  198585. else
  198586. png_error(png_ptr, "zlib error");
  198587. }
  198588. /* see if it is time to write another IDAT */
  198589. if (!(png_ptr->zstream.avail_out))
  198590. {
  198591. /* write the IDAT and reset the zlib output buffer */
  198592. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  198593. png_ptr->zstream.next_out = png_ptr->zbuf;
  198594. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198595. }
  198596. /* repeat until all data has been compressed */
  198597. } while (png_ptr->zstream.avail_in);
  198598. /* swap the current and previous rows */
  198599. if (png_ptr->prev_row != NULL)
  198600. {
  198601. png_bytep tptr;
  198602. tptr = png_ptr->prev_row;
  198603. png_ptr->prev_row = png_ptr->row_buf;
  198604. png_ptr->row_buf = tptr;
  198605. }
  198606. /* finish row - updates counters and flushes zlib if last row */
  198607. png_write_finish_row(png_ptr);
  198608. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198609. png_ptr->flush_rows++;
  198610. if (png_ptr->flush_dist > 0 &&
  198611. png_ptr->flush_rows >= png_ptr->flush_dist)
  198612. {
  198613. png_write_flush(png_ptr);
  198614. }
  198615. #endif
  198616. }
  198617. #endif /* PNG_WRITE_SUPPORTED */
  198618. /********* End of inlined file: pngwutil.c *********/
  198619. }
  198620. #else
  198621. #define PNG_INTERNAL
  198622. #define PNG_SETJMP_NOT_SUPPORTED
  198623. #include <png.h>
  198624. #include <pngconf.h>
  198625. #endif
  198626. }
  198627. #ifdef _MSC_VER
  198628. #pragma warning (pop)
  198629. #endif
  198630. BEGIN_JUCE_NAMESPACE
  198631. using namespace pnglibNamespace;
  198632. using ::calloc;
  198633. using ::malloc;
  198634. using ::free;
  198635. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  198636. {
  198637. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  198638. in->read (data, (int) length);
  198639. }
  198640. struct PNGErrorStruct {};
  198641. static void pngErrorCallback (png_structp, png_const_charp)
  198642. {
  198643. throw PNGErrorStruct();
  198644. }
  198645. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  198646. {
  198647. Image* image = 0;
  198648. png_structp pngReadStruct;
  198649. png_infop pngInfoStruct;
  198650. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198651. if (pngReadStruct != 0)
  198652. {
  198653. pngInfoStruct = png_create_info_struct (pngReadStruct);
  198654. if (pngInfoStruct == 0)
  198655. {
  198656. png_destroy_read_struct (&pngReadStruct, 0, 0);
  198657. return 0;
  198658. }
  198659. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  198660. // read the header..
  198661. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  198662. png_uint_32 width, height;
  198663. int bitDepth, colorType, interlaceType;
  198664. png_read_info (pngReadStruct, pngInfoStruct);
  198665. png_get_IHDR (pngReadStruct, pngInfoStruct,
  198666. &width, &height,
  198667. &bitDepth, &colorType,
  198668. &interlaceType, 0, 0);
  198669. if (bitDepth == 16)
  198670. png_set_strip_16 (pngReadStruct);
  198671. if (colorType == PNG_COLOR_TYPE_PALETTE)
  198672. png_set_expand (pngReadStruct);
  198673. if (bitDepth < 8)
  198674. png_set_expand (pngReadStruct);
  198675. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  198676. png_set_expand (pngReadStruct);
  198677. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  198678. png_set_gray_to_rgb (pngReadStruct);
  198679. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  198680. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  198681. || pngInfoStruct->num_trans > 0;
  198682. // Load the image into a temp buffer in the pnglib format..
  198683. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  198684. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  198685. int y;
  198686. for (y = (int) height; --y >= 0;)
  198687. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  198688. png_read_image (pngReadStruct, rows);
  198689. png_read_end (pngReadStruct, pngInfoStruct);
  198690. juce_free (rows);
  198691. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  198692. // now convert the data to a juce image format..
  198693. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  198694. width, height, hasAlphaChan);
  198695. int stride, pixelStride;
  198696. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  198697. uint8* srcRow = tempBuffer;
  198698. uint8* destRow = pixels;
  198699. for (y = 0; y < (int) height; ++y)
  198700. {
  198701. const uint8* src = srcRow;
  198702. srcRow += (width << 2);
  198703. uint8* dest = destRow;
  198704. destRow += stride;
  198705. if (hasAlphaChan)
  198706. {
  198707. for (int i = width; --i >= 0;)
  198708. {
  198709. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  198710. ((PixelARGB*) dest)->premultiply();
  198711. dest += pixelStride;
  198712. src += 4;
  198713. }
  198714. }
  198715. else
  198716. {
  198717. for (int i = width; --i >= 0;)
  198718. {
  198719. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  198720. dest += pixelStride;
  198721. src += 4;
  198722. }
  198723. }
  198724. }
  198725. image->releasePixelDataReadWrite (pixels);
  198726. juce_free (tempBuffer);
  198727. }
  198728. return image;
  198729. }
  198730. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  198731. {
  198732. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  198733. const bool ok = out->write (data, length);
  198734. (void) ok;
  198735. jassert (ok);
  198736. }
  198737. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  198738. {
  198739. const int width = image.getWidth();
  198740. const int height = image.getHeight();
  198741. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  198742. if (pngWriteStruct == 0)
  198743. return false;
  198744. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  198745. if (pngInfoStruct == 0)
  198746. {
  198747. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  198748. return false;
  198749. }
  198750. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  198751. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  198752. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  198753. : PNG_COLOR_TYPE_RGB,
  198754. PNG_INTERLACE_NONE,
  198755. PNG_COMPRESSION_TYPE_BASE,
  198756. PNG_FILTER_TYPE_BASE);
  198757. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  198758. png_color_8 sig_bit;
  198759. sig_bit.red = 8;
  198760. sig_bit.green = 8;
  198761. sig_bit.blue = 8;
  198762. sig_bit.alpha = 8;
  198763. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  198764. png_write_info (pngWriteStruct, pngInfoStruct);
  198765. png_set_shift (pngWriteStruct, &sig_bit);
  198766. png_set_packing (pngWriteStruct);
  198767. for (int y = 0; y < height; ++y)
  198768. {
  198769. uint8* dst = (uint8*) rowData;
  198770. int stride, pixelStride;
  198771. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  198772. const uint8* src = pixels;
  198773. if (image.hasAlphaChannel())
  198774. {
  198775. for (int i = width; --i >= 0;)
  198776. {
  198777. PixelARGB p (*(const PixelARGB*) src);
  198778. p.unpremultiply();
  198779. *dst++ = p.getRed();
  198780. *dst++ = p.getGreen();
  198781. *dst++ = p.getBlue();
  198782. *dst++ = p.getAlpha();
  198783. src += pixelStride;
  198784. }
  198785. }
  198786. else
  198787. {
  198788. for (int i = width; --i >= 0;)
  198789. {
  198790. *dst++ = ((const PixelRGB*) src)->getRed();
  198791. *dst++ = ((const PixelRGB*) src)->getGreen();
  198792. *dst++ = ((const PixelRGB*) src)->getBlue();
  198793. src += pixelStride;
  198794. }
  198795. }
  198796. png_write_rows (pngWriteStruct, &rowData, 1);
  198797. image.releasePixelDataReadOnly (pixels);
  198798. }
  198799. juce_free (rowData);
  198800. png_write_end (pngWriteStruct, pngInfoStruct);
  198801. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  198802. out.flush();
  198803. return true;
  198804. }
  198805. END_JUCE_NAMESPACE
  198806. /********* End of inlined file: juce_PNGLoader.cpp *********/
  198807. #endif
  198808. //==============================================================================
  198809. #if JUCE_WIN32
  198810. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  198811. /*
  198812. This file wraps together all the win32-specific code, so that
  198813. we can include all the native headers just once, and compile all our
  198814. platform-specific stuff in one big lump, keeping it out of the way of
  198815. the rest of the codebase.
  198816. */
  198817. BEGIN_JUCE_NAMESPACE
  198818. #define JUCE_INCLUDED_FILE 1
  198819. // Now include the actual code files..
  198820. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198821. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198822. // compiled on its own).
  198823. #if JUCE_INCLUDED_FILE
  198824. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198825. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198826. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198827. #ifndef DOXYGEN
  198828. // use with DynamicLibraryLoader to simplify importing functions
  198829. //
  198830. // functionName: function to import
  198831. // localFunctionName: name you want to use to actually call it (must be different)
  198832. // returnType: the return type
  198833. // object: the DynamicLibraryLoader to use
  198834. // params: list of params (bracketed)
  198835. //
  198836. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  198837. typedef returnType (WINAPI *type##localFunctionName) params; \
  198838. type##localFunctionName localFunctionName \
  198839. = (type##localFunctionName)object.findProcAddress (#functionName);
  198840. // loads and unloads a DLL automatically
  198841. class JUCE_API DynamicLibraryLoader
  198842. {
  198843. public:
  198844. DynamicLibraryLoader (const String& name);
  198845. ~DynamicLibraryLoader();
  198846. void* findProcAddress (const String& functionName);
  198847. private:
  198848. void* libHandle;
  198849. };
  198850. #endif
  198851. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  198852. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  198853. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198854. {
  198855. libHandle = LoadLibrary (name);
  198856. }
  198857. DynamicLibraryLoader::~DynamicLibraryLoader()
  198858. {
  198859. FreeLibrary ((HMODULE) libHandle);
  198860. }
  198861. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198862. {
  198863. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198864. }
  198865. #endif
  198866. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198867. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  198868. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  198869. // compiled on its own).
  198870. #if JUCE_INCLUDED_FILE
  198871. extern void juce_updateMultiMonitorInfo() throw();
  198872. extern void juce_initialiseThreadEvents() throw();
  198873. void Logger::outputDebugString (const String& text) throw()
  198874. {
  198875. OutputDebugString (text + T("\n"));
  198876. }
  198877. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  198878. {
  198879. String text;
  198880. va_list args;
  198881. va_start (args, format);
  198882. text.vprintf(format, args);
  198883. outputDebugString (text);
  198884. }
  198885. static int64 hiResTicksPerSecond;
  198886. static double hiResTicksScaleFactor;
  198887. #if JUCE_USE_INTRINSICS
  198888. // CPU info functions using intrinsics...
  198889. #pragma intrinsic (__cpuid)
  198890. #pragma intrinsic (__rdtsc)
  198891. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  198892. {
  198893. int info [4];
  198894. __cpuid (info, 1);
  198895. if (familyModel != 0)
  198896. *familyModel = info [0];
  198897. if (extFeatures != 0)
  198898. *extFeatures = info[1];
  198899. return info[3];
  198900. }*/
  198901. const String SystemStats::getCpuVendor() throw()
  198902. {
  198903. int info [4];
  198904. __cpuid (info, 0);
  198905. char v [12];
  198906. memcpy (v, info + 1, 4);
  198907. memcpy (v + 4, info + 3, 4);
  198908. memcpy (v + 8, info + 2, 4);
  198909. return String (v, 12);
  198910. }
  198911. #else
  198912. // CPU info functions using old fashioned inline asm...
  198913. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  198914. {
  198915. unsigned int cpu = 0;
  198916. unsigned int ext = 0;
  198917. unsigned int family = 0;
  198918. #if JUCE_GCC
  198919. unsigned int dummy = 0;
  198920. #endif
  198921. #ifndef __MINGW32__
  198922. __try
  198923. #endif
  198924. {
  198925. #if JUCE_GCC
  198926. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  198927. #else
  198928. __asm
  198929. {
  198930. mov eax, 1
  198931. cpuid
  198932. mov cpu, edx
  198933. mov family, eax
  198934. mov ext, ebx
  198935. }
  198936. #endif
  198937. }
  198938. #ifndef __MINGW32__
  198939. __except (EXCEPTION_EXECUTE_HANDLER)
  198940. {
  198941. return 0;
  198942. }
  198943. #endif
  198944. if (familyModel != 0)
  198945. *familyModel = family;
  198946. if (extFeatures != 0)
  198947. *extFeatures = ext;
  198948. return cpu;
  198949. }*/
  198950. static void juce_getCpuVendor (char* const v)
  198951. {
  198952. int vendor[4];
  198953. zeromem (vendor, 16);
  198954. #ifdef JUCE_64BIT
  198955. #else
  198956. #ifndef __MINGW32__
  198957. __try
  198958. #endif
  198959. {
  198960. #if JUCE_GCC
  198961. unsigned int dummy = 0;
  198962. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  198963. #else
  198964. __asm
  198965. {
  198966. mov eax, 0
  198967. cpuid
  198968. mov [vendor], ebx
  198969. mov [vendor + 4], edx
  198970. mov [vendor + 8], ecx
  198971. }
  198972. #endif
  198973. }
  198974. #ifndef __MINGW32__
  198975. __except (EXCEPTION_EXECUTE_HANDLER)
  198976. {
  198977. *v = 0;
  198978. }
  198979. #endif
  198980. #endif
  198981. memcpy (v, vendor, 16);
  198982. }
  198983. const String SystemStats::getCpuVendor() throw()
  198984. {
  198985. char v [16];
  198986. juce_getCpuVendor (v);
  198987. return String (v, 16);
  198988. }
  198989. #endif
  198990. struct CPUFlags
  198991. {
  198992. bool hasMMX : 1;
  198993. bool hasSSE : 1;
  198994. bool hasSSE2 : 1;
  198995. bool has3DNow : 1;
  198996. };
  198997. static CPUFlags cpuFlags;
  198998. bool SystemStats::hasMMX() throw()
  198999. {
  199000. return cpuFlags.hasMMX;
  199001. }
  199002. bool SystemStats::hasSSE() throw()
  199003. {
  199004. return cpuFlags.hasSSE;
  199005. }
  199006. bool SystemStats::hasSSE2() throw()
  199007. {
  199008. return cpuFlags.hasSSE2;
  199009. }
  199010. bool SystemStats::has3DNow() throw()
  199011. {
  199012. return cpuFlags.has3DNow;
  199013. }
  199014. void SystemStats::initialiseStats() throw()
  199015. {
  199016. juce_initialiseThreadEvents();
  199017. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  199018. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  199019. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  199020. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  199021. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  199022. #else
  199023. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  199024. #endif
  199025. LARGE_INTEGER f;
  199026. QueryPerformanceFrequency (&f);
  199027. hiResTicksPerSecond = f.QuadPart;
  199028. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  199029. String s (SystemStats::getJUCEVersion());
  199030. #ifdef JUCE_DEBUG
  199031. const MMRESULT res = timeBeginPeriod (1);
  199032. jassert (res == TIMERR_NOERROR);
  199033. #else
  199034. timeBeginPeriod (1);
  199035. #endif
  199036. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199037. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  199038. #endif
  199039. }
  199040. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  199041. {
  199042. OSVERSIONINFO info;
  199043. info.dwOSVersionInfoSize = sizeof (info);
  199044. GetVersionEx (&info);
  199045. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  199046. {
  199047. switch (info.dwMajorVersion)
  199048. {
  199049. case 5:
  199050. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  199051. case 6:
  199052. return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  199053. default:
  199054. jassertfalse // !! not a supported OS!
  199055. break;
  199056. }
  199057. }
  199058. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  199059. {
  199060. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  199061. return Win98;
  199062. }
  199063. return UnknownOS;
  199064. }
  199065. const String SystemStats::getOperatingSystemName() throw()
  199066. {
  199067. const char* name = "Unknown OS";
  199068. switch (getOperatingSystemType())
  199069. {
  199070. case WinVista:
  199071. name = "Windows Vista";
  199072. break;
  199073. case WinXP:
  199074. name = "Windows XP";
  199075. break;
  199076. case Win2000:
  199077. name = "Windows 2000";
  199078. break;
  199079. case Win98:
  199080. name = "Windows 98";
  199081. break;
  199082. default:
  199083. jassertfalse // !! new type of OS?
  199084. break;
  199085. }
  199086. return name;
  199087. }
  199088. bool SystemStats::isOperatingSystem64Bit() throw()
  199089. {
  199090. #ifdef _WIN64
  199091. return true;
  199092. #else
  199093. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  199094. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  199095. BOOL isWow64 = FALSE;
  199096. return (fnIsWow64Process != 0)
  199097. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  199098. && (isWow64 != FALSE);
  199099. #endif
  199100. }
  199101. int SystemStats::getMemorySizeInMegabytes() throw()
  199102. {
  199103. MEMORYSTATUS mem;
  199104. GlobalMemoryStatus (&mem);
  199105. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  199106. }
  199107. int SystemStats::getNumCpus() throw()
  199108. {
  199109. SYSTEM_INFO systemInfo;
  199110. GetSystemInfo (&systemInfo);
  199111. return systemInfo.dwNumberOfProcessors;
  199112. }
  199113. uint32 juce_millisecondsSinceStartup() throw()
  199114. {
  199115. return (uint32) GetTickCount();
  199116. }
  199117. int64 Time::getHighResolutionTicks() throw()
  199118. {
  199119. LARGE_INTEGER ticks;
  199120. QueryPerformanceCounter (&ticks);
  199121. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  199122. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  199123. // fix for a very obscure PCI hardware bug that can make the counter
  199124. // sometimes jump forwards by a few seconds..
  199125. static int64 hiResTicksOffset = 0;
  199126. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  199127. if (offsetDrift > (hiResTicksPerSecond >> 1))
  199128. hiResTicksOffset = newOffset;
  199129. return ticks.QuadPart + hiResTicksOffset;
  199130. }
  199131. double Time::getMillisecondCounterHiRes() throw()
  199132. {
  199133. return getHighResolutionTicks() * hiResTicksScaleFactor;
  199134. }
  199135. int64 Time::getHighResolutionTicksPerSecond() throw()
  199136. {
  199137. return hiResTicksPerSecond;
  199138. }
  199139. int64 SystemStats::getClockCycleCounter() throw()
  199140. {
  199141. #if JUCE_USE_INTRINSICS
  199142. // MS intrinsics version...
  199143. return __rdtsc();
  199144. #elif JUCE_GCC
  199145. // GNU inline asm version...
  199146. unsigned int hi = 0, lo = 0;
  199147. __asm__ __volatile__ (
  199148. "xor %%eax, %%eax \n\
  199149. xor %%edx, %%edx \n\
  199150. rdtsc \n\
  199151. movl %%eax, %[lo] \n\
  199152. movl %%edx, %[hi]"
  199153. :
  199154. : [hi] "m" (hi),
  199155. [lo] "m" (lo)
  199156. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  199157. return (int64) ((((uint64) hi) << 32) | lo);
  199158. #else
  199159. // MSVC inline asm version...
  199160. unsigned int hi = 0, lo = 0;
  199161. __asm
  199162. {
  199163. xor eax, eax
  199164. xor edx, edx
  199165. rdtsc
  199166. mov lo, eax
  199167. mov hi, edx
  199168. }
  199169. return (int64) ((((uint64) hi) << 32) | lo);
  199170. #endif
  199171. }
  199172. int SystemStats::getCpuSpeedInMegaherz() throw()
  199173. {
  199174. const int64 cycles = SystemStats::getClockCycleCounter();
  199175. const uint32 millis = Time::getMillisecondCounter();
  199176. int lastResult = 0;
  199177. for (;;)
  199178. {
  199179. int n = 1000000;
  199180. while (--n > 0) {}
  199181. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  199182. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  199183. if (millisElapsed > 80)
  199184. {
  199185. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  199186. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  199187. return newResult;
  199188. lastResult = newResult;
  199189. }
  199190. }
  199191. }
  199192. bool Time::setSystemTimeToThisTime() const throw()
  199193. {
  199194. SYSTEMTIME st;
  199195. st.wDayOfWeek = 0;
  199196. st.wYear = (WORD) getYear();
  199197. st.wMonth = (WORD) (getMonth() + 1);
  199198. st.wDay = (WORD) getDayOfMonth();
  199199. st.wHour = (WORD) getHours();
  199200. st.wMinute = (WORD) getMinutes();
  199201. st.wSecond = (WORD) getSeconds();
  199202. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  199203. // do this twice because of daylight saving conversion problems - the
  199204. // first one sets it up, the second one kicks it in.
  199205. return SetLocalTime (&st) != 0
  199206. && SetLocalTime (&st) != 0;
  199207. }
  199208. int SystemStats::getPageSize() throw()
  199209. {
  199210. SYSTEM_INFO systemInfo;
  199211. GetSystemInfo (&systemInfo);
  199212. return systemInfo.dwPageSize;
  199213. }
  199214. #endif
  199215. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  199216. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  199217. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199218. // compiled on its own).
  199219. #if JUCE_INCLUDED_FILE
  199220. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199221. extern HWND juce_messageWindowHandle;
  199222. #endif
  199223. CriticalSection::CriticalSection() throw()
  199224. {
  199225. // (just to check the MS haven't changed this structure and broken things...)
  199226. #if _MSC_VER >= 1400
  199227. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  199228. #else
  199229. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  199230. #endif
  199231. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  199232. }
  199233. CriticalSection::~CriticalSection() throw()
  199234. {
  199235. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  199236. }
  199237. void CriticalSection::enter() const throw()
  199238. {
  199239. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  199240. }
  199241. bool CriticalSection::tryEnter() const throw()
  199242. {
  199243. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  199244. }
  199245. void CriticalSection::exit() const throw()
  199246. {
  199247. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  199248. }
  199249. WaitableEvent::WaitableEvent() throw()
  199250. : internal (CreateEvent (0, FALSE, FALSE, 0))
  199251. {
  199252. }
  199253. WaitableEvent::~WaitableEvent() throw()
  199254. {
  199255. CloseHandle (internal);
  199256. }
  199257. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  199258. {
  199259. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  199260. }
  199261. void WaitableEvent::signal() const throw()
  199262. {
  199263. SetEvent (internal);
  199264. }
  199265. void WaitableEvent::reset() const throw()
  199266. {
  199267. ResetEvent (internal);
  199268. }
  199269. void JUCE_API juce_threadEntryPoint (void*);
  199270. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  199271. {
  199272. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  199273. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  199274. GetCurrentThreadId(), TRUE);
  199275. #endif
  199276. juce_threadEntryPoint (userData);
  199277. _endthreadex (0);
  199278. return 0;
  199279. }
  199280. void juce_CloseThreadHandle (void* handle) throw()
  199281. {
  199282. CloseHandle ((HANDLE) handle);
  199283. }
  199284. void* juce_createThread (void* userData) throw()
  199285. {
  199286. unsigned int threadId;
  199287. return (void*) _beginthreadex (0, 0,
  199288. &threadEntryProc,
  199289. userData,
  199290. 0, &threadId);
  199291. }
  199292. void juce_killThread (void* handle) throw()
  199293. {
  199294. if (handle != 0)
  199295. {
  199296. #ifdef JUCE_DEBUG
  199297. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  199298. #endif
  199299. TerminateThread (handle, 0);
  199300. }
  199301. }
  199302. void juce_setCurrentThreadName (const String& name) throw()
  199303. {
  199304. #if defined (JUCE_DEBUG) && JUCE_MSVC
  199305. struct
  199306. {
  199307. DWORD dwType;
  199308. LPCSTR szName;
  199309. DWORD dwThreadID;
  199310. DWORD dwFlags;
  199311. } info;
  199312. info.dwType = 0x1000;
  199313. info.szName = name;
  199314. info.dwThreadID = GetCurrentThreadId();
  199315. info.dwFlags = 0;
  199316. #define MS_VC_EXCEPTION 0x406d1388
  199317. __try
  199318. {
  199319. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  199320. }
  199321. __except (EXCEPTION_CONTINUE_EXECUTION)
  199322. {}
  199323. #else
  199324. (void) name;
  199325. #endif
  199326. }
  199327. Thread::ThreadID Thread::getCurrentThreadId() throw()
  199328. {
  199329. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  199330. }
  199331. // priority 1 to 10 where 5=normal, 1=low
  199332. bool juce_setThreadPriority (void* threadHandle, int priority) throw()
  199333. {
  199334. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  199335. if (priority < 1)
  199336. pri = THREAD_PRIORITY_IDLE;
  199337. else if (priority < 2)
  199338. pri = THREAD_PRIORITY_LOWEST;
  199339. else if (priority < 5)
  199340. pri = THREAD_PRIORITY_BELOW_NORMAL;
  199341. else if (priority < 7)
  199342. pri = THREAD_PRIORITY_NORMAL;
  199343. else if (priority < 9)
  199344. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  199345. else if (priority < 10)
  199346. pri = THREAD_PRIORITY_HIGHEST;
  199347. if (threadHandle == 0)
  199348. threadHandle = GetCurrentThread();
  199349. return SetThreadPriority (threadHandle, pri) != FALSE;
  199350. }
  199351. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  199352. {
  199353. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  199354. }
  199355. static HANDLE sleepEvent = 0;
  199356. void juce_initialiseThreadEvents() throw()
  199357. {
  199358. if (sleepEvent == 0)
  199359. #ifdef JUCE_DEBUG
  199360. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  199361. #else
  199362. sleepEvent = CreateEvent (0, 0, 0, 0);
  199363. #endif
  199364. }
  199365. void Thread::yield() throw()
  199366. {
  199367. Sleep (0);
  199368. }
  199369. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  199370. {
  199371. if (millisecs >= 10)
  199372. {
  199373. Sleep (millisecs);
  199374. }
  199375. else
  199376. {
  199377. jassert (sleepEvent != 0);
  199378. // unlike Sleep() this is guaranteed to return to the current thread after
  199379. // the time expires, so we'll use this for short waits, which are more likely
  199380. // to need to be accurate
  199381. WaitForSingleObject (sleepEvent, millisecs);
  199382. }
  199383. }
  199384. static int lastProcessPriority = -1;
  199385. // called by WindowDriver because Windows does wierd things to process priority
  199386. // when you swap apps, and this forces an update when the app is brought to the front.
  199387. void juce_repeatLastProcessPriority() throw()
  199388. {
  199389. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  199390. {
  199391. DWORD p;
  199392. switch (lastProcessPriority)
  199393. {
  199394. case Process::LowPriority:
  199395. p = IDLE_PRIORITY_CLASS;
  199396. break;
  199397. case Process::NormalPriority:
  199398. p = NORMAL_PRIORITY_CLASS;
  199399. break;
  199400. case Process::HighPriority:
  199401. p = HIGH_PRIORITY_CLASS;
  199402. break;
  199403. case Process::RealtimePriority:
  199404. p = REALTIME_PRIORITY_CLASS;
  199405. break;
  199406. default:
  199407. jassertfalse // bad priority value
  199408. return;
  199409. }
  199410. SetPriorityClass (GetCurrentProcess(), p);
  199411. }
  199412. }
  199413. void Process::setPriority (ProcessPriority prior)
  199414. {
  199415. if (lastProcessPriority != (int) prior)
  199416. {
  199417. lastProcessPriority = (int) prior;
  199418. juce_repeatLastProcessPriority();
  199419. }
  199420. }
  199421. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  199422. {
  199423. return IsDebuggerPresent() != FALSE;
  199424. }
  199425. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  199426. {
  199427. return juce_isRunningUnderDebugger();
  199428. }
  199429. void Process::raisePrivilege()
  199430. {
  199431. jassertfalse // xxx not implemented
  199432. }
  199433. void Process::lowerPrivilege()
  199434. {
  199435. jassertfalse // xxx not implemented
  199436. }
  199437. void Process::terminate()
  199438. {
  199439. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  199440. _CrtDumpMemoryLeaks();
  199441. #endif
  199442. // bullet in the head in case there's a problem shutting down..
  199443. ExitProcess (0);
  199444. }
  199445. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  199446. {
  199447. void* result = 0;
  199448. JUCE_TRY
  199449. {
  199450. result = (void*) LoadLibrary (name);
  199451. }
  199452. JUCE_CATCH_ALL
  199453. return result;
  199454. }
  199455. void PlatformUtilities::freeDynamicLibrary (void* h)
  199456. {
  199457. JUCE_TRY
  199458. {
  199459. if (h != 0)
  199460. FreeLibrary ((HMODULE) h);
  199461. }
  199462. JUCE_CATCH_ALL
  199463. }
  199464. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  199465. {
  199466. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  199467. : 0;
  199468. }
  199469. InterProcessLock::InterProcessLock (const String& name_) throw()
  199470. : internal (0),
  199471. name (name_),
  199472. reentrancyLevel (0)
  199473. {
  199474. }
  199475. InterProcessLock::~InterProcessLock() throw()
  199476. {
  199477. exit();
  199478. }
  199479. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  199480. {
  199481. if (reentrancyLevel++ == 0)
  199482. {
  199483. internal = CreateMutex (0, TRUE, name);
  199484. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  199485. {
  199486. if (timeOutMillisecs == 0
  199487. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  199488. == WAIT_TIMEOUT)
  199489. {
  199490. ReleaseMutex (internal);
  199491. CloseHandle (internal);
  199492. internal = 0;
  199493. }
  199494. }
  199495. }
  199496. return (internal != 0);
  199497. }
  199498. void InterProcessLock::exit() throw()
  199499. {
  199500. if (--reentrancyLevel == 0 && internal != 0)
  199501. {
  199502. ReleaseMutex (internal);
  199503. CloseHandle (internal);
  199504. internal = 0;
  199505. }
  199506. }
  199507. #endif
  199508. /********* End of inlined file: juce_win32_Threads.cpp *********/
  199509. /********* Start of inlined file: juce_win32_Files.cpp *********/
  199510. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  199511. // compiled on its own).
  199512. #if JUCE_INCLUDED_FILE
  199513. #ifndef CSIDL_MYMUSIC
  199514. #define CSIDL_MYMUSIC 0x000d
  199515. #endif
  199516. #ifndef CSIDL_MYVIDEO
  199517. #define CSIDL_MYVIDEO 0x000e
  199518. #endif
  199519. const tchar File::separator = T('\\');
  199520. const tchar* File::separatorString = T("\\");
  199521. bool juce_fileExists (const String& fileName,
  199522. const bool dontCountDirectories) throw()
  199523. {
  199524. if (fileName.isEmpty())
  199525. return false;
  199526. const DWORD attr = GetFileAttributes (fileName);
  199527. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  199528. : (attr != 0xffffffff);
  199529. }
  199530. bool juce_isDirectory (const String& fileName) throw()
  199531. {
  199532. const DWORD attr = GetFileAttributes (fileName);
  199533. return (attr != 0xffffffff)
  199534. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199535. }
  199536. bool juce_canWriteToFile (const String& fileName) throw()
  199537. {
  199538. const DWORD attr = GetFileAttributes (fileName);
  199539. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  199540. }
  199541. bool juce_setFileReadOnly (const String& fileName,
  199542. bool isReadOnly) throw()
  199543. {
  199544. DWORD attr = GetFileAttributes (fileName);
  199545. if (attr == 0xffffffff)
  199546. return false;
  199547. if (isReadOnly != juce_canWriteToFile (fileName))
  199548. return true;
  199549. if (isReadOnly)
  199550. attr |= FILE_ATTRIBUTE_READONLY;
  199551. else
  199552. attr &= ~FILE_ATTRIBUTE_READONLY;
  199553. return SetFileAttributes (fileName, attr) != FALSE;
  199554. }
  199555. bool File::isHidden() const throw()
  199556. {
  199557. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  199558. }
  199559. bool juce_deleteFile (const String& fileName) throw()
  199560. {
  199561. if (juce_isDirectory (fileName))
  199562. return RemoveDirectory (fileName) != 0;
  199563. return DeleteFile (fileName) != 0;
  199564. }
  199565. bool File::moveToTrash() const throw()
  199566. {
  199567. if (! exists())
  199568. return true;
  199569. SHFILEOPSTRUCT fos;
  199570. zerostruct (fos);
  199571. // The string we pass in must be double null terminated..
  199572. String doubleNullTermPath (getFullPathName() + " ");
  199573. TCHAR* p = (TCHAR*) (const TCHAR*) doubleNullTermPath;
  199574. p [getFullPathName().length()] = 0;
  199575. fos.wFunc = FO_DELETE;
  199576. fos.hwnd = (HWND) 0;
  199577. fos.pFrom = p;
  199578. fos.pTo = NULL;
  199579. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  199580. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  199581. return SHFileOperation (&fos) == 0;
  199582. }
  199583. bool juce_moveFile (const String& source, const String& dest) throw()
  199584. {
  199585. return MoveFile (source, dest) != 0;
  199586. }
  199587. bool juce_copyFile (const String& source, const String& dest) throw()
  199588. {
  199589. return CopyFile (source, dest, false) != 0;
  199590. }
  199591. void juce_createDirectory (const String& fileName) throw()
  199592. {
  199593. if (! juce_fileExists (fileName, true))
  199594. {
  199595. CreateDirectory (fileName, 0);
  199596. }
  199597. }
  199598. // return 0 if not possible
  199599. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  199600. {
  199601. HANDLE h;
  199602. if (forWriting)
  199603. {
  199604. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  199605. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  199606. if (h != INVALID_HANDLE_VALUE)
  199607. SetFilePointer (h, 0, 0, FILE_END);
  199608. else
  199609. h = 0;
  199610. }
  199611. else
  199612. {
  199613. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  199614. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  199615. if (h == INVALID_HANDLE_VALUE)
  199616. h = 0;
  199617. }
  199618. return (void*) h;
  199619. }
  199620. void juce_fileClose (void* handle) throw()
  199621. {
  199622. CloseHandle (handle);
  199623. }
  199624. int juce_fileRead (void* handle, void* buffer, int size) throw()
  199625. {
  199626. DWORD num = 0;
  199627. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  199628. return num;
  199629. }
  199630. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  199631. {
  199632. DWORD num;
  199633. WriteFile ((HANDLE) handle,
  199634. buffer, size,
  199635. &num, 0);
  199636. return num;
  199637. }
  199638. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  199639. {
  199640. LARGE_INTEGER li;
  199641. li.QuadPart = pos;
  199642. li.LowPart = SetFilePointer ((HANDLE) handle,
  199643. li.LowPart,
  199644. &li.HighPart,
  199645. FILE_BEGIN); // (returns -1 if it fails)
  199646. return li.QuadPart;
  199647. }
  199648. int64 juce_fileGetPosition (void* handle) throw()
  199649. {
  199650. LARGE_INTEGER li;
  199651. li.QuadPart = 0;
  199652. li.LowPart = SetFilePointer ((HANDLE) handle,
  199653. 0, &li.HighPart,
  199654. FILE_CURRENT); // (returns -1 if it fails)
  199655. return jmax ((int64) 0, li.QuadPart);
  199656. }
  199657. void juce_fileFlush (void* handle) throw()
  199658. {
  199659. FlushFileBuffers ((HANDLE) handle);
  199660. }
  199661. int64 juce_getFileSize (const String& fileName) throw()
  199662. {
  199663. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199664. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199665. {
  199666. return (((int64) attributes.nFileSizeHigh) << 32)
  199667. | attributes.nFileSizeLow;
  199668. }
  199669. return 0;
  199670. }
  199671. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  199672. {
  199673. // tell me if this fails!
  199674. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  199675. #if JUCE_GCC
  199676. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  199677. #else
  199678. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  199679. #endif
  199680. }
  199681. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  199682. {
  199683. #if JUCE_GCC
  199684. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  199685. #else
  199686. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  199687. #endif
  199688. }
  199689. void juce_getFileTimes (const String& fileName,
  199690. int64& modificationTime,
  199691. int64& accessTime,
  199692. int64& creationTime) throw()
  199693. {
  199694. WIN32_FILE_ATTRIBUTE_DATA attributes;
  199695. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  199696. {
  199697. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  199698. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  199699. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  199700. }
  199701. else
  199702. {
  199703. creationTime = accessTime = modificationTime = 0;
  199704. }
  199705. }
  199706. bool juce_setFileTimes (const String& fileName,
  199707. int64 modificationTime,
  199708. int64 accessTime,
  199709. int64 creationTime) throw()
  199710. {
  199711. FILETIME m, a, c;
  199712. if (modificationTime > 0)
  199713. timeToFileTime (modificationTime, &m);
  199714. if (accessTime > 0)
  199715. timeToFileTime (accessTime, &a);
  199716. if (creationTime > 0)
  199717. timeToFileTime (creationTime, &c);
  199718. void* const h = juce_fileOpen (fileName, true);
  199719. bool ok = false;
  199720. if (h != 0)
  199721. {
  199722. ok = SetFileTime ((HANDLE) h,
  199723. (creationTime > 0) ? &c : 0,
  199724. (accessTime > 0) ? &a : 0,
  199725. (modificationTime > 0) ? &m : 0) != 0;
  199726. juce_fileClose (h);
  199727. }
  199728. return ok;
  199729. }
  199730. // return '\0' separated list of strings
  199731. const StringArray juce_getFileSystemRoots() throw()
  199732. {
  199733. TCHAR buffer [2048];
  199734. buffer[0] = 0;
  199735. buffer[1] = 0;
  199736. GetLogicalDriveStrings (2048, buffer);
  199737. TCHAR* n = buffer;
  199738. StringArray roots;
  199739. while (*n != 0)
  199740. {
  199741. roots.add (String (n));
  199742. while (*n++ != 0)
  199743. {
  199744. }
  199745. }
  199746. roots.sort (true);
  199747. return roots;
  199748. }
  199749. const String juce_getVolumeLabel (const String& filenameOnVolume,
  199750. int& volumeSerialNumber) throw()
  199751. {
  199752. TCHAR n [4];
  199753. n[0] = *(const TCHAR*) filenameOnVolume;
  199754. n[1] = L':';
  199755. n[2] = L'\\';
  199756. n[3] = 0;
  199757. TCHAR dest [64];
  199758. DWORD serialNum;
  199759. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  199760. {
  199761. dest[0] = 0;
  199762. serialNum = 0;
  199763. }
  199764. volumeSerialNumber = serialNum;
  199765. return String (dest);
  199766. }
  199767. static int64 getDiskSpaceInfo (String fn, const bool total) throw()
  199768. {
  199769. if (fn[1] == T(':'))
  199770. fn = fn.substring (0, 2) + T("\\");
  199771. ULARGE_INTEGER spc, tot, totFree;
  199772. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  199773. return (int64) (total ? tot.QuadPart
  199774. : spc.QuadPart);
  199775. return 0;
  199776. }
  199777. int64 File::getBytesFreeOnVolume() const throw()
  199778. {
  199779. return getDiskSpaceInfo (getFullPathName(), false);
  199780. }
  199781. int64 File::getVolumeTotalSize() const throw()
  199782. {
  199783. return getDiskSpaceInfo (getFullPathName(), true);
  199784. }
  199785. static unsigned int getWindowsDriveType (const String& fileName) throw()
  199786. {
  199787. TCHAR n[4];
  199788. n[0] = *(const TCHAR*) fileName;
  199789. n[1] = L':';
  199790. n[2] = L'\\';
  199791. n[3] = 0;
  199792. return GetDriveType (n);
  199793. }
  199794. bool File::isOnCDRomDrive() const throw()
  199795. {
  199796. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  199797. }
  199798. bool File::isOnHardDisk() const throw()
  199799. {
  199800. if (fullPath.isEmpty())
  199801. return false;
  199802. const unsigned int n = getWindowsDriveType (getFullPathName());
  199803. if (fullPath.toLowerCase()[0] <= 'b'
  199804. && fullPath[1] == T(':'))
  199805. {
  199806. return n != DRIVE_REMOVABLE;
  199807. }
  199808. else
  199809. {
  199810. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  199811. }
  199812. }
  199813. bool File::isOnRemovableDrive() const throw()
  199814. {
  199815. if (fullPath.isEmpty())
  199816. return false;
  199817. const unsigned int n = getWindowsDriveType (getFullPathName());
  199818. return n == DRIVE_CDROM
  199819. || n == DRIVE_REMOTE
  199820. || n == DRIVE_REMOVABLE
  199821. || n == DRIVE_RAMDISK;
  199822. }
  199823. #define MAX_PATH_CHARS (MAX_PATH + 256)
  199824. static const File juce_getSpecialFolderPath (int type) throw()
  199825. {
  199826. WCHAR path [MAX_PATH_CHARS];
  199827. if (SHGetSpecialFolderPath (0, path, type, 0))
  199828. return File (String (path));
  199829. return File::nonexistent;
  199830. }
  199831. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  199832. {
  199833. int csidlType = 0;
  199834. switch (type)
  199835. {
  199836. case userHomeDirectory:
  199837. case userDocumentsDirectory:
  199838. csidlType = CSIDL_PERSONAL;
  199839. break;
  199840. case userDesktopDirectory:
  199841. csidlType = CSIDL_DESKTOP;
  199842. break;
  199843. case userApplicationDataDirectory:
  199844. csidlType = CSIDL_APPDATA;
  199845. break;
  199846. case commonApplicationDataDirectory:
  199847. csidlType = CSIDL_COMMON_APPDATA;
  199848. break;
  199849. case globalApplicationsDirectory:
  199850. csidlType = CSIDL_PROGRAM_FILES;
  199851. break;
  199852. case userMusicDirectory:
  199853. csidlType = CSIDL_MYMUSIC;
  199854. break;
  199855. case userMoviesDirectory:
  199856. csidlType = CSIDL_MYVIDEO;
  199857. break;
  199858. case tempDirectory:
  199859. {
  199860. WCHAR dest [2048];
  199861. dest[0] = 0;
  199862. GetTempPath (2048, dest);
  199863. return File (String (dest));
  199864. }
  199865. case currentExecutableFile:
  199866. case currentApplicationFile:
  199867. {
  199868. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  199869. WCHAR dest [MAX_PATH_CHARS];
  199870. dest[0] = 0;
  199871. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  199872. return File (String (dest));
  199873. }
  199874. break;
  199875. default:
  199876. jassertfalse // unknown type?
  199877. return File::nonexistent;
  199878. }
  199879. return juce_getSpecialFolderPath (csidlType);
  199880. }
  199881. const File File::getCurrentWorkingDirectory() throw()
  199882. {
  199883. WCHAR dest [MAX_PATH_CHARS];
  199884. dest[0] = 0;
  199885. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  199886. return File (String (dest));
  199887. }
  199888. bool File::setAsCurrentWorkingDirectory() const throw()
  199889. {
  199890. return SetCurrentDirectory (getFullPathName()) != FALSE;
  199891. }
  199892. const String File::getVersion() const throw()
  199893. {
  199894. String result;
  199895. DWORD handle = 0;
  199896. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  199897. void* buffer = juce_calloc (bufferSize);
  199898. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  199899. {
  199900. VS_FIXEDFILEINFO* vffi;
  199901. UINT len = 0;
  199902. if (VerQueryValue (buffer, _T("\\"), (LPVOID*) &vffi, &len))
  199903. {
  199904. result.printf (T("%d.%d.%d.%d"),
  199905. HIWORD (vffi->dwFileVersionMS),
  199906. LOWORD (vffi->dwFileVersionMS),
  199907. HIWORD (vffi->dwFileVersionLS),
  199908. LOWORD (vffi->dwFileVersionLS));
  199909. }
  199910. }
  199911. juce_free (buffer);
  199912. return result;
  199913. }
  199914. const File File::getLinkedTarget() const throw()
  199915. {
  199916. File result (*this);
  199917. String p (getFullPathName());
  199918. if (! exists())
  199919. p += T(".lnk");
  199920. else if (getFileExtension() != T(".lnk"))
  199921. return result;
  199922. ComSmartPtr <IShellLink> shellLink;
  199923. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink, CLSCTX_INPROC_SERVER)))
  199924. {
  199925. ComSmartPtr <IPersistFile> persistFile;
  199926. if (SUCCEEDED (shellLink->QueryInterface (IID_IPersistFile, (LPVOID*) &persistFile)))
  199927. {
  199928. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  199929. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  199930. {
  199931. WIN32_FIND_DATA winFindData;
  199932. WCHAR resolvedPath [MAX_PATH];
  199933. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  199934. result = File (resolvedPath);
  199935. }
  199936. }
  199937. }
  199938. return result;
  199939. }
  199940. template <class FindDataType>
  199941. static void getFindFileInfo (FindDataType& findData,
  199942. String& filename, bool* const isDir, bool* const isHidden,
  199943. int64* const fileSize, Time* const modTime, Time* const creationTime,
  199944. bool* const isReadOnly) throw()
  199945. {
  199946. filename = findData.cFileName;
  199947. if (isDir != 0)
  199948. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  199949. if (isHidden != 0)
  199950. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  199951. if (fileSize != 0)
  199952. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  199953. if (modTime != 0)
  199954. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  199955. if (creationTime != 0)
  199956. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  199957. if (isReadOnly != 0)
  199958. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  199959. }
  199960. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  199961. bool* isDir, bool* isHidden, int64* fileSize,
  199962. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199963. {
  199964. String wc (directory);
  199965. if (! wc.endsWithChar (File::separator))
  199966. wc += File::separator;
  199967. wc += wildCard;
  199968. WIN32_FIND_DATA findData;
  199969. HANDLE h = FindFirstFile (wc, &findData);
  199970. if (h != INVALID_HANDLE_VALUE)
  199971. {
  199972. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  199973. modTime, creationTime, isReadOnly);
  199974. return h;
  199975. }
  199976. firstResult = String::empty;
  199977. return 0;
  199978. }
  199979. bool juce_findFileNext (void* handle, String& resultFile,
  199980. bool* isDir, bool* isHidden, int64* fileSize,
  199981. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  199982. {
  199983. WIN32_FIND_DATA findData;
  199984. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  199985. {
  199986. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  199987. modTime, creationTime, isReadOnly);
  199988. return true;
  199989. }
  199990. resultFile = String::empty;
  199991. return false;
  199992. }
  199993. void juce_findFileClose (void* handle) throw()
  199994. {
  199995. FindClose (handle);
  199996. }
  199997. bool juce_launchFile (const String& fileName,
  199998. const String& parameters) throw()
  199999. {
  200000. HINSTANCE hInstance = 0;
  200001. JUCE_TRY
  200002. {
  200003. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  200004. }
  200005. JUCE_CATCH_ALL
  200006. return hInstance > (HINSTANCE) 32;
  200007. }
  200008. struct NamedPipeInternal
  200009. {
  200010. HANDLE pipeH;
  200011. HANDLE cancelEvent;
  200012. bool connected, createdPipe;
  200013. NamedPipeInternal()
  200014. : pipeH (0),
  200015. cancelEvent (0),
  200016. connected (false),
  200017. createdPipe (false)
  200018. {
  200019. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  200020. }
  200021. ~NamedPipeInternal()
  200022. {
  200023. disconnect();
  200024. if (pipeH != 0)
  200025. CloseHandle (pipeH);
  200026. CloseHandle (cancelEvent);
  200027. }
  200028. bool connect (const int timeOutMs)
  200029. {
  200030. if (! createdPipe)
  200031. return true;
  200032. if (! connected)
  200033. {
  200034. OVERLAPPED over;
  200035. zerostruct (over);
  200036. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200037. if (ConnectNamedPipe (pipeH, &over))
  200038. {
  200039. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  200040. }
  200041. else
  200042. {
  200043. const int err = GetLastError();
  200044. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  200045. {
  200046. HANDLE handles[] = { over.hEvent, cancelEvent };
  200047. if (WaitForMultipleObjects (2, handles, FALSE,
  200048. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  200049. connected = true;
  200050. }
  200051. else if (err == ERROR_PIPE_CONNECTED)
  200052. {
  200053. connected = true;
  200054. }
  200055. }
  200056. CloseHandle (over.hEvent);
  200057. }
  200058. return connected;
  200059. }
  200060. void disconnect()
  200061. {
  200062. if (connected)
  200063. {
  200064. DisconnectNamedPipe (pipeH);
  200065. connected = false;
  200066. }
  200067. }
  200068. };
  200069. void NamedPipe::close()
  200070. {
  200071. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200072. delete intern;
  200073. internal = 0;
  200074. }
  200075. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  200076. {
  200077. close();
  200078. NamedPipeInternal* const intern = new NamedPipeInternal();
  200079. String file ("\\\\.\\pipe\\");
  200080. file += pipeName;
  200081. intern->createdPipe = createPipe;
  200082. if (createPipe)
  200083. {
  200084. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  200085. PIPE_UNLIMITED_INSTANCES,
  200086. 4096, 4096, 0, NULL);
  200087. }
  200088. else
  200089. {
  200090. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  200091. FILE_FLAG_OVERLAPPED, 0);
  200092. }
  200093. if (intern->pipeH != INVALID_HANDLE_VALUE)
  200094. {
  200095. internal = intern;
  200096. return true;
  200097. }
  200098. delete intern;
  200099. return false;
  200100. }
  200101. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  200102. {
  200103. int bytesRead = -1;
  200104. bool waitAgain = true;
  200105. while (waitAgain && internal != 0)
  200106. {
  200107. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200108. waitAgain = false;
  200109. if (! intern->connect (timeOutMilliseconds))
  200110. break;
  200111. if (maxBytesToRead <= 0)
  200112. return 0;
  200113. OVERLAPPED over;
  200114. zerostruct (over);
  200115. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200116. unsigned long numRead;
  200117. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  200118. {
  200119. bytesRead = (int) numRead;
  200120. }
  200121. else if (GetLastError() == ERROR_IO_PENDING)
  200122. {
  200123. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200124. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200125. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200126. : INFINITE);
  200127. if (waitResult != WAIT_OBJECT_0)
  200128. {
  200129. // if the operation timed out, let's cancel it...
  200130. CancelIo (intern->pipeH);
  200131. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  200132. }
  200133. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  200134. {
  200135. bytesRead = (int) numRead;
  200136. }
  200137. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200138. {
  200139. intern->disconnect();
  200140. waitAgain = true;
  200141. }
  200142. }
  200143. else
  200144. {
  200145. waitAgain = internal != 0;
  200146. Sleep (5);
  200147. }
  200148. CloseHandle (over.hEvent);
  200149. }
  200150. return bytesRead;
  200151. }
  200152. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  200153. {
  200154. int bytesWritten = -1;
  200155. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200156. if (intern != 0 && intern->connect (timeOutMilliseconds))
  200157. {
  200158. if (numBytesToWrite <= 0)
  200159. return 0;
  200160. OVERLAPPED over;
  200161. zerostruct (over);
  200162. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  200163. unsigned long numWritten;
  200164. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  200165. {
  200166. bytesWritten = (int) numWritten;
  200167. }
  200168. else if (GetLastError() == ERROR_IO_PENDING)
  200169. {
  200170. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  200171. DWORD waitResult;
  200172. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  200173. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  200174. : INFINITE);
  200175. if (waitResult != WAIT_OBJECT_0)
  200176. {
  200177. CancelIo (intern->pipeH);
  200178. WaitForSingleObject (over.hEvent, INFINITE);
  200179. }
  200180. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  200181. {
  200182. bytesWritten = (int) numWritten;
  200183. }
  200184. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  200185. {
  200186. intern->disconnect();
  200187. }
  200188. }
  200189. CloseHandle (over.hEvent);
  200190. }
  200191. return bytesWritten;
  200192. }
  200193. void NamedPipe::cancelPendingReads()
  200194. {
  200195. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  200196. if (intern != 0)
  200197. SetEvent (intern->cancelEvent);
  200198. }
  200199. #endif
  200200. /********* End of inlined file: juce_win32_Files.cpp *********/
  200201. /********* Start of inlined file: juce_win32_Network.cpp *********/
  200202. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200203. // compiled on its own).
  200204. #if JUCE_INCLUDED_FILE
  200205. #ifndef INTERNET_FLAG_NEED_FILE
  200206. #define INTERNET_FLAG_NEED_FILE 0x00000010
  200207. #endif
  200208. bool juce_isOnLine()
  200209. {
  200210. DWORD connectionType;
  200211. return InternetGetConnectedState (&connectionType, 0) != 0
  200212. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  200213. }
  200214. struct ConnectionAndRequestStruct
  200215. {
  200216. HINTERNET connection, request;
  200217. };
  200218. static HINTERNET sessionHandle = 0;
  200219. void* juce_openInternetFile (const String& url,
  200220. const String& headers,
  200221. const MemoryBlock& postData,
  200222. const bool isPost,
  200223. URL::OpenStreamProgressCallback* callback,
  200224. void* callbackContext,
  200225. int timeOutMs)
  200226. {
  200227. if (sessionHandle == 0)
  200228. sessionHandle = InternetOpen (_T("juce"),
  200229. INTERNET_OPEN_TYPE_PRECONFIG,
  200230. 0, 0, 0);
  200231. if (sessionHandle != 0)
  200232. {
  200233. // break up the url..
  200234. TCHAR file[1024], server[1024];
  200235. URL_COMPONENTS uc;
  200236. zerostruct (uc);
  200237. uc.dwStructSize = sizeof (uc);
  200238. uc.dwUrlPathLength = sizeof (file);
  200239. uc.dwHostNameLength = sizeof (server);
  200240. uc.lpszUrlPath = file;
  200241. uc.lpszHostName = server;
  200242. if (InternetCrackUrl (url, 0, 0, &uc))
  200243. {
  200244. if (timeOutMs == 0)
  200245. timeOutMs = 30000;
  200246. else if (timeOutMs < 0)
  200247. timeOutMs = -1;
  200248. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  200249. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  200250. HINTERNET connection = InternetConnect (sessionHandle,
  200251. uc.lpszHostName,
  200252. uc.nPort,
  200253. _T(""), _T(""),
  200254. isFtp ? INTERNET_SERVICE_FTP
  200255. : INTERNET_SERVICE_HTTP,
  200256. 0, 0);
  200257. if (connection != 0)
  200258. {
  200259. if (isFtp)
  200260. {
  200261. HINTERNET request = FtpOpenFile (connection,
  200262. uc.lpszUrlPath,
  200263. GENERIC_READ,
  200264. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  200265. 0);
  200266. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  200267. result->connection = connection;
  200268. result->request = request;
  200269. return result;
  200270. }
  200271. else
  200272. {
  200273. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  200274. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  200275. if (url.startsWithIgnoreCase (T("https:")))
  200276. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  200277. // IE7 seems to automatically work out when it's https)
  200278. HINTERNET request = HttpOpenRequest (connection,
  200279. isPost ? _T("POST")
  200280. : _T("GET"),
  200281. uc.lpszUrlPath,
  200282. 0, 0, mimeTypes, flags, 0);
  200283. if (request != 0)
  200284. {
  200285. INTERNET_BUFFERS buffers;
  200286. zerostruct (buffers);
  200287. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  200288. buffers.lpcszHeader = (LPCTSTR) headers;
  200289. buffers.dwHeadersLength = headers.length();
  200290. buffers.dwBufferTotal = (DWORD) postData.getSize();
  200291. ConnectionAndRequestStruct* result = 0;
  200292. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  200293. {
  200294. int bytesSent = 0;
  200295. for (;;)
  200296. {
  200297. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  200298. DWORD bytesDone = 0;
  200299. if (bytesToDo > 0
  200300. && ! InternetWriteFile (request,
  200301. ((const char*) postData.getData()) + bytesSent,
  200302. bytesToDo, &bytesDone))
  200303. {
  200304. break;
  200305. }
  200306. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  200307. {
  200308. result = new ConnectionAndRequestStruct();
  200309. result->connection = connection;
  200310. result->request = request;
  200311. HttpEndRequest (request, 0, 0, 0);
  200312. return result;
  200313. }
  200314. bytesSent += bytesDone;
  200315. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  200316. break;
  200317. }
  200318. }
  200319. InternetCloseHandle (request);
  200320. }
  200321. InternetCloseHandle (connection);
  200322. }
  200323. }
  200324. }
  200325. }
  200326. return 0;
  200327. }
  200328. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  200329. {
  200330. DWORD bytesRead = 0;
  200331. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200332. if (crs != 0)
  200333. InternetReadFile (crs->request,
  200334. buffer, bytesToRead,
  200335. &bytesRead);
  200336. return bytesRead;
  200337. }
  200338. int juce_seekInInternetFile (void* handle, int newPosition)
  200339. {
  200340. if (handle != 0)
  200341. {
  200342. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200343. return InternetSetFilePointer (crs->request,
  200344. newPosition, 0,
  200345. FILE_BEGIN, 0);
  200346. }
  200347. else
  200348. {
  200349. return -1;
  200350. }
  200351. }
  200352. int64 juce_getInternetFileContentLength (void* handle)
  200353. {
  200354. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  200355. if (crs != 0)
  200356. {
  200357. DWORD index = 0;
  200358. DWORD result = 0;
  200359. DWORD size = sizeof (result);
  200360. if (HttpQueryInfo (crs->request,
  200361. HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER,
  200362. &result,
  200363. &size,
  200364. &index))
  200365. {
  200366. return (int64) result;
  200367. }
  200368. }
  200369. return -1;
  200370. }
  200371. void juce_closeInternetFile (void* handle)
  200372. {
  200373. if (handle != 0)
  200374. {
  200375. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  200376. InternetCloseHandle (crs->request);
  200377. InternetCloseHandle (crs->connection);
  200378. delete crs;
  200379. }
  200380. }
  200381. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  200382. {
  200383. int numFound = 0;
  200384. DynamicLibraryLoader dll ("iphlpapi.dll");
  200385. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  200386. if (getAdaptersInfo != 0)
  200387. {
  200388. ULONG len = sizeof (IP_ADAPTER_INFO);
  200389. MemoryBlock mb;
  200390. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200391. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  200392. {
  200393. mb.setSize (len);
  200394. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  200395. }
  200396. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  200397. {
  200398. PIP_ADAPTER_INFO adapter = adapterInfo;
  200399. while (adapter != 0)
  200400. {
  200401. int64 mac = 0;
  200402. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  200403. mac = (mac << 8) | adapter->Address[i];
  200404. if (littleEndian)
  200405. mac = (int64) swapByteOrder ((uint64) mac);
  200406. if (numFound < maxNum && mac != 0)
  200407. addresses [numFound++] = mac;
  200408. adapter = adapter->Next;
  200409. }
  200410. }
  200411. }
  200412. return numFound;
  200413. }
  200414. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  200415. {
  200416. int numFound = 0;
  200417. DynamicLibraryLoader dll ("netapi32.dll");
  200418. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  200419. if (NetbiosCall != 0)
  200420. {
  200421. NCB ncb;
  200422. zerostruct (ncb);
  200423. typedef struct _ASTAT_
  200424. {
  200425. ADAPTER_STATUS adapt;
  200426. NAME_BUFFER NameBuff [30];
  200427. } ASTAT;
  200428. ASTAT astat;
  200429. zerostruct (astat);
  200430. LANA_ENUM enums;
  200431. zerostruct (enums);
  200432. ncb.ncb_command = NCBENUM;
  200433. ncb.ncb_buffer = (unsigned char*) &enums;
  200434. ncb.ncb_length = sizeof (LANA_ENUM);
  200435. NetbiosCall (&ncb);
  200436. for (int i = 0; i < enums.length; ++i)
  200437. {
  200438. zerostruct (ncb);
  200439. ncb.ncb_command = NCBRESET;
  200440. ncb.ncb_lana_num = enums.lana[i];
  200441. if (NetbiosCall (&ncb) == 0)
  200442. {
  200443. zerostruct (ncb);
  200444. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  200445. ncb.ncb_command = NCBASTAT;
  200446. ncb.ncb_lana_num = enums.lana[i];
  200447. ncb.ncb_buffer = (unsigned char*) &astat;
  200448. ncb.ncb_length = sizeof (ASTAT);
  200449. if (NetbiosCall (&ncb) == 0)
  200450. {
  200451. if (astat.adapt.adapter_type == 0xfe)
  200452. {
  200453. int64 mac = 0;
  200454. for (unsigned int i = 0; i < 6; ++i)
  200455. mac = (mac << 8) | astat.adapt.adapter_address[i];
  200456. if (littleEndian)
  200457. mac = (int64) swapByteOrder ((uint64) mac);
  200458. if (numFound < maxNum && mac != 0)
  200459. addresses [numFound++] = mac;
  200460. }
  200461. }
  200462. }
  200463. }
  200464. }
  200465. return numFound;
  200466. }
  200467. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  200468. {
  200469. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  200470. if (numFound == 0)
  200471. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  200472. return numFound;
  200473. }
  200474. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  200475. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  200476. const String& emailSubject,
  200477. const String& bodyText,
  200478. const StringArray& filesToAttach)
  200479. {
  200480. HMODULE h = LoadLibraryA ("MAPI32.dll");
  200481. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  200482. bool ok = false;
  200483. if (mapiSendMail != 0)
  200484. {
  200485. MapiMessage message;
  200486. zerostruct (message);
  200487. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  200488. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  200489. MapiRecipDesc recip;
  200490. zerostruct (recip);
  200491. recip.ulRecipClass = MAPI_TO;
  200492. String targetEmailAddress_ (targetEmailAddress);
  200493. if (targetEmailAddress_.isEmpty())
  200494. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  200495. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress_;
  200496. message.nRecipCount = 1;
  200497. message.lpRecips = &recip;
  200498. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  200499. mb.fillWith (0);
  200500. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  200501. message.nFileCount = filesToAttach.size();
  200502. message.lpFiles = files;
  200503. for (int i = 0; i < filesToAttach.size(); ++i)
  200504. {
  200505. files[i].nPosition = (ULONG) -1;
  200506. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  200507. }
  200508. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  200509. }
  200510. FreeLibrary (h);
  200511. return ok;
  200512. }
  200513. #endif
  200514. /********* End of inlined file: juce_win32_Network.cpp *********/
  200515. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  200516. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200517. // compiled on its own).
  200518. #if JUCE_INCLUDED_FILE
  200519. static HKEY findKeyForPath (String name,
  200520. const bool createForWriting,
  200521. String& valueName) throw()
  200522. {
  200523. HKEY rootKey = 0;
  200524. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  200525. rootKey = HKEY_CURRENT_USER;
  200526. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  200527. rootKey = HKEY_LOCAL_MACHINE;
  200528. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  200529. rootKey = HKEY_CLASSES_ROOT;
  200530. if (rootKey != 0)
  200531. {
  200532. name = name.substring (name.indexOfChar (T('\\')) + 1);
  200533. const int lastSlash = name.lastIndexOfChar (T('\\'));
  200534. valueName = name.substring (lastSlash + 1);
  200535. name = name.substring (0, lastSlash);
  200536. HKEY key;
  200537. DWORD result;
  200538. if (createForWriting)
  200539. {
  200540. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  200541. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  200542. return key;
  200543. }
  200544. else
  200545. {
  200546. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  200547. return key;
  200548. }
  200549. }
  200550. return 0;
  200551. }
  200552. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  200553. const String& defaultValue)
  200554. {
  200555. String valueName, s;
  200556. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200557. if (k != 0)
  200558. {
  200559. WCHAR buffer [2048];
  200560. unsigned long bufferSize = sizeof (buffer);
  200561. DWORD type = REG_SZ;
  200562. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  200563. s = buffer;
  200564. else
  200565. s = defaultValue;
  200566. RegCloseKey (k);
  200567. }
  200568. return s;
  200569. }
  200570. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  200571. const String& value)
  200572. {
  200573. String valueName;
  200574. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200575. if (k != 0)
  200576. {
  200577. RegSetValueEx (k, valueName, 0, REG_SZ,
  200578. (const BYTE*) (const WCHAR*) value,
  200579. sizeof (WCHAR) * (value.length() + 1));
  200580. RegCloseKey (k);
  200581. }
  200582. }
  200583. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  200584. {
  200585. bool exists = false;
  200586. String valueName;
  200587. HKEY k = findKeyForPath (regValuePath, false, valueName);
  200588. if (k != 0)
  200589. {
  200590. unsigned char buffer [2048];
  200591. unsigned long bufferSize = sizeof (buffer);
  200592. DWORD type = 0;
  200593. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  200594. exists = true;
  200595. RegCloseKey (k);
  200596. }
  200597. return exists;
  200598. }
  200599. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  200600. {
  200601. String valueName;
  200602. HKEY k = findKeyForPath (regValuePath, true, valueName);
  200603. if (k != 0)
  200604. {
  200605. RegDeleteValue (k, valueName);
  200606. RegCloseKey (k);
  200607. }
  200608. }
  200609. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  200610. {
  200611. String valueName;
  200612. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  200613. if (k != 0)
  200614. {
  200615. RegDeleteKey (k, valueName);
  200616. RegCloseKey (k);
  200617. }
  200618. }
  200619. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  200620. const String& symbolicDescription,
  200621. const String& fullDescription,
  200622. const File& targetExecutable,
  200623. int iconResourceNumber)
  200624. {
  200625. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  200626. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  200627. if (iconResourceNumber != 0)
  200628. setRegistryValue (key + "\\DefaultIcon\\",
  200629. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  200630. setRegistryValue (key + "\\", fullDescription);
  200631. setRegistryValue (key + "\\shell\\open\\command\\",
  200632. targetExecutable.getFullPathName() + " %1");
  200633. }
  200634. bool juce_IsRunningInWine() throw()
  200635. {
  200636. HKEY key;
  200637. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  200638. {
  200639. RegCloseKey (key);
  200640. return true;
  200641. }
  200642. return false;
  200643. }
  200644. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  200645. {
  200646. String s (::GetCommandLineW());
  200647. StringArray tokens;
  200648. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  200649. return tokens.joinIntoString (T(" "), 1);
  200650. }
  200651. static void* currentModuleHandle = 0;
  200652. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  200653. {
  200654. if (currentModuleHandle == 0)
  200655. currentModuleHandle = GetModuleHandle (0);
  200656. return currentModuleHandle;
  200657. }
  200658. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  200659. {
  200660. currentModuleHandle = newHandle;
  200661. }
  200662. void PlatformUtilities::fpuReset()
  200663. {
  200664. #if JUCE_MSVC
  200665. _clearfp();
  200666. #endif
  200667. }
  200668. void PlatformUtilities::beep()
  200669. {
  200670. MessageBeep (MB_OK);
  200671. }
  200672. #endif
  200673. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  200674. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  200675. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  200676. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200677. // compiled on its own).
  200678. #if JUCE_INCLUDED_FILE
  200679. static const unsigned int specialId = WM_APP + 0x4400;
  200680. static const unsigned int broadcastId = WM_APP + 0x4403;
  200681. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  200682. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  200683. HWND juce_messageWindowHandle = 0;
  200684. extern long improbableWindowNumber; // defined in windowing.cpp
  200685. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  200686. const UINT message,
  200687. const WPARAM wParam,
  200688. const LPARAM lParam) throw()
  200689. {
  200690. JUCE_TRY
  200691. {
  200692. if (h == juce_messageWindowHandle)
  200693. {
  200694. if (message == specialCallbackId)
  200695. {
  200696. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  200697. return (LRESULT) (*func) ((void*) lParam);
  200698. }
  200699. else if (message == specialId)
  200700. {
  200701. // these are trapped early in the dispatch call, but must also be checked
  200702. // here in case there are windows modal dialog boxes doing their own
  200703. // dispatch loop and not calling our version
  200704. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  200705. return 0;
  200706. }
  200707. else if (message == broadcastId)
  200708. {
  200709. String* const messageString = (String*) lParam;
  200710. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  200711. delete messageString;
  200712. return 0;
  200713. }
  200714. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  200715. {
  200716. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  200717. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  200718. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  200719. return 0;
  200720. }
  200721. }
  200722. }
  200723. JUCE_CATCH_EXCEPTION
  200724. return DefWindowProc (h, message, wParam, lParam);
  200725. }
  200726. static bool isEventBlockedByModalComps (MSG& m)
  200727. {
  200728. if (Component::getNumCurrentlyModalComponents() == 0
  200729. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  200730. return false;
  200731. switch (m.message)
  200732. {
  200733. case WM_MOUSEMOVE:
  200734. case WM_NCMOUSEMOVE:
  200735. case 0x020A: /* WM_MOUSEWHEEL */
  200736. case 0x020E: /* WM_MOUSEHWHEEL */
  200737. case WM_KEYUP:
  200738. case WM_SYSKEYUP:
  200739. case WM_CHAR:
  200740. case WM_APPCOMMAND:
  200741. case WM_LBUTTONUP:
  200742. case WM_MBUTTONUP:
  200743. case WM_RBUTTONUP:
  200744. case WM_MOUSEACTIVATE:
  200745. case WM_NCMOUSEHOVER:
  200746. case WM_MOUSEHOVER:
  200747. return true;
  200748. case WM_NCLBUTTONDOWN:
  200749. case WM_NCLBUTTONDBLCLK:
  200750. case WM_NCRBUTTONDOWN:
  200751. case WM_NCRBUTTONDBLCLK:
  200752. case WM_NCMBUTTONDOWN:
  200753. case WM_NCMBUTTONDBLCLK:
  200754. case WM_LBUTTONDOWN:
  200755. case WM_LBUTTONDBLCLK:
  200756. case WM_MBUTTONDOWN:
  200757. case WM_MBUTTONDBLCLK:
  200758. case WM_RBUTTONDOWN:
  200759. case WM_RBUTTONDBLCLK:
  200760. case WM_KEYDOWN:
  200761. case WM_SYSKEYDOWN:
  200762. {
  200763. Component* const modal = Component::getCurrentlyModalComponent (0);
  200764. if (modal != 0)
  200765. modal->inputAttemptWhenModal();
  200766. return true;
  200767. }
  200768. default:
  200769. break;
  200770. }
  200771. return false;
  200772. }
  200773. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  200774. {
  200775. MSG m;
  200776. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  200777. return false;
  200778. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  200779. {
  200780. if (m.message == specialId
  200781. && m.hwnd == juce_messageWindowHandle)
  200782. {
  200783. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  200784. }
  200785. else if (! isEventBlockedByModalComps (m))
  200786. {
  200787. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  200788. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  200789. {
  200790. // if it's someone else's window being clicked on, and the focus is
  200791. // currently on a juce window, pass the kb focus over..
  200792. HWND currentFocus = GetFocus();
  200793. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  200794. SetFocus (m.hwnd);
  200795. }
  200796. TranslateMessage (&m);
  200797. DispatchMessage (&m);
  200798. }
  200799. }
  200800. return true;
  200801. }
  200802. bool juce_postMessageToSystemQueue (void* message)
  200803. {
  200804. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  200805. }
  200806. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  200807. void* userData)
  200808. {
  200809. if (MessageManager::getInstance()->isThisTheMessageThread())
  200810. {
  200811. return (*callback) (userData);
  200812. }
  200813. else
  200814. {
  200815. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  200816. // deadlock because the message manager is blocked from running, and can't
  200817. // call your function..
  200818. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  200819. return (void*) SendMessage (juce_messageWindowHandle,
  200820. specialCallbackId,
  200821. (WPARAM) callback,
  200822. (LPARAM) userData);
  200823. }
  200824. }
  200825. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  200826. {
  200827. if (hwnd != juce_messageWindowHandle)
  200828. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  200829. return TRUE;
  200830. }
  200831. void MessageManager::broadcastMessage (const String& value) throw()
  200832. {
  200833. VoidArray windows;
  200834. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  200835. const String localCopy (value);
  200836. COPYDATASTRUCT data;
  200837. data.dwData = broadcastId;
  200838. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  200839. data.lpData = (void*) (const juce_wchar*) localCopy;
  200840. for (int i = windows.size(); --i >= 0;)
  200841. {
  200842. HWND hwnd = (HWND) windows.getUnchecked(i);
  200843. TCHAR windowName [64]; // no need to read longer strings than this
  200844. GetWindowText (hwnd, windowName, 64);
  200845. windowName [63] = 0;
  200846. if (String (windowName) == String (messageWindowName))
  200847. {
  200848. DWORD_PTR result;
  200849. SendMessageTimeout (hwnd, WM_COPYDATA,
  200850. (WPARAM) juce_messageWindowHandle,
  200851. (LPARAM) &data,
  200852. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  200853. 8000,
  200854. &result);
  200855. }
  200856. }
  200857. }
  200858. static const String getMessageWindowClassName()
  200859. {
  200860. // this name has to be different for each app/dll instance because otherwise
  200861. // poor old Win32 can get a bit confused (even despite it not being a process-global
  200862. // window class).
  200863. static int number = 0;
  200864. if (number == 0)
  200865. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  200866. return T("JUCEcs_") + String (number);
  200867. }
  200868. void MessageManager::doPlatformSpecificInitialisation()
  200869. {
  200870. OleInitialize (0);
  200871. const String className (getMessageWindowClassName());
  200872. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  200873. WNDCLASSEX wc;
  200874. zerostruct (wc);
  200875. wc.cbSize = sizeof (wc);
  200876. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  200877. wc.cbWndExtra = 4;
  200878. wc.hInstance = hmod;
  200879. wc.lpszClassName = className;
  200880. RegisterClassEx (&wc);
  200881. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  200882. messageWindowName,
  200883. 0, 0, 0, 0, 0, 0, 0,
  200884. hmod, 0);
  200885. }
  200886. void MessageManager::doPlatformSpecificShutdown()
  200887. {
  200888. DestroyWindow (juce_messageWindowHandle);
  200889. UnregisterClass (getMessageWindowClassName(), 0);
  200890. OleUninitialize();
  200891. }
  200892. #endif
  200893. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  200894. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  200895. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  200896. // compiled on its own).
  200897. #if JUCE_INCLUDED_FILE
  200898. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  200899. // these are in the windows SDK, but need to be repeated here for GCC..
  200900. #ifndef GET_APPCOMMAND_LPARAM
  200901. #define FAPPCOMMAND_MASK 0xF000
  200902. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  200903. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  200904. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  200905. #define APPCOMMAND_MEDIA_STOP 13
  200906. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  200907. #define WM_APPCOMMAND 0x0319
  200908. #endif
  200909. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  200910. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  200911. extern bool juce_IsRunningInWine() throw();
  200912. #ifndef ULW_ALPHA
  200913. #define ULW_ALPHA 0x00000002
  200914. #endif
  200915. #ifndef AC_SRC_ALPHA
  200916. #define AC_SRC_ALPHA 0x01
  200917. #endif
  200918. #define DEBUG_REPAINT_TIMES 0
  200919. static HPALETTE palette = 0;
  200920. static bool createPaletteIfNeeded = true;
  200921. static bool shouldDeactivateTitleBar = true;
  200922. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  200923. #define WM_TRAYNOTIFY WM_USER + 100
  200924. using ::abs;
  200925. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  200926. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  200927. bool Desktop::canUseSemiTransparentWindows() throw()
  200928. {
  200929. if (updateLayeredWindow == 0)
  200930. {
  200931. if (! juce_IsRunningInWine())
  200932. {
  200933. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  200934. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  200935. }
  200936. }
  200937. return updateLayeredWindow != 0;
  200938. }
  200939. #undef DefWindowProc
  200940. #define DefWindowProc DefWindowProcW
  200941. const int extendedKeyModifier = 0x10000;
  200942. const int KeyPress::spaceKey = VK_SPACE;
  200943. const int KeyPress::returnKey = VK_RETURN;
  200944. const int KeyPress::escapeKey = VK_ESCAPE;
  200945. const int KeyPress::backspaceKey = VK_BACK;
  200946. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  200947. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  200948. const int KeyPress::tabKey = VK_TAB;
  200949. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  200950. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  200951. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  200952. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  200953. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  200954. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  200955. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  200956. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  200957. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  200958. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  200959. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  200960. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  200961. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  200962. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  200963. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  200964. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  200965. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  200966. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  200967. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  200968. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  200969. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  200970. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  200971. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  200972. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  200973. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  200974. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  200975. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  200976. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  200977. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  200978. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  200979. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  200980. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  200981. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  200982. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  200983. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  200984. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  200985. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  200986. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  200987. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  200988. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  200989. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  200990. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  200991. const int KeyPress::playKey = 0x30000;
  200992. const int KeyPress::stopKey = 0x30001;
  200993. const int KeyPress::fastForwardKey = 0x30002;
  200994. const int KeyPress::rewindKey = 0x30003;
  200995. class WindowsBitmapImage : public Image
  200996. {
  200997. public:
  200998. HBITMAP hBitmap;
  200999. BITMAPV4HEADER bitmapInfo;
  201000. HDC hdc;
  201001. unsigned char* bitmapData;
  201002. WindowsBitmapImage (const PixelFormat format_,
  201003. const int w, const int h, const bool clearImage)
  201004. : Image (format_, w, h)
  201005. {
  201006. jassert (format_ == RGB || format_ == ARGB);
  201007. pixelStride = (format_ == RGB) ? 3 : 4;
  201008. zerostruct (bitmapInfo);
  201009. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  201010. bitmapInfo.bV4Width = w;
  201011. bitmapInfo.bV4Height = h;
  201012. bitmapInfo.bV4Planes = 1;
  201013. bitmapInfo.bV4CSType = 1;
  201014. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  201015. if (format_ == ARGB)
  201016. {
  201017. bitmapInfo.bV4AlphaMask = 0xff000000;
  201018. bitmapInfo.bV4RedMask = 0xff0000;
  201019. bitmapInfo.bV4GreenMask = 0xff00;
  201020. bitmapInfo.bV4BlueMask = 0xff;
  201021. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  201022. }
  201023. else
  201024. {
  201025. bitmapInfo.bV4V4Compression = BI_RGB;
  201026. }
  201027. lineStride = -((w * pixelStride + 3) & ~3);
  201028. HDC dc = GetDC (0);
  201029. hdc = CreateCompatibleDC (dc);
  201030. ReleaseDC (0, dc);
  201031. SetMapMode (hdc, MM_TEXT);
  201032. hBitmap = CreateDIBSection (hdc,
  201033. (BITMAPINFO*) &(bitmapInfo),
  201034. DIB_RGB_COLORS,
  201035. (void**) &bitmapData,
  201036. 0, 0);
  201037. SelectObject (hdc, hBitmap);
  201038. if (format_ == ARGB && clearImage)
  201039. zeromem (bitmapData, abs (h * lineStride));
  201040. imageData = bitmapData - (lineStride * (h - 1));
  201041. }
  201042. ~WindowsBitmapImage()
  201043. {
  201044. DeleteDC (hdc);
  201045. DeleteObject (hBitmap);
  201046. imageData = 0; // to stop the base class freeing this
  201047. }
  201048. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  201049. const int x, const int y,
  201050. const RectangleList& maskedRegion) throw()
  201051. {
  201052. static HDRAWDIB hdd = 0;
  201053. static bool needToCreateDrawDib = true;
  201054. if (needToCreateDrawDib)
  201055. {
  201056. needToCreateDrawDib = false;
  201057. HDC dc = GetDC (0);
  201058. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201059. ReleaseDC (0, dc);
  201060. // only open if we're not palettised
  201061. if (n > 8)
  201062. hdd = DrawDibOpen();
  201063. }
  201064. if (createPaletteIfNeeded)
  201065. {
  201066. HDC dc = GetDC (0);
  201067. const int n = GetDeviceCaps (dc, BITSPIXEL);
  201068. ReleaseDC (0, dc);
  201069. if (n <= 8)
  201070. palette = CreateHalftonePalette (dc);
  201071. createPaletteIfNeeded = false;
  201072. }
  201073. if (palette != 0)
  201074. {
  201075. SelectPalette (dc, palette, FALSE);
  201076. RealizePalette (dc);
  201077. SetStretchBltMode (dc, HALFTONE);
  201078. }
  201079. SetMapMode (dc, MM_TEXT);
  201080. if (transparent)
  201081. {
  201082. POINT p, pos;
  201083. SIZE size;
  201084. RECT windowBounds;
  201085. GetWindowRect (hwnd, &windowBounds);
  201086. p.x = -x;
  201087. p.y = -y;
  201088. pos.x = windowBounds.left;
  201089. pos.y = windowBounds.top;
  201090. size.cx = windowBounds.right - windowBounds.left;
  201091. size.cy = windowBounds.bottom - windowBounds.top;
  201092. BLENDFUNCTION bf;
  201093. bf.AlphaFormat = AC_SRC_ALPHA;
  201094. bf.BlendFlags = 0;
  201095. bf.BlendOp = AC_SRC_OVER;
  201096. bf.SourceConstantAlpha = 0xff;
  201097. if (! maskedRegion.isEmpty())
  201098. {
  201099. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201100. {
  201101. const Rectangle& r = *i.getRectangle();
  201102. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201103. }
  201104. }
  201105. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  201106. }
  201107. else
  201108. {
  201109. int savedDC = 0;
  201110. if (! maskedRegion.isEmpty())
  201111. {
  201112. savedDC = SaveDC (dc);
  201113. for (RectangleList::Iterator i (maskedRegion); i.next();)
  201114. {
  201115. const Rectangle& r = *i.getRectangle();
  201116. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  201117. }
  201118. }
  201119. const int w = getWidth();
  201120. const int h = getHeight();
  201121. if (hdd == 0)
  201122. {
  201123. StretchDIBits (dc,
  201124. x, y, w, h,
  201125. 0, 0, w, h,
  201126. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  201127. DIB_RGB_COLORS, SRCCOPY);
  201128. }
  201129. else
  201130. {
  201131. DrawDibDraw (hdd, dc, x, y, -1, -1,
  201132. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  201133. 0, 0, w, h, 0);
  201134. }
  201135. if (! maskedRegion.isEmpty())
  201136. RestoreDC (dc, savedDC);
  201137. }
  201138. }
  201139. juce_UseDebuggingNewOperator
  201140. private:
  201141. WindowsBitmapImage (const WindowsBitmapImage&);
  201142. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  201143. };
  201144. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  201145. static int currentModifiers = 0;
  201146. static int modifiersAtLastCallback = 0;
  201147. static void updateKeyModifiers() throw()
  201148. {
  201149. currentModifiers &= ~(ModifierKeys::shiftModifier
  201150. | ModifierKeys::ctrlModifier
  201151. | ModifierKeys::altModifier);
  201152. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  201153. currentModifiers |= ModifierKeys::shiftModifier;
  201154. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  201155. currentModifiers |= ModifierKeys::ctrlModifier;
  201156. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  201157. currentModifiers |= ModifierKeys::altModifier;
  201158. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  201159. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  201160. }
  201161. void ModifierKeys::updateCurrentModifiers() throw()
  201162. {
  201163. currentModifierFlags = currentModifiers;
  201164. }
  201165. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  201166. {
  201167. SHORT k = (SHORT) keyCode;
  201168. if ((keyCode & extendedKeyModifier) == 0
  201169. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  201170. k += (SHORT) T('A') - (SHORT) T('a');
  201171. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  201172. (SHORT) '+', VK_OEM_PLUS,
  201173. (SHORT) '-', VK_OEM_MINUS,
  201174. (SHORT) '.', VK_OEM_PERIOD,
  201175. (SHORT) ';', VK_OEM_1,
  201176. (SHORT) ':', VK_OEM_1,
  201177. (SHORT) '/', VK_OEM_2,
  201178. (SHORT) '?', VK_OEM_2,
  201179. (SHORT) '[', VK_OEM_4,
  201180. (SHORT) ']', VK_OEM_6 };
  201181. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  201182. if (k == translatedValues [i])
  201183. k = translatedValues [i + 1];
  201184. return (GetKeyState (k) & 0x8000) != 0;
  201185. }
  201186. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  201187. {
  201188. updateKeyModifiers();
  201189. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201190. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  201191. currentModifiers |= ModifierKeys::leftButtonModifier;
  201192. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  201193. currentModifiers |= ModifierKeys::rightButtonModifier;
  201194. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  201195. currentModifiers |= ModifierKeys::middleButtonModifier;
  201196. return ModifierKeys (currentModifiers);
  201197. }
  201198. static int64 getMouseEventTime() throw()
  201199. {
  201200. static int64 eventTimeOffset = 0;
  201201. static DWORD lastMessageTime = 0;
  201202. const DWORD thisMessageTime = GetMessageTime();
  201203. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  201204. {
  201205. lastMessageTime = thisMessageTime;
  201206. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  201207. }
  201208. return eventTimeOffset + thisMessageTime;
  201209. }
  201210. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  201211. {
  201212. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  201213. return callback (userData);
  201214. else
  201215. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  201216. }
  201217. class Win32ComponentPeer : public ComponentPeer
  201218. {
  201219. public:
  201220. Win32ComponentPeer (Component* const component,
  201221. const int windowStyleFlags)
  201222. : ComponentPeer (component, windowStyleFlags),
  201223. dontRepaint (false),
  201224. fullScreen (false),
  201225. isDragging (false),
  201226. isMouseOver (false),
  201227. hasCreatedCaret (false),
  201228. currentWindowIcon (0),
  201229. taskBarIcon (0),
  201230. dropTarget (0)
  201231. {
  201232. callFunctionIfNotLocked (&createWindowCallback, (void*) this);
  201233. setTitle (component->getName());
  201234. if ((windowStyleFlags & windowHasDropShadow) != 0
  201235. && Desktop::canUseSemiTransparentWindows())
  201236. {
  201237. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  201238. if (shadower != 0)
  201239. shadower->setOwner (component);
  201240. }
  201241. else
  201242. {
  201243. shadower = 0;
  201244. }
  201245. }
  201246. ~Win32ComponentPeer()
  201247. {
  201248. setTaskBarIcon (0);
  201249. deleteAndZero (shadower);
  201250. // do this before the next bit to avoid messages arriving for this window
  201251. // before it's destroyed
  201252. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  201253. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  201254. if (currentWindowIcon != 0)
  201255. DestroyIcon (currentWindowIcon);
  201256. if (dropTarget != 0)
  201257. {
  201258. dropTarget->Release();
  201259. dropTarget = 0;
  201260. }
  201261. }
  201262. void* getNativeHandle() const
  201263. {
  201264. return (void*) hwnd;
  201265. }
  201266. void setVisible (bool shouldBeVisible)
  201267. {
  201268. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  201269. if (shouldBeVisible)
  201270. InvalidateRect (hwnd, 0, 0);
  201271. else
  201272. lastPaintTime = 0;
  201273. }
  201274. void setTitle (const String& title)
  201275. {
  201276. SetWindowText (hwnd, title);
  201277. }
  201278. void setPosition (int x, int y)
  201279. {
  201280. offsetWithinParent (x, y);
  201281. SetWindowPos (hwnd, 0,
  201282. x - windowBorder.getLeft(),
  201283. y - windowBorder.getTop(),
  201284. 0, 0,
  201285. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201286. }
  201287. void repaintNowIfTransparent()
  201288. {
  201289. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  201290. handlePaintMessage();
  201291. }
  201292. void updateBorderSize()
  201293. {
  201294. WINDOWINFO info;
  201295. info.cbSize = sizeof (info);
  201296. if (GetWindowInfo (hwnd, &info))
  201297. {
  201298. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  201299. info.rcClient.left - info.rcWindow.left,
  201300. info.rcWindow.bottom - info.rcClient.bottom,
  201301. info.rcWindow.right - info.rcClient.right);
  201302. }
  201303. }
  201304. void setSize (int w, int h)
  201305. {
  201306. SetWindowPos (hwnd, 0, 0, 0,
  201307. w + windowBorder.getLeftAndRight(),
  201308. h + windowBorder.getTopAndBottom(),
  201309. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201310. updateBorderSize();
  201311. repaintNowIfTransparent();
  201312. }
  201313. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  201314. {
  201315. fullScreen = isNowFullScreen;
  201316. offsetWithinParent (x, y);
  201317. SetWindowPos (hwnd, 0,
  201318. x - windowBorder.getLeft(),
  201319. y - windowBorder.getTop(),
  201320. w + windowBorder.getLeftAndRight(),
  201321. h + windowBorder.getTopAndBottom(),
  201322. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  201323. updateBorderSize();
  201324. repaintNowIfTransparent();
  201325. }
  201326. void getBounds (int& x, int& y, int& w, int& h) const
  201327. {
  201328. RECT r;
  201329. GetWindowRect (hwnd, &r);
  201330. x = r.left;
  201331. y = r.top;
  201332. w = r.right - x;
  201333. h = r.bottom - y;
  201334. HWND parentH = GetParent (hwnd);
  201335. if (parentH != 0)
  201336. {
  201337. GetWindowRect (parentH, &r);
  201338. x -= r.left;
  201339. y -= r.top;
  201340. }
  201341. x += windowBorder.getLeft();
  201342. y += windowBorder.getTop();
  201343. w -= windowBorder.getLeftAndRight();
  201344. h -= windowBorder.getTopAndBottom();
  201345. }
  201346. int getScreenX() const
  201347. {
  201348. RECT r;
  201349. GetWindowRect (hwnd, &r);
  201350. return r.left + windowBorder.getLeft();
  201351. }
  201352. int getScreenY() const
  201353. {
  201354. RECT r;
  201355. GetWindowRect (hwnd, &r);
  201356. return r.top + windowBorder.getTop();
  201357. }
  201358. void relativePositionToGlobal (int& x, int& y)
  201359. {
  201360. RECT r;
  201361. GetWindowRect (hwnd, &r);
  201362. x += r.left + windowBorder.getLeft();
  201363. y += r.top + windowBorder.getTop();
  201364. }
  201365. void globalPositionToRelative (int& x, int& y)
  201366. {
  201367. RECT r;
  201368. GetWindowRect (hwnd, &r);
  201369. x -= r.left + windowBorder.getLeft();
  201370. y -= r.top + windowBorder.getTop();
  201371. }
  201372. void setMinimised (bool shouldBeMinimised)
  201373. {
  201374. if (shouldBeMinimised != isMinimised())
  201375. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  201376. }
  201377. bool isMinimised() const
  201378. {
  201379. WINDOWPLACEMENT wp;
  201380. wp.length = sizeof (WINDOWPLACEMENT);
  201381. GetWindowPlacement (hwnd, &wp);
  201382. return wp.showCmd == SW_SHOWMINIMIZED;
  201383. }
  201384. void setFullScreen (bool shouldBeFullScreen)
  201385. {
  201386. setMinimised (false);
  201387. if (fullScreen != shouldBeFullScreen)
  201388. {
  201389. fullScreen = shouldBeFullScreen;
  201390. const ComponentDeletionWatcher deletionChecker (component);
  201391. if (! fullScreen)
  201392. {
  201393. const Rectangle boundsCopy (lastNonFullscreenBounds);
  201394. if (hasTitleBar())
  201395. ShowWindow (hwnd, SW_SHOWNORMAL);
  201396. if (! boundsCopy.isEmpty())
  201397. {
  201398. setBounds (boundsCopy.getX(),
  201399. boundsCopy.getY(),
  201400. boundsCopy.getWidth(),
  201401. boundsCopy.getHeight(),
  201402. false);
  201403. }
  201404. }
  201405. else
  201406. {
  201407. if (hasTitleBar())
  201408. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  201409. else
  201410. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  201411. }
  201412. if (! deletionChecker.hasBeenDeleted())
  201413. handleMovedOrResized();
  201414. }
  201415. }
  201416. bool isFullScreen() const
  201417. {
  201418. if (! hasTitleBar())
  201419. return fullScreen;
  201420. WINDOWPLACEMENT wp;
  201421. wp.length = sizeof (wp);
  201422. GetWindowPlacement (hwnd, &wp);
  201423. return wp.showCmd == SW_SHOWMAXIMIZED;
  201424. }
  201425. bool contains (int x, int y, bool trueIfInAChildWindow) const
  201426. {
  201427. RECT r;
  201428. GetWindowRect (hwnd, &r);
  201429. POINT p;
  201430. p.x = x + r.left + windowBorder.getLeft();
  201431. p.y = y + r.top + windowBorder.getTop();
  201432. HWND w = WindowFromPoint (p);
  201433. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  201434. }
  201435. const BorderSize getFrameSize() const
  201436. {
  201437. return windowBorder;
  201438. }
  201439. bool setAlwaysOnTop (bool alwaysOnTop)
  201440. {
  201441. const bool oldDeactivate = shouldDeactivateTitleBar;
  201442. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201443. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  201444. 0, 0, 0, 0,
  201445. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201446. shouldDeactivateTitleBar = oldDeactivate;
  201447. if (shadower != 0)
  201448. shadower->componentBroughtToFront (*component);
  201449. return true;
  201450. }
  201451. void toFront (bool makeActive)
  201452. {
  201453. setMinimised (false);
  201454. const bool oldDeactivate = shouldDeactivateTitleBar;
  201455. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201456. callFunctionIfNotLocked (makeActive ? &toFrontCallback1
  201457. : &toFrontCallback2,
  201458. (void*) hwnd);
  201459. shouldDeactivateTitleBar = oldDeactivate;
  201460. if (! makeActive)
  201461. {
  201462. // in this case a broughttofront call won't have occured, so do it now..
  201463. handleBroughtToFront();
  201464. }
  201465. }
  201466. void toBehind (ComponentPeer* other)
  201467. {
  201468. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  201469. jassert (otherPeer != 0); // wrong type of window?
  201470. if (otherPeer != 0)
  201471. {
  201472. setMinimised (false);
  201473. // must be careful not to try to put a topmost window behind a normal one, or win32
  201474. // promotes the normal one to be topmost!
  201475. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  201476. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  201477. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201478. else if (otherPeer->getComponent()->isAlwaysOnTop())
  201479. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  201480. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201481. }
  201482. }
  201483. bool isFocused() const
  201484. {
  201485. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  201486. }
  201487. void grabFocus()
  201488. {
  201489. const bool oldDeactivate = shouldDeactivateTitleBar;
  201490. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  201491. callFunctionIfNotLocked (&setFocusCallback, (void*) hwnd);
  201492. shouldDeactivateTitleBar = oldDeactivate;
  201493. }
  201494. void textInputRequired (int /*x*/, int /*y*/)
  201495. {
  201496. if (! hasCreatedCaret)
  201497. {
  201498. hasCreatedCaret = true;
  201499. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  201500. }
  201501. ShowCaret (hwnd);
  201502. SetCaretPos (0, 0);
  201503. }
  201504. void repaint (int x, int y, int w, int h)
  201505. {
  201506. const RECT r = { x, y, x + w, y + h };
  201507. InvalidateRect (hwnd, &r, FALSE);
  201508. }
  201509. void performAnyPendingRepaintsNow()
  201510. {
  201511. MSG m;
  201512. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  201513. DispatchMessage (&m);
  201514. }
  201515. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  201516. {
  201517. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  201518. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  201519. return 0;
  201520. }
  201521. void setTaskBarIcon (const Image* const image)
  201522. {
  201523. if (image != 0)
  201524. {
  201525. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  201526. if (taskBarIcon == 0)
  201527. {
  201528. taskBarIcon = new NOTIFYICONDATA();
  201529. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  201530. taskBarIcon->hWnd = (HWND) hwnd;
  201531. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  201532. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  201533. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  201534. taskBarIcon->hIcon = hicon;
  201535. taskBarIcon->szTip[0] = 0;
  201536. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  201537. }
  201538. else
  201539. {
  201540. HICON oldIcon = taskBarIcon->hIcon;
  201541. taskBarIcon->hIcon = hicon;
  201542. taskBarIcon->uFlags = NIF_ICON;
  201543. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201544. DestroyIcon (oldIcon);
  201545. }
  201546. DestroyIcon (hicon);
  201547. }
  201548. else if (taskBarIcon != 0)
  201549. {
  201550. taskBarIcon->uFlags = 0;
  201551. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  201552. DestroyIcon (taskBarIcon->hIcon);
  201553. deleteAndZero (taskBarIcon);
  201554. }
  201555. }
  201556. void setTaskBarIconToolTip (const String& toolTip) const
  201557. {
  201558. if (taskBarIcon != 0)
  201559. {
  201560. taskBarIcon->uFlags = NIF_TIP;
  201561. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  201562. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  201563. }
  201564. }
  201565. bool isInside (HWND h) const
  201566. {
  201567. return GetAncestor (hwnd, GA_ROOT) == h;
  201568. }
  201569. juce_UseDebuggingNewOperator
  201570. bool dontRepaint;
  201571. private:
  201572. HWND hwnd;
  201573. DropShadower* shadower;
  201574. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  201575. BorderSize windowBorder;
  201576. HICON currentWindowIcon;
  201577. NOTIFYICONDATA* taskBarIcon;
  201578. IDropTarget* dropTarget;
  201579. class TemporaryImage : public Timer
  201580. {
  201581. public:
  201582. TemporaryImage()
  201583. : image (0)
  201584. {
  201585. }
  201586. ~TemporaryImage()
  201587. {
  201588. delete image;
  201589. }
  201590. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  201591. {
  201592. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  201593. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  201594. {
  201595. delete image;
  201596. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  201597. }
  201598. startTimer (3000);
  201599. return image;
  201600. }
  201601. void timerCallback()
  201602. {
  201603. stopTimer();
  201604. deleteAndZero (image);
  201605. }
  201606. private:
  201607. WindowsBitmapImage* image;
  201608. TemporaryImage (const TemporaryImage&);
  201609. const TemporaryImage& operator= (const TemporaryImage&);
  201610. };
  201611. TemporaryImage offscreenImageGenerator;
  201612. class WindowClassHolder : public DeletedAtShutdown
  201613. {
  201614. public:
  201615. WindowClassHolder()
  201616. : windowClassName ("JUCE_")
  201617. {
  201618. // this name has to be different for each app/dll instance because otherwise
  201619. // poor old Win32 can get a bit confused (even despite it not being a process-global
  201620. // window class).
  201621. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  201622. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  201623. TCHAR moduleFile [1024];
  201624. moduleFile[0] = 0;
  201625. GetModuleFileName (moduleHandle, moduleFile, 1024);
  201626. WORD iconNum = 0;
  201627. WNDCLASSEX wcex;
  201628. wcex.cbSize = sizeof (wcex);
  201629. wcex.style = CS_OWNDC;
  201630. wcex.lpfnWndProc = (WNDPROC) windowProc;
  201631. wcex.lpszClassName = windowClassName;
  201632. wcex.cbClsExtra = 0;
  201633. wcex.cbWndExtra = 32;
  201634. wcex.hInstance = moduleHandle;
  201635. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201636. iconNum = 1;
  201637. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  201638. wcex.hCursor = 0;
  201639. wcex.hbrBackground = 0;
  201640. wcex.lpszMenuName = 0;
  201641. RegisterClassEx (&wcex);
  201642. }
  201643. ~WindowClassHolder()
  201644. {
  201645. if (ComponentPeer::getNumPeers() == 0)
  201646. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  201647. clearSingletonInstance();
  201648. }
  201649. String windowClassName;
  201650. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  201651. };
  201652. static void* createWindowCallback (void* userData)
  201653. {
  201654. ((Win32ComponentPeer*) userData)->createWindow();
  201655. return 0;
  201656. }
  201657. void createWindow()
  201658. {
  201659. DWORD exstyle = WS_EX_ACCEPTFILES;
  201660. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  201661. if (hasTitleBar())
  201662. {
  201663. type |= WS_OVERLAPPED;
  201664. exstyle |= WS_EX_APPWINDOW;
  201665. if ((styleFlags & windowHasCloseButton) != 0)
  201666. {
  201667. type |= WS_SYSMENU;
  201668. }
  201669. else
  201670. {
  201671. // annoyingly, windows won't let you have a min/max button without a close button
  201672. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  201673. }
  201674. if ((styleFlags & windowIsResizable) != 0)
  201675. type |= WS_THICKFRAME;
  201676. }
  201677. else
  201678. {
  201679. type |= WS_POPUP | WS_SYSMENU;
  201680. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  201681. exstyle |= WS_EX_TOOLWINDOW;
  201682. else
  201683. exstyle |= WS_EX_APPWINDOW;
  201684. }
  201685. if ((styleFlags & windowHasMinimiseButton) != 0)
  201686. type |= WS_MINIMIZEBOX;
  201687. if ((styleFlags & windowHasMaximiseButton) != 0)
  201688. type |= WS_MAXIMIZEBOX;
  201689. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  201690. exstyle |= WS_EX_TRANSPARENT;
  201691. if ((styleFlags & windowIsSemiTransparent) != 0
  201692. && Desktop::canUseSemiTransparentWindows())
  201693. exstyle |= WS_EX_LAYERED;
  201694. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  201695. if (hwnd != 0)
  201696. {
  201697. SetWindowLongPtr (hwnd, 0, 0);
  201698. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  201699. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  201700. if (dropTarget == 0)
  201701. dropTarget = new JuceDropTarget (this);
  201702. RegisterDragDrop (hwnd, dropTarget);
  201703. updateBorderSize();
  201704. // Calling this function here is (for some reason) necessary to make Windows
  201705. // correctly enable the menu items that we specify in the wm_initmenu message.
  201706. GetSystemMenu (hwnd, false);
  201707. }
  201708. else
  201709. {
  201710. jassertfalse
  201711. }
  201712. }
  201713. static void* destroyWindowCallback (void* handle)
  201714. {
  201715. RevokeDragDrop ((HWND) handle);
  201716. DestroyWindow ((HWND) handle);
  201717. return 0;
  201718. }
  201719. static void* toFrontCallback1 (void* h)
  201720. {
  201721. SetForegroundWindow ((HWND) h);
  201722. return 0;
  201723. }
  201724. static void* toFrontCallback2 (void* h)
  201725. {
  201726. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  201727. return 0;
  201728. }
  201729. static void* setFocusCallback (void* h)
  201730. {
  201731. SetFocus ((HWND) h);
  201732. return 0;
  201733. }
  201734. static void* getFocusCallback (void*)
  201735. {
  201736. return (void*) GetFocus();
  201737. }
  201738. void offsetWithinParent (int& x, int& y) const
  201739. {
  201740. if (isTransparent())
  201741. {
  201742. HWND parentHwnd = GetParent (hwnd);
  201743. if (parentHwnd != 0)
  201744. {
  201745. RECT parentRect;
  201746. GetWindowRect (parentHwnd, &parentRect);
  201747. x += parentRect.left;
  201748. y += parentRect.top;
  201749. }
  201750. }
  201751. }
  201752. bool isTransparent() const
  201753. {
  201754. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  201755. }
  201756. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  201757. void setIcon (const Image& newIcon)
  201758. {
  201759. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  201760. if (hicon != 0)
  201761. {
  201762. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  201763. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  201764. if (currentWindowIcon != 0)
  201765. DestroyIcon (currentWindowIcon);
  201766. currentWindowIcon = hicon;
  201767. }
  201768. }
  201769. void handlePaintMessage()
  201770. {
  201771. #if DEBUG_REPAINT_TIMES
  201772. const double paintStart = Time::getMillisecondCounterHiRes();
  201773. #endif
  201774. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  201775. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  201776. PAINTSTRUCT paintStruct;
  201777. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  201778. // message and become re-entrant, but that's OK
  201779. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  201780. // corrupt the image it's using to paint into, so do a check here.
  201781. static bool reentrant = false;
  201782. if (reentrant)
  201783. {
  201784. DeleteObject (rgn);
  201785. EndPaint (hwnd, &paintStruct);
  201786. return;
  201787. }
  201788. reentrant = true;
  201789. // this is the rectangle to update..
  201790. int x = paintStruct.rcPaint.left;
  201791. int y = paintStruct.rcPaint.top;
  201792. int w = paintStruct.rcPaint.right - x;
  201793. int h = paintStruct.rcPaint.bottom - y;
  201794. const bool transparent = isTransparent();
  201795. if (transparent)
  201796. {
  201797. // it's not possible to have a transparent window with a title bar at the moment!
  201798. jassert (! hasTitleBar());
  201799. RECT r;
  201800. GetWindowRect (hwnd, &r);
  201801. x = y = 0;
  201802. w = r.right - r.left;
  201803. h = r.bottom - r.top;
  201804. }
  201805. if (w > 0 && h > 0)
  201806. {
  201807. clearMaskedRegion();
  201808. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  201809. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  201810. RectangleList* const contextClip = context.getRawClipRegion();
  201811. contextClip->clear();
  201812. context.setOrigin (-x, -y);
  201813. bool needToPaintAll = true;
  201814. if (regionType == COMPLEXREGION && ! transparent)
  201815. {
  201816. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  201817. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  201818. DeleteObject (clipRgn);
  201819. char rgnData [8192];
  201820. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  201821. if (res > 0 && res <= sizeof (rgnData))
  201822. {
  201823. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  201824. if (hdr->iType == RDH_RECTANGLES
  201825. && hdr->rcBound.right - hdr->rcBound.left >= w
  201826. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  201827. {
  201828. needToPaintAll = false;
  201829. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  201830. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  201831. while (--num >= 0)
  201832. {
  201833. // (need to move this one pixel to the left because of a win32 bug)
  201834. const int cx = jmax (x, rects->left - 1);
  201835. const int cy = rects->top;
  201836. const int cw = rects->right - cx;
  201837. const int ch = rects->bottom - rects->top;
  201838. if (cx + cw - x <= w && cy + ch - y <= h)
  201839. {
  201840. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  201841. }
  201842. else
  201843. {
  201844. needToPaintAll = true;
  201845. break;
  201846. }
  201847. ++rects;
  201848. }
  201849. }
  201850. }
  201851. }
  201852. if (needToPaintAll)
  201853. {
  201854. contextClip->clear();
  201855. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  201856. }
  201857. if (transparent)
  201858. {
  201859. RectangleList::Iterator i (*contextClip);
  201860. while (i.next())
  201861. {
  201862. const Rectangle& r = *i.getRectangle();
  201863. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  201864. }
  201865. }
  201866. // if the component's not opaque, this won't draw properly unless the platform can support this
  201867. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  201868. updateCurrentModifiers();
  201869. handlePaint (context);
  201870. if (! dontRepaint)
  201871. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  201872. }
  201873. DeleteObject (rgn);
  201874. EndPaint (hwnd, &paintStruct);
  201875. reentrant = false;
  201876. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  201877. _fpreset(); // because some graphics cards can unmask FP exceptions
  201878. #endif
  201879. lastPaintTime = Time::getMillisecondCounter();
  201880. #if DEBUG_REPAINT_TIMES
  201881. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  201882. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  201883. #endif
  201884. }
  201885. void doMouseMove (const int x, const int y)
  201886. {
  201887. static uint32 lastMouseTime = 0;
  201888. // this can be set to throttle the mouse-messages to less than a
  201889. // certain number per second, as things can get unresponsive
  201890. // if each drag or move callback has to do a lot of work.
  201891. const int maxMouseMovesPerSecond = 60;
  201892. const int64 mouseEventTime = getMouseEventTime();
  201893. if (! isMouseOver)
  201894. {
  201895. isMouseOver = true;
  201896. TRACKMOUSEEVENT tme;
  201897. tme.cbSize = sizeof (tme);
  201898. tme.dwFlags = TME_LEAVE;
  201899. tme.hwndTrack = hwnd;
  201900. tme.dwHoverTime = 0;
  201901. if (! TrackMouseEvent (&tme))
  201902. {
  201903. jassertfalse;
  201904. }
  201905. updateKeyModifiers();
  201906. handleMouseEnter (x, y, mouseEventTime);
  201907. }
  201908. else if (! isDragging)
  201909. {
  201910. if (((unsigned int) x) < (unsigned int) component->getWidth()
  201911. && ((unsigned int) y) < (unsigned int) component->getHeight())
  201912. {
  201913. RECT r;
  201914. GetWindowRect (hwnd, &r);
  201915. POINT p;
  201916. p.x = x + r.left + windowBorder.getLeft();
  201917. p.y = y + r.top + windowBorder.getTop();
  201918. if (WindowFromPoint (p) == hwnd)
  201919. {
  201920. const uint32 now = Time::getMillisecondCounter();
  201921. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201922. {
  201923. lastMouseTime = now;
  201924. handleMouseMove (x, y, mouseEventTime);
  201925. }
  201926. }
  201927. }
  201928. }
  201929. else
  201930. {
  201931. const uint32 now = Time::getMillisecondCounter();
  201932. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  201933. {
  201934. lastMouseTime = now;
  201935. handleMouseDrag (x, y, mouseEventTime);
  201936. }
  201937. }
  201938. }
  201939. void doMouseDown (const int x, const int y, const WPARAM wParam)
  201940. {
  201941. if (GetCapture() != hwnd)
  201942. SetCapture (hwnd);
  201943. doMouseMove (x, y);
  201944. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201945. if ((wParam & MK_LBUTTON) != 0)
  201946. currentModifiers |= ModifierKeys::leftButtonModifier;
  201947. if ((wParam & MK_RBUTTON) != 0)
  201948. currentModifiers |= ModifierKeys::rightButtonModifier;
  201949. if ((wParam & MK_MBUTTON) != 0)
  201950. currentModifiers |= ModifierKeys::middleButtonModifier;
  201951. updateKeyModifiers();
  201952. isDragging = true;
  201953. handleMouseDown (x, y, getMouseEventTime());
  201954. }
  201955. void doMouseUp (const int x, const int y, const WPARAM wParam)
  201956. {
  201957. int numButtons = 0;
  201958. if ((wParam & MK_LBUTTON) != 0)
  201959. ++numButtons;
  201960. if ((wParam & MK_RBUTTON) != 0)
  201961. ++numButtons;
  201962. if ((wParam & MK_MBUTTON) != 0)
  201963. ++numButtons;
  201964. const int oldModifiers = currentModifiers;
  201965. // update the currentmodifiers only after the callback, so the callback
  201966. // knows which button was released.
  201967. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  201968. if ((wParam & MK_LBUTTON) != 0)
  201969. currentModifiers |= ModifierKeys::leftButtonModifier;
  201970. if ((wParam & MK_RBUTTON) != 0)
  201971. currentModifiers |= ModifierKeys::rightButtonModifier;
  201972. if ((wParam & MK_MBUTTON) != 0)
  201973. currentModifiers |= ModifierKeys::middleButtonModifier;
  201974. updateKeyModifiers();
  201975. isDragging = false;
  201976. // release the mouse capture if the user's not still got a button down
  201977. if (numButtons == 0 && hwnd == GetCapture())
  201978. ReleaseCapture();
  201979. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  201980. }
  201981. void doCaptureChanged()
  201982. {
  201983. if (isDragging)
  201984. {
  201985. RECT wr;
  201986. GetWindowRect (hwnd, &wr);
  201987. const DWORD mp = GetMessagePos();
  201988. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  201989. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  201990. (WPARAM) getMouseEventTime());
  201991. }
  201992. }
  201993. void doMouseExit()
  201994. {
  201995. if (isMouseOver)
  201996. {
  201997. isMouseOver = false;
  201998. RECT wr;
  201999. GetWindowRect (hwnd, &wr);
  202000. const DWORD mp = GetMessagePos();
  202001. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  202002. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  202003. getMouseEventTime());
  202004. }
  202005. }
  202006. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  202007. {
  202008. updateKeyModifiers();
  202009. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  202010. handleMouseWheel (isVertical ? 0 : amount,
  202011. isVertical ? amount : 0,
  202012. getMouseEventTime());
  202013. }
  202014. void sendModifierKeyChangeIfNeeded()
  202015. {
  202016. if (modifiersAtLastCallback != currentModifiers)
  202017. {
  202018. modifiersAtLastCallback = currentModifiers;
  202019. handleModifierKeysChange();
  202020. }
  202021. }
  202022. bool doKeyUp (const WPARAM key)
  202023. {
  202024. updateKeyModifiers();
  202025. switch (key)
  202026. {
  202027. case VK_SHIFT:
  202028. case VK_CONTROL:
  202029. case VK_MENU:
  202030. case VK_CAPITAL:
  202031. case VK_LWIN:
  202032. case VK_RWIN:
  202033. case VK_APPS:
  202034. case VK_NUMLOCK:
  202035. case VK_SCROLL:
  202036. case VK_LSHIFT:
  202037. case VK_RSHIFT:
  202038. case VK_LCONTROL:
  202039. case VK_LMENU:
  202040. case VK_RCONTROL:
  202041. case VK_RMENU:
  202042. sendModifierKeyChangeIfNeeded();
  202043. }
  202044. return handleKeyUpOrDown (false)
  202045. || Component::getCurrentlyModalComponent() != 0;
  202046. }
  202047. bool doKeyDown (const WPARAM key)
  202048. {
  202049. updateKeyModifiers();
  202050. bool used = false;
  202051. switch (key)
  202052. {
  202053. case VK_SHIFT:
  202054. case VK_LSHIFT:
  202055. case VK_RSHIFT:
  202056. case VK_CONTROL:
  202057. case VK_LCONTROL:
  202058. case VK_RCONTROL:
  202059. case VK_MENU:
  202060. case VK_LMENU:
  202061. case VK_RMENU:
  202062. case VK_LWIN:
  202063. case VK_RWIN:
  202064. case VK_CAPITAL:
  202065. case VK_NUMLOCK:
  202066. case VK_SCROLL:
  202067. case VK_APPS:
  202068. sendModifierKeyChangeIfNeeded();
  202069. break;
  202070. case VK_LEFT:
  202071. case VK_RIGHT:
  202072. case VK_UP:
  202073. case VK_DOWN:
  202074. case VK_PRIOR:
  202075. case VK_NEXT:
  202076. case VK_HOME:
  202077. case VK_END:
  202078. case VK_DELETE:
  202079. case VK_INSERT:
  202080. case VK_F1:
  202081. case VK_F2:
  202082. case VK_F3:
  202083. case VK_F4:
  202084. case VK_F5:
  202085. case VK_F6:
  202086. case VK_F7:
  202087. case VK_F8:
  202088. case VK_F9:
  202089. case VK_F10:
  202090. case VK_F11:
  202091. case VK_F12:
  202092. case VK_F13:
  202093. case VK_F14:
  202094. case VK_F15:
  202095. case VK_F16:
  202096. used = handleKeyUpOrDown (true);
  202097. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  202098. break;
  202099. case VK_ADD:
  202100. case VK_SUBTRACT:
  202101. case VK_MULTIPLY:
  202102. case VK_DIVIDE:
  202103. case VK_SEPARATOR:
  202104. case VK_DECIMAL:
  202105. used = handleKeyUpOrDown (true);
  202106. break;
  202107. default:
  202108. used = handleKeyUpOrDown (true);
  202109. {
  202110. MSG msg;
  202111. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  202112. {
  202113. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  202114. // manually generate the key-press event that matches this key-down.
  202115. const UINT keyChar = MapVirtualKey (key, 2);
  202116. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  202117. }
  202118. }
  202119. break;
  202120. }
  202121. if (Component::getCurrentlyModalComponent() != 0)
  202122. used = true;
  202123. return used;
  202124. }
  202125. bool doKeyChar (int key, const LPARAM flags)
  202126. {
  202127. updateKeyModifiers();
  202128. juce_wchar textChar = (juce_wchar) key;
  202129. const int virtualScanCode = (flags >> 16) & 0xff;
  202130. if (key >= '0' && key <= '9')
  202131. {
  202132. switch (virtualScanCode) // check for a numeric keypad scan-code
  202133. {
  202134. case 0x52:
  202135. case 0x4f:
  202136. case 0x50:
  202137. case 0x51:
  202138. case 0x4b:
  202139. case 0x4c:
  202140. case 0x4d:
  202141. case 0x47:
  202142. case 0x48:
  202143. case 0x49:
  202144. key = (key - '0') + KeyPress::numberPad0;
  202145. break;
  202146. default:
  202147. break;
  202148. }
  202149. }
  202150. else
  202151. {
  202152. // convert the scan code to an unmodified character code..
  202153. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  202154. UINT keyChar = MapVirtualKey (virtualKey, 2);
  202155. keyChar = LOWORD (keyChar);
  202156. if (keyChar != 0)
  202157. key = (int) keyChar;
  202158. // avoid sending junk text characters for some control-key combinations
  202159. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  202160. textChar = 0;
  202161. }
  202162. return handleKeyPress (key, textChar);
  202163. }
  202164. bool doAppCommand (const LPARAM lParam)
  202165. {
  202166. int key = 0;
  202167. switch (GET_APPCOMMAND_LPARAM (lParam))
  202168. {
  202169. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  202170. key = KeyPress::playKey;
  202171. break;
  202172. case APPCOMMAND_MEDIA_STOP:
  202173. key = KeyPress::stopKey;
  202174. break;
  202175. case APPCOMMAND_MEDIA_NEXTTRACK:
  202176. key = KeyPress::fastForwardKey;
  202177. break;
  202178. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  202179. key = KeyPress::rewindKey;
  202180. break;
  202181. }
  202182. if (key != 0)
  202183. {
  202184. updateKeyModifiers();
  202185. if (hwnd == GetActiveWindow())
  202186. {
  202187. handleKeyPress (key, 0);
  202188. return true;
  202189. }
  202190. }
  202191. return false;
  202192. }
  202193. class JuceDropTarget : public IDropTarget
  202194. {
  202195. public:
  202196. JuceDropTarget (Win32ComponentPeer* const owner_)
  202197. : owner (owner_),
  202198. refCount (1)
  202199. {
  202200. }
  202201. virtual ~JuceDropTarget()
  202202. {
  202203. jassert (refCount == 0);
  202204. }
  202205. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  202206. {
  202207. if (id == IID_IUnknown || id == IID_IDropTarget)
  202208. {
  202209. AddRef();
  202210. *result = this;
  202211. return S_OK;
  202212. }
  202213. *result = 0;
  202214. return E_NOINTERFACE;
  202215. }
  202216. ULONG __stdcall AddRef() { return ++refCount; }
  202217. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  202218. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202219. {
  202220. updateFileList (pDataObject);
  202221. int x = mousePos.x, y = mousePos.y;
  202222. owner->globalPositionToRelative (x, y);
  202223. owner->handleFileDragMove (files, x, y);
  202224. *pdwEffect = DROPEFFECT_COPY;
  202225. return S_OK;
  202226. }
  202227. HRESULT __stdcall DragLeave()
  202228. {
  202229. owner->handleFileDragExit (files);
  202230. return S_OK;
  202231. }
  202232. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202233. {
  202234. int x = mousePos.x, y = mousePos.y;
  202235. owner->globalPositionToRelative (x, y);
  202236. owner->handleFileDragMove (files, x, y);
  202237. *pdwEffect = DROPEFFECT_COPY;
  202238. return S_OK;
  202239. }
  202240. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  202241. {
  202242. updateFileList (pDataObject);
  202243. int x = mousePos.x, y = mousePos.y;
  202244. owner->globalPositionToRelative (x, y);
  202245. owner->handleFileDragDrop (files, x, y);
  202246. *pdwEffect = DROPEFFECT_COPY;
  202247. return S_OK;
  202248. }
  202249. private:
  202250. Win32ComponentPeer* const owner;
  202251. int refCount;
  202252. StringArray files;
  202253. void updateFileList (IDataObject* const pDataObject)
  202254. {
  202255. files.clear();
  202256. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  202257. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  202258. if (pDataObject->GetData (&format, &medium) == S_OK)
  202259. {
  202260. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  202261. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  202262. unsigned int i = 0;
  202263. if (pDropFiles->fWide)
  202264. {
  202265. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  202266. for (;;)
  202267. {
  202268. unsigned int len = 0;
  202269. while (i + len < totalLen && fname [i + len] != 0)
  202270. ++len;
  202271. if (len == 0)
  202272. break;
  202273. files.add (String (fname + i, len));
  202274. i += len + 1;
  202275. }
  202276. }
  202277. else
  202278. {
  202279. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  202280. for (;;)
  202281. {
  202282. unsigned int len = 0;
  202283. while (i + len < totalLen && fname [i + len] != 0)
  202284. ++len;
  202285. if (len == 0)
  202286. break;
  202287. files.add (String (fname + i, len));
  202288. i += len + 1;
  202289. }
  202290. }
  202291. GlobalUnlock (medium.hGlobal);
  202292. }
  202293. }
  202294. JuceDropTarget (const JuceDropTarget&);
  202295. const JuceDropTarget& operator= (const JuceDropTarget&);
  202296. };
  202297. void doSettingChange()
  202298. {
  202299. Desktop::getInstance().refreshMonitorSizes();
  202300. if (fullScreen && ! isMinimised())
  202301. {
  202302. const Rectangle r (component->getParentMonitorArea());
  202303. SetWindowPos (hwnd, 0,
  202304. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  202305. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  202306. }
  202307. }
  202308. public:
  202309. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202310. {
  202311. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  202312. if (peer != 0)
  202313. return peer->peerWindowProc (h, message, wParam, lParam);
  202314. return DefWindowProc (h, message, wParam, lParam);
  202315. }
  202316. private:
  202317. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  202318. {
  202319. {
  202320. if (isValidPeer (this))
  202321. {
  202322. switch (message)
  202323. {
  202324. case WM_NCHITTEST:
  202325. if (hasTitleBar())
  202326. break;
  202327. return HTCLIENT;
  202328. case WM_PAINT:
  202329. handlePaintMessage();
  202330. return 0;
  202331. case WM_NCPAINT:
  202332. if (wParam != 1)
  202333. handlePaintMessage();
  202334. if (hasTitleBar())
  202335. break;
  202336. return 0;
  202337. case WM_ERASEBKGND:
  202338. case WM_NCCALCSIZE:
  202339. if (hasTitleBar())
  202340. break;
  202341. return 1;
  202342. case WM_MOUSEMOVE:
  202343. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  202344. return 0;
  202345. case WM_MOUSELEAVE:
  202346. doMouseExit();
  202347. return 0;
  202348. case WM_LBUTTONDOWN:
  202349. case WM_MBUTTONDOWN:
  202350. case WM_RBUTTONDOWN:
  202351. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202352. return 0;
  202353. case WM_LBUTTONUP:
  202354. case WM_MBUTTONUP:
  202355. case WM_RBUTTONUP:
  202356. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  202357. return 0;
  202358. case WM_CAPTURECHANGED:
  202359. doCaptureChanged();
  202360. return 0;
  202361. case WM_NCMOUSEMOVE:
  202362. if (hasTitleBar())
  202363. break;
  202364. return 0;
  202365. case 0x020A: /* WM_MOUSEWHEEL */
  202366. doMouseWheel (wParam, true);
  202367. return 0;
  202368. case 0x020E: /* WM_MOUSEHWHEEL */
  202369. doMouseWheel (wParam, false);
  202370. return 0;
  202371. case WM_WINDOWPOSCHANGING:
  202372. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  202373. {
  202374. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  202375. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  202376. {
  202377. if (constrainer != 0)
  202378. {
  202379. const Rectangle current (component->getX() - windowBorder.getLeft(),
  202380. component->getY() - windowBorder.getTop(),
  202381. component->getWidth() + windowBorder.getLeftAndRight(),
  202382. component->getHeight() + windowBorder.getTopAndBottom());
  202383. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  202384. current,
  202385. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  202386. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  202387. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  202388. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  202389. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  202390. }
  202391. }
  202392. }
  202393. return 0;
  202394. case WM_WINDOWPOSCHANGED:
  202395. handleMovedOrResized();
  202396. if (dontRepaint)
  202397. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  202398. else
  202399. return 0;
  202400. case WM_KEYDOWN:
  202401. case WM_SYSKEYDOWN:
  202402. if (doKeyDown (wParam))
  202403. return 0;
  202404. break;
  202405. case WM_KEYUP:
  202406. case WM_SYSKEYUP:
  202407. if (doKeyUp (wParam))
  202408. return 0;
  202409. break;
  202410. case WM_CHAR:
  202411. if (doKeyChar ((int) wParam, lParam))
  202412. return 0;
  202413. break;
  202414. case WM_APPCOMMAND:
  202415. if (doAppCommand (lParam))
  202416. return TRUE;
  202417. break;
  202418. case WM_SETFOCUS:
  202419. updateKeyModifiers();
  202420. handleFocusGain();
  202421. break;
  202422. case WM_KILLFOCUS:
  202423. if (hasCreatedCaret)
  202424. {
  202425. hasCreatedCaret = false;
  202426. DestroyCaret();
  202427. }
  202428. handleFocusLoss();
  202429. break;
  202430. case WM_ACTIVATEAPP:
  202431. // Windows does weird things to process priority when you swap apps,
  202432. // so this forces an update when the app is brought to the front
  202433. if (wParam != FALSE)
  202434. juce_repeatLastProcessPriority();
  202435. else
  202436. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  202437. juce_CheckCurrentlyFocusedTopLevelWindow();
  202438. modifiersAtLastCallback = -1;
  202439. return 0;
  202440. case WM_ACTIVATE:
  202441. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  202442. {
  202443. modifiersAtLastCallback = -1;
  202444. updateKeyModifiers();
  202445. if (isMinimised())
  202446. {
  202447. component->repaint();
  202448. handleMovedOrResized();
  202449. if (! isValidMessageListener())
  202450. return 0;
  202451. }
  202452. if (LOWORD (wParam) == WA_CLICKACTIVE
  202453. && component->isCurrentlyBlockedByAnotherModalComponent())
  202454. {
  202455. int mx, my;
  202456. component->getMouseXYRelative (mx, my);
  202457. Component* const underMouse = component->getComponentAt (mx, my);
  202458. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  202459. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  202460. return 0;
  202461. }
  202462. handleBroughtToFront();
  202463. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202464. Component::getCurrentlyModalComponent()->toFront (true);
  202465. return 0;
  202466. }
  202467. break;
  202468. case WM_NCACTIVATE:
  202469. // while a temporary window is being shown, prevent Windows from deactivating the
  202470. // title bars of our main windows.
  202471. if (wParam == 0 && ! shouldDeactivateTitleBar)
  202472. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  202473. break;
  202474. case WM_MOUSEACTIVATE:
  202475. if (! component->getMouseClickGrabsKeyboardFocus())
  202476. return MA_NOACTIVATE;
  202477. break;
  202478. case WM_SHOWWINDOW:
  202479. if (wParam != 0)
  202480. handleBroughtToFront();
  202481. break;
  202482. case WM_CLOSE:
  202483. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  202484. handleUserClosingWindow();
  202485. return 0;
  202486. case WM_QUIT:
  202487. if (JUCEApplication::getInstance() != 0)
  202488. JUCEApplication::getInstance()->systemRequestedQuit();
  202489. return 0;
  202490. case WM_QUERYENDSESSION:
  202491. if (JUCEApplication::getInstance() != 0)
  202492. {
  202493. JUCEApplication::getInstance()->systemRequestedQuit();
  202494. return MessageManager::getInstance()->hasStopMessageBeenSent();
  202495. }
  202496. return TRUE;
  202497. case WM_TRAYNOTIFY:
  202498. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202499. {
  202500. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  202501. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202502. {
  202503. Component* const current = Component::getCurrentlyModalComponent();
  202504. if (current != 0)
  202505. current->inputAttemptWhenModal();
  202506. }
  202507. }
  202508. else
  202509. {
  202510. const int oldModifiers = currentModifiers;
  202511. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  202512. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  202513. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  202514. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  202515. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  202516. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  202517. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  202518. {
  202519. SetFocus (hwnd);
  202520. SetForegroundWindow (hwnd);
  202521. component->mouseDown (e);
  202522. }
  202523. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  202524. {
  202525. e.mods = ModifierKeys (oldModifiers);
  202526. component->mouseUp (e);
  202527. }
  202528. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  202529. {
  202530. e.mods = ModifierKeys (oldModifiers);
  202531. component->mouseDoubleClick (e);
  202532. }
  202533. else if (lParam == WM_MOUSEMOVE)
  202534. {
  202535. component->mouseMove (e);
  202536. }
  202537. }
  202538. break;
  202539. case WM_SYNCPAINT:
  202540. return 0;
  202541. case WM_PALETTECHANGED:
  202542. InvalidateRect (h, 0, 0);
  202543. break;
  202544. case WM_DISPLAYCHANGE:
  202545. InvalidateRect (h, 0, 0);
  202546. createPaletteIfNeeded = true;
  202547. // intentional fall-through...
  202548. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  202549. doSettingChange();
  202550. break;
  202551. case WM_INITMENU:
  202552. if (! hasTitleBar())
  202553. {
  202554. if (isFullScreen())
  202555. {
  202556. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  202557. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  202558. }
  202559. else if (! isMinimised())
  202560. {
  202561. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  202562. }
  202563. }
  202564. break;
  202565. case WM_SYSCOMMAND:
  202566. switch (wParam & 0xfff0)
  202567. {
  202568. case SC_CLOSE:
  202569. if (sendInputAttemptWhenModalMessage())
  202570. return 0;
  202571. if (hasTitleBar())
  202572. {
  202573. PostMessage (h, WM_CLOSE, 0, 0);
  202574. return 0;
  202575. }
  202576. break;
  202577. case SC_KEYMENU:
  202578. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  202579. // obscure situations that can arise if a modal loop is started from an alt-key
  202580. // keypress).
  202581. if (hasTitleBar() && h == GetCapture())
  202582. ReleaseCapture();
  202583. break;
  202584. case SC_MAXIMIZE:
  202585. if (sendInputAttemptWhenModalMessage())
  202586. return 0;
  202587. setFullScreen (true);
  202588. return 0;
  202589. case SC_MINIMIZE:
  202590. if (sendInputAttemptWhenModalMessage())
  202591. return 0;
  202592. if (! hasTitleBar())
  202593. {
  202594. setMinimised (true);
  202595. return 0;
  202596. }
  202597. break;
  202598. case SC_RESTORE:
  202599. if (sendInputAttemptWhenModalMessage())
  202600. return 0;
  202601. if (hasTitleBar())
  202602. {
  202603. if (isFullScreen())
  202604. {
  202605. setFullScreen (false);
  202606. return 0;
  202607. }
  202608. }
  202609. else
  202610. {
  202611. if (isMinimised())
  202612. setMinimised (false);
  202613. else if (isFullScreen())
  202614. setFullScreen (false);
  202615. return 0;
  202616. }
  202617. break;
  202618. }
  202619. break;
  202620. case WM_NCLBUTTONDOWN:
  202621. case WM_NCRBUTTONDOWN:
  202622. case WM_NCMBUTTONDOWN:
  202623. sendInputAttemptWhenModalMessage();
  202624. break;
  202625. //case WM_IME_STARTCOMPOSITION;
  202626. // return 0;
  202627. case WM_GETDLGCODE:
  202628. return DLGC_WANTALLKEYS;
  202629. default:
  202630. break;
  202631. }
  202632. }
  202633. }
  202634. // (the message manager lock exits before calling this, to avoid deadlocks if
  202635. // this calls into non-juce windows)
  202636. return DefWindowProc (h, message, wParam, lParam);
  202637. }
  202638. bool sendInputAttemptWhenModalMessage()
  202639. {
  202640. if (component->isCurrentlyBlockedByAnotherModalComponent())
  202641. {
  202642. Component* const current = Component::getCurrentlyModalComponent();
  202643. if (current != 0)
  202644. current->inputAttemptWhenModal();
  202645. return true;
  202646. }
  202647. return false;
  202648. }
  202649. Win32ComponentPeer (const Win32ComponentPeer&);
  202650. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  202651. };
  202652. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  202653. {
  202654. return new Win32ComponentPeer (this, styleFlags);
  202655. }
  202656. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  202657. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  202658. {
  202659. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202660. if (wp != 0)
  202661. wp->setTaskBarIcon (&newImage);
  202662. }
  202663. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  202664. {
  202665. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  202666. if (wp != 0)
  202667. wp->setTaskBarIconToolTip (tooltip);
  202668. }
  202669. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  202670. {
  202671. DWORD val = GetWindowLong (h, styleType);
  202672. if (bitIsSet)
  202673. val |= feature;
  202674. else
  202675. val &= ~feature;
  202676. SetWindowLongPtr (h, styleType, val);
  202677. SetWindowPos (h, 0, 0, 0, 0, 0,
  202678. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  202679. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  202680. }
  202681. bool Process::isForegroundProcess() throw()
  202682. {
  202683. HWND fg = GetForegroundWindow();
  202684. if (fg == 0)
  202685. return true;
  202686. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  202687. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  202688. // have to see if any of our windows are children of the foreground window
  202689. fg = GetAncestor (fg, GA_ROOT);
  202690. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  202691. {
  202692. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  202693. if (wp != 0 && wp->isInside (fg))
  202694. return true;
  202695. }
  202696. return false;
  202697. }
  202698. bool AlertWindow::showNativeDialogBox (const String& title,
  202699. const String& bodyText,
  202700. bool isOkCancel)
  202701. {
  202702. return MessageBox (0, bodyText, title,
  202703. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  202704. : MB_OK)) == IDOK;
  202705. }
  202706. void Desktop::getMousePosition (int& x, int& y) throw()
  202707. {
  202708. POINT mousePos;
  202709. GetCursorPos (&mousePos);
  202710. x = mousePos.x;
  202711. y = mousePos.y;
  202712. }
  202713. void Desktop::setMousePosition (int x, int y) throw()
  202714. {
  202715. SetCursorPos (x, y);
  202716. }
  202717. class ScreenSaverDefeater : public Timer,
  202718. public DeletedAtShutdown
  202719. {
  202720. public:
  202721. ScreenSaverDefeater() throw()
  202722. {
  202723. startTimer (10000);
  202724. timerCallback();
  202725. }
  202726. ~ScreenSaverDefeater() {}
  202727. void timerCallback()
  202728. {
  202729. if (Process::isForegroundProcess())
  202730. {
  202731. // simulate a shift key getting pressed..
  202732. INPUT input[2];
  202733. input[0].type = INPUT_KEYBOARD;
  202734. input[0].ki.wVk = VK_SHIFT;
  202735. input[0].ki.dwFlags = 0;
  202736. input[0].ki.dwExtraInfo = 0;
  202737. input[1].type = INPUT_KEYBOARD;
  202738. input[1].ki.wVk = VK_SHIFT;
  202739. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  202740. input[1].ki.dwExtraInfo = 0;
  202741. SendInput (2, input, sizeof (INPUT));
  202742. }
  202743. }
  202744. };
  202745. static ScreenSaverDefeater* screenSaverDefeater = 0;
  202746. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202747. {
  202748. if (isEnabled)
  202749. {
  202750. deleteAndZero (screenSaverDefeater);
  202751. }
  202752. else if (screenSaverDefeater == 0)
  202753. {
  202754. screenSaverDefeater = new ScreenSaverDefeater();
  202755. }
  202756. }
  202757. bool Desktop::isScreenSaverEnabled() throw()
  202758. {
  202759. return screenSaverDefeater == 0;
  202760. }
  202761. /* (The code below is the "correct" way to disable the screen saver, but it
  202762. completely fails on winXP when the saver is password-protected...)
  202763. static bool juce_screenSaverEnabled = true;
  202764. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  202765. {
  202766. juce_screenSaverEnabled = isEnabled;
  202767. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  202768. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  202769. }
  202770. bool Desktop::isScreenSaverEnabled() throw()
  202771. {
  202772. return juce_screenSaverEnabled;
  202773. }
  202774. */
  202775. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  202776. {
  202777. if (enableOrDisable)
  202778. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  202779. }
  202780. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  202781. {
  202782. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  202783. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  202784. return TRUE;
  202785. }
  202786. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  202787. {
  202788. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  202789. // make sure the first in the list is the main monitor
  202790. for (int i = 1; i < monitorCoords.size(); ++i)
  202791. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  202792. monitorCoords.swap (i, 0);
  202793. if (monitorCoords.size() == 0)
  202794. {
  202795. RECT r;
  202796. GetWindowRect (GetDesktopWindow(), &r);
  202797. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  202798. }
  202799. if (clipToWorkArea)
  202800. {
  202801. // clip the main monitor to the active non-taskbar area
  202802. RECT r;
  202803. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  202804. Rectangle& screen = monitorCoords.getReference (0);
  202805. screen.setPosition (jmax (screen.getX(), r.left),
  202806. jmax (screen.getY(), r.top));
  202807. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  202808. jmin (screen.getBottom(), r.bottom) - screen.getY());
  202809. }
  202810. }
  202811. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  202812. {
  202813. Image* im = 0;
  202814. if (bitmap != 0)
  202815. {
  202816. BITMAP bm;
  202817. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  202818. && bm.bmWidth > 0 && bm.bmHeight > 0)
  202819. {
  202820. HDC tempDC = GetDC (0);
  202821. HDC dc = CreateCompatibleDC (tempDC);
  202822. ReleaseDC (0, tempDC);
  202823. SelectObject (dc, bitmap);
  202824. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  202825. for (int y = bm.bmHeight; --y >= 0;)
  202826. {
  202827. for (int x = bm.bmWidth; --x >= 0;)
  202828. {
  202829. COLORREF col = GetPixel (dc, x, y);
  202830. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  202831. (uint8) GetGValue (col),
  202832. (uint8) GetBValue (col)));
  202833. }
  202834. }
  202835. DeleteDC (dc);
  202836. }
  202837. }
  202838. return im;
  202839. }
  202840. static Image* createImageFromHICON (HICON icon) throw()
  202841. {
  202842. ICONINFO info;
  202843. if (GetIconInfo (icon, &info))
  202844. {
  202845. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  202846. if (mask == 0)
  202847. return 0;
  202848. Image* const image = createImageFromHBITMAP (info.hbmColor);
  202849. if (image == 0)
  202850. return mask;
  202851. for (int y = image->getHeight(); --y >= 0;)
  202852. {
  202853. for (int x = image->getWidth(); --x >= 0;)
  202854. {
  202855. const float brightness = mask->getPixelAt (x, y).getBrightness();
  202856. if (brightness > 0.0f)
  202857. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  202858. }
  202859. }
  202860. delete mask;
  202861. return image;
  202862. }
  202863. return 0;
  202864. }
  202865. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  202866. {
  202867. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  202868. ICONINFO info;
  202869. info.fIcon = isIcon;
  202870. info.xHotspot = hotspotX;
  202871. info.yHotspot = hotspotY;
  202872. info.hbmMask = mask;
  202873. HICON hi = 0;
  202874. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  202875. {
  202876. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  202877. Graphics g (bitmap);
  202878. g.drawImageAt (&image, 0, 0);
  202879. info.hbmColor = bitmap.hBitmap;
  202880. hi = CreateIconIndirect (&info);
  202881. }
  202882. else
  202883. {
  202884. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  202885. HDC colDC = CreateCompatibleDC (GetDC (0));
  202886. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  202887. SelectObject (colDC, colour);
  202888. SelectObject (alphaDC, mask);
  202889. for (int y = image.getHeight(); --y >= 0;)
  202890. {
  202891. for (int x = image.getWidth(); --x >= 0;)
  202892. {
  202893. const Colour c (image.getPixelAt (x, y));
  202894. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  202895. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  202896. }
  202897. }
  202898. DeleteDC (colDC);
  202899. DeleteDC (alphaDC);
  202900. info.hbmColor = colour;
  202901. hi = CreateIconIndirect (&info);
  202902. DeleteObject (colour);
  202903. }
  202904. DeleteObject (mask);
  202905. return hi;
  202906. }
  202907. Image* juce_createIconForFile (const File& file)
  202908. {
  202909. Image* image = 0;
  202910. TCHAR filename [1024];
  202911. file.getFullPathName().copyToBuffer (filename, 1023);
  202912. WORD iconNum = 0;
  202913. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  202914. filename, &iconNum);
  202915. if (icon != 0)
  202916. {
  202917. image = createImageFromHICON (icon);
  202918. DestroyIcon (icon);
  202919. }
  202920. return image;
  202921. }
  202922. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  202923. {
  202924. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  202925. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  202926. const Image* im = &image;
  202927. Image* newIm = 0;
  202928. if (image.getWidth() > maxW || image.getHeight() > maxH)
  202929. {
  202930. im = newIm = image.createCopy (maxW, maxH);
  202931. hotspotX = (hotspotX * maxW) / image.getWidth();
  202932. hotspotY = (hotspotY * maxH) / image.getHeight();
  202933. }
  202934. void* cursorH = 0;
  202935. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  202936. if (os == SystemStats::WinXP)
  202937. {
  202938. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  202939. }
  202940. else
  202941. {
  202942. const int stride = (maxW + 7) >> 3;
  202943. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  202944. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  202945. int index = 0;
  202946. for (int y = 0; y < maxH; ++y)
  202947. {
  202948. for (int x = 0; x < maxW; ++x)
  202949. {
  202950. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  202951. const Colour pixelColour (im->getPixelAt (x, y));
  202952. if (pixelColour.getAlpha() < 127)
  202953. andPlane [index + (x >> 3)] |= bit;
  202954. else if (pixelColour.getBrightness() >= 0.5f)
  202955. xorPlane [index + (x >> 3)] |= bit;
  202956. }
  202957. index += stride;
  202958. }
  202959. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  202960. juce_free (andPlane);
  202961. juce_free (xorPlane);
  202962. }
  202963. delete newIm;
  202964. return cursorH;
  202965. }
  202966. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  202967. {
  202968. if (cursorHandle != 0 && ! isStandard)
  202969. DestroyCursor ((HCURSOR) cursorHandle);
  202970. }
  202971. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  202972. {
  202973. LPCTSTR cursorName = IDC_ARROW;
  202974. switch (type)
  202975. {
  202976. case MouseCursor::NormalCursor:
  202977. cursorName = IDC_ARROW;
  202978. break;
  202979. case MouseCursor::NoCursor:
  202980. return 0;
  202981. case MouseCursor::DraggingHandCursor:
  202982. {
  202983. static void* dragHandCursor = 0;
  202984. if (dragHandCursor == 0)
  202985. {
  202986. static const unsigned char dragHandData[] =
  202987. { 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,
  202988. 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,
  202989. 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 };
  202990. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  202991. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  202992. delete image;
  202993. }
  202994. return dragHandCursor;
  202995. }
  202996. case MouseCursor::WaitCursor:
  202997. cursorName = IDC_WAIT;
  202998. break;
  202999. case MouseCursor::IBeamCursor:
  203000. cursorName = IDC_IBEAM;
  203001. break;
  203002. case MouseCursor::PointingHandCursor:
  203003. cursorName = MAKEINTRESOURCE(32649);
  203004. break;
  203005. case MouseCursor::LeftRightResizeCursor:
  203006. case MouseCursor::LeftEdgeResizeCursor:
  203007. case MouseCursor::RightEdgeResizeCursor:
  203008. cursorName = IDC_SIZEWE;
  203009. break;
  203010. case MouseCursor::UpDownResizeCursor:
  203011. case MouseCursor::TopEdgeResizeCursor:
  203012. case MouseCursor::BottomEdgeResizeCursor:
  203013. cursorName = IDC_SIZENS;
  203014. break;
  203015. case MouseCursor::TopLeftCornerResizeCursor:
  203016. case MouseCursor::BottomRightCornerResizeCursor:
  203017. cursorName = IDC_SIZENWSE;
  203018. break;
  203019. case MouseCursor::TopRightCornerResizeCursor:
  203020. case MouseCursor::BottomLeftCornerResizeCursor:
  203021. cursorName = IDC_SIZENESW;
  203022. break;
  203023. case MouseCursor::UpDownLeftRightResizeCursor:
  203024. cursorName = IDC_SIZEALL;
  203025. break;
  203026. case MouseCursor::CrosshairCursor:
  203027. cursorName = IDC_CROSS;
  203028. break;
  203029. case MouseCursor::CopyingCursor:
  203030. // can't seem to find one of these in the win32 list..
  203031. break;
  203032. }
  203033. HCURSOR cursorH = LoadCursor (0, cursorName);
  203034. if (cursorH == 0)
  203035. cursorH = LoadCursor (0, IDC_ARROW);
  203036. return (void*) cursorH;
  203037. }
  203038. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  203039. {
  203040. SetCursor ((HCURSOR) getHandle());
  203041. }
  203042. void MouseCursor::showInAllWindows() const throw()
  203043. {
  203044. showInWindow (0);
  203045. }
  203046. class JuceDropSource : public IDropSource
  203047. {
  203048. int refCount;
  203049. public:
  203050. JuceDropSource()
  203051. : refCount (1)
  203052. {
  203053. }
  203054. virtual ~JuceDropSource()
  203055. {
  203056. jassert (refCount == 0);
  203057. }
  203058. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203059. {
  203060. if (id == IID_IUnknown || id == IID_IDropSource)
  203061. {
  203062. AddRef();
  203063. *result = this;
  203064. return S_OK;
  203065. }
  203066. *result = 0;
  203067. return E_NOINTERFACE;
  203068. }
  203069. ULONG __stdcall AddRef() { return ++refCount; }
  203070. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203071. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  203072. {
  203073. if (escapePressed)
  203074. return DRAGDROP_S_CANCEL;
  203075. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  203076. return DRAGDROP_S_DROP;
  203077. return S_OK;
  203078. }
  203079. HRESULT __stdcall GiveFeedback (DWORD)
  203080. {
  203081. return DRAGDROP_S_USEDEFAULTCURSORS;
  203082. }
  203083. };
  203084. class JuceEnumFormatEtc : public IEnumFORMATETC
  203085. {
  203086. public:
  203087. JuceEnumFormatEtc (const FORMATETC* const format_)
  203088. : refCount (1),
  203089. format (format_),
  203090. index (0)
  203091. {
  203092. }
  203093. virtual ~JuceEnumFormatEtc()
  203094. {
  203095. jassert (refCount == 0);
  203096. }
  203097. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203098. {
  203099. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  203100. {
  203101. AddRef();
  203102. *result = this;
  203103. return S_OK;
  203104. }
  203105. *result = 0;
  203106. return E_NOINTERFACE;
  203107. }
  203108. ULONG __stdcall AddRef() { return ++refCount; }
  203109. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203110. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  203111. {
  203112. if (result == 0)
  203113. return E_POINTER;
  203114. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  203115. newOne->index = index;
  203116. *result = newOne;
  203117. return S_OK;
  203118. }
  203119. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  203120. {
  203121. if (pceltFetched != 0)
  203122. *pceltFetched = 0;
  203123. else if (celt != 1)
  203124. return S_FALSE;
  203125. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  203126. {
  203127. copyFormatEtc (lpFormatEtc [0], *format);
  203128. ++index;
  203129. if (pceltFetched != 0)
  203130. *pceltFetched = 1;
  203131. return S_OK;
  203132. }
  203133. return S_FALSE;
  203134. }
  203135. HRESULT __stdcall Skip (ULONG celt)
  203136. {
  203137. if (index + (int) celt >= 1)
  203138. return S_FALSE;
  203139. index += celt;
  203140. return S_OK;
  203141. }
  203142. HRESULT __stdcall Reset()
  203143. {
  203144. index = 0;
  203145. return S_OK;
  203146. }
  203147. private:
  203148. int refCount;
  203149. const FORMATETC* const format;
  203150. int index;
  203151. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  203152. {
  203153. dest = source;
  203154. if (source.ptd != 0)
  203155. {
  203156. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  203157. *(dest.ptd) = *(source.ptd);
  203158. }
  203159. }
  203160. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  203161. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  203162. };
  203163. class JuceDataObject : public IDataObject
  203164. {
  203165. JuceDropSource* const dropSource;
  203166. const FORMATETC* const format;
  203167. const STGMEDIUM* const medium;
  203168. int refCount;
  203169. JuceDataObject (const JuceDataObject&);
  203170. const JuceDataObject& operator= (const JuceDataObject&);
  203171. public:
  203172. JuceDataObject (JuceDropSource* const dropSource_,
  203173. const FORMATETC* const format_,
  203174. const STGMEDIUM* const medium_)
  203175. : dropSource (dropSource_),
  203176. format (format_),
  203177. medium (medium_),
  203178. refCount (1)
  203179. {
  203180. }
  203181. virtual ~JuceDataObject()
  203182. {
  203183. jassert (refCount == 0);
  203184. }
  203185. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203186. {
  203187. if (id == IID_IUnknown || id == IID_IDataObject)
  203188. {
  203189. AddRef();
  203190. *result = this;
  203191. return S_OK;
  203192. }
  203193. *result = 0;
  203194. return E_NOINTERFACE;
  203195. }
  203196. ULONG __stdcall AddRef() { return ++refCount; }
  203197. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  203198. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  203199. {
  203200. if (pFormatEtc->tymed == format->tymed
  203201. && pFormatEtc->cfFormat == format->cfFormat
  203202. && pFormatEtc->dwAspect == format->dwAspect)
  203203. {
  203204. pMedium->tymed = format->tymed;
  203205. pMedium->pUnkForRelease = 0;
  203206. if (format->tymed == TYMED_HGLOBAL)
  203207. {
  203208. const SIZE_T len = GlobalSize (medium->hGlobal);
  203209. void* const src = GlobalLock (medium->hGlobal);
  203210. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  203211. memcpy (dst, src, len);
  203212. GlobalUnlock (medium->hGlobal);
  203213. pMedium->hGlobal = dst;
  203214. return S_OK;
  203215. }
  203216. }
  203217. return DV_E_FORMATETC;
  203218. }
  203219. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  203220. {
  203221. if (f == 0)
  203222. return E_INVALIDARG;
  203223. if (f->tymed == format->tymed
  203224. && f->cfFormat == format->cfFormat
  203225. && f->dwAspect == format->dwAspect)
  203226. return S_OK;
  203227. return DV_E_FORMATETC;
  203228. }
  203229. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  203230. {
  203231. pFormatEtcOut->ptd = 0;
  203232. return E_NOTIMPL;
  203233. }
  203234. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  203235. {
  203236. if (result == 0)
  203237. return E_POINTER;
  203238. if (direction == DATADIR_GET)
  203239. {
  203240. *result = new JuceEnumFormatEtc (format);
  203241. return S_OK;
  203242. }
  203243. *result = 0;
  203244. return E_NOTIMPL;
  203245. }
  203246. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  203247. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  203248. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  203249. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  203250. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  203251. };
  203252. static HDROP createHDrop (const StringArray& fileNames) throw()
  203253. {
  203254. int totalChars = 0;
  203255. for (int i = fileNames.size(); --i >= 0;)
  203256. totalChars += fileNames[i].length() + 1;
  203257. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  203258. sizeof (DROPFILES)
  203259. + sizeof (WCHAR) * (totalChars + 2));
  203260. if (hDrop != 0)
  203261. {
  203262. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  203263. pDropFiles->pFiles = sizeof (DROPFILES);
  203264. pDropFiles->fWide = true;
  203265. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  203266. for (int i = 0; i < fileNames.size(); ++i)
  203267. {
  203268. fileNames[i].copyToBuffer (fname, 2048);
  203269. fname += fileNames[i].length() + 1;
  203270. }
  203271. *fname = 0;
  203272. GlobalUnlock (hDrop);
  203273. }
  203274. return hDrop;
  203275. }
  203276. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  203277. {
  203278. JuceDropSource* const source = new JuceDropSource();
  203279. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  203280. DWORD effect;
  203281. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  203282. data->Release();
  203283. source->Release();
  203284. return res == DRAGDROP_S_DROP;
  203285. }
  203286. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  203287. {
  203288. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203289. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203290. medium.hGlobal = createHDrop (files);
  203291. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  203292. : DROPEFFECT_COPY);
  203293. }
  203294. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  203295. {
  203296. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  203297. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  203298. const int numChars = text.length();
  203299. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  203300. char* d = (char*) GlobalLock (medium.hGlobal);
  203301. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  203302. format.cfFormat = CF_UNICODETEXT;
  203303. GlobalUnlock (medium.hGlobal);
  203304. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  203305. }
  203306. #endif
  203307. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  203308. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203309. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203310. // compiled on its own).
  203311. #if JUCE_INCLUDED_FILE
  203312. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203313. NEWTEXTMETRICEXW*,
  203314. int type,
  203315. LPARAM lParam)
  203316. {
  203317. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203318. {
  203319. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203320. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203321. }
  203322. return 1;
  203323. }
  203324. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203325. NEWTEXTMETRICEXW*,
  203326. int type,
  203327. LPARAM lParam)
  203328. {
  203329. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  203330. {
  203331. LOGFONTW lf;
  203332. zerostruct (lf);
  203333. lf.lfWeight = FW_DONTCARE;
  203334. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203335. lf.lfQuality = DEFAULT_QUALITY;
  203336. lf.lfCharSet = DEFAULT_CHARSET;
  203337. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203338. lf.lfPitchAndFamily = FF_DONTCARE;
  203339. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203340. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203341. HDC dc = CreateCompatibleDC (0);
  203342. EnumFontFamiliesEx (dc, &lf,
  203343. (FONTENUMPROCW) &wfontEnum2,
  203344. lParam, 0);
  203345. DeleteDC (dc);
  203346. }
  203347. return 1;
  203348. }
  203349. const StringArray Font::findAllTypefaceNames() throw()
  203350. {
  203351. StringArray results;
  203352. HDC dc = CreateCompatibleDC (0);
  203353. {
  203354. LOGFONTW lf;
  203355. zerostruct (lf);
  203356. lf.lfWeight = FW_DONTCARE;
  203357. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203358. lf.lfQuality = DEFAULT_QUALITY;
  203359. lf.lfCharSet = DEFAULT_CHARSET;
  203360. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203361. lf.lfPitchAndFamily = FF_DONTCARE;
  203362. lf.lfFaceName[0] = 0;
  203363. EnumFontFamiliesEx (dc, &lf,
  203364. (FONTENUMPROCW) &wfontEnum1,
  203365. (LPARAM) &results, 0);
  203366. }
  203367. DeleteDC (dc);
  203368. results.sort (true);
  203369. return results;
  203370. }
  203371. extern bool juce_IsRunningInWine() throw();
  203372. void Typeface::getDefaultFontNames (String& defaultSans,
  203373. String& defaultSerif,
  203374. String& defaultFixed) throw()
  203375. {
  203376. if (juce_IsRunningInWine())
  203377. {
  203378. // If we're running in Wine, then use fonts that might be available on Linux..
  203379. defaultSans = "Bitstream Vera Sans";
  203380. defaultSerif = "Bitstream Vera Serif";
  203381. defaultFixed = "Bitstream Vera Sans Mono";
  203382. }
  203383. else
  203384. {
  203385. defaultSans = "Verdana";
  203386. defaultSerif = "Times";
  203387. defaultFixed = "Lucida Console";
  203388. }
  203389. }
  203390. class FontDCHolder : private DeletedAtShutdown
  203391. {
  203392. HDC dc;
  203393. String fontName;
  203394. KERNINGPAIR* kps;
  203395. int numKPs;
  203396. bool bold, italic;
  203397. int size;
  203398. FontDCHolder (const FontDCHolder&);
  203399. const FontDCHolder& operator= (const FontDCHolder&);
  203400. public:
  203401. HFONT fontH;
  203402. FontDCHolder() throw()
  203403. : dc (0),
  203404. kps (0),
  203405. numKPs (0),
  203406. bold (false),
  203407. italic (false),
  203408. size (0)
  203409. {
  203410. }
  203411. ~FontDCHolder() throw()
  203412. {
  203413. if (dc != 0)
  203414. {
  203415. DeleteDC (dc);
  203416. DeleteObject (fontH);
  203417. juce_free (kps);
  203418. }
  203419. clearSingletonInstance();
  203420. }
  203421. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203422. HDC loadFont (const String& fontName_,
  203423. const bool bold_,
  203424. const bool italic_,
  203425. const int size_) throw()
  203426. {
  203427. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203428. {
  203429. fontName = fontName_;
  203430. bold = bold_;
  203431. italic = italic_;
  203432. size = size_;
  203433. if (dc != 0)
  203434. {
  203435. DeleteDC (dc);
  203436. DeleteObject (fontH);
  203437. juce_free (kps);
  203438. kps = 0;
  203439. }
  203440. fontH = 0;
  203441. dc = CreateCompatibleDC (0);
  203442. SetMapperFlags (dc, 0);
  203443. SetMapMode (dc, MM_TEXT);
  203444. LOGFONTW lfw;
  203445. zerostruct (lfw);
  203446. lfw.lfCharSet = DEFAULT_CHARSET;
  203447. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203448. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203449. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203450. lfw.lfQuality = PROOF_QUALITY;
  203451. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203452. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203453. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203454. lfw.lfHeight = size > 0 ? size : -256;
  203455. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203456. if (standardSizedFont != 0)
  203457. {
  203458. if (SelectObject (dc, standardSizedFont) != 0)
  203459. {
  203460. fontH = standardSizedFont;
  203461. if (size == 0)
  203462. {
  203463. OUTLINETEXTMETRIC otm;
  203464. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203465. {
  203466. lfw.lfHeight = -(int) otm.otmEMSquare;
  203467. fontH = CreateFontIndirect (&lfw);
  203468. SelectObject (dc, fontH);
  203469. DeleteObject (standardSizedFont);
  203470. }
  203471. }
  203472. }
  203473. else
  203474. {
  203475. jassertfalse
  203476. }
  203477. }
  203478. else
  203479. {
  203480. jassertfalse
  203481. }
  203482. }
  203483. return dc;
  203484. }
  203485. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203486. {
  203487. if (kps == 0)
  203488. {
  203489. numKPs = GetKerningPairs (dc, 0, 0);
  203490. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203491. GetKerningPairs (dc, numKPs, kps);
  203492. }
  203493. numKPs_ = numKPs;
  203494. return kps;
  203495. }
  203496. };
  203497. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203498. static bool addGlyphToTypeface (HDC dc,
  203499. juce_wchar character,
  203500. Typeface& dest,
  203501. bool addKerning)
  203502. {
  203503. Path destShape;
  203504. GLYPHMETRICS gm;
  203505. float height;
  203506. BOOL ok = false;
  203507. {
  203508. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203509. WORD index = 0;
  203510. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203511. && index == 0xffff)
  203512. {
  203513. return false;
  203514. }
  203515. }
  203516. TEXTMETRIC tm;
  203517. ok = GetTextMetrics (dc, &tm);
  203518. height = (float) tm.tmHeight;
  203519. if (! ok)
  203520. {
  203521. dest.addGlyph (character, destShape, 0);
  203522. return true;
  203523. }
  203524. const float scaleX = 1.0f / height;
  203525. const float scaleY = -1.0f / height;
  203526. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203527. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203528. &gm, 0, 0, &identityMatrix);
  203529. if (bufSize > 0)
  203530. {
  203531. char* const data = (char*) juce_malloc (bufSize);
  203532. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203533. bufSize, data, &identityMatrix);
  203534. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203535. while ((char*) pheader < data + bufSize)
  203536. {
  203537. #define remapX(v) (scaleX * (v).x.value)
  203538. #define remapY(v) (scaleY * (v).y.value)
  203539. float x = remapX (pheader->pfxStart);
  203540. float y = remapY (pheader->pfxStart);
  203541. destShape.startNewSubPath (x, y);
  203542. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203543. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203544. while ((const char*) curve < curveEnd)
  203545. {
  203546. if (curve->wType == TT_PRIM_LINE)
  203547. {
  203548. for (int i = 0; i < curve->cpfx; ++i)
  203549. {
  203550. x = remapX (curve->apfx [i]);
  203551. y = remapY (curve->apfx [i]);
  203552. destShape.lineTo (x, y);
  203553. }
  203554. }
  203555. else if (curve->wType == TT_PRIM_QSPLINE)
  203556. {
  203557. for (int i = 0; i < curve->cpfx - 1; ++i)
  203558. {
  203559. const float x2 = remapX (curve->apfx [i]);
  203560. const float y2 = remapY (curve->apfx [i]);
  203561. float x3, y3;
  203562. if (i < curve->cpfx - 2)
  203563. {
  203564. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203565. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203566. }
  203567. else
  203568. {
  203569. x3 = remapX (curve->apfx [i + 1]);
  203570. y3 = remapY (curve->apfx [i + 1]);
  203571. }
  203572. destShape.quadraticTo (x2, y2, x3, y3);
  203573. x = x3;
  203574. y = y3;
  203575. }
  203576. }
  203577. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203578. }
  203579. pheader = (const TTPOLYGONHEADER*) curve;
  203580. destShape.closeSubPath();
  203581. }
  203582. juce_free (data);
  203583. }
  203584. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203585. if (addKerning)
  203586. {
  203587. int numKPs;
  203588. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203589. for (int i = 0; i < numKPs; ++i)
  203590. {
  203591. if (kps[i].wFirst == character)
  203592. {
  203593. dest.addKerningPair (kps[i].wFirst,
  203594. kps[i].wSecond,
  203595. kps[i].iKernAmount / height);
  203596. }
  203597. }
  203598. }
  203599. return true;
  203600. }
  203601. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203602. {
  203603. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203604. return addGlyphToTypeface (dc, character, *this, true);
  203605. }
  203606. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203607. {
  203608. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203609. int bufSize;
  203610. GLYPHMETRICS gm;
  203611. const UINT format = GGO_GRAY2_BITMAP;
  203612. const int shift = 6;
  203613. if (wGetGlyphOutlineW != 0)
  203614. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203615. else
  203616. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203617. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203618. if (bufSize > 0)
  203619. {
  203620. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203621. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203622. uint8* const data = (uint8*) juce_calloc (bufSize);
  203623. if (wGetGlyphOutlineW != 0)
  203624. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203625. else
  203626. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203627. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203628. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203629. {
  203630. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203631. {
  203632. const int level = data [x + y * stride] << shift;
  203633. if (level > 0)
  203634. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203635. }
  203636. }
  203637. juce_free (data);
  203638. }
  203639. return im;
  203640. }*/
  203641. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203642. bool bold,
  203643. bool italic,
  203644. bool addAllGlyphsToFont) throw()
  203645. {
  203646. clear();
  203647. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203648. float height;
  203649. int firstChar, lastChar;
  203650. {
  203651. TEXTMETRIC tm;
  203652. GetTextMetrics (dc, &tm);
  203653. height = (float) tm.tmHeight;
  203654. firstChar = tm.tmFirstChar;
  203655. lastChar = tm.tmLastChar;
  203656. setAscent (tm.tmAscent / height);
  203657. setDefaultCharacter (tm.tmDefaultChar);
  203658. }
  203659. setName (fontName);
  203660. setBold (bold);
  203661. setItalic (italic);
  203662. if (addAllGlyphsToFont)
  203663. {
  203664. for (int character = firstChar; character <= lastChar; ++character)
  203665. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203666. int numKPs;
  203667. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203668. for (int i = 0; i < numKPs; ++i)
  203669. {
  203670. addKerningPair (kps[i].wFirst,
  203671. kps[i].wSecond,
  203672. kps[i].iKernAmount / height);
  203673. }
  203674. }
  203675. }
  203676. #endif
  203677. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203678. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203679. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203680. // compiled on its own).
  203681. #if JUCE_INCLUDED_FILE
  203682. static const void* defaultDirPath = 0;
  203683. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203684. static Component* currentExtraFileWin = 0;
  203685. static bool areThereAnyAlwaysOnTopWindows()
  203686. {
  203687. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203688. {
  203689. Component* c = Desktop::getInstance().getComponent (i);
  203690. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203691. return true;
  203692. }
  203693. return false;
  203694. }
  203695. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203696. {
  203697. if (msg == BFFM_INITIALIZED)
  203698. {
  203699. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203700. }
  203701. else if (msg == BFFM_VALIDATEFAILEDW)
  203702. {
  203703. returnedString = (LPCWSTR) lParam;
  203704. }
  203705. else if (msg == BFFM_VALIDATEFAILEDA)
  203706. {
  203707. returnedString = (const char*) lParam;
  203708. }
  203709. return 0;
  203710. }
  203711. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw();
  203712. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203713. {
  203714. if (currentExtraFileWin != 0)
  203715. {
  203716. if (uiMsg == WM_INITDIALOG)
  203717. {
  203718. HWND dialogH = GetParent (hdlg);
  203719. jassert (dialogH != 0);
  203720. if (dialogH == 0)
  203721. dialogH = hdlg;
  203722. RECT r, cr;
  203723. GetWindowRect (dialogH, &r);
  203724. GetClientRect (dialogH, &cr);
  203725. SetWindowPos (dialogH, 0,
  203726. r.left, r.top,
  203727. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203728. jmax (150, r.bottom - r.top),
  203729. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203730. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203731. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203732. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203733. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203734. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203735. }
  203736. else if (uiMsg == WM_NOTIFY)
  203737. {
  203738. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203739. if (ofn->hdr.code == CDN_SELCHANGE)
  203740. {
  203741. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203742. if (comp != 0)
  203743. {
  203744. TCHAR path [MAX_PATH * 2];
  203745. path[0] = 0;
  203746. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203747. const String fn ((const WCHAR*) path);
  203748. comp->selectedFileChanged (File (fn));
  203749. }
  203750. }
  203751. }
  203752. }
  203753. return 0;
  203754. }
  203755. class FPComponentHolder : public Component
  203756. {
  203757. public:
  203758. FPComponentHolder()
  203759. {
  203760. setVisible (true);
  203761. setOpaque (true);
  203762. }
  203763. ~FPComponentHolder()
  203764. {
  203765. }
  203766. void paint (Graphics& g)
  203767. {
  203768. g.fillAll (Colours::lightgrey);
  203769. }
  203770. private:
  203771. FPComponentHolder (const FPComponentHolder&);
  203772. const FPComponentHolder& operator= (const FPComponentHolder&);
  203773. };
  203774. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203775. const String& title,
  203776. const File& currentFileOrDirectory,
  203777. const String& filter,
  203778. bool selectsDirectory,
  203779. bool isSaveDialogue,
  203780. bool warnAboutOverwritingExistingFiles,
  203781. bool selectMultipleFiles,
  203782. FilePreviewComponent* extraInfoComponent)
  203783. {
  203784. const int numCharsAvailable = 32768;
  203785. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203786. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203787. int fnameIdx = 0;
  203788. JUCE_TRY
  203789. {
  203790. // use a modal window as the parent for this dialog box
  203791. // to block input from other app windows
  203792. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203793. Component w (String::empty);
  203794. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203795. mainMon.getY() + mainMon.getHeight() / 4,
  203796. 0, 0);
  203797. w.setOpaque (true);
  203798. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203799. w.addToDesktop (0);
  203800. if (extraInfoComponent == 0)
  203801. w.enterModalState();
  203802. String initialDir;
  203803. if (currentFileOrDirectory.isDirectory())
  203804. {
  203805. initialDir = currentFileOrDirectory.getFullPathName();
  203806. }
  203807. else
  203808. {
  203809. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203810. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203811. }
  203812. if (currentExtraFileWin->isValidComponent())
  203813. {
  203814. jassertfalse
  203815. return;
  203816. }
  203817. if (selectsDirectory)
  203818. {
  203819. LPITEMIDLIST list = 0;
  203820. filenameSpace.fillWith (0);
  203821. {
  203822. BROWSEINFO bi;
  203823. zerostruct (bi);
  203824. bi.hwndOwner = (HWND) w.getWindowHandle();
  203825. bi.pszDisplayName = fname;
  203826. bi.lpszTitle = title;
  203827. bi.lpfn = browseCallbackProc;
  203828. #ifdef BIF_USENEWUI
  203829. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203830. #else
  203831. bi.ulFlags = 0x50;
  203832. #endif
  203833. defaultDirPath = (const WCHAR*) initialDir;
  203834. list = SHBrowseForFolder (&bi);
  203835. if (! SHGetPathFromIDListW (list, fname))
  203836. {
  203837. fname[0] = 0;
  203838. returnedString = String::empty;
  203839. }
  203840. }
  203841. LPMALLOC al;
  203842. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203843. al->Free (list);
  203844. defaultDirPath = 0;
  203845. if (returnedString.isNotEmpty())
  203846. {
  203847. const String stringFName (fname);
  203848. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203849. returnedString = String::empty;
  203850. return;
  203851. }
  203852. }
  203853. else
  203854. {
  203855. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203856. if (warnAboutOverwritingExistingFiles)
  203857. flags |= OFN_OVERWRITEPROMPT;
  203858. if (selectMultipleFiles)
  203859. flags |= OFN_ALLOWMULTISELECT;
  203860. if (extraInfoComponent != 0)
  203861. {
  203862. flags |= OFN_ENABLEHOOK;
  203863. currentExtraFileWin = new FPComponentHolder();
  203864. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203865. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203866. extraInfoComponent->getHeight());
  203867. currentExtraFileWin->addToDesktop (0);
  203868. currentExtraFileWin->enterModalState();
  203869. }
  203870. {
  203871. WCHAR filters [1024];
  203872. zeromem (filters, sizeof (filters));
  203873. filter.copyToBuffer (filters, 1024);
  203874. filter.copyToBuffer (filters + filter.length() + 1,
  203875. 1022 - filter.length());
  203876. OPENFILENAMEW of;
  203877. zerostruct (of);
  203878. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203879. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203880. #else
  203881. of.lStructSize = sizeof (of);
  203882. #endif
  203883. of.hwndOwner = (HWND) w.getWindowHandle();
  203884. of.lpstrFilter = filters;
  203885. of.nFilterIndex = 1;
  203886. of.lpstrFile = fname;
  203887. of.nMaxFile = numCharsAvailable;
  203888. of.lpstrInitialDir = initialDir;
  203889. of.lpstrTitle = title;
  203890. of.Flags = flags;
  203891. if (extraInfoComponent != 0)
  203892. of.lpfnHook = &openCallback;
  203893. if (isSaveDialogue)
  203894. {
  203895. if (! GetSaveFileName (&of))
  203896. fname[0] = 0;
  203897. else
  203898. fnameIdx = of.nFileOffset;
  203899. }
  203900. else
  203901. {
  203902. if (! GetOpenFileName (&of))
  203903. fname[0] = 0;
  203904. else
  203905. fnameIdx = of.nFileOffset;
  203906. }
  203907. }
  203908. }
  203909. }
  203910. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203911. catch (...)
  203912. {
  203913. fname[0] = 0;
  203914. }
  203915. #endif
  203916. deleteAndZero (currentExtraFileWin);
  203917. const WCHAR* const files = fname;
  203918. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203919. {
  203920. const WCHAR* filename = files + fnameIdx;
  203921. while (*filename != 0)
  203922. {
  203923. const String filepath (String (files) + T("\\") + String (filename));
  203924. results.add (new File (filepath));
  203925. filename += CharacterFunctions::length (filename) + 1;
  203926. }
  203927. }
  203928. else if (files[0] != 0)
  203929. {
  203930. results.add (new File (files));
  203931. }
  203932. }
  203933. #endif
  203934. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203935. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  203936. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203937. // compiled on its own).
  203938. #if JUCE_INCLUDED_FILE
  203939. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  203940. {
  203941. if (OpenClipboard (0) != 0)
  203942. {
  203943. if (EmptyClipboard() != 0)
  203944. {
  203945. const int len = text.length();
  203946. if (len > 0)
  203947. {
  203948. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  203949. (len + 1) * sizeof (wchar_t));
  203950. if (bufH != 0)
  203951. {
  203952. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  203953. text.copyToBuffer (data, len);
  203954. GlobalUnlock (bufH);
  203955. SetClipboardData (CF_UNICODETEXT, bufH);
  203956. }
  203957. }
  203958. }
  203959. CloseClipboard();
  203960. }
  203961. }
  203962. const String SystemClipboard::getTextFromClipboard() throw()
  203963. {
  203964. String result;
  203965. if (OpenClipboard (0) != 0)
  203966. {
  203967. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  203968. if (bufH != 0)
  203969. {
  203970. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  203971. if (data != 0)
  203972. {
  203973. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  203974. GlobalUnlock (bufH);
  203975. }
  203976. }
  203977. CloseClipboard();
  203978. }
  203979. return result;
  203980. }
  203981. #endif
  203982. /********* End of inlined file: juce_win32_Misc.cpp *********/
  203983. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  203984. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203985. // compiled on its own).
  203986. #if JUCE_INCLUDED_FILE
  203987. class JuceIStorage : public IStorage
  203988. {
  203989. int refCount;
  203990. public:
  203991. JuceIStorage() : refCount (1) {}
  203992. virtual ~JuceIStorage()
  203993. {
  203994. jassert (refCount == 0);
  203995. }
  203996. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  203997. {
  203998. if (id == IID_IUnknown || id == IID_IStorage)
  203999. {
  204000. AddRef();
  204001. *result = this;
  204002. return S_OK;
  204003. }
  204004. *result = 0;
  204005. return E_NOINTERFACE;
  204006. }
  204007. ULONG __stdcall AddRef() { return ++refCount; }
  204008. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204009. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204010. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  204011. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  204012. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  204013. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  204014. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  204015. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  204016. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  204017. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  204018. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  204019. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  204020. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  204021. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  204022. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  204023. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  204024. juce_UseDebuggingNewOperator
  204025. };
  204026. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  204027. {
  204028. int refCount;
  204029. HWND window;
  204030. public:
  204031. JuceOleInPlaceFrame (HWND window_)
  204032. : refCount (1),
  204033. window (window_)
  204034. {
  204035. }
  204036. virtual ~JuceOleInPlaceFrame()
  204037. {
  204038. jassert (refCount == 0);
  204039. }
  204040. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204041. {
  204042. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  204043. {
  204044. AddRef();
  204045. *result = this;
  204046. return S_OK;
  204047. }
  204048. *result = 0;
  204049. return E_NOINTERFACE;
  204050. }
  204051. ULONG __stdcall AddRef() { return ++refCount; }
  204052. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204053. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204054. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204055. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  204056. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204057. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  204058. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  204059. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  204060. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  204061. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  204062. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  204063. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  204064. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  204065. juce_UseDebuggingNewOperator
  204066. };
  204067. class JuceIOleInPlaceSite : public IOleInPlaceSite
  204068. {
  204069. int refCount;
  204070. HWND window;
  204071. JuceOleInPlaceFrame* frame;
  204072. public:
  204073. JuceIOleInPlaceSite (HWND window_)
  204074. : refCount (1),
  204075. window (window_)
  204076. {
  204077. frame = new JuceOleInPlaceFrame (window);
  204078. }
  204079. virtual ~JuceIOleInPlaceSite()
  204080. {
  204081. jassert (refCount == 0);
  204082. frame->Release();
  204083. }
  204084. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204085. {
  204086. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  204087. {
  204088. AddRef();
  204089. *result = this;
  204090. return S_OK;
  204091. }
  204092. *result = 0;
  204093. return E_NOINTERFACE;
  204094. }
  204095. ULONG __stdcall AddRef() { return ++refCount; }
  204096. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204097. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  204098. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  204099. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  204100. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  204101. HRESULT __stdcall OnUIActivate() { return S_OK; }
  204102. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  204103. {
  204104. frame->AddRef();
  204105. *lplpFrame = frame;
  204106. *lplpDoc = 0;
  204107. lpFrameInfo->fMDIApp = FALSE;
  204108. lpFrameInfo->hwndFrame = window;
  204109. lpFrameInfo->haccel = 0;
  204110. lpFrameInfo->cAccelEntries = 0;
  204111. return S_OK;
  204112. }
  204113. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  204114. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  204115. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  204116. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  204117. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  204118. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  204119. juce_UseDebuggingNewOperator
  204120. };
  204121. class JuceIOleClientSite : public IOleClientSite
  204122. {
  204123. int refCount;
  204124. JuceIOleInPlaceSite* inplaceSite;
  204125. public:
  204126. JuceIOleClientSite (HWND window)
  204127. : refCount (1)
  204128. {
  204129. inplaceSite = new JuceIOleInPlaceSite (window);
  204130. }
  204131. virtual ~JuceIOleClientSite()
  204132. {
  204133. jassert (refCount == 0);
  204134. inplaceSite->Release();
  204135. }
  204136. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204137. {
  204138. if (id == IID_IUnknown || id == IID_IOleClientSite)
  204139. {
  204140. AddRef();
  204141. *result = this;
  204142. return S_OK;
  204143. }
  204144. else if (id == IID_IOleInPlaceSite)
  204145. {
  204146. inplaceSite->AddRef();
  204147. *result = inplaceSite;
  204148. return S_OK;
  204149. }
  204150. *result = 0;
  204151. return E_NOINTERFACE;
  204152. }
  204153. ULONG __stdcall AddRef() { return ++refCount; }
  204154. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  204155. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  204156. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  204157. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  204158. HRESULT __stdcall ShowObject() { return S_OK; }
  204159. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  204160. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  204161. juce_UseDebuggingNewOperator
  204162. };
  204163. class ActiveXControlData : public ComponentMovementWatcher
  204164. {
  204165. ActiveXControlComponent* const owner;
  204166. bool wasShowing;
  204167. public:
  204168. HWND controlHWND;
  204169. IStorage* storage;
  204170. IOleClientSite* clientSite;
  204171. IOleObject* control;
  204172. ActiveXControlData (HWND hwnd,
  204173. ActiveXControlComponent* const owner_)
  204174. : ComponentMovementWatcher (owner_),
  204175. owner (owner_),
  204176. wasShowing (owner_ != 0 && owner_->isShowing()),
  204177. controlHWND (0),
  204178. storage (new JuceIStorage()),
  204179. clientSite (new JuceIOleClientSite (hwnd)),
  204180. control (0)
  204181. {
  204182. }
  204183. ~ActiveXControlData()
  204184. {
  204185. if (control != 0)
  204186. {
  204187. control->Close (OLECLOSE_NOSAVE);
  204188. control->Release();
  204189. }
  204190. clientSite->Release();
  204191. storage->Release();
  204192. }
  204193. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  204194. {
  204195. Component* const topComp = owner->getTopLevelComponent();
  204196. if (topComp->getPeer() != 0)
  204197. {
  204198. int x = 0, y = 0;
  204199. owner->relativePositionToOtherComponent (topComp, x, y);
  204200. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  204201. }
  204202. }
  204203. void componentPeerChanged()
  204204. {
  204205. const bool isShowingNow = owner->isShowing();
  204206. if (wasShowing != isShowingNow)
  204207. {
  204208. wasShowing = isShowingNow;
  204209. owner->setControlVisible (isShowingNow);
  204210. }
  204211. componentMovedOrResized (true, true);
  204212. }
  204213. void componentVisibilityChanged (Component&)
  204214. {
  204215. componentPeerChanged();
  204216. }
  204217. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  204218. {
  204219. return ((ActiveXControlData*) ax->control) != 0
  204220. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  204221. }
  204222. };
  204223. static VoidArray activeXComps;
  204224. static HWND getHWND (const ActiveXControlComponent* const component)
  204225. {
  204226. HWND hwnd = 0;
  204227. const IID iid = IID_IOleWindow;
  204228. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  204229. if (window != 0)
  204230. {
  204231. window->GetWindow (&hwnd);
  204232. window->Release();
  204233. }
  204234. return hwnd;
  204235. }
  204236. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  204237. {
  204238. RECT activeXRect, peerRect;
  204239. GetWindowRect (hwnd, &activeXRect);
  204240. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  204241. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  204242. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  204243. const int64 mouseEventTime = getMouseEventTime();
  204244. const int oldModifiers = currentModifiers;
  204245. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  204246. switch (message)
  204247. {
  204248. case WM_MOUSEMOVE:
  204249. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  204250. peer->handleMouseDrag (mx, my, mouseEventTime);
  204251. else
  204252. peer->handleMouseMove (mx, my, mouseEventTime);
  204253. break;
  204254. case WM_LBUTTONDOWN:
  204255. case WM_MBUTTONDOWN:
  204256. case WM_RBUTTONDOWN:
  204257. peer->handleMouseDown (mx, my, mouseEventTime);
  204258. break;
  204259. case WM_LBUTTONUP:
  204260. case WM_MBUTTONUP:
  204261. case WM_RBUTTONUP:
  204262. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  204263. break;
  204264. default:
  204265. break;
  204266. }
  204267. }
  204268. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  204269. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  204270. {
  204271. for (int i = activeXComps.size(); --i >= 0;)
  204272. {
  204273. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  204274. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  204275. {
  204276. switch (message)
  204277. {
  204278. case WM_MOUSEMOVE:
  204279. case WM_LBUTTONDOWN:
  204280. case WM_MBUTTONDOWN:
  204281. case WM_RBUTTONDOWN:
  204282. case WM_LBUTTONUP:
  204283. case WM_MBUTTONUP:
  204284. case WM_RBUTTONUP:
  204285. case WM_LBUTTONDBLCLK:
  204286. case WM_MBUTTONDBLCLK:
  204287. case WM_RBUTTONDBLCLK:
  204288. if (ax->isShowing())
  204289. {
  204290. ComponentPeer* const peer = ax->getPeer();
  204291. if (peer != 0)
  204292. {
  204293. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  204294. if (! ax->areMouseEventsAllowed())
  204295. return 0;
  204296. }
  204297. }
  204298. break;
  204299. default:
  204300. break;
  204301. }
  204302. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  204303. }
  204304. }
  204305. return DefWindowProc (hwnd, message, wParam, lParam);
  204306. }
  204307. ActiveXControlComponent::ActiveXControlComponent()
  204308. : originalWndProc (0),
  204309. control (0),
  204310. mouseEventsAllowed (true)
  204311. {
  204312. activeXComps.add (this);
  204313. }
  204314. ActiveXControlComponent::~ActiveXControlComponent()
  204315. {
  204316. deleteControl();
  204317. activeXComps.removeValue (this);
  204318. }
  204319. void ActiveXControlComponent::paint (Graphics& g)
  204320. {
  204321. if (control == 0)
  204322. g.fillAll (Colours::lightgrey);
  204323. }
  204324. bool ActiveXControlComponent::createControl (const void* controlIID)
  204325. {
  204326. deleteControl();
  204327. ComponentPeer* const peer = getPeer();
  204328. // the component must have already been added to a real window when you call this!
  204329. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  204330. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  204331. {
  204332. int x = 0, y = 0;
  204333. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  204334. HWND hwnd = (HWND) peer->getNativeHandle();
  204335. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  204336. HRESULT hr;
  204337. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  204338. info->clientSite, info->storage,
  204339. (void**) &(info->control))) == S_OK)
  204340. {
  204341. info->control->SetHostNames (L"Juce", 0);
  204342. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  204343. {
  204344. RECT rect;
  204345. rect.left = x;
  204346. rect.top = y;
  204347. rect.right = x + getWidth();
  204348. rect.bottom = y + getHeight();
  204349. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  204350. {
  204351. control = info;
  204352. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  204353. info->controlHWND = getHWND (this);
  204354. if (info->controlHWND != 0)
  204355. {
  204356. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  204357. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  204358. }
  204359. return true;
  204360. }
  204361. }
  204362. }
  204363. delete info;
  204364. }
  204365. return false;
  204366. }
  204367. void ActiveXControlComponent::deleteControl()
  204368. {
  204369. ActiveXControlData* const info = (ActiveXControlData*) control;
  204370. if (info != 0)
  204371. {
  204372. delete info;
  204373. control = 0;
  204374. originalWndProc = 0;
  204375. }
  204376. }
  204377. void* ActiveXControlComponent::queryInterface (const void* iid) const
  204378. {
  204379. ActiveXControlData* const info = (ActiveXControlData*) control;
  204380. void* result = 0;
  204381. if (info != 0 && info->control != 0
  204382. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  204383. return result;
  204384. return 0;
  204385. }
  204386. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  204387. {
  204388. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204389. if (hwnd != 0)
  204390. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  204391. }
  204392. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  204393. {
  204394. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  204395. if (hwnd != 0)
  204396. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  204397. }
  204398. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  204399. {
  204400. mouseEventsAllowed = eventsCanReachControl;
  204401. }
  204402. #endif
  204403. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  204404. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204405. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204406. // compiled on its own).
  204407. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  204408. using namespace QTOLibrary;
  204409. using namespace QTOControlLib;
  204410. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  204411. static bool isQTAvailable = false;
  204412. struct QTMovieCompInternal
  204413. {
  204414. QTMovieCompInternal()
  204415. : dataHandle (0)
  204416. {
  204417. }
  204418. ~QTMovieCompInternal()
  204419. {
  204420. clearHandle();
  204421. }
  204422. IQTControlPtr qtControlInternal;
  204423. IQTMoviePtr qtMovieInternal;
  204424. Handle dataHandle;
  204425. void clearHandle()
  204426. {
  204427. if (dataHandle != 0)
  204428. {
  204429. DisposeHandle (dataHandle);
  204430. dataHandle = 0;
  204431. }
  204432. }
  204433. };
  204434. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  204435. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  204436. QuickTimeMovieComponent::QuickTimeMovieComponent()
  204437. : movieLoaded (false),
  204438. controllerVisible (true)
  204439. {
  204440. internal = new QTMovieCompInternal();
  204441. setMouseEventsAllowed (false);
  204442. }
  204443. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  204444. {
  204445. closeMovie();
  204446. qtControl = 0;
  204447. deleteControl();
  204448. delete internal;
  204449. internal = 0;
  204450. }
  204451. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  204452. {
  204453. if (! isQTAvailable)
  204454. {
  204455. isQTAvailable = (InitializeQTML (0) == noErr)
  204456. && (EnterMovies() == noErr);
  204457. }
  204458. return isQTAvailable;
  204459. }
  204460. void QuickTimeMovieComponent::createControlIfNeeded()
  204461. {
  204462. if (isShowing() && ! isControlCreated())
  204463. {
  204464. const IID qtIID = __uuidof (QTControl);
  204465. if (createControl (&qtIID))
  204466. {
  204467. const IID qtInterfaceIID = __uuidof (IQTControl);
  204468. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  204469. if (qtControl != 0)
  204470. {
  204471. qtControl->Release(); // it has one ref too many at this point
  204472. qtControl->QuickTimeInitialize();
  204473. qtControl->PutSizing (qtMovieFitsControl);
  204474. if (movieFile != File::nonexistent)
  204475. loadMovie (movieFile, controllerVisible);
  204476. }
  204477. }
  204478. }
  204479. }
  204480. bool QuickTimeMovieComponent::isControlCreated() const
  204481. {
  204482. return isControlOpen();
  204483. }
  204484. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  204485. const bool isControllerVisible)
  204486. {
  204487. movieFile = File::nonexistent;
  204488. movieLoaded = false;
  204489. qtMovie = 0;
  204490. controllerVisible = isControllerVisible;
  204491. createControlIfNeeded();
  204492. if (isControlCreated())
  204493. {
  204494. if (qtControl != 0)
  204495. {
  204496. qtControl->Put_MovieHandle (0);
  204497. ((QTMovieCompInternal*) internal)->clearHandle();
  204498. Movie movie;
  204499. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  204500. {
  204501. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  204502. qtMovie = qtControl->GetMovie();
  204503. if (qtMovie != 0)
  204504. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  204505. : qtMovieControllerTypeNone);
  204506. }
  204507. if (movie == 0)
  204508. ((QTMovieCompInternal*) internal)->clearHandle();
  204509. }
  204510. movieLoaded = (qtMovie != 0);
  204511. }
  204512. else
  204513. {
  204514. // You're trying to open a movie when the control hasn't yet been created, probably because
  204515. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  204516. jassertfalse
  204517. }
  204518. delete movieStream;
  204519. return movieLoaded;
  204520. }
  204521. void QuickTimeMovieComponent::closeMovie()
  204522. {
  204523. stop();
  204524. movieFile = File::nonexistent;
  204525. movieLoaded = false;
  204526. qtMovie = 0;
  204527. if (qtControl != 0)
  204528. qtControl->Put_MovieHandle (0);
  204529. ((QTMovieCompInternal*) internal)->clearHandle();
  204530. }
  204531. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  204532. {
  204533. return movieFile;
  204534. }
  204535. bool QuickTimeMovieComponent::isMovieOpen() const
  204536. {
  204537. return movieLoaded;
  204538. }
  204539. double QuickTimeMovieComponent::getMovieDuration() const
  204540. {
  204541. if (qtMovie != 0)
  204542. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  204543. return 0.0;
  204544. }
  204545. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  204546. {
  204547. if (qtMovie != 0)
  204548. {
  204549. struct QTRECT r = qtMovie->GetNaturalRect();
  204550. width = r.right - r.left;
  204551. height = r.bottom - r.top;
  204552. }
  204553. else
  204554. {
  204555. width = height = 0;
  204556. }
  204557. }
  204558. void QuickTimeMovieComponent::play()
  204559. {
  204560. if (qtMovie != 0)
  204561. qtMovie->Play();
  204562. }
  204563. void QuickTimeMovieComponent::stop()
  204564. {
  204565. if (qtMovie != 0)
  204566. qtMovie->Stop();
  204567. }
  204568. bool QuickTimeMovieComponent::isPlaying() const
  204569. {
  204570. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  204571. }
  204572. void QuickTimeMovieComponent::setPosition (const double seconds)
  204573. {
  204574. if (qtMovie != 0)
  204575. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  204576. }
  204577. double QuickTimeMovieComponent::getPosition() const
  204578. {
  204579. if (qtMovie != 0)
  204580. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  204581. return 0.0;
  204582. }
  204583. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  204584. {
  204585. if (qtMovie != 0)
  204586. qtMovie->PutRate (newSpeed);
  204587. }
  204588. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  204589. {
  204590. if (qtMovie != 0)
  204591. {
  204592. qtMovie->PutAudioVolume (newVolume);
  204593. qtMovie->PutAudioMute (newVolume <= 0);
  204594. }
  204595. }
  204596. float QuickTimeMovieComponent::getMovieVolume() const
  204597. {
  204598. if (qtMovie != 0)
  204599. return qtMovie->GetAudioVolume();
  204600. return 0.0f;
  204601. }
  204602. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  204603. {
  204604. if (qtMovie != 0)
  204605. qtMovie->PutLoop (shouldLoop);
  204606. }
  204607. bool QuickTimeMovieComponent::isLooping() const
  204608. {
  204609. return qtMovie != 0 && qtMovie->GetLoop();
  204610. }
  204611. bool QuickTimeMovieComponent::isControllerVisible() const
  204612. {
  204613. return controllerVisible;
  204614. }
  204615. void QuickTimeMovieComponent::parentHierarchyChanged()
  204616. {
  204617. createControlIfNeeded();
  204618. QTCompBaseClass::parentHierarchyChanged();
  204619. }
  204620. void QuickTimeMovieComponent::visibilityChanged()
  204621. {
  204622. createControlIfNeeded();
  204623. QTCompBaseClass::visibilityChanged();
  204624. }
  204625. void QuickTimeMovieComponent::paint (Graphics& g)
  204626. {
  204627. if (! isControlCreated())
  204628. g.fillAll (Colours::black);
  204629. }
  204630. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  204631. {
  204632. Handle dataRef = 0;
  204633. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  204634. if (err == noErr)
  204635. {
  204636. Str255 suffix;
  204637. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  204638. StringPtr name = suffix;
  204639. err = PtrAndHand (name, dataRef, name[0] + 1);
  204640. if (err == noErr)
  204641. {
  204642. long atoms[3];
  204643. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  204644. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  204645. atoms[2] = EndianU32_NtoB (MovieFileType);
  204646. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  204647. if (err == noErr)
  204648. return dataRef;
  204649. }
  204650. DisposeHandle (dataRef);
  204651. }
  204652. return 0;
  204653. }
  204654. static CFStringRef juceStringToCFString (const String& s)
  204655. {
  204656. const int len = s.length();
  204657. const juce_wchar* const t = (const juce_wchar*) s;
  204658. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  204659. for (int i = 0; i <= len; ++i)
  204660. temp[i] = t[i];
  204661. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  204662. juce_free (temp);
  204663. return result;
  204664. }
  204665. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  204666. {
  204667. Boolean trueBool = true;
  204668. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204669. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  204670. props[prop].propValueSize = sizeof (trueBool);
  204671. props[prop].propValueAddress = &trueBool;
  204672. ++prop;
  204673. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  204674. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  204675. props[prop].propValueSize = sizeof (trueBool);
  204676. props[prop].propValueAddress = &trueBool;
  204677. ++prop;
  204678. Boolean isActive = true;
  204679. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  204680. props[prop].propID = kQTNewMoviePropertyID_Active;
  204681. props[prop].propValueSize = sizeof (isActive);
  204682. props[prop].propValueAddress = &isActive;
  204683. ++prop;
  204684. MacSetPort (0);
  204685. jassert (prop <= 5);
  204686. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  204687. return err == noErr;
  204688. }
  204689. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  204690. {
  204691. if (input == 0)
  204692. return false;
  204693. dataHandle = 0;
  204694. bool ok = false;
  204695. QTNewMoviePropertyElement props[5];
  204696. zeromem (props, sizeof (props));
  204697. int prop = 0;
  204698. DataReferenceRecord dr;
  204699. props[prop].propClass = kQTPropertyClass_DataLocation;
  204700. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  204701. props[prop].propValueSize = sizeof (dr);
  204702. props[prop].propValueAddress = (void*) &dr;
  204703. ++prop;
  204704. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  204705. if (fin != 0)
  204706. {
  204707. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  204708. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  204709. &dr.dataRef, &dr.dataRefType);
  204710. ok = openMovie (props, prop, movie);
  204711. DisposeHandle (dr.dataRef);
  204712. CFRelease (filePath);
  204713. }
  204714. else
  204715. {
  204716. // sanity-check because this currently needs to load the whole stream into memory..
  204717. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  204718. dataHandle = NewHandle ((Size) input->getTotalLength());
  204719. HLock (dataHandle);
  204720. // read the entire stream into memory - this is a pain, but can't get it to work
  204721. // properly using a custom callback to supply the data.
  204722. input->read (*dataHandle, (int) input->getTotalLength());
  204723. HUnlock (dataHandle);
  204724. // different types to get QT to try. (We should really be a bit smarter here by
  204725. // working out in advance which one the stream contains, rather than just trying
  204726. // each one)
  204727. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  204728. "\04.avi", "\04.m4a" };
  204729. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  204730. {
  204731. /* // this fails for some bizarre reason - it can be bodged to work with
  204732. // movies, but can't seem to do it for other file types..
  204733. QTNewMovieUserProcRecord procInfo;
  204734. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  204735. procInfo.getMovieUserProcRefcon = this;
  204736. procInfo.defaultDataRef.dataRef = dataRef;
  204737. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  204738. props[prop].propClass = kQTPropertyClass_DataLocation;
  204739. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  204740. props[prop].propValueSize = sizeof (procInfo);
  204741. props[prop].propValueAddress = (void*) &procInfo;
  204742. ++prop; */
  204743. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  204744. dr.dataRefType = HandleDataHandlerSubType;
  204745. ok = openMovie (props, prop, movie);
  204746. DisposeHandle (dr.dataRef);
  204747. }
  204748. }
  204749. return ok;
  204750. }
  204751. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  204752. const bool isControllerVisible)
  204753. {
  204754. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  204755. movieFile = movieFile_;
  204756. return ok;
  204757. }
  204758. void QuickTimeMovieComponent::goToStart()
  204759. {
  204760. setPosition (0.0);
  204761. }
  204762. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  204763. const RectanglePlacement& placement)
  204764. {
  204765. int normalWidth, normalHeight;
  204766. getMovieNormalSize (normalWidth, normalHeight);
  204767. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  204768. {
  204769. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  204770. placement.applyTo (x, y, w, h,
  204771. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  204772. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  204773. if (w > 0 && h > 0)
  204774. {
  204775. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  204776. roundDoubleToInt (w), roundDoubleToInt (h));
  204777. }
  204778. }
  204779. else
  204780. {
  204781. setBounds (spaceToFitWithin);
  204782. }
  204783. }
  204784. #endif
  204785. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  204786. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204787. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204788. // compiled on its own).
  204789. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  204790. class WebBrowserComponentInternal : public ActiveXControlComponent
  204791. {
  204792. public:
  204793. WebBrowserComponentInternal()
  204794. : browser (0),
  204795. connectionPoint (0),
  204796. adviseCookie (0)
  204797. {
  204798. }
  204799. ~WebBrowserComponentInternal()
  204800. {
  204801. if (connectionPoint != 0)
  204802. connectionPoint->Unadvise (adviseCookie);
  204803. if (browser != 0)
  204804. browser->Release();
  204805. }
  204806. void createBrowser()
  204807. {
  204808. createControl (&CLSID_WebBrowser);
  204809. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204810. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204811. if (connectionPointContainer != 0)
  204812. {
  204813. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204814. &connectionPoint);
  204815. if (connectionPoint != 0)
  204816. {
  204817. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204818. jassert (owner != 0);
  204819. EventHandler* handler = new EventHandler (owner);
  204820. connectionPoint->Advise (handler, &adviseCookie);
  204821. }
  204822. }
  204823. }
  204824. void goToURL (const String& url,
  204825. const StringArray* headers,
  204826. const MemoryBlock* postData)
  204827. {
  204828. if (browser != 0)
  204829. {
  204830. LPSAFEARRAY sa = 0;
  204831. _variant_t flags, frame, postDataVar, headersVar;
  204832. if (headers != 0)
  204833. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204834. if (postData != 0 && postData->getSize() > 0)
  204835. {
  204836. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204837. if (sa != 0)
  204838. {
  204839. void* data = 0;
  204840. SafeArrayAccessData (sa, &data);
  204841. jassert (data != 0);
  204842. if (data != 0)
  204843. {
  204844. postData->copyTo (data, 0, postData->getSize());
  204845. SafeArrayUnaccessData (sa);
  204846. VARIANT postDataVar2;
  204847. VariantInit (&postDataVar2);
  204848. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204849. V_ARRAY (&postDataVar2) = sa;
  204850. postDataVar = postDataVar2;
  204851. }
  204852. }
  204853. }
  204854. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204855. &flags, &frame,
  204856. &postDataVar, &headersVar);
  204857. if (sa != 0)
  204858. SafeArrayDestroy (sa);
  204859. }
  204860. }
  204861. IWebBrowser2* browser;
  204862. juce_UseDebuggingNewOperator
  204863. private:
  204864. IConnectionPoint* connectionPoint;
  204865. DWORD adviseCookie;
  204866. class EventHandler : public IDispatch
  204867. {
  204868. public:
  204869. EventHandler (WebBrowserComponent* owner_)
  204870. : owner (owner_),
  204871. refCount (0)
  204872. {
  204873. }
  204874. ~EventHandler()
  204875. {
  204876. }
  204877. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204878. {
  204879. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204880. {
  204881. AddRef();
  204882. *result = this;
  204883. return S_OK;
  204884. }
  204885. *result = 0;
  204886. return E_NOINTERFACE;
  204887. }
  204888. ULONG __stdcall AddRef() { return ++refCount; }
  204889. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204890. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204891. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204892. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204893. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204894. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204895. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204896. UINT __RPC_FAR* /*puArgErr*/)
  204897. {
  204898. switch (dispIdMember)
  204899. {
  204900. case DISPID_BEFORENAVIGATE2:
  204901. {
  204902. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204903. String url;
  204904. if ((vurl->vt & VT_BYREF) != 0)
  204905. url = *vurl->pbstrVal;
  204906. else
  204907. url = vurl->bstrVal;
  204908. *pDispParams->rgvarg->pboolVal
  204909. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204910. : VARIANT_TRUE;
  204911. return S_OK;
  204912. }
  204913. default:
  204914. break;
  204915. }
  204916. return E_NOTIMPL;
  204917. }
  204918. juce_UseDebuggingNewOperator
  204919. private:
  204920. WebBrowserComponent* const owner;
  204921. int refCount;
  204922. EventHandler (const EventHandler&);
  204923. const EventHandler& operator= (const EventHandler&);
  204924. };
  204925. };
  204926. WebBrowserComponent::WebBrowserComponent()
  204927. : browser (0),
  204928. blankPageShown (false)
  204929. {
  204930. setOpaque (true);
  204931. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204932. }
  204933. WebBrowserComponent::~WebBrowserComponent()
  204934. {
  204935. delete browser;
  204936. }
  204937. void WebBrowserComponent::goToURL (const String& url,
  204938. const StringArray* headers,
  204939. const MemoryBlock* postData)
  204940. {
  204941. lastURL = url;
  204942. lastHeaders.clear();
  204943. if (headers != 0)
  204944. lastHeaders = *headers;
  204945. lastPostData.setSize (0);
  204946. if (postData != 0)
  204947. lastPostData = *postData;
  204948. blankPageShown = false;
  204949. browser->goToURL (url, headers, postData);
  204950. }
  204951. void WebBrowserComponent::stop()
  204952. {
  204953. if (browser->browser != 0)
  204954. browser->browser->Stop();
  204955. }
  204956. void WebBrowserComponent::goBack()
  204957. {
  204958. lastURL = String::empty;
  204959. blankPageShown = false;
  204960. if (browser->browser != 0)
  204961. browser->browser->GoBack();
  204962. }
  204963. void WebBrowserComponent::goForward()
  204964. {
  204965. lastURL = String::empty;
  204966. if (browser->browser != 0)
  204967. browser->browser->GoForward();
  204968. }
  204969. void WebBrowserComponent::refresh()
  204970. {
  204971. if (browser->browser != 0)
  204972. browser->browser->Refresh();
  204973. }
  204974. void WebBrowserComponent::paint (Graphics& g)
  204975. {
  204976. if (browser->browser == 0)
  204977. g.fillAll (Colours::white);
  204978. }
  204979. void WebBrowserComponent::checkWindowAssociation()
  204980. {
  204981. if (isShowing())
  204982. {
  204983. if (browser->browser == 0 && getPeer() != 0)
  204984. {
  204985. browser->createBrowser();
  204986. reloadLastURL();
  204987. }
  204988. else
  204989. {
  204990. if (blankPageShown)
  204991. goBack();
  204992. }
  204993. }
  204994. else
  204995. {
  204996. if (browser != 0 && ! blankPageShown)
  204997. {
  204998. // when the component becomes invisible, some stuff like flash
  204999. // carries on playing audio, so we need to force it onto a blank
  205000. // page to avoid this..
  205001. blankPageShown = true;
  205002. browser->goToURL ("about:blank", 0, 0);
  205003. }
  205004. }
  205005. }
  205006. void WebBrowserComponent::reloadLastURL()
  205007. {
  205008. if (lastURL.isNotEmpty())
  205009. {
  205010. goToURL (lastURL, &lastHeaders, &lastPostData);
  205011. lastURL = String::empty;
  205012. }
  205013. }
  205014. void WebBrowserComponent::parentHierarchyChanged()
  205015. {
  205016. checkWindowAssociation();
  205017. }
  205018. void WebBrowserComponent::resized()
  205019. {
  205020. browser->setSize (getWidth(), getHeight());
  205021. }
  205022. void WebBrowserComponent::visibilityChanged()
  205023. {
  205024. checkWindowAssociation();
  205025. }
  205026. bool WebBrowserComponent::pageAboutToLoad (const String&)
  205027. {
  205028. return true;
  205029. }
  205030. #endif
  205031. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  205032. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205033. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205034. // compiled on its own).
  205035. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  205036. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  205037. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  205038. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  205039. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  205040. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  205041. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  205042. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  205043. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  205044. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  205045. #define WGL_ACCELERATION_ARB 0x2003
  205046. #define WGL_SWAP_METHOD_ARB 0x2007
  205047. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  205048. #define WGL_PIXEL_TYPE_ARB 0x2013
  205049. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  205050. #define WGL_COLOR_BITS_ARB 0x2014
  205051. #define WGL_RED_BITS_ARB 0x2015
  205052. #define WGL_GREEN_BITS_ARB 0x2017
  205053. #define WGL_BLUE_BITS_ARB 0x2019
  205054. #define WGL_ALPHA_BITS_ARB 0x201B
  205055. #define WGL_DEPTH_BITS_ARB 0x2022
  205056. #define WGL_STENCIL_BITS_ARB 0x2023
  205057. #define WGL_FULL_ACCELERATION_ARB 0x2027
  205058. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  205059. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  205060. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  205061. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  205062. #define WGL_STEREO_ARB 0x2012
  205063. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  205064. #define WGL_SAMPLES_ARB 0x2042
  205065. #define WGL_TYPE_RGBA_ARB 0x202B
  205066. static void getWglExtensions (HDC dc, StringArray& result) throw()
  205067. {
  205068. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  205069. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  205070. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  205071. else
  205072. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  205073. }
  205074. class WindowedGLContext : public OpenGLContext
  205075. {
  205076. public:
  205077. WindowedGLContext (Component* const component_,
  205078. HGLRC contextToShareWith,
  205079. const OpenGLPixelFormat& pixelFormat)
  205080. : renderContext (0),
  205081. nativeWindow (0),
  205082. dc (0),
  205083. component (component_)
  205084. {
  205085. jassert (component != 0);
  205086. createNativeWindow();
  205087. // Use a default pixel format that should be supported everywhere
  205088. PIXELFORMATDESCRIPTOR pfd;
  205089. zerostruct (pfd);
  205090. pfd.nSize = sizeof (pfd);
  205091. pfd.nVersion = 1;
  205092. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  205093. pfd.iPixelType = PFD_TYPE_RGBA;
  205094. pfd.cColorBits = 24;
  205095. pfd.cDepthBits = 16;
  205096. const int format = ChoosePixelFormat (dc, &pfd);
  205097. if (format != 0)
  205098. SetPixelFormat (dc, format, &pfd);
  205099. renderContext = wglCreateContext (dc);
  205100. makeActive();
  205101. setPixelFormat (pixelFormat);
  205102. if (contextToShareWith != 0 && renderContext != 0)
  205103. wglShareLists (contextToShareWith, renderContext);
  205104. }
  205105. ~WindowedGLContext()
  205106. {
  205107. makeInactive();
  205108. wglDeleteContext (renderContext);
  205109. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205110. delete nativeWindow;
  205111. }
  205112. bool makeActive() const throw()
  205113. {
  205114. jassert (renderContext != 0);
  205115. return wglMakeCurrent (dc, renderContext) != 0;
  205116. }
  205117. bool makeInactive() const throw()
  205118. {
  205119. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  205120. }
  205121. bool isActive() const throw()
  205122. {
  205123. return wglGetCurrentContext() == renderContext;
  205124. }
  205125. const OpenGLPixelFormat getPixelFormat() const
  205126. {
  205127. OpenGLPixelFormat pf;
  205128. makeActive();
  205129. StringArray availableExtensions;
  205130. getWglExtensions (dc, availableExtensions);
  205131. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  205132. return pf;
  205133. }
  205134. void* getRawContext() const throw()
  205135. {
  205136. return renderContext;
  205137. }
  205138. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  205139. {
  205140. makeActive();
  205141. PIXELFORMATDESCRIPTOR pfd;
  205142. zerostruct (pfd);
  205143. pfd.nSize = sizeof (pfd);
  205144. pfd.nVersion = 1;
  205145. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  205146. pfd.iPixelType = PFD_TYPE_RGBA;
  205147. pfd.iLayerType = PFD_MAIN_PLANE;
  205148. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  205149. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  205150. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  205151. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  205152. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  205153. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  205154. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  205155. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  205156. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  205157. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  205158. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  205159. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  205160. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  205161. int format = 0;
  205162. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  205163. StringArray availableExtensions;
  205164. getWglExtensions (dc, availableExtensions);
  205165. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205166. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  205167. {
  205168. int attributes[64];
  205169. int n = 0;
  205170. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  205171. attributes[n++] = GL_TRUE;
  205172. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  205173. attributes[n++] = GL_TRUE;
  205174. attributes[n++] = WGL_ACCELERATION_ARB;
  205175. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  205176. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  205177. attributes[n++] = GL_TRUE;
  205178. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  205179. attributes[n++] = WGL_TYPE_RGBA_ARB;
  205180. attributes[n++] = WGL_COLOR_BITS_ARB;
  205181. attributes[n++] = pfd.cColorBits;
  205182. attributes[n++] = WGL_RED_BITS_ARB;
  205183. attributes[n++] = pixelFormat.redBits;
  205184. attributes[n++] = WGL_GREEN_BITS_ARB;
  205185. attributes[n++] = pixelFormat.greenBits;
  205186. attributes[n++] = WGL_BLUE_BITS_ARB;
  205187. attributes[n++] = pixelFormat.blueBits;
  205188. attributes[n++] = WGL_ALPHA_BITS_ARB;
  205189. attributes[n++] = pixelFormat.alphaBits;
  205190. attributes[n++] = WGL_DEPTH_BITS_ARB;
  205191. attributes[n++] = pixelFormat.depthBufferBits;
  205192. if (pixelFormat.stencilBufferBits > 0)
  205193. {
  205194. attributes[n++] = WGL_STENCIL_BITS_ARB;
  205195. attributes[n++] = pixelFormat.stencilBufferBits;
  205196. }
  205197. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  205198. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  205199. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  205200. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  205201. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  205202. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  205203. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205204. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  205205. if (availableExtensions.contains ("WGL_ARB_multisample")
  205206. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  205207. {
  205208. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  205209. attributes[n++] = 1;
  205210. attributes[n++] = WGL_SAMPLES_ARB;
  205211. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  205212. }
  205213. attributes[n++] = 0;
  205214. UINT formatsCount;
  205215. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  205216. (void) ok;
  205217. jassert (ok);
  205218. }
  205219. else
  205220. {
  205221. format = ChoosePixelFormat (dc, &pfd);
  205222. }
  205223. if (format != 0)
  205224. {
  205225. makeInactive();
  205226. // win32 can't change the pixel format of a window, so need to delete the
  205227. // old one and create a new one..
  205228. jassert (nativeWindow != 0);
  205229. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  205230. delete nativeWindow;
  205231. createNativeWindow();
  205232. if (SetPixelFormat (dc, format, &pfd))
  205233. {
  205234. wglDeleteContext (renderContext);
  205235. renderContext = wglCreateContext (dc);
  205236. jassert (renderContext != 0);
  205237. return renderContext != 0;
  205238. }
  205239. }
  205240. return false;
  205241. }
  205242. void updateWindowPosition (int x, int y, int w, int h, int)
  205243. {
  205244. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  205245. x, y, w, h,
  205246. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205247. }
  205248. void repaint()
  205249. {
  205250. int x, y, w, h;
  205251. nativeWindow->getBounds (x, y, w, h);
  205252. nativeWindow->repaint (0, 0, w, h);
  205253. }
  205254. void swapBuffers()
  205255. {
  205256. SwapBuffers (dc);
  205257. }
  205258. bool setSwapInterval (const int numFramesPerSwap)
  205259. {
  205260. makeActive();
  205261. StringArray availableExtensions;
  205262. getWglExtensions (dc, availableExtensions);
  205263. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  205264. return availableExtensions.contains ("WGL_EXT_swap_control")
  205265. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  205266. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  205267. }
  205268. int getSwapInterval() const
  205269. {
  205270. makeActive();
  205271. StringArray availableExtensions;
  205272. getWglExtensions (dc, availableExtensions);
  205273. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  205274. if (availableExtensions.contains ("WGL_EXT_swap_control")
  205275. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  205276. return wglGetSwapIntervalEXT();
  205277. return 0;
  205278. }
  205279. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  205280. {
  205281. jassert (isActive());
  205282. StringArray availableExtensions;
  205283. getWglExtensions (dc, availableExtensions);
  205284. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205285. int numTypes = 0;
  205286. if (availableExtensions.contains("WGL_ARB_pixel_format")
  205287. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205288. {
  205289. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  205290. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  205291. jassertfalse
  205292. }
  205293. else
  205294. {
  205295. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  205296. }
  205297. OpenGLPixelFormat pf;
  205298. for (int i = 0; i < numTypes; ++i)
  205299. {
  205300. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  205301. {
  205302. bool alreadyListed = false;
  205303. for (int j = results.size(); --j >= 0;)
  205304. if (pf == *results.getUnchecked(j))
  205305. alreadyListed = true;
  205306. if (! alreadyListed)
  205307. results.add (new OpenGLPixelFormat (pf));
  205308. }
  205309. }
  205310. }
  205311. void* getNativeWindowHandle() const
  205312. {
  205313. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  205314. }
  205315. juce_UseDebuggingNewOperator
  205316. HGLRC renderContext;
  205317. private:
  205318. Win32ComponentPeer* nativeWindow;
  205319. Component* const component;
  205320. HDC dc;
  205321. void createNativeWindow()
  205322. {
  205323. nativeWindow = new Win32ComponentPeer (component, 0);
  205324. nativeWindow->dontRepaint = true;
  205325. nativeWindow->setVisible (true);
  205326. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  205327. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  205328. if (peer != 0)
  205329. {
  205330. SetParent (hwnd, (HWND) peer->getNativeHandle());
  205331. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  205332. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  205333. }
  205334. dc = GetDC (hwnd);
  205335. }
  205336. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  205337. OpenGLPixelFormat& result,
  205338. const StringArray& availableExtensions) const throw()
  205339. {
  205340. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  205341. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  205342. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  205343. {
  205344. int attributes[32];
  205345. int numAttributes = 0;
  205346. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  205347. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  205348. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  205349. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  205350. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  205351. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  205352. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  205353. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  205354. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  205355. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  205356. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  205357. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  205358. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  205359. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  205360. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  205361. if (availableExtensions.contains ("WGL_ARB_multisample"))
  205362. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  205363. int values[32];
  205364. zeromem (values, sizeof (values));
  205365. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  205366. {
  205367. int n = 0;
  205368. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  205369. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  205370. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  205371. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  205372. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  205373. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  205374. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  205375. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  205376. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  205377. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  205378. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  205379. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  205380. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  205381. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  205382. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  205383. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  205384. return isValidFormat;
  205385. }
  205386. else
  205387. {
  205388. jassertfalse
  205389. }
  205390. }
  205391. else
  205392. {
  205393. PIXELFORMATDESCRIPTOR pfd;
  205394. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  205395. {
  205396. result.redBits = pfd.cRedBits;
  205397. result.greenBits = pfd.cGreenBits;
  205398. result.blueBits = pfd.cBlueBits;
  205399. result.alphaBits = pfd.cAlphaBits;
  205400. result.depthBufferBits = pfd.cDepthBits;
  205401. result.stencilBufferBits = pfd.cStencilBits;
  205402. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  205403. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  205404. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  205405. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  205406. result.fullSceneAntiAliasingNumSamples = 0;
  205407. return true;
  205408. }
  205409. else
  205410. {
  205411. jassertfalse
  205412. }
  205413. }
  205414. return false;
  205415. }
  205416. WindowedGLContext (const WindowedGLContext&);
  205417. const WindowedGLContext& operator= (const WindowedGLContext&);
  205418. };
  205419. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  205420. const OpenGLPixelFormat& pixelFormat,
  205421. const OpenGLContext* const contextToShareWith)
  205422. {
  205423. WindowedGLContext* c = new WindowedGLContext (component,
  205424. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  205425. pixelFormat);
  205426. if (c->renderContext == 0)
  205427. deleteAndZero (c);
  205428. return c;
  205429. }
  205430. void* OpenGLComponent::getNativeWindowHandle() const
  205431. {
  205432. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  205433. }
  205434. void juce_glViewport (const int w, const int h)
  205435. {
  205436. glViewport (0, 0, w, h);
  205437. }
  205438. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  205439. OwnedArray <OpenGLPixelFormat>& results)
  205440. {
  205441. Component tempComp;
  205442. {
  205443. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  205444. wc.makeActive();
  205445. wc.findAlternativeOpenGLPixelFormats (results);
  205446. }
  205447. }
  205448. #endif
  205449. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  205450. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  205451. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205452. // compiled on its own).
  205453. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  205454. //***************************************************************************
  205455. // %%% TARGET STATUS VALUES %%%
  205456. //***************************************************************************
  205457. #define STATUS_GOOD 0x00 // Status Good
  205458. #define STATUS_CHKCOND 0x02 // Check Condition
  205459. #define STATUS_CONDMET 0x04 // Condition Met
  205460. #define STATUS_BUSY 0x08 // Busy
  205461. #define STATUS_INTERM 0x10 // Intermediate
  205462. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  205463. #define STATUS_RESCONF 0x18 // Reservation conflict
  205464. #define STATUS_COMTERM 0x22 // Command Terminated
  205465. #define STATUS_QFULL 0x28 // Queue full
  205466. //***************************************************************************
  205467. // %%% SCSI MISCELLANEOUS EQUATES %%%
  205468. //***************************************************************************
  205469. #define MAXLUN 7 // Maximum Logical Unit Id
  205470. #define MAXTARG 7 // Maximum Target Id
  205471. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  205472. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  205473. //***************************************************************************
  205474. // %%% Commands for all Device Types %%%
  205475. //***************************************************************************
  205476. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  205477. #define SCSI_COMPARE 0x39 // Compare (O)
  205478. #define SCSI_COPY 0x18 // Copy (O)
  205479. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  205480. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  205481. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  205482. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  205483. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  205484. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  205485. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  205486. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  205487. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  205488. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  205489. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  205490. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  205491. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  205492. //***************************************************************************
  205493. // %%% Commands Unique to Direct Access Devices %%%
  205494. //***************************************************************************
  205495. #define SCSI_COMPARE 0x39 // Compare (O)
  205496. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  205497. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  205498. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  205499. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  205500. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  205501. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  205502. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  205503. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  205504. #define SCSI_READ_LONG 0x3E // Read Long (O)
  205505. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  205506. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  205507. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  205508. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  205509. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  205510. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  205511. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  205512. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  205513. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  205514. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  205515. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  205516. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  205517. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  205518. #define SCSI_VERIFY 0x2F // Verify (O)
  205519. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  205520. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  205521. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  205522. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  205523. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  205524. //***************************************************************************
  205525. // %%% Commands Unique to Sequential Access Devices %%%
  205526. //***************************************************************************
  205527. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  205528. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  205529. #define SCSI_LOCATE 0x2B // Locate (O)
  205530. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  205531. #define SCSI_READ_POS 0x34 // Read Position (O)
  205532. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  205533. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  205534. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  205535. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  205536. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  205537. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  205538. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  205539. //***************************************************************************
  205540. // %%% Commands Unique to Printer Devices %%%
  205541. //***************************************************************************
  205542. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  205543. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  205544. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  205545. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  205546. //***************************************************************************
  205547. // %%% Commands Unique to Processor Devices %%%
  205548. //***************************************************************************
  205549. #define SCSI_RECEIVE 0x08 // Receive (O)
  205550. #define SCSI_SEND 0x0A // Send (O)
  205551. //***************************************************************************
  205552. // %%% Commands Unique to Write-Once Devices %%%
  205553. //***************************************************************************
  205554. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  205555. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  205556. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  205557. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  205558. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  205559. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  205560. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  205561. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  205562. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  205563. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  205564. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  205565. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  205566. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  205567. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  205568. //***************************************************************************
  205569. // %%% Commands Unique to CD-ROM Devices %%%
  205570. //***************************************************************************
  205571. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  205572. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  205573. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  205574. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  205575. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  205576. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  205577. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  205578. #define SCSI_READHEADER 0x44 // Read Header (O)
  205579. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  205580. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  205581. //***************************************************************************
  205582. // %%% Commands Unique to Scanner Devices %%%
  205583. //***************************************************************************
  205584. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  205585. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  205586. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  205587. #define SCSI_SCAN 0x1B // Scan (O)
  205588. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  205589. //***************************************************************************
  205590. // %%% Commands Unique to Optical Memory Devices %%%
  205591. //***************************************************************************
  205592. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  205593. //***************************************************************************
  205594. // %%% Commands Unique to Medium Changer Devices %%%
  205595. //***************************************************************************
  205596. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  205597. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  205598. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  205599. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  205600. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  205601. //***************************************************************************
  205602. // %%% Commands Unique to Communication Devices %%%
  205603. //***************************************************************************
  205604. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  205605. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  205606. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  205607. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  205608. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  205609. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  205610. //***************************************************************************
  205611. // %%% Request Sense Data Format %%%
  205612. //***************************************************************************
  205613. typedef struct {
  205614. BYTE ErrorCode; // Error Code (70H or 71H)
  205615. BYTE SegmentNum; // Number of current segment descriptor
  205616. BYTE SenseKey; // Sense Key(See bit definitions too)
  205617. BYTE InfoByte0; // Information MSB
  205618. BYTE InfoByte1; // Information MID
  205619. BYTE InfoByte2; // Information MID
  205620. BYTE InfoByte3; // Information LSB
  205621. BYTE AddSenLen; // Additional Sense Length
  205622. BYTE ComSpecInf0; // Command Specific Information MSB
  205623. BYTE ComSpecInf1; // Command Specific Information MID
  205624. BYTE ComSpecInf2; // Command Specific Information MID
  205625. BYTE ComSpecInf3; // Command Specific Information LSB
  205626. BYTE AddSenseCode; // Additional Sense Code
  205627. BYTE AddSenQual; // Additional Sense Code Qualifier
  205628. BYTE FieldRepUCode; // Field Replaceable Unit Code
  205629. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  205630. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  205631. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  205632. BYTE AddSenseBytes; // Additional Sense Bytes
  205633. } SENSE_DATA_FMT;
  205634. //***************************************************************************
  205635. // %%% REQUEST SENSE ERROR CODE %%%
  205636. //***************************************************************************
  205637. #define SERROR_CURRENT 0x70 // Current Errors
  205638. #define SERROR_DEFERED 0x71 // Deferred Errors
  205639. //***************************************************************************
  205640. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  205641. //***************************************************************************
  205642. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  205643. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  205644. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  205645. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  205646. //***************************************************************************
  205647. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  205648. //***************************************************************************
  205649. #define KEY_NOSENSE 0x00 // No Sense
  205650. #define KEY_RECERROR 0x01 // Recovered Error
  205651. #define KEY_NOTREADY 0x02 // Not Ready
  205652. #define KEY_MEDIUMERR 0x03 // Medium Error
  205653. #define KEY_HARDERROR 0x04 // Hardware Error
  205654. #define KEY_ILLGLREQ 0x05 // Illegal Request
  205655. #define KEY_UNITATT 0x06 // Unit Attention
  205656. #define KEY_DATAPROT 0x07 // Data Protect
  205657. #define KEY_BLANKCHK 0x08 // Blank Check
  205658. #define KEY_VENDSPEC 0x09 // Vendor Specific
  205659. #define KEY_COPYABORT 0x0A // Copy Abort
  205660. #define KEY_EQUAL 0x0C // Equal (Search)
  205661. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  205662. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  205663. #define KEY_RESERVED 0x0F // Reserved
  205664. //***************************************************************************
  205665. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  205666. //***************************************************************************
  205667. #define DTYPE_DASD 0x00 // Disk Device
  205668. #define DTYPE_SEQD 0x01 // Tape Device
  205669. #define DTYPE_PRNT 0x02 // Printer
  205670. #define DTYPE_PROC 0x03 // Processor
  205671. #define DTYPE_WORM 0x04 // Write-once read-multiple
  205672. #define DTYPE_CROM 0x05 // CD-ROM device
  205673. #define DTYPE_SCAN 0x06 // Scanner device
  205674. #define DTYPE_OPTI 0x07 // Optical memory device
  205675. #define DTYPE_JUKE 0x08 // Medium Changer device
  205676. #define DTYPE_COMM 0x09 // Communications device
  205677. #define DTYPE_RESL 0x0A // Reserved (low)
  205678. #define DTYPE_RESH 0x1E // Reserved (high)
  205679. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  205680. //***************************************************************************
  205681. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  205682. //***************************************************************************
  205683. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  205684. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  205685. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  205686. #define ANSI_RESLO 0x3 // Reserved (low)
  205687. #define ANSI_RESHI 0x7 // Reserved (high)
  205688. typedef struct
  205689. {
  205690. USHORT Length;
  205691. UCHAR ScsiStatus;
  205692. UCHAR PathId;
  205693. UCHAR TargetId;
  205694. UCHAR Lun;
  205695. UCHAR CdbLength;
  205696. UCHAR SenseInfoLength;
  205697. UCHAR DataIn;
  205698. ULONG DataTransferLength;
  205699. ULONG TimeOutValue;
  205700. ULONG DataBufferOffset;
  205701. ULONG SenseInfoOffset;
  205702. UCHAR Cdb[16];
  205703. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  205704. typedef struct
  205705. {
  205706. USHORT Length;
  205707. UCHAR ScsiStatus;
  205708. UCHAR PathId;
  205709. UCHAR TargetId;
  205710. UCHAR Lun;
  205711. UCHAR CdbLength;
  205712. UCHAR SenseInfoLength;
  205713. UCHAR DataIn;
  205714. ULONG DataTransferLength;
  205715. ULONG TimeOutValue;
  205716. PVOID DataBuffer;
  205717. ULONG SenseInfoOffset;
  205718. UCHAR Cdb[16];
  205719. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  205720. typedef struct
  205721. {
  205722. SCSI_PASS_THROUGH_DIRECT spt;
  205723. ULONG Filler;
  205724. UCHAR ucSenseBuf[32];
  205725. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  205726. typedef struct
  205727. {
  205728. ULONG Length;
  205729. UCHAR PortNumber;
  205730. UCHAR PathId;
  205731. UCHAR TargetId;
  205732. UCHAR Lun;
  205733. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  205734. #define METHOD_BUFFERED 0
  205735. #define METHOD_IN_DIRECT 1
  205736. #define METHOD_OUT_DIRECT 2
  205737. #define METHOD_NEITHER 3
  205738. #define FILE_ANY_ACCESS 0
  205739. #ifndef FILE_READ_ACCESS
  205740. #define FILE_READ_ACCESS (0x0001)
  205741. #endif
  205742. #ifndef FILE_WRITE_ACCESS
  205743. #define FILE_WRITE_ACCESS (0x0002)
  205744. #endif
  205745. #define IOCTL_SCSI_BASE 0x00000004
  205746. #define SCSI_IOCTL_DATA_OUT 0
  205747. #define SCSI_IOCTL_DATA_IN 1
  205748. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  205749. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  205750. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  205751. )
  205752. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205753. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  205754. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  205755. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  205756. #define SENSE_LEN 14
  205757. #define SRB_DIR_SCSI 0x00
  205758. #define SRB_POSTING 0x01
  205759. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  205760. #define SRB_DIR_IN 0x08
  205761. #define SRB_DIR_OUT 0x10
  205762. #define SRB_EVENT_NOTIFY 0x40
  205763. #define RESIDUAL_COUNT_SUPPORTED 0x02
  205764. #define MAX_SRB_TIMEOUT 1080001u
  205765. #define DEFAULT_SRB_TIMEOUT 1080001u
  205766. #define SC_HA_INQUIRY 0x00
  205767. #define SC_GET_DEV_TYPE 0x01
  205768. #define SC_EXEC_SCSI_CMD 0x02
  205769. #define SC_ABORT_SRB 0x03
  205770. #define SC_RESET_DEV 0x04
  205771. #define SC_SET_HA_PARMS 0x05
  205772. #define SC_GET_DISK_INFO 0x06
  205773. #define SC_RESCAN_SCSI_BUS 0x07
  205774. #define SC_GETSET_TIMEOUTS 0x08
  205775. #define SS_PENDING 0x00
  205776. #define SS_COMP 0x01
  205777. #define SS_ABORTED 0x02
  205778. #define SS_ABORT_FAIL 0x03
  205779. #define SS_ERR 0x04
  205780. #define SS_INVALID_CMD 0x80
  205781. #define SS_INVALID_HA 0x81
  205782. #define SS_NO_DEVICE 0x82
  205783. #define SS_INVALID_SRB 0xE0
  205784. #define SS_OLD_MANAGER 0xE1
  205785. #define SS_BUFFER_ALIGN 0xE1
  205786. #define SS_ILLEGAL_MODE 0xE2
  205787. #define SS_NO_ASPI 0xE3
  205788. #define SS_FAILED_INIT 0xE4
  205789. #define SS_ASPI_IS_BUSY 0xE5
  205790. #define SS_BUFFER_TO_BIG 0xE6
  205791. #define SS_BUFFER_TOO_BIG 0xE6
  205792. #define SS_MISMATCHED_COMPONENTS 0xE7
  205793. #define SS_NO_ADAPTERS 0xE8
  205794. #define SS_INSUFFICIENT_RESOURCES 0xE9
  205795. #define SS_ASPI_IS_SHUTDOWN 0xEA
  205796. #define SS_BAD_INSTALL 0xEB
  205797. #define HASTAT_OK 0x00
  205798. #define HASTAT_SEL_TO 0x11
  205799. #define HASTAT_DO_DU 0x12
  205800. #define HASTAT_BUS_FREE 0x13
  205801. #define HASTAT_PHASE_ERR 0x14
  205802. #define HASTAT_TIMEOUT 0x09
  205803. #define HASTAT_COMMAND_TIMEOUT 0x0B
  205804. #define HASTAT_MESSAGE_REJECT 0x0D
  205805. #define HASTAT_BUS_RESET 0x0E
  205806. #define HASTAT_PARITY_ERROR 0x0F
  205807. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  205808. #define PACKED
  205809. #pragma pack(1)
  205810. typedef struct
  205811. {
  205812. BYTE SRB_Cmd;
  205813. BYTE SRB_Status;
  205814. BYTE SRB_HaID;
  205815. BYTE SRB_Flags;
  205816. DWORD SRB_Hdr_Rsvd;
  205817. BYTE HA_Count;
  205818. BYTE HA_SCSI_ID;
  205819. BYTE HA_ManagerId[16];
  205820. BYTE HA_Identifier[16];
  205821. BYTE HA_Unique[16];
  205822. WORD HA_Rsvd1;
  205823. BYTE pad[20];
  205824. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  205825. typedef struct
  205826. {
  205827. BYTE SRB_Cmd;
  205828. BYTE SRB_Status;
  205829. BYTE SRB_HaID;
  205830. BYTE SRB_Flags;
  205831. DWORD SRB_Hdr_Rsvd;
  205832. BYTE SRB_Target;
  205833. BYTE SRB_Lun;
  205834. BYTE SRB_DeviceType;
  205835. BYTE SRB_Rsvd1;
  205836. BYTE pad[68];
  205837. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  205838. typedef struct
  205839. {
  205840. BYTE SRB_Cmd;
  205841. BYTE SRB_Status;
  205842. BYTE SRB_HaID;
  205843. BYTE SRB_Flags;
  205844. DWORD SRB_Hdr_Rsvd;
  205845. BYTE SRB_Target;
  205846. BYTE SRB_Lun;
  205847. WORD SRB_Rsvd1;
  205848. DWORD SRB_BufLen;
  205849. BYTE FAR *SRB_BufPointer;
  205850. BYTE SRB_SenseLen;
  205851. BYTE SRB_CDBLen;
  205852. BYTE SRB_HaStat;
  205853. BYTE SRB_TargStat;
  205854. VOID FAR *SRB_PostProc;
  205855. BYTE SRB_Rsvd2[20];
  205856. BYTE CDBByte[16];
  205857. BYTE SenseArea[SENSE_LEN+2];
  205858. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  205859. typedef struct
  205860. {
  205861. BYTE SRB_Cmd;
  205862. BYTE SRB_Status;
  205863. BYTE SRB_HaId;
  205864. BYTE SRB_Flags;
  205865. DWORD SRB_Hdr_Rsvd;
  205866. } PACKED SRB, *PSRB, FAR *LPSRB;
  205867. #pragma pack()
  205868. struct CDDeviceInfo
  205869. {
  205870. char vendor[9];
  205871. char productId[17];
  205872. char rev[5];
  205873. char vendorSpec[21];
  205874. BYTE ha;
  205875. BYTE tgt;
  205876. BYTE lun;
  205877. char scsiDriveLetter; // will be 0 if not using scsi
  205878. };
  205879. class CDReadBuffer
  205880. {
  205881. public:
  205882. int startFrame;
  205883. int numFrames;
  205884. int dataStartOffset;
  205885. int dataLength;
  205886. BYTE* buffer;
  205887. int bufferSize;
  205888. int index;
  205889. bool wantsIndex;
  205890. CDReadBuffer (const int numberOfFrames)
  205891. : startFrame (0),
  205892. numFrames (0),
  205893. dataStartOffset (0),
  205894. dataLength (0),
  205895. index (0),
  205896. wantsIndex (false)
  205897. {
  205898. bufferSize = 2352 * numberOfFrames;
  205899. buffer = (BYTE*) malloc (bufferSize);
  205900. }
  205901. ~CDReadBuffer()
  205902. {
  205903. free (buffer);
  205904. }
  205905. bool isZero() const
  205906. {
  205907. BYTE* p = buffer + dataStartOffset;
  205908. for (int i = dataLength; --i >= 0;)
  205909. if (*p++ != 0)
  205910. return false;
  205911. return true;
  205912. }
  205913. };
  205914. class CDDeviceHandle;
  205915. class CDController
  205916. {
  205917. public:
  205918. CDController();
  205919. virtual ~CDController();
  205920. virtual bool read (CDReadBuffer* t) = 0;
  205921. virtual void shutDown();
  205922. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  205923. int getLastIndex();
  205924. public:
  205925. bool initialised;
  205926. CDDeviceHandle* deviceInfo;
  205927. int framesToCheck, framesOverlap;
  205928. void prepare (SRB_ExecSCSICmd& s);
  205929. void perform (SRB_ExecSCSICmd& s);
  205930. void setPaused (bool paused);
  205931. };
  205932. #pragma pack(1)
  205933. struct TOCTRACK
  205934. {
  205935. BYTE rsvd;
  205936. BYTE ADR;
  205937. BYTE trackNumber;
  205938. BYTE rsvd2;
  205939. BYTE addr[4];
  205940. };
  205941. struct TOC
  205942. {
  205943. WORD tocLen;
  205944. BYTE firstTrack;
  205945. BYTE lastTrack;
  205946. TOCTRACK tracks[100];
  205947. };
  205948. #pragma pack()
  205949. enum
  205950. {
  205951. READTYPE_ANY = 0,
  205952. READTYPE_ATAPI1 = 1,
  205953. READTYPE_ATAPI2 = 2,
  205954. READTYPE_READ6 = 3,
  205955. READTYPE_READ10 = 4,
  205956. READTYPE_READ_D8 = 5,
  205957. READTYPE_READ_D4 = 6,
  205958. READTYPE_READ_D4_1 = 7,
  205959. READTYPE_READ10_2 = 8
  205960. };
  205961. class CDDeviceHandle
  205962. {
  205963. public:
  205964. CDDeviceHandle (const CDDeviceInfo* const device)
  205965. : scsiHandle (0),
  205966. readType (READTYPE_ANY),
  205967. controller (0)
  205968. {
  205969. memcpy (&info, device, sizeof (info));
  205970. }
  205971. ~CDDeviceHandle()
  205972. {
  205973. if (controller != 0)
  205974. {
  205975. controller->shutDown();
  205976. delete controller;
  205977. }
  205978. if (scsiHandle != 0)
  205979. CloseHandle (scsiHandle);
  205980. }
  205981. bool readTOC (TOC* lpToc, bool useMSF);
  205982. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  205983. void openDrawer (bool shouldBeOpen);
  205984. CDDeviceInfo info;
  205985. HANDLE scsiHandle;
  205986. BYTE readType;
  205987. private:
  205988. CDController* controller;
  205989. bool testController (const int readType,
  205990. CDController* const newController,
  205991. CDReadBuffer* const bufferToUse);
  205992. };
  205993. DWORD (*fGetASPI32SupportInfo)(void);
  205994. DWORD (*fSendASPI32Command)(LPSRB);
  205995. static HINSTANCE winAspiLib = 0;
  205996. static bool usingScsi = false;
  205997. static bool initialised = false;
  205998. static bool InitialiseCDRipper()
  205999. {
  206000. if (! initialised)
  206001. {
  206002. initialised = true;
  206003. OSVERSIONINFO info;
  206004. info.dwOSVersionInfoSize = sizeof (info);
  206005. GetVersionEx (&info);
  206006. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  206007. if (! usingScsi)
  206008. {
  206009. fGetASPI32SupportInfo = 0;
  206010. fSendASPI32Command = 0;
  206011. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  206012. if (winAspiLib != 0)
  206013. {
  206014. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  206015. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  206016. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  206017. return false;
  206018. }
  206019. else
  206020. {
  206021. usingScsi = true;
  206022. }
  206023. }
  206024. }
  206025. return true;
  206026. }
  206027. static void DeinitialiseCDRipper()
  206028. {
  206029. if (winAspiLib != 0)
  206030. {
  206031. fGetASPI32SupportInfo = 0;
  206032. fSendASPI32Command = 0;
  206033. FreeLibrary (winAspiLib);
  206034. winAspiLib = 0;
  206035. }
  206036. initialised = false;
  206037. }
  206038. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  206039. {
  206040. TCHAR devicePath[8];
  206041. devicePath[0] = '\\';
  206042. devicePath[1] = '\\';
  206043. devicePath[2] = '.';
  206044. devicePath[3] = '\\';
  206045. devicePath[4] = driveLetter;
  206046. devicePath[5] = ':';
  206047. devicePath[6] = 0;
  206048. OSVERSIONINFO info;
  206049. info.dwOSVersionInfoSize = sizeof (info);
  206050. GetVersionEx (&info);
  206051. DWORD flags = GENERIC_READ;
  206052. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  206053. flags = GENERIC_READ | GENERIC_WRITE;
  206054. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206055. if (h == INVALID_HANDLE_VALUE)
  206056. {
  206057. flags ^= GENERIC_WRITE;
  206058. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  206059. }
  206060. return h;
  206061. }
  206062. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  206063. const char driveLetter,
  206064. HANDLE& deviceHandle,
  206065. const bool retryOnFailure = true)
  206066. {
  206067. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  206068. zerostruct (s);
  206069. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  206070. s.spt.CdbLength = srb->SRB_CDBLen;
  206071. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  206072. ? SCSI_IOCTL_DATA_IN
  206073. : ((srb->SRB_Flags & SRB_DIR_OUT)
  206074. ? SCSI_IOCTL_DATA_OUT
  206075. : SCSI_IOCTL_DATA_UNSPECIFIED));
  206076. s.spt.DataTransferLength = srb->SRB_BufLen;
  206077. s.spt.TimeOutValue = 5;
  206078. s.spt.DataBuffer = srb->SRB_BufPointer;
  206079. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206080. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  206081. srb->SRB_Status = SS_ERR;
  206082. srb->SRB_TargStat = 0x0004;
  206083. DWORD bytesReturned = 0;
  206084. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206085. &s, sizeof (s),
  206086. &s, sizeof (s),
  206087. &bytesReturned, 0) != 0)
  206088. {
  206089. srb->SRB_Status = SS_COMP;
  206090. }
  206091. else if (retryOnFailure)
  206092. {
  206093. const DWORD error = GetLastError();
  206094. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  206095. {
  206096. if (error != ERROR_INVALID_HANDLE)
  206097. CloseHandle (deviceHandle);
  206098. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  206099. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  206100. }
  206101. }
  206102. return srb->SRB_Status;
  206103. }
  206104. // Controller types..
  206105. class ControllerType1 : public CDController
  206106. {
  206107. public:
  206108. ControllerType1() {}
  206109. ~ControllerType1() {}
  206110. bool read (CDReadBuffer* rb)
  206111. {
  206112. if (rb->numFrames * 2352 > rb->bufferSize)
  206113. return false;
  206114. SRB_ExecSCSICmd s;
  206115. prepare (s);
  206116. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206117. s.SRB_BufLen = rb->bufferSize;
  206118. s.SRB_BufPointer = rb->buffer;
  206119. s.SRB_CDBLen = 12;
  206120. s.CDBByte[0] = 0xBE;
  206121. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206122. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206123. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206124. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206125. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  206126. perform (s);
  206127. if (s.SRB_Status != SS_COMP)
  206128. return false;
  206129. rb->dataLength = rb->numFrames * 2352;
  206130. rb->dataStartOffset = 0;
  206131. return true;
  206132. }
  206133. };
  206134. class ControllerType2 : public CDController
  206135. {
  206136. public:
  206137. ControllerType2() {}
  206138. ~ControllerType2() {}
  206139. void shutDown()
  206140. {
  206141. if (initialised)
  206142. {
  206143. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  206144. SRB_ExecSCSICmd s;
  206145. prepare (s);
  206146. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  206147. s.SRB_BufLen = 0x0C;
  206148. s.SRB_BufPointer = bufPointer;
  206149. s.SRB_CDBLen = 6;
  206150. s.CDBByte[0] = 0x15;
  206151. s.CDBByte[4] = 0x0C;
  206152. perform (s);
  206153. }
  206154. }
  206155. bool init()
  206156. {
  206157. SRB_ExecSCSICmd s;
  206158. s.SRB_Status = SS_ERR;
  206159. if (deviceInfo->readType == READTYPE_READ10_2)
  206160. {
  206161. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  206162. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  206163. for (int i = 0; i < 2; ++i)
  206164. {
  206165. prepare (s);
  206166. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206167. s.SRB_BufLen = 0x14;
  206168. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  206169. s.SRB_CDBLen = 6;
  206170. s.CDBByte[0] = 0x15;
  206171. s.CDBByte[1] = 0x10;
  206172. s.CDBByte[4] = 0x14;
  206173. perform (s);
  206174. if (s.SRB_Status != SS_COMP)
  206175. return false;
  206176. }
  206177. }
  206178. else
  206179. {
  206180. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  206181. prepare (s);
  206182. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206183. s.SRB_BufLen = 0x0C;
  206184. s.SRB_BufPointer = bufPointer;
  206185. s.SRB_CDBLen = 6;
  206186. s.CDBByte[0] = 0x15;
  206187. s.CDBByte[4] = 0x0C;
  206188. perform (s);
  206189. }
  206190. return s.SRB_Status == SS_COMP;
  206191. }
  206192. bool read (CDReadBuffer* rb)
  206193. {
  206194. if (rb->numFrames * 2352 > rb->bufferSize)
  206195. return false;
  206196. if (!initialised)
  206197. {
  206198. initialised = init();
  206199. if (!initialised)
  206200. return false;
  206201. }
  206202. SRB_ExecSCSICmd s;
  206203. prepare (s);
  206204. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206205. s.SRB_BufLen = rb->bufferSize;
  206206. s.SRB_BufPointer = rb->buffer;
  206207. s.SRB_CDBLen = 10;
  206208. s.CDBByte[0] = 0x28;
  206209. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206210. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206211. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206212. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206213. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206214. perform (s);
  206215. if (s.SRB_Status != SS_COMP)
  206216. return false;
  206217. rb->dataLength = rb->numFrames * 2352;
  206218. rb->dataStartOffset = 0;
  206219. return true;
  206220. }
  206221. };
  206222. class ControllerType3 : public CDController
  206223. {
  206224. public:
  206225. ControllerType3() {}
  206226. ~ControllerType3() {}
  206227. bool read (CDReadBuffer* rb)
  206228. {
  206229. if (rb->numFrames * 2352 > rb->bufferSize)
  206230. return false;
  206231. if (!initialised)
  206232. {
  206233. setPaused (false);
  206234. initialised = true;
  206235. }
  206236. SRB_ExecSCSICmd s;
  206237. prepare (s);
  206238. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206239. s.SRB_BufLen = rb->numFrames * 2352;
  206240. s.SRB_BufPointer = rb->buffer;
  206241. s.SRB_CDBLen = 12;
  206242. s.CDBByte[0] = 0xD8;
  206243. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206244. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206245. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206246. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  206247. perform (s);
  206248. if (s.SRB_Status != SS_COMP)
  206249. return false;
  206250. rb->dataLength = rb->numFrames * 2352;
  206251. rb->dataStartOffset = 0;
  206252. return true;
  206253. }
  206254. };
  206255. class ControllerType4 : public CDController
  206256. {
  206257. public:
  206258. ControllerType4() {}
  206259. ~ControllerType4() {}
  206260. bool selectD4Mode()
  206261. {
  206262. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  206263. SRB_ExecSCSICmd s;
  206264. prepare (s);
  206265. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206266. s.SRB_CDBLen = 6;
  206267. s.SRB_BufLen = 12;
  206268. s.SRB_BufPointer = bufPointer;
  206269. s.CDBByte[0] = 0x15;
  206270. s.CDBByte[1] = 0x10;
  206271. s.CDBByte[4] = 0x08;
  206272. perform (s);
  206273. return s.SRB_Status == SS_COMP;
  206274. }
  206275. bool read (CDReadBuffer* rb)
  206276. {
  206277. if (rb->numFrames * 2352 > rb->bufferSize)
  206278. return false;
  206279. if (!initialised)
  206280. {
  206281. setPaused (true);
  206282. if (deviceInfo->readType == READTYPE_READ_D4_1)
  206283. selectD4Mode();
  206284. initialised = true;
  206285. }
  206286. SRB_ExecSCSICmd s;
  206287. prepare (s);
  206288. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206289. s.SRB_BufLen = rb->bufferSize;
  206290. s.SRB_BufPointer = rb->buffer;
  206291. s.SRB_CDBLen = 10;
  206292. s.CDBByte[0] = 0xD4;
  206293. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  206294. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  206295. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  206296. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  206297. perform (s);
  206298. if (s.SRB_Status != SS_COMP)
  206299. return false;
  206300. rb->dataLength = rb->numFrames * 2352;
  206301. rb->dataStartOffset = 0;
  206302. return true;
  206303. }
  206304. };
  206305. CDController::CDController() : initialised (false)
  206306. {
  206307. }
  206308. CDController::~CDController()
  206309. {
  206310. }
  206311. void CDController::prepare (SRB_ExecSCSICmd& s)
  206312. {
  206313. zerostruct (s);
  206314. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206315. s.SRB_HaID = deviceInfo->info.ha;
  206316. s.SRB_Target = deviceInfo->info.tgt;
  206317. s.SRB_Lun = deviceInfo->info.lun;
  206318. s.SRB_SenseLen = SENSE_LEN;
  206319. }
  206320. void CDController::perform (SRB_ExecSCSICmd& s)
  206321. {
  206322. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206323. s.SRB_PostProc = (void*)event;
  206324. ResetEvent (event);
  206325. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  206326. deviceInfo->info.scsiDriveLetter,
  206327. deviceInfo->scsiHandle)
  206328. : fSendASPI32Command ((LPSRB)&s);
  206329. if (status == SS_PENDING)
  206330. WaitForSingleObject (event, 4000);
  206331. CloseHandle (event);
  206332. }
  206333. void CDController::setPaused (bool paused)
  206334. {
  206335. SRB_ExecSCSICmd s;
  206336. prepare (s);
  206337. s.SRB_Flags = SRB_EVENT_NOTIFY;
  206338. s.SRB_CDBLen = 10;
  206339. s.CDBByte[0] = 0x4B;
  206340. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  206341. perform (s);
  206342. }
  206343. void CDController::shutDown()
  206344. {
  206345. }
  206346. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  206347. {
  206348. if (overlapBuffer != 0)
  206349. {
  206350. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  206351. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  206352. if (doJitter
  206353. && overlapBuffer->startFrame > 0
  206354. && overlapBuffer->numFrames > 0
  206355. && overlapBuffer->dataLength > 0)
  206356. {
  206357. const int numFrames = rb->numFrames;
  206358. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  206359. {
  206360. rb->startFrame -= framesOverlap;
  206361. if (framesToCheck < framesOverlap
  206362. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  206363. rb->numFrames += framesOverlap;
  206364. }
  206365. else
  206366. {
  206367. overlapBuffer->dataLength = 0;
  206368. overlapBuffer->startFrame = 0;
  206369. overlapBuffer->numFrames = 0;
  206370. }
  206371. }
  206372. if (! read (rb))
  206373. return false;
  206374. if (doJitter)
  206375. {
  206376. const int checkLen = framesToCheck * 2352;
  206377. const int maxToCheck = rb->dataLength - checkLen;
  206378. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  206379. return true;
  206380. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  206381. bool found = false;
  206382. for (int i = 0; i < maxToCheck; ++i)
  206383. {
  206384. if (!memcmp (p, rb->buffer + i, checkLen))
  206385. {
  206386. i += checkLen;
  206387. rb->dataStartOffset = i;
  206388. rb->dataLength -= i;
  206389. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  206390. found = true;
  206391. break;
  206392. }
  206393. }
  206394. rb->numFrames = rb->dataLength / 2352;
  206395. rb->dataLength = 2352 * rb->numFrames;
  206396. if (!found)
  206397. return false;
  206398. }
  206399. if (canDoJitter)
  206400. {
  206401. memcpy (overlapBuffer->buffer,
  206402. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  206403. 2352 * framesToCheck);
  206404. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  206405. overlapBuffer->numFrames = framesToCheck;
  206406. overlapBuffer->dataLength = 2352 * framesToCheck;
  206407. overlapBuffer->dataStartOffset = 0;
  206408. }
  206409. else
  206410. {
  206411. overlapBuffer->startFrame = 0;
  206412. overlapBuffer->numFrames = 0;
  206413. overlapBuffer->dataLength = 0;
  206414. }
  206415. return true;
  206416. }
  206417. else
  206418. {
  206419. return read (rb);
  206420. }
  206421. }
  206422. int CDController::getLastIndex()
  206423. {
  206424. char qdata[100];
  206425. SRB_ExecSCSICmd s;
  206426. prepare (s);
  206427. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206428. s.SRB_BufLen = sizeof (qdata);
  206429. s.SRB_BufPointer = (BYTE*)qdata;
  206430. s.SRB_CDBLen = 12;
  206431. s.CDBByte[0] = 0x42;
  206432. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  206433. s.CDBByte[2] = 64;
  206434. s.CDBByte[3] = 1; // get current position
  206435. s.CDBByte[7] = 0;
  206436. s.CDBByte[8] = (BYTE)sizeof (qdata);
  206437. perform (s);
  206438. if (s.SRB_Status == SS_COMP)
  206439. return qdata[7];
  206440. return 0;
  206441. }
  206442. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  206443. {
  206444. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206445. SRB_ExecSCSICmd s;
  206446. zerostruct (s);
  206447. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206448. s.SRB_HaID = info.ha;
  206449. s.SRB_Target = info.tgt;
  206450. s.SRB_Lun = info.lun;
  206451. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206452. s.SRB_BufLen = 0x324;
  206453. s.SRB_BufPointer = (BYTE*)lpToc;
  206454. s.SRB_SenseLen = 0x0E;
  206455. s.SRB_CDBLen = 0x0A;
  206456. s.SRB_PostProc = (void*)event;
  206457. s.CDBByte[0] = 0x43;
  206458. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  206459. s.CDBByte[7] = 0x03;
  206460. s.CDBByte[8] = 0x24;
  206461. ResetEvent (event);
  206462. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206463. : fSendASPI32Command ((LPSRB)&s);
  206464. if (status == SS_PENDING)
  206465. WaitForSingleObject (event, 4000);
  206466. CloseHandle (event);
  206467. return (s.SRB_Status == SS_COMP);
  206468. }
  206469. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  206470. CDReadBuffer* const overlapBuffer)
  206471. {
  206472. if (controller == 0)
  206473. {
  206474. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  206475. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  206476. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  206477. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  206478. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  206479. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  206480. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  206481. }
  206482. buffer->index = 0;
  206483. if ((controller != 0)
  206484. && controller->readAudio (buffer, overlapBuffer))
  206485. {
  206486. if (buffer->wantsIndex)
  206487. buffer->index = controller->getLastIndex();
  206488. return true;
  206489. }
  206490. return false;
  206491. }
  206492. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  206493. {
  206494. if (shouldBeOpen)
  206495. {
  206496. if (controller != 0)
  206497. {
  206498. controller->shutDown();
  206499. delete controller;
  206500. controller = 0;
  206501. }
  206502. if (scsiHandle != 0)
  206503. {
  206504. CloseHandle (scsiHandle);
  206505. scsiHandle = 0;
  206506. }
  206507. }
  206508. SRB_ExecSCSICmd s;
  206509. zerostruct (s);
  206510. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206511. s.SRB_HaID = info.ha;
  206512. s.SRB_Target = info.tgt;
  206513. s.SRB_Lun = info.lun;
  206514. s.SRB_SenseLen = SENSE_LEN;
  206515. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206516. s.SRB_BufLen = 0;
  206517. s.SRB_BufPointer = 0;
  206518. s.SRB_CDBLen = 12;
  206519. s.CDBByte[0] = 0x1b;
  206520. s.CDBByte[1] = (BYTE)(info.lun << 5);
  206521. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  206522. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206523. s.SRB_PostProc = (void*)event;
  206524. ResetEvent (event);
  206525. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  206526. : fSendASPI32Command ((LPSRB)&s);
  206527. if (status == SS_PENDING)
  206528. WaitForSingleObject (event, 4000);
  206529. CloseHandle (event);
  206530. }
  206531. bool CDDeviceHandle::testController (const int type,
  206532. CDController* const newController,
  206533. CDReadBuffer* const rb)
  206534. {
  206535. controller = newController;
  206536. readType = (BYTE)type;
  206537. controller->deviceInfo = this;
  206538. controller->framesToCheck = 1;
  206539. controller->framesOverlap = 3;
  206540. bool passed = false;
  206541. memset (rb->buffer, 0xcd, rb->bufferSize);
  206542. if (controller->read (rb))
  206543. {
  206544. passed = true;
  206545. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  206546. int wrong = 0;
  206547. for (int i = rb->dataLength / 4; --i >= 0;)
  206548. {
  206549. if (*p++ == (int) 0xcdcdcdcd)
  206550. {
  206551. if (++wrong == 4)
  206552. {
  206553. passed = false;
  206554. break;
  206555. }
  206556. }
  206557. else
  206558. {
  206559. wrong = 0;
  206560. }
  206561. }
  206562. }
  206563. if (! passed)
  206564. {
  206565. controller->shutDown();
  206566. delete controller;
  206567. controller = 0;
  206568. }
  206569. return passed;
  206570. }
  206571. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  206572. {
  206573. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  206574. const int bufSize = 128;
  206575. BYTE buffer[bufSize];
  206576. zeromem (buffer, bufSize);
  206577. SRB_ExecSCSICmd s;
  206578. zerostruct (s);
  206579. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  206580. s.SRB_HaID = ha;
  206581. s.SRB_Target = tgt;
  206582. s.SRB_Lun = lun;
  206583. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  206584. s.SRB_BufLen = bufSize;
  206585. s.SRB_BufPointer = buffer;
  206586. s.SRB_SenseLen = SENSE_LEN;
  206587. s.SRB_CDBLen = 6;
  206588. s.SRB_PostProc = (void*)event;
  206589. s.CDBByte[0] = SCSI_INQUIRY;
  206590. s.CDBByte[4] = 100;
  206591. ResetEvent (event);
  206592. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  206593. WaitForSingleObject (event, 4000);
  206594. CloseHandle (event);
  206595. if (s.SRB_Status == SS_COMP)
  206596. {
  206597. memcpy (dev->vendor, &buffer[8], 8);
  206598. memcpy (dev->productId, &buffer[16], 16);
  206599. memcpy (dev->rev, &buffer[32], 4);
  206600. memcpy (dev->vendorSpec, &buffer[36], 20);
  206601. }
  206602. }
  206603. static int FindCDDevices (CDDeviceInfo* const list,
  206604. int maxItems)
  206605. {
  206606. int count = 0;
  206607. if (usingScsi)
  206608. {
  206609. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  206610. {
  206611. TCHAR drivePath[8];
  206612. drivePath[0] = driveLetter;
  206613. drivePath[1] = ':';
  206614. drivePath[2] = '\\';
  206615. drivePath[3] = 0;
  206616. if (GetDriveType (drivePath) == DRIVE_CDROM)
  206617. {
  206618. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  206619. if (h != INVALID_HANDLE_VALUE)
  206620. {
  206621. BYTE buffer[100], passThroughStruct[1024];
  206622. zeromem (buffer, sizeof (buffer));
  206623. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206624. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  206625. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  206626. p->spt.CdbLength = 6;
  206627. p->spt.SenseInfoLength = 24;
  206628. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  206629. p->spt.DataTransferLength = 100;
  206630. p->spt.TimeOutValue = 2;
  206631. p->spt.DataBuffer = buffer;
  206632. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  206633. p->spt.Cdb[0] = 0x12;
  206634. p->spt.Cdb[4] = 100;
  206635. DWORD bytesReturned = 0;
  206636. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  206637. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206638. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  206639. &bytesReturned, 0) != 0)
  206640. {
  206641. zeromem (&list[count], sizeof (CDDeviceInfo));
  206642. list[count].scsiDriveLetter = driveLetter;
  206643. memcpy (list[count].vendor, &buffer[8], 8);
  206644. memcpy (list[count].productId, &buffer[16], 16);
  206645. memcpy (list[count].rev, &buffer[32], 4);
  206646. memcpy (list[count].vendorSpec, &buffer[36], 20);
  206647. zeromem (passThroughStruct, sizeof (passThroughStruct));
  206648. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  206649. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  206650. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  206651. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  206652. &bytesReturned, 0) != 0)
  206653. {
  206654. list[count].ha = scsiAddr->PortNumber;
  206655. list[count].tgt = scsiAddr->TargetId;
  206656. list[count].lun = scsiAddr->Lun;
  206657. ++count;
  206658. }
  206659. }
  206660. CloseHandle (h);
  206661. }
  206662. }
  206663. }
  206664. }
  206665. else
  206666. {
  206667. const DWORD d = fGetASPI32SupportInfo();
  206668. BYTE status = HIBYTE (LOWORD (d));
  206669. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  206670. return 0;
  206671. const int numAdapters = LOBYTE (LOWORD (d));
  206672. for (BYTE ha = 0; ha < numAdapters; ++ha)
  206673. {
  206674. SRB_HAInquiry s;
  206675. zerostruct (s);
  206676. s.SRB_Cmd = SC_HA_INQUIRY;
  206677. s.SRB_HaID = ha;
  206678. fSendASPI32Command ((LPSRB)&s);
  206679. if (s.SRB_Status == SS_COMP)
  206680. {
  206681. maxItems = (int)s.HA_Unique[3];
  206682. if (maxItems == 0)
  206683. maxItems = 8;
  206684. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  206685. {
  206686. for (BYTE lun = 0; lun < 8; ++lun)
  206687. {
  206688. SRB_GDEVBlock sb;
  206689. zerostruct (sb);
  206690. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  206691. sb.SRB_HaID = ha;
  206692. sb.SRB_Target = tgt;
  206693. sb.SRB_Lun = lun;
  206694. fSendASPI32Command ((LPSRB) &sb);
  206695. if (sb.SRB_Status == SS_COMP
  206696. && sb.SRB_DeviceType == DTYPE_CROM)
  206697. {
  206698. zeromem (&list[count], sizeof (CDDeviceInfo));
  206699. list[count].ha = ha;
  206700. list[count].tgt = tgt;
  206701. list[count].lun = lun;
  206702. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  206703. ++count;
  206704. }
  206705. }
  206706. }
  206707. }
  206708. }
  206709. }
  206710. return count;
  206711. }
  206712. static int ripperUsers = 0;
  206713. static bool initialisedOk = false;
  206714. class DeinitialiseTimer : private Timer,
  206715. private DeletedAtShutdown
  206716. {
  206717. DeinitialiseTimer (const DeinitialiseTimer&);
  206718. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  206719. public:
  206720. DeinitialiseTimer()
  206721. {
  206722. startTimer (4000);
  206723. }
  206724. ~DeinitialiseTimer()
  206725. {
  206726. if (--ripperUsers == 0)
  206727. DeinitialiseCDRipper();
  206728. }
  206729. void timerCallback()
  206730. {
  206731. delete this;
  206732. }
  206733. juce_UseDebuggingNewOperator
  206734. };
  206735. static void incUserCount()
  206736. {
  206737. if (ripperUsers++ == 0)
  206738. initialisedOk = InitialiseCDRipper();
  206739. }
  206740. static void decUserCount()
  206741. {
  206742. new DeinitialiseTimer();
  206743. }
  206744. struct CDDeviceWrapper
  206745. {
  206746. CDDeviceHandle* cdH;
  206747. CDReadBuffer* overlapBuffer;
  206748. bool jitter;
  206749. };
  206750. static int getAddressOf (const TOCTRACK* const t)
  206751. {
  206752. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  206753. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  206754. }
  206755. static int getMSFAddressOf (const TOCTRACK* const t)
  206756. {
  206757. return 60 * t->addr[1] + t->addr[2];
  206758. }
  206759. static const int samplesPerFrame = 44100 / 75;
  206760. static const int bytesPerFrame = samplesPerFrame * 4;
  206761. const StringArray AudioCDReader::getAvailableCDNames()
  206762. {
  206763. StringArray results;
  206764. incUserCount();
  206765. if (initialisedOk)
  206766. {
  206767. CDDeviceInfo list[8];
  206768. const int num = FindCDDevices (list, 8);
  206769. decUserCount();
  206770. for (int i = 0; i < num; ++i)
  206771. {
  206772. String s;
  206773. if (list[i].scsiDriveLetter > 0)
  206774. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  206775. s << String (list[i].vendor).trim()
  206776. << T(" ") << String (list[i].productId).trim()
  206777. << T(" ") << String (list[i].rev).trim();
  206778. results.add (s);
  206779. }
  206780. }
  206781. return results;
  206782. }
  206783. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  206784. {
  206785. SRB_GDEVBlock s;
  206786. zerostruct (s);
  206787. s.SRB_Cmd = SC_GET_DEV_TYPE;
  206788. s.SRB_HaID = device->ha;
  206789. s.SRB_Target = device->tgt;
  206790. s.SRB_Lun = device->lun;
  206791. if (usingScsi)
  206792. {
  206793. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  206794. if (h != INVALID_HANDLE_VALUE)
  206795. {
  206796. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  206797. cdh->scsiHandle = h;
  206798. return cdh;
  206799. }
  206800. }
  206801. else
  206802. {
  206803. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  206804. && s.SRB_DeviceType == DTYPE_CROM)
  206805. {
  206806. return new CDDeviceHandle (device);
  206807. }
  206808. }
  206809. return 0;
  206810. }
  206811. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  206812. {
  206813. incUserCount();
  206814. if (initialisedOk)
  206815. {
  206816. CDDeviceInfo list[8];
  206817. const int num = FindCDDevices (list, 8);
  206818. if (((unsigned int) deviceIndex) < (unsigned int) num)
  206819. {
  206820. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  206821. if (handle != 0)
  206822. {
  206823. CDDeviceWrapper* const d = new CDDeviceWrapper();
  206824. d->cdH = handle;
  206825. d->overlapBuffer = new CDReadBuffer(3);
  206826. return new AudioCDReader (d);
  206827. }
  206828. }
  206829. }
  206830. decUserCount();
  206831. return 0;
  206832. }
  206833. AudioCDReader::AudioCDReader (void* handle_)
  206834. : AudioFormatReader (0, T("CD Audio")),
  206835. handle (handle_),
  206836. indexingEnabled (false),
  206837. lastIndex (0),
  206838. firstFrameInBuffer (0),
  206839. samplesInBuffer (0)
  206840. {
  206841. jassert (handle_ != 0);
  206842. refreshTrackLengths();
  206843. sampleRate = 44100.0;
  206844. bitsPerSample = 16;
  206845. lengthInSamples = getPositionOfTrackStart (numTracks);
  206846. numChannels = 2;
  206847. usesFloatingPointData = false;
  206848. buffer.setSize (4 * bytesPerFrame, true);
  206849. }
  206850. AudioCDReader::~AudioCDReader()
  206851. {
  206852. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  206853. delete device->cdH;
  206854. delete device->overlapBuffer;
  206855. delete device;
  206856. decUserCount();
  206857. }
  206858. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  206859. int64 startSampleInFile, int numSamples)
  206860. {
  206861. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206862. bool ok = true;
  206863. while (numSamples > 0)
  206864. {
  206865. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  206866. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  206867. if (startSampleInFile >= bufferStartSample
  206868. && startSampleInFile < bufferEndSample)
  206869. {
  206870. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  206871. int* const l = destSamples[0] + startOffsetInDestBuffer;
  206872. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206873. const short* src = (const short*) buffer.getData();
  206874. src += 2 * (startSampleInFile - bufferStartSample);
  206875. for (int i = 0; i < toDo; ++i)
  206876. {
  206877. l[i] = src [i << 1] << 16;
  206878. if (r != 0)
  206879. r[i] = src [(i << 1) + 1] << 16;
  206880. }
  206881. startOffsetInDestBuffer += toDo;
  206882. startSampleInFile += toDo;
  206883. numSamples -= toDo;
  206884. }
  206885. else
  206886. {
  206887. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  206888. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  206889. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  206890. {
  206891. device->overlapBuffer->dataLength = 0;
  206892. device->overlapBuffer->startFrame = 0;
  206893. device->overlapBuffer->numFrames = 0;
  206894. device->jitter = false;
  206895. }
  206896. firstFrameInBuffer = frameNeeded;
  206897. lastIndex = 0;
  206898. CDReadBuffer readBuffer (framesInBuffer + 4);
  206899. readBuffer.wantsIndex = indexingEnabled;
  206900. int i;
  206901. for (i = 5; --i >= 0;)
  206902. {
  206903. readBuffer.startFrame = frameNeeded;
  206904. readBuffer.numFrames = framesInBuffer;
  206905. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  206906. break;
  206907. else
  206908. device->overlapBuffer->dataLength = 0;
  206909. }
  206910. if (i >= 0)
  206911. {
  206912. memcpy ((char*) buffer.getData(),
  206913. readBuffer.buffer + readBuffer.dataStartOffset,
  206914. readBuffer.dataLength);
  206915. samplesInBuffer = readBuffer.dataLength >> 2;
  206916. lastIndex = readBuffer.index;
  206917. }
  206918. else
  206919. {
  206920. int* l = destSamples[0] + startOffsetInDestBuffer;
  206921. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  206922. while (--numSamples >= 0)
  206923. {
  206924. *l++ = 0;
  206925. if (r != 0)
  206926. *r++ = 0;
  206927. }
  206928. // sometimes the read fails for just the very last couple of blocks, so
  206929. // we'll ignore and errors in the last half-second of the disk..
  206930. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  206931. break;
  206932. }
  206933. }
  206934. }
  206935. return ok;
  206936. }
  206937. bool AudioCDReader::isCDStillPresent() const
  206938. {
  206939. TOC toc;
  206940. zerostruct (toc);
  206941. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  206942. }
  206943. int AudioCDReader::getNumTracks() const
  206944. {
  206945. return numTracks;
  206946. }
  206947. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  206948. {
  206949. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  206950. : 0;
  206951. }
  206952. void AudioCDReader::refreshTrackLengths()
  206953. {
  206954. zeromem (trackStarts, sizeof (trackStarts));
  206955. zeromem (audioTracks, sizeof (audioTracks));
  206956. TOC toc;
  206957. zerostruct (toc);
  206958. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  206959. {
  206960. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  206961. for (int i = 0; i <= numTracks; ++i)
  206962. {
  206963. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  206964. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  206965. }
  206966. }
  206967. else
  206968. {
  206969. numTracks = 0;
  206970. }
  206971. }
  206972. bool AudioCDReader::isTrackAudio (int trackNum) const
  206973. {
  206974. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  206975. : false;
  206976. }
  206977. void AudioCDReader::enableIndexScanning (bool b)
  206978. {
  206979. indexingEnabled = b;
  206980. }
  206981. int AudioCDReader::getLastIndex() const
  206982. {
  206983. return lastIndex;
  206984. }
  206985. const int framesPerIndexRead = 4;
  206986. int AudioCDReader::getIndexAt (int samplePos)
  206987. {
  206988. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  206989. const int frameNeeded = samplePos / samplesPerFrame;
  206990. device->overlapBuffer->dataLength = 0;
  206991. device->overlapBuffer->startFrame = 0;
  206992. device->overlapBuffer->numFrames = 0;
  206993. device->jitter = false;
  206994. firstFrameInBuffer = 0;
  206995. lastIndex = 0;
  206996. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  206997. readBuffer.wantsIndex = true;
  206998. int i;
  206999. for (i = 5; --i >= 0;)
  207000. {
  207001. readBuffer.startFrame = frameNeeded;
  207002. readBuffer.numFrames = framesPerIndexRead;
  207003. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207004. break;
  207005. }
  207006. if (i >= 0)
  207007. return readBuffer.index;
  207008. return -1;
  207009. }
  207010. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  207011. {
  207012. Array <int> indexes;
  207013. const int trackStart = getPositionOfTrackStart (trackNumber);
  207014. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  207015. bool needToScan = true;
  207016. if (trackEnd - trackStart > 20 * 44100)
  207017. {
  207018. // check the end of the track for indexes before scanning the whole thing
  207019. needToScan = false;
  207020. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  207021. bool seenAnIndex = false;
  207022. while (pos <= trackEnd - samplesPerFrame)
  207023. {
  207024. const int index = getIndexAt (pos);
  207025. if (index == 0)
  207026. {
  207027. // lead-out, so skip back a bit if we've not found any indexes yet..
  207028. if (seenAnIndex)
  207029. break;
  207030. pos -= 44100 * 5;
  207031. if (pos < trackStart)
  207032. break;
  207033. }
  207034. else
  207035. {
  207036. if (index > 0)
  207037. seenAnIndex = true;
  207038. if (index > 1)
  207039. {
  207040. needToScan = true;
  207041. break;
  207042. }
  207043. pos += samplesPerFrame * framesPerIndexRead;
  207044. }
  207045. }
  207046. }
  207047. if (needToScan)
  207048. {
  207049. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  207050. int pos = trackStart;
  207051. int last = -1;
  207052. while (pos < trackEnd - samplesPerFrame * 10)
  207053. {
  207054. const int frameNeeded = pos / samplesPerFrame;
  207055. device->overlapBuffer->dataLength = 0;
  207056. device->overlapBuffer->startFrame = 0;
  207057. device->overlapBuffer->numFrames = 0;
  207058. device->jitter = false;
  207059. firstFrameInBuffer = 0;
  207060. CDReadBuffer readBuffer (4);
  207061. readBuffer.wantsIndex = true;
  207062. int i;
  207063. for (i = 5; --i >= 0;)
  207064. {
  207065. readBuffer.startFrame = frameNeeded;
  207066. readBuffer.numFrames = framesPerIndexRead;
  207067. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  207068. break;
  207069. }
  207070. if (i < 0)
  207071. break;
  207072. if (readBuffer.index > last && readBuffer.index > 1)
  207073. {
  207074. last = readBuffer.index;
  207075. indexes.add (pos);
  207076. }
  207077. pos += samplesPerFrame * framesPerIndexRead;
  207078. }
  207079. indexes.removeValue (trackStart);
  207080. }
  207081. return indexes;
  207082. }
  207083. int AudioCDReader::getCDDBId()
  207084. {
  207085. refreshTrackLengths();
  207086. if (numTracks > 0)
  207087. {
  207088. TOC toc;
  207089. zerostruct (toc);
  207090. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  207091. {
  207092. int n = 0;
  207093. for (int i = numTracks; --i >= 0;)
  207094. {
  207095. int j = getMSFAddressOf (&toc.tracks[i]);
  207096. while (j > 0)
  207097. {
  207098. n += (j % 10);
  207099. j /= 10;
  207100. }
  207101. }
  207102. if (n != 0)
  207103. {
  207104. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  207105. - getMSFAddressOf (&toc.tracks[0]);
  207106. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  207107. }
  207108. }
  207109. }
  207110. return 0;
  207111. }
  207112. void AudioCDReader::ejectDisk()
  207113. {
  207114. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  207115. }
  207116. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  207117. {
  207118. CoInitialize (0);
  207119. IDiscMaster* dm;
  207120. IDiscRecorder* result = 0;
  207121. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  207122. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  207123. IID_IDiscMaster,
  207124. (void**) &dm)))
  207125. {
  207126. if (SUCCEEDED (dm->Open()))
  207127. {
  207128. IEnumDiscRecorders* drEnum = 0;
  207129. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  207130. {
  207131. IDiscRecorder* dr = 0;
  207132. DWORD dummy;
  207133. int index = 0;
  207134. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  207135. {
  207136. if (indexToOpen == index)
  207137. {
  207138. result = dr;
  207139. break;
  207140. }
  207141. else if (list != 0)
  207142. {
  207143. BSTR path;
  207144. if (SUCCEEDED (dr->GetPath (&path)))
  207145. list->add ((const WCHAR*) path);
  207146. }
  207147. ++index;
  207148. dr->Release();
  207149. }
  207150. drEnum->Release();
  207151. }
  207152. /*if (redbookFormat != 0)
  207153. {
  207154. IEnumDiscMasterFormats* mfEnum;
  207155. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  207156. {
  207157. IID formatIID;
  207158. DWORD dummy;
  207159. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  207160. {
  207161. }
  207162. mfEnum->Release();
  207163. }
  207164. redbookFormat
  207165. }*/
  207166. if (master == 0)
  207167. dm->Close();
  207168. }
  207169. if (master != 0)
  207170. *master = dm;
  207171. else
  207172. dm->Release();
  207173. }
  207174. return result;
  207175. }
  207176. const StringArray AudioCDBurner::findAvailableDevices()
  207177. {
  207178. StringArray devs;
  207179. enumCDBurners (&devs, -1, 0);
  207180. return devs;
  207181. }
  207182. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  207183. {
  207184. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  207185. if (b->internal == 0)
  207186. deleteAndZero (b);
  207187. return b;
  207188. }
  207189. class CDBurnerInfo : public IDiscMasterProgressEvents
  207190. {
  207191. public:
  207192. CDBurnerInfo()
  207193. : refCount (1),
  207194. progress (0),
  207195. shouldCancel (false),
  207196. listener (0)
  207197. {
  207198. }
  207199. ~CDBurnerInfo()
  207200. {
  207201. }
  207202. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207203. {
  207204. if (result == 0)
  207205. return E_POINTER;
  207206. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  207207. {
  207208. AddRef();
  207209. *result = this;
  207210. return S_OK;
  207211. }
  207212. *result = 0;
  207213. return E_NOINTERFACE;
  207214. }
  207215. ULONG __stdcall AddRef() { return ++refCount; }
  207216. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207217. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  207218. {
  207219. if (listener != 0 && ! shouldCancel)
  207220. shouldCancel = listener->audioCDBurnProgress (progress);
  207221. *pbCancel = shouldCancel;
  207222. return S_OK;
  207223. }
  207224. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  207225. {
  207226. progress = nCompleted / (float) nTotal;
  207227. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  207228. return E_NOTIMPL;
  207229. }
  207230. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  207231. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  207232. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  207233. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207234. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  207235. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207236. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  207237. IDiscMaster* discMaster;
  207238. IDiscRecorder* discRecorder;
  207239. IRedbookDiscMaster* redbook;
  207240. AudioCDBurner::BurnProgressListener* listener;
  207241. float progress;
  207242. bool shouldCancel;
  207243. private:
  207244. int refCount;
  207245. };
  207246. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  207247. : internal (0)
  207248. {
  207249. IDiscMaster* discMaster;
  207250. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  207251. if (dr != 0)
  207252. {
  207253. IRedbookDiscMaster* redbook;
  207254. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  207255. hr = discMaster->SetActiveDiscRecorder (dr);
  207256. CDBurnerInfo* const info = new CDBurnerInfo();
  207257. internal = info;
  207258. info->discMaster = discMaster;
  207259. info->discRecorder = dr;
  207260. info->redbook = redbook;
  207261. }
  207262. }
  207263. AudioCDBurner::~AudioCDBurner()
  207264. {
  207265. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207266. if (info != 0)
  207267. {
  207268. info->discRecorder->Close();
  207269. info->redbook->Release();
  207270. info->discRecorder->Release();
  207271. info->discMaster->Release();
  207272. info->Release();
  207273. }
  207274. }
  207275. bool AudioCDBurner::isDiskPresent() const
  207276. {
  207277. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207278. HRESULT hr = info->discRecorder->OpenExclusive();
  207279. long type, flags;
  207280. hr = info->discRecorder->QueryMediaType (&type, &flags);
  207281. info->discRecorder->Close();
  207282. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  207283. }
  207284. int AudioCDBurner::getNumAvailableAudioBlocks() const
  207285. {
  207286. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207287. long blocksFree = 0;
  207288. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  207289. return blocksFree;
  207290. }
  207291. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  207292. const bool ejectDiscAfterwards,
  207293. const bool performFakeBurnForTesting)
  207294. {
  207295. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207296. info->listener = listener;
  207297. info->progress = 0;
  207298. info->shouldCancel = false;
  207299. UINT_PTR cookie;
  207300. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  207301. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  207302. ejectDiscAfterwards);
  207303. String error;
  207304. if (hr != S_OK)
  207305. {
  207306. const char* e = "Couldn't open or write to the CD device";
  207307. if (hr == IMAPI_E_USERABORT)
  207308. e = "User cancelled the write operation";
  207309. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  207310. e = "No Disk present";
  207311. error = e;
  207312. }
  207313. info->discMaster->ProgressUnadvise (cookie);
  207314. info->listener = 0;
  207315. return error;
  207316. }
  207317. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  207318. {
  207319. if (source == 0)
  207320. return false;
  207321. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  207322. long bytesPerBlock;
  207323. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  207324. const int samplesPerBlock = bytesPerBlock / 4;
  207325. bool ok = true;
  207326. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  207327. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  207328. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  207329. int samplesDone = 0;
  207330. source->prepareToPlay (samplesPerBlock, 44100.0);
  207331. while (ok)
  207332. {
  207333. {
  207334. AudioSourceChannelInfo info;
  207335. info.buffer = &sourceBuffer;
  207336. info.numSamples = samplesPerBlock;
  207337. info.startSample = 0;
  207338. sourceBuffer.clear();
  207339. source->getNextAudioBlock (info);
  207340. }
  207341. zeromem (buffer, bytesPerBlock);
  207342. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  207343. buffer, samplesPerBlock, 4);
  207344. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  207345. buffer + 2, samplesPerBlock, 4);
  207346. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  207347. if (hr != S_OK)
  207348. ok = false;
  207349. samplesDone += samplesPerBlock;
  207350. if (samplesDone >= numSamples)
  207351. break;
  207352. }
  207353. juce_free (buffer);
  207354. hr = info->redbook->CloseAudioTrack();
  207355. delete source;
  207356. return ok && hr == S_OK;
  207357. }
  207358. #endif
  207359. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  207360. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  207361. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207362. // compiled on its own).
  207363. #if JUCE_INCLUDED_FILE
  207364. static const int midiBufferSize = 1024 * 10;
  207365. static const int numInHeaders = 32;
  207366. static const int inBufferSize = 256;
  207367. static Array <void*, CriticalSection> activeMidiThreads;
  207368. using ::free;
  207369. class MidiInThread : public Thread
  207370. {
  207371. public:
  207372. MidiInThread (MidiInput* const input_,
  207373. MidiInputCallback* const callback_)
  207374. : Thread ("Juce Midi"),
  207375. hIn (0),
  207376. input (input_),
  207377. callback (callback_),
  207378. isStarted (false),
  207379. startTime (0),
  207380. pendingLength(0)
  207381. {
  207382. for (int i = numInHeaders; --i >= 0;)
  207383. {
  207384. zeromem (&hdr[i], sizeof (MIDIHDR));
  207385. hdr[i].lpData = inData[i];
  207386. hdr[i].dwBufferLength = inBufferSize;
  207387. }
  207388. };
  207389. ~MidiInThread()
  207390. {
  207391. stop();
  207392. if (hIn != 0)
  207393. {
  207394. int count = 5;
  207395. while (--count >= 0)
  207396. {
  207397. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  207398. break;
  207399. Sleep (20);
  207400. }
  207401. }
  207402. }
  207403. void handle (const uint32 message, const uint32 timeStamp) throw()
  207404. {
  207405. const int byte = message & 0xff;
  207406. if (byte < 0x80)
  207407. return;
  207408. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  207409. const double time = timeStampToTime (timeStamp);
  207410. lock.enter();
  207411. if (pendingLength < midiBufferSize - 12)
  207412. {
  207413. char* const p = pending + pendingLength;
  207414. *(double*) p = time;
  207415. *(uint32*) (p + 8) = numBytes;
  207416. *(uint32*) (p + 12) = message;
  207417. pendingLength += 12 + numBytes;
  207418. }
  207419. else
  207420. {
  207421. jassertfalse // midi buffer overflow! You might need to increase the size..
  207422. }
  207423. lock.exit();
  207424. notify();
  207425. }
  207426. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  207427. {
  207428. const int num = hdr->dwBytesRecorded;
  207429. if (num > 0)
  207430. {
  207431. const double time = timeStampToTime (timeStamp);
  207432. lock.enter();
  207433. if (pendingLength < midiBufferSize - (8 + num))
  207434. {
  207435. char* const p = pending + pendingLength;
  207436. *(double*) p = time;
  207437. *(uint32*) (p + 8) = num;
  207438. memcpy (p + 12, hdr->lpData, num);
  207439. pendingLength += 12 + num;
  207440. }
  207441. else
  207442. {
  207443. jassertfalse // midi buffer overflow! You might need to increase the size..
  207444. }
  207445. lock.exit();
  207446. notify();
  207447. }
  207448. }
  207449. void writeBlock (const int i) throw()
  207450. {
  207451. hdr[i].dwBytesRecorded = 0;
  207452. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207453. jassert (res == MMSYSERR_NOERROR);
  207454. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  207455. jassert (res == MMSYSERR_NOERROR);
  207456. }
  207457. void run()
  207458. {
  207459. MemoryBlock pendingCopy (64);
  207460. while (! threadShouldExit())
  207461. {
  207462. for (int i = 0; i < numInHeaders; ++i)
  207463. {
  207464. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207465. {
  207466. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  207467. (void) res;
  207468. jassert (res == MMSYSERR_NOERROR);
  207469. writeBlock (i);
  207470. }
  207471. }
  207472. lock.enter();
  207473. int len = pendingLength;
  207474. if (len > 0)
  207475. {
  207476. pendingCopy.ensureSize (len);
  207477. pendingCopy.copyFrom (pending, 0, len);
  207478. pendingLength = 0;
  207479. }
  207480. lock.exit();
  207481. //xxx needs to figure out if blocks are broken up or not
  207482. if (len == 0)
  207483. {
  207484. wait (500);
  207485. }
  207486. else
  207487. {
  207488. const char* p = (const char*) pendingCopy.getData();
  207489. while (len > 0)
  207490. {
  207491. const double time = *(const double*) p;
  207492. const int messageLen = *(const int*) (p + 8);
  207493. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  207494. callback->handleIncomingMidiMessage (input, message);
  207495. p += 12 + messageLen;
  207496. len -= 12 + messageLen;
  207497. }
  207498. }
  207499. }
  207500. }
  207501. void start() throw()
  207502. {
  207503. jassert (hIn != 0);
  207504. if (hIn != 0 && ! isStarted)
  207505. {
  207506. stop();
  207507. activeMidiThreads.addIfNotAlreadyThere (this);
  207508. int i;
  207509. for (i = 0; i < numInHeaders; ++i)
  207510. writeBlock (i);
  207511. startTime = Time::getMillisecondCounter();
  207512. MMRESULT res = midiInStart (hIn);
  207513. jassert (res == MMSYSERR_NOERROR);
  207514. if (res == MMSYSERR_NOERROR)
  207515. {
  207516. isStarted = true;
  207517. pendingLength = 0;
  207518. startThread (6);
  207519. }
  207520. }
  207521. }
  207522. void stop() throw()
  207523. {
  207524. if (isStarted)
  207525. {
  207526. stopThread (5000);
  207527. midiInReset (hIn);
  207528. midiInStop (hIn);
  207529. activeMidiThreads.removeValue (this);
  207530. lock.enter();
  207531. lock.exit();
  207532. for (int i = numInHeaders; --i >= 0;)
  207533. {
  207534. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  207535. {
  207536. int c = 10;
  207537. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  207538. Sleep (20);
  207539. jassert (c >= 0);
  207540. }
  207541. }
  207542. isStarted = false;
  207543. pendingLength = 0;
  207544. }
  207545. }
  207546. juce_UseDebuggingNewOperator
  207547. HMIDIIN hIn;
  207548. private:
  207549. MidiInput* input;
  207550. MidiInputCallback* callback;
  207551. bool isStarted;
  207552. uint32 startTime;
  207553. CriticalSection lock;
  207554. MIDIHDR hdr [numInHeaders];
  207555. char inData [numInHeaders] [inBufferSize];
  207556. int pendingLength;
  207557. char pending [midiBufferSize];
  207558. double timeStampToTime (uint32 timeStamp) throw()
  207559. {
  207560. timeStamp += startTime;
  207561. const uint32 now = Time::getMillisecondCounter();
  207562. if (timeStamp > now)
  207563. {
  207564. if (timeStamp > now + 2)
  207565. --startTime;
  207566. timeStamp = now;
  207567. }
  207568. return 0.001 * timeStamp;
  207569. }
  207570. MidiInThread (const MidiInThread&);
  207571. const MidiInThread& operator= (const MidiInThread&);
  207572. };
  207573. static void CALLBACK midiInCallback (HMIDIIN,
  207574. UINT uMsg,
  207575. DWORD_PTR dwInstance,
  207576. DWORD_PTR midiMessage,
  207577. DWORD_PTR timeStamp)
  207578. {
  207579. MidiInThread* const thread = (MidiInThread*) dwInstance;
  207580. if (thread != 0 && activeMidiThreads.contains (thread))
  207581. {
  207582. if (uMsg == MIM_DATA)
  207583. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  207584. else if (uMsg == MIM_LONGDATA)
  207585. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  207586. }
  207587. }
  207588. const StringArray MidiInput::getDevices()
  207589. {
  207590. StringArray s;
  207591. const int num = midiInGetNumDevs();
  207592. for (int i = 0; i < num; ++i)
  207593. {
  207594. MIDIINCAPS mc;
  207595. zerostruct (mc);
  207596. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207597. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207598. }
  207599. return s;
  207600. }
  207601. int MidiInput::getDefaultDeviceIndex()
  207602. {
  207603. return 0;
  207604. }
  207605. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  207606. {
  207607. if (callback == 0)
  207608. return 0;
  207609. UINT deviceId = MIDI_MAPPER;
  207610. int n = 0;
  207611. String name;
  207612. const int num = midiInGetNumDevs();
  207613. for (int i = 0; i < num; ++i)
  207614. {
  207615. MIDIINCAPS mc;
  207616. zerostruct (mc);
  207617. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207618. {
  207619. if (index == n)
  207620. {
  207621. deviceId = i;
  207622. name = String (mc.szPname, sizeof (mc.szPname));
  207623. break;
  207624. }
  207625. ++n;
  207626. }
  207627. }
  207628. MidiInput* const in = new MidiInput (name);
  207629. MidiInThread* const thread = new MidiInThread (in, callback);
  207630. HMIDIIN h;
  207631. HRESULT err = midiInOpen (&h, deviceId,
  207632. (DWORD_PTR) &midiInCallback,
  207633. (DWORD_PTR) thread,
  207634. CALLBACK_FUNCTION);
  207635. if (err == MMSYSERR_NOERROR)
  207636. {
  207637. thread->hIn = h;
  207638. in->internal = (void*) thread;
  207639. return in;
  207640. }
  207641. else
  207642. {
  207643. delete in;
  207644. delete thread;
  207645. return 0;
  207646. }
  207647. }
  207648. MidiInput::MidiInput (const String& name_)
  207649. : name (name_),
  207650. internal (0)
  207651. {
  207652. }
  207653. MidiInput::~MidiInput()
  207654. {
  207655. if (internal != 0)
  207656. {
  207657. MidiInThread* const thread = (MidiInThread*) internal;
  207658. delete thread;
  207659. }
  207660. }
  207661. void MidiInput::start()
  207662. {
  207663. ((MidiInThread*) internal)->start();
  207664. }
  207665. void MidiInput::stop()
  207666. {
  207667. ((MidiInThread*) internal)->stop();
  207668. }
  207669. struct MidiOutHandle
  207670. {
  207671. int refCount;
  207672. UINT deviceId;
  207673. HMIDIOUT handle;
  207674. juce_UseDebuggingNewOperator
  207675. };
  207676. static VoidArray handles (4);
  207677. const StringArray MidiOutput::getDevices()
  207678. {
  207679. StringArray s;
  207680. const int num = midiOutGetNumDevs();
  207681. for (int i = 0; i < num; ++i)
  207682. {
  207683. MIDIOUTCAPS mc;
  207684. zerostruct (mc);
  207685. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207686. s.add (String (mc.szPname, sizeof (mc.szPname)));
  207687. }
  207688. return s;
  207689. }
  207690. int MidiOutput::getDefaultDeviceIndex()
  207691. {
  207692. const int num = midiOutGetNumDevs();
  207693. int n = 0;
  207694. for (int i = 0; i < num; ++i)
  207695. {
  207696. MIDIOUTCAPS mc;
  207697. zerostruct (mc);
  207698. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207699. {
  207700. if ((mc.wTechnology & MOD_MAPPER) != 0)
  207701. return n;
  207702. ++n;
  207703. }
  207704. }
  207705. return 0;
  207706. }
  207707. MidiOutput* MidiOutput::openDevice (int index)
  207708. {
  207709. UINT deviceId = MIDI_MAPPER;
  207710. const int num = midiOutGetNumDevs();
  207711. int i, n = 0;
  207712. for (i = 0; i < num; ++i)
  207713. {
  207714. MIDIOUTCAPS mc;
  207715. zerostruct (mc);
  207716. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  207717. {
  207718. // use the microsoft sw synth as a default - best not to allow deviceId
  207719. // to be MIDI_MAPPER, or else device sharing breaks
  207720. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  207721. deviceId = i;
  207722. if (index == n)
  207723. {
  207724. deviceId = i;
  207725. break;
  207726. }
  207727. ++n;
  207728. }
  207729. }
  207730. for (i = handles.size(); --i >= 0;)
  207731. {
  207732. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  207733. if (han != 0 && han->deviceId == deviceId)
  207734. {
  207735. han->refCount++;
  207736. MidiOutput* const out = new MidiOutput();
  207737. out->internal = (void*) han;
  207738. return out;
  207739. }
  207740. }
  207741. for (i = 4; --i >= 0;)
  207742. {
  207743. HMIDIOUT h = 0;
  207744. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  207745. if (res == MMSYSERR_NOERROR)
  207746. {
  207747. MidiOutHandle* const han = new MidiOutHandle();
  207748. han->deviceId = deviceId;
  207749. han->refCount = 1;
  207750. han->handle = h;
  207751. handles.add (han);
  207752. MidiOutput* const out = new MidiOutput();
  207753. out->internal = (void*) han;
  207754. return out;
  207755. }
  207756. else if (res == MMSYSERR_ALLOCATED)
  207757. {
  207758. Sleep (100);
  207759. }
  207760. else
  207761. {
  207762. break;
  207763. }
  207764. }
  207765. return 0;
  207766. }
  207767. MidiOutput::~MidiOutput()
  207768. {
  207769. MidiOutHandle* const h = (MidiOutHandle*) internal;
  207770. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  207771. {
  207772. midiOutClose (h->handle);
  207773. handles.removeValue ((void*) h);
  207774. delete h;
  207775. }
  207776. }
  207777. void MidiOutput::reset()
  207778. {
  207779. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  207780. midiOutReset (h->handle);
  207781. }
  207782. bool MidiOutput::getVolume (float& leftVol,
  207783. float& rightVol)
  207784. {
  207785. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207786. DWORD n;
  207787. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  207788. {
  207789. const unsigned short* const nn = (const unsigned short*) &n;
  207790. rightVol = nn[0] / (float) 0xffff;
  207791. leftVol = nn[1] / (float) 0xffff;
  207792. return true;
  207793. }
  207794. else
  207795. {
  207796. rightVol = leftVol = 1.0f;
  207797. return false;
  207798. }
  207799. }
  207800. void MidiOutput::setVolume (float leftVol,
  207801. float rightVol)
  207802. {
  207803. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  207804. DWORD n;
  207805. unsigned short* const nn = (unsigned short*) &n;
  207806. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  207807. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  207808. midiOutSetVolume (handle->handle, n);
  207809. }
  207810. void MidiOutput::sendMessageNow (const MidiMessage& message)
  207811. {
  207812. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  207813. if (message.getRawDataSize() > 3
  207814. || message.isSysEx())
  207815. {
  207816. MIDIHDR h;
  207817. zerostruct (h);
  207818. h.lpData = (char*) message.getRawData();
  207819. h.dwBufferLength = message.getRawDataSize();
  207820. h.dwBytesRecorded = message.getRawDataSize();
  207821. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  207822. {
  207823. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  207824. if (res == MMSYSERR_NOERROR)
  207825. {
  207826. while ((h.dwFlags & MHDR_DONE) == 0)
  207827. Sleep (1);
  207828. int count = 500; // 1 sec timeout
  207829. while (--count >= 0)
  207830. {
  207831. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  207832. if (res == MIDIERR_STILLPLAYING)
  207833. Sleep (2);
  207834. else
  207835. break;
  207836. }
  207837. }
  207838. }
  207839. }
  207840. else
  207841. {
  207842. midiOutShortMsg (handle->handle,
  207843. *(unsigned int*) message.getRawData());
  207844. }
  207845. }
  207846. #endif
  207847. /********* End of inlined file: juce_win32_Midi.cpp *********/
  207848. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  207849. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  207850. // compiled on its own).
  207851. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  207852. #undef WINDOWS
  207853. // #define ASIO_DEBUGGING
  207854. #ifdef ASIO_DEBUGGING
  207855. #define log(a) { Logger::writeToLog (a); DBG (a) }
  207856. #else
  207857. #define log(a) {}
  207858. #endif
  207859. #ifdef ASIO_DEBUGGING
  207860. static void logError (const String& context, long error)
  207861. {
  207862. String err ("unknown error");
  207863. if (error == ASE_NotPresent)
  207864. err = "Not Present";
  207865. else if (error == ASE_HWMalfunction)
  207866. err = "Hardware Malfunction";
  207867. else if (error == ASE_InvalidParameter)
  207868. err = "Invalid Parameter";
  207869. else if (error == ASE_InvalidMode)
  207870. err = "Invalid Mode";
  207871. else if (error == ASE_SPNotAdvancing)
  207872. err = "Sample position not advancing";
  207873. else if (error == ASE_NoClock)
  207874. err = "No Clock";
  207875. else if (error == ASE_NoMemory)
  207876. err = "Out of memory";
  207877. log (T("!!error: ") + context + T(" - ") + err);
  207878. }
  207879. #else
  207880. #define logError(a, b) {}
  207881. #endif
  207882. class ASIOAudioIODevice;
  207883. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  207884. static const int maxASIOChannels = 160;
  207885. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  207886. private Timer
  207887. {
  207888. public:
  207889. Component ourWindow;
  207890. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  207891. const String& optionalDllForDirectLoading_)
  207892. : AudioIODevice (name_, T("ASIO")),
  207893. asioObject (0),
  207894. classId (classId_),
  207895. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  207896. currentBitDepth (16),
  207897. currentSampleRate (0),
  207898. tempBuffer (0),
  207899. isOpen_ (false),
  207900. isStarted (false),
  207901. postOutput (true),
  207902. insideControlPanelModalLoop (false),
  207903. shouldUsePreferredSize (false)
  207904. {
  207905. name = name_;
  207906. ourWindow.addToDesktop (0);
  207907. windowHandle = ourWindow.getWindowHandle();
  207908. jassert (currentASIODev [slotNumber] == 0);
  207909. currentASIODev [slotNumber] = this;
  207910. openDevice();
  207911. }
  207912. ~ASIOAudioIODevice()
  207913. {
  207914. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  207915. if (currentASIODev[i] == this)
  207916. currentASIODev[i] = 0;
  207917. close();
  207918. log ("ASIO - exiting");
  207919. removeCurrentDriver();
  207920. juce_free (tempBuffer);
  207921. }
  207922. void updateSampleRates()
  207923. {
  207924. // find a list of sample rates..
  207925. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  207926. sampleRates.clear();
  207927. if (asioObject != 0)
  207928. {
  207929. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  207930. {
  207931. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  207932. if (err == 0)
  207933. {
  207934. sampleRates.add ((int) possibleSampleRates[index]);
  207935. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  207936. }
  207937. else if (err != ASE_NoClock)
  207938. {
  207939. logError (T("CanSampleRate"), err);
  207940. }
  207941. }
  207942. if (sampleRates.size() == 0)
  207943. {
  207944. double cr = 0;
  207945. const long err = asioObject->getSampleRate (&cr);
  207946. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  207947. if (err == 0)
  207948. sampleRates.add ((int) cr);
  207949. }
  207950. }
  207951. }
  207952. const StringArray getOutputChannelNames()
  207953. {
  207954. return outputChannelNames;
  207955. }
  207956. const StringArray getInputChannelNames()
  207957. {
  207958. return inputChannelNames;
  207959. }
  207960. int getNumSampleRates()
  207961. {
  207962. return sampleRates.size();
  207963. }
  207964. double getSampleRate (int index)
  207965. {
  207966. return sampleRates [index];
  207967. }
  207968. int getNumBufferSizesAvailable()
  207969. {
  207970. return bufferSizes.size();
  207971. }
  207972. int getBufferSizeSamples (int index)
  207973. {
  207974. return bufferSizes [index];
  207975. }
  207976. int getDefaultBufferSize()
  207977. {
  207978. return preferredSize;
  207979. }
  207980. const String open (const BitArray& inputChannels,
  207981. const BitArray& outputChannels,
  207982. double sr,
  207983. int bufferSizeSamples)
  207984. {
  207985. close();
  207986. currentCallback = 0;
  207987. if (bufferSizeSamples <= 0)
  207988. shouldUsePreferredSize = true;
  207989. if (asioObject == 0 || ! isASIOOpen)
  207990. {
  207991. log ("Warning: device not open");
  207992. const String err (openDevice());
  207993. if (asioObject == 0 || ! isASIOOpen)
  207994. return err;
  207995. }
  207996. isStarted = false;
  207997. bufferIndex = -1;
  207998. long err = 0;
  207999. long newPreferredSize = 0;
  208000. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  208001. minSize = 0;
  208002. maxSize = 0;
  208003. newPreferredSize = 0;
  208004. granularity = 0;
  208005. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  208006. {
  208007. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  208008. shouldUsePreferredSize = true;
  208009. preferredSize = newPreferredSize;
  208010. }
  208011. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  208012. // dynamic changes to the buffer size...
  208013. shouldUsePreferredSize = shouldUsePreferredSize
  208014. || getName().containsIgnoreCase (T("Digidesign"));
  208015. if (shouldUsePreferredSize)
  208016. {
  208017. log ("Using preferred size for buffer..");
  208018. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208019. {
  208020. bufferSizeSamples = preferredSize;
  208021. }
  208022. else
  208023. {
  208024. bufferSizeSamples = 1024;
  208025. logError ("GetBufferSize1", err);
  208026. }
  208027. shouldUsePreferredSize = false;
  208028. }
  208029. int sampleRate = roundDoubleToInt (sr);
  208030. currentSampleRate = sampleRate;
  208031. currentBlockSizeSamples = bufferSizeSamples;
  208032. currentChansOut.clear();
  208033. currentChansIn.clear();
  208034. zeromem (inBuffers, sizeof (inBuffers));
  208035. zeromem (outBuffers, sizeof (outBuffers));
  208036. updateSampleRates();
  208037. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  208038. sampleRate = sampleRates[0];
  208039. jassert (sampleRate != 0);
  208040. if (sampleRate == 0)
  208041. sampleRate = 44100;
  208042. long numSources = 32;
  208043. ASIOClockSource clocks[32];
  208044. zeromem (clocks, sizeof (clocks));
  208045. asioObject->getClockSources (clocks, &numSources);
  208046. bool isSourceSet = false;
  208047. // careful not to remove this loop because it does more than just logging!
  208048. int i;
  208049. for (i = 0; i < numSources; ++i)
  208050. {
  208051. String s ("clock: ");
  208052. s += clocks[i].name;
  208053. if (clocks[i].isCurrentSource)
  208054. {
  208055. isSourceSet = true;
  208056. s << " (cur)";
  208057. }
  208058. log (s);
  208059. }
  208060. if (numSources > 1 && ! isSourceSet)
  208061. {
  208062. log ("setting clock source");
  208063. asioObject->setClockSource (clocks[0].index);
  208064. Thread::sleep (20);
  208065. }
  208066. else
  208067. {
  208068. if (numSources == 0)
  208069. {
  208070. log ("ASIO - no clock sources!");
  208071. }
  208072. }
  208073. double cr = 0;
  208074. err = asioObject->getSampleRate (&cr);
  208075. if (err == 0)
  208076. {
  208077. currentSampleRate = cr;
  208078. }
  208079. else
  208080. {
  208081. logError ("GetSampleRate", err);
  208082. currentSampleRate = 0;
  208083. }
  208084. error = String::empty;
  208085. needToReset = false;
  208086. isReSync = false;
  208087. err = 0;
  208088. bool buffersCreated = false;
  208089. if (currentSampleRate != sampleRate)
  208090. {
  208091. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  208092. err = asioObject->setSampleRate (sampleRate);
  208093. if (err == ASE_NoClock && numSources > 0)
  208094. {
  208095. log ("trying to set a clock source..");
  208096. Thread::sleep (10);
  208097. err = asioObject->setClockSource (clocks[0].index);
  208098. if (err != 0)
  208099. {
  208100. logError ("SetClock", err);
  208101. }
  208102. Thread::sleep (10);
  208103. err = asioObject->setSampleRate (sampleRate);
  208104. }
  208105. }
  208106. if (err == 0)
  208107. {
  208108. currentSampleRate = sampleRate;
  208109. if (needToReset)
  208110. {
  208111. if (isReSync)
  208112. {
  208113. log ("Resync request");
  208114. }
  208115. log ("! Resetting ASIO after sample rate change");
  208116. removeCurrentDriver();
  208117. loadDriver();
  208118. const String error (initDriver());
  208119. if (error.isNotEmpty())
  208120. {
  208121. log (T("ASIOInit: ") + error);
  208122. }
  208123. needToReset = false;
  208124. isReSync = false;
  208125. }
  208126. numActiveInputChans = 0;
  208127. numActiveOutputChans = 0;
  208128. ASIOBufferInfo* info = bufferInfos;
  208129. int i;
  208130. for (i = 0; i < totalNumInputChans; ++i)
  208131. {
  208132. if (inputChannels[i])
  208133. {
  208134. currentChansIn.setBit (i);
  208135. info->isInput = 1;
  208136. info->channelNum = i;
  208137. info->buffers[0] = info->buffers[1] = 0;
  208138. ++info;
  208139. ++numActiveInputChans;
  208140. }
  208141. }
  208142. for (i = 0; i < totalNumOutputChans; ++i)
  208143. {
  208144. if (outputChannels[i])
  208145. {
  208146. currentChansOut.setBit (i);
  208147. info->isInput = 0;
  208148. info->channelNum = i;
  208149. info->buffers[0] = info->buffers[1] = 0;
  208150. ++info;
  208151. ++numActiveOutputChans;
  208152. }
  208153. }
  208154. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  208155. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208156. if (currentASIODev[0] == this)
  208157. {
  208158. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208159. callbacks.asioMessage = &asioMessagesCallback0;
  208160. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208161. }
  208162. else if (currentASIODev[1] == this)
  208163. {
  208164. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208165. callbacks.asioMessage = &asioMessagesCallback1;
  208166. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208167. }
  208168. else if (currentASIODev[2] == this)
  208169. {
  208170. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208171. callbacks.asioMessage = &asioMessagesCallback2;
  208172. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208173. }
  208174. else
  208175. {
  208176. jassertfalse
  208177. }
  208178. log ("disposing buffers");
  208179. err = asioObject->disposeBuffers();
  208180. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  208181. err = asioObject->createBuffers (bufferInfos,
  208182. totalBuffers,
  208183. currentBlockSizeSamples,
  208184. &callbacks);
  208185. if (err != 0)
  208186. {
  208187. currentBlockSizeSamples = preferredSize;
  208188. logError ("create buffers 2", err);
  208189. asioObject->disposeBuffers();
  208190. err = asioObject->createBuffers (bufferInfos,
  208191. totalBuffers,
  208192. currentBlockSizeSamples,
  208193. &callbacks);
  208194. }
  208195. if (err == 0)
  208196. {
  208197. buffersCreated = true;
  208198. juce_free (tempBuffer);
  208199. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  208200. int n = 0;
  208201. Array <int> types;
  208202. currentBitDepth = 16;
  208203. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  208204. {
  208205. if (inputChannels[i])
  208206. {
  208207. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  208208. ASIOChannelInfo channelInfo;
  208209. zerostruct (channelInfo);
  208210. channelInfo.channel = i;
  208211. channelInfo.isInput = 1;
  208212. asioObject->getChannelInfo (&channelInfo);
  208213. types.addIfNotAlreadyThere (channelInfo.type);
  208214. typeToFormatParameters (channelInfo.type,
  208215. inputChannelBitDepths[n],
  208216. inputChannelBytesPerSample[n],
  208217. inputChannelIsFloat[n],
  208218. inputChannelLittleEndian[n]);
  208219. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  208220. ++n;
  208221. }
  208222. }
  208223. jassert (numActiveInputChans == n);
  208224. n = 0;
  208225. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  208226. {
  208227. if (outputChannels[i])
  208228. {
  208229. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  208230. ASIOChannelInfo channelInfo;
  208231. zerostruct (channelInfo);
  208232. channelInfo.channel = i;
  208233. channelInfo.isInput = 0;
  208234. asioObject->getChannelInfo (&channelInfo);
  208235. types.addIfNotAlreadyThere (channelInfo.type);
  208236. typeToFormatParameters (channelInfo.type,
  208237. outputChannelBitDepths[n],
  208238. outputChannelBytesPerSample[n],
  208239. outputChannelIsFloat[n],
  208240. outputChannelLittleEndian[n]);
  208241. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  208242. ++n;
  208243. }
  208244. }
  208245. jassert (numActiveOutputChans == n);
  208246. for (i = types.size(); --i >= 0;)
  208247. {
  208248. log (T("channel format: ") + String (types[i]));
  208249. }
  208250. jassert (n <= totalBuffers);
  208251. for (i = 0; i < numActiveOutputChans; ++i)
  208252. {
  208253. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  208254. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  208255. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  208256. {
  208257. log ("!! Null buffers");
  208258. }
  208259. else
  208260. {
  208261. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  208262. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  208263. }
  208264. }
  208265. inputLatency = outputLatency = 0;
  208266. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208267. {
  208268. log ("ASIO - no latencies");
  208269. }
  208270. else
  208271. {
  208272. log (T("ASIO latencies: ")
  208273. + String ((int) outputLatency)
  208274. + T(", ")
  208275. + String ((int) inputLatency));
  208276. }
  208277. isOpen_ = true;
  208278. log ("starting ASIO");
  208279. calledback = false;
  208280. err = asioObject->start();
  208281. if (err != 0)
  208282. {
  208283. isOpen_ = false;
  208284. log ("ASIO - stop on failure");
  208285. Thread::sleep (10);
  208286. asioObject->stop();
  208287. error = "Can't start device";
  208288. Thread::sleep (10);
  208289. }
  208290. else
  208291. {
  208292. int count = 300;
  208293. while (--count > 0 && ! calledback)
  208294. Thread::sleep (10);
  208295. isStarted = true;
  208296. if (! calledback)
  208297. {
  208298. error = "Device didn't start correctly";
  208299. log ("ASIO didn't callback - stopping..");
  208300. asioObject->stop();
  208301. }
  208302. }
  208303. }
  208304. else
  208305. {
  208306. error = "Can't create i/o buffers";
  208307. }
  208308. }
  208309. else
  208310. {
  208311. error = "Can't set sample rate: ";
  208312. error << sampleRate;
  208313. }
  208314. if (error.isNotEmpty())
  208315. {
  208316. logError (error, err);
  208317. if (asioObject != 0 && buffersCreated)
  208318. asioObject->disposeBuffers();
  208319. Thread::sleep (20);
  208320. isStarted = false;
  208321. isOpen_ = false;
  208322. close();
  208323. }
  208324. needToReset = false;
  208325. isReSync = false;
  208326. return error;
  208327. }
  208328. void close()
  208329. {
  208330. error = String::empty;
  208331. stopTimer();
  208332. stop();
  208333. if (isASIOOpen && isOpen_)
  208334. {
  208335. const ScopedLock sl (callbackLock);
  208336. isOpen_ = false;
  208337. isStarted = false;
  208338. needToReset = false;
  208339. isReSync = false;
  208340. log ("ASIO - stopping");
  208341. if (asioObject != 0)
  208342. {
  208343. Thread::sleep (20);
  208344. asioObject->stop();
  208345. Thread::sleep (10);
  208346. asioObject->disposeBuffers();
  208347. }
  208348. Thread::sleep (10);
  208349. }
  208350. }
  208351. bool isOpen()
  208352. {
  208353. return isOpen_ || insideControlPanelModalLoop;
  208354. }
  208355. int getCurrentBufferSizeSamples()
  208356. {
  208357. return currentBlockSizeSamples;
  208358. }
  208359. double getCurrentSampleRate()
  208360. {
  208361. return currentSampleRate;
  208362. }
  208363. const BitArray getActiveOutputChannels() const
  208364. {
  208365. return currentChansOut;
  208366. }
  208367. const BitArray getActiveInputChannels() const
  208368. {
  208369. return currentChansIn;
  208370. }
  208371. int getCurrentBitDepth()
  208372. {
  208373. return currentBitDepth;
  208374. }
  208375. int getOutputLatencyInSamples()
  208376. {
  208377. return outputLatency + currentBlockSizeSamples / 4;
  208378. }
  208379. int getInputLatencyInSamples()
  208380. {
  208381. return inputLatency + currentBlockSizeSamples / 4;
  208382. }
  208383. void start (AudioIODeviceCallback* callback)
  208384. {
  208385. if (callback != 0)
  208386. {
  208387. callback->audioDeviceAboutToStart (this);
  208388. const ScopedLock sl (callbackLock);
  208389. currentCallback = callback;
  208390. }
  208391. }
  208392. void stop()
  208393. {
  208394. AudioIODeviceCallback* const lastCallback = currentCallback;
  208395. {
  208396. const ScopedLock sl (callbackLock);
  208397. currentCallback = 0;
  208398. }
  208399. if (lastCallback != 0)
  208400. lastCallback->audioDeviceStopped();
  208401. }
  208402. bool isPlaying()
  208403. {
  208404. return isASIOOpen && (currentCallback != 0);
  208405. }
  208406. const String getLastError()
  208407. {
  208408. return error;
  208409. }
  208410. bool hasControlPanel() const
  208411. {
  208412. return true;
  208413. }
  208414. bool showControlPanel()
  208415. {
  208416. log ("ASIO - showing control panel");
  208417. Component modalWindow (String::empty);
  208418. modalWindow.setOpaque (true);
  208419. modalWindow.addToDesktop (0);
  208420. modalWindow.enterModalState();
  208421. bool done = false;
  208422. JUCE_TRY
  208423. {
  208424. // are there are devices that need to be closed before showing their control panel?
  208425. // close();
  208426. insideControlPanelModalLoop = true;
  208427. const uint32 started = Time::getMillisecondCounter();
  208428. if (asioObject != 0)
  208429. {
  208430. asioObject->controlPanel();
  208431. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  208432. log (T("spent: ") + String (spent));
  208433. if (spent > 300)
  208434. {
  208435. shouldUsePreferredSize = true;
  208436. done = true;
  208437. }
  208438. }
  208439. }
  208440. JUCE_CATCH_ALL
  208441. insideControlPanelModalLoop = false;
  208442. return done;
  208443. }
  208444. void resetRequest() throw()
  208445. {
  208446. needToReset = true;
  208447. }
  208448. void resyncRequest() throw()
  208449. {
  208450. needToReset = true;
  208451. isReSync = true;
  208452. }
  208453. void timerCallback()
  208454. {
  208455. if (! insideControlPanelModalLoop)
  208456. {
  208457. stopTimer();
  208458. // used to cause a reset
  208459. log ("! ASIO restart request!");
  208460. if (isOpen_)
  208461. {
  208462. AudioIODeviceCallback* const oldCallback = currentCallback;
  208463. close();
  208464. open (BitArray (currentChansIn), BitArray (currentChansOut),
  208465. currentSampleRate, currentBlockSizeSamples);
  208466. if (oldCallback != 0)
  208467. start (oldCallback);
  208468. }
  208469. }
  208470. else
  208471. {
  208472. startTimer (100);
  208473. }
  208474. }
  208475. juce_UseDebuggingNewOperator
  208476. private:
  208477. IASIO* volatile asioObject;
  208478. ASIOCallbacks callbacks;
  208479. void* windowHandle;
  208480. CLSID classId;
  208481. const String optionalDllForDirectLoading;
  208482. String error;
  208483. long totalNumInputChans, totalNumOutputChans;
  208484. StringArray inputChannelNames, outputChannelNames;
  208485. Array<int> sampleRates, bufferSizes;
  208486. long inputLatency, outputLatency;
  208487. long minSize, maxSize, preferredSize, granularity;
  208488. int volatile currentBlockSizeSamples;
  208489. int volatile currentBitDepth;
  208490. double volatile currentSampleRate;
  208491. BitArray currentChansOut, currentChansIn;
  208492. AudioIODeviceCallback* volatile currentCallback;
  208493. CriticalSection callbackLock;
  208494. ASIOBufferInfo bufferInfos [maxASIOChannels];
  208495. float* inBuffers [maxASIOChannels];
  208496. float* outBuffers [maxASIOChannels];
  208497. int inputChannelBitDepths [maxASIOChannels];
  208498. int outputChannelBitDepths [maxASIOChannels];
  208499. int inputChannelBytesPerSample [maxASIOChannels];
  208500. int outputChannelBytesPerSample [maxASIOChannels];
  208501. bool inputChannelIsFloat [maxASIOChannels];
  208502. bool outputChannelIsFloat [maxASIOChannels];
  208503. bool inputChannelLittleEndian [maxASIOChannels];
  208504. bool outputChannelLittleEndian [maxASIOChannels];
  208505. WaitableEvent event1;
  208506. float* tempBuffer;
  208507. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  208508. bool isOpen_, isStarted;
  208509. bool volatile isASIOOpen;
  208510. bool volatile calledback;
  208511. bool volatile littleEndian, postOutput, needToReset, isReSync;
  208512. bool volatile insideControlPanelModalLoop;
  208513. bool volatile shouldUsePreferredSize;
  208514. void removeCurrentDriver()
  208515. {
  208516. if (asioObject != 0)
  208517. {
  208518. asioObject->Release();
  208519. asioObject = 0;
  208520. }
  208521. }
  208522. bool loadDriver()
  208523. {
  208524. removeCurrentDriver();
  208525. JUCE_TRY
  208526. {
  208527. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  208528. classId, (void**) &asioObject) == S_OK)
  208529. {
  208530. return true;
  208531. }
  208532. // If a class isn't registered but we have a path for it, we can fallback to
  208533. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  208534. if (optionalDllForDirectLoading.isNotEmpty())
  208535. {
  208536. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  208537. if (h != 0)
  208538. {
  208539. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  208540. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  208541. if (dllGetClassObject != 0)
  208542. {
  208543. IClassFactory* classFactory = 0;
  208544. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  208545. if (classFactory != 0)
  208546. {
  208547. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  208548. classFactory->Release();
  208549. }
  208550. return asioObject != 0;
  208551. }
  208552. }
  208553. }
  208554. }
  208555. JUCE_CATCH_ALL
  208556. asioObject = 0;
  208557. return false;
  208558. }
  208559. const String initDriver()
  208560. {
  208561. if (asioObject != 0)
  208562. {
  208563. char buffer [256];
  208564. zeromem (buffer, sizeof (buffer));
  208565. if (! asioObject->init (windowHandle))
  208566. {
  208567. asioObject->getErrorMessage (buffer);
  208568. return String (buffer, sizeof (buffer) - 1);
  208569. }
  208570. // just in case any daft drivers expect this to be called..
  208571. asioObject->getDriverName (buffer);
  208572. return String::empty;
  208573. }
  208574. return "No Driver";
  208575. }
  208576. const String openDevice()
  208577. {
  208578. // use this in case the driver starts opening dialog boxes..
  208579. Component modalWindow (String::empty);
  208580. modalWindow.setOpaque (true);
  208581. modalWindow.addToDesktop (0);
  208582. modalWindow.enterModalState();
  208583. // open the device and get its info..
  208584. log (T("opening ASIO device: ") + getName());
  208585. needToReset = false;
  208586. isReSync = false;
  208587. outputChannelNames.clear();
  208588. inputChannelNames.clear();
  208589. bufferSizes.clear();
  208590. sampleRates.clear();
  208591. isASIOOpen = false;
  208592. isOpen_ = false;
  208593. totalNumInputChans = 0;
  208594. totalNumOutputChans = 0;
  208595. numActiveInputChans = 0;
  208596. numActiveOutputChans = 0;
  208597. currentCallback = 0;
  208598. error = String::empty;
  208599. if (getName().isEmpty())
  208600. return error;
  208601. long err = 0;
  208602. if (loadDriver())
  208603. {
  208604. if ((error = initDriver()).isEmpty())
  208605. {
  208606. numActiveInputChans = 0;
  208607. numActiveOutputChans = 0;
  208608. totalNumInputChans = 0;
  208609. totalNumOutputChans = 0;
  208610. if (asioObject != 0
  208611. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  208612. {
  208613. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  208614. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  208615. {
  208616. // find a list of buffer sizes..
  208617. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  208618. if (granularity >= 0)
  208619. {
  208620. granularity = jmax (1, (int) granularity);
  208621. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  208622. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  208623. }
  208624. else if (granularity < 0)
  208625. {
  208626. for (int i = 0; i < 18; ++i)
  208627. {
  208628. const int s = (1 << i);
  208629. if (s >= minSize && s <= maxSize)
  208630. bufferSizes.add (s);
  208631. }
  208632. }
  208633. if (! bufferSizes.contains (preferredSize))
  208634. bufferSizes.insert (0, preferredSize);
  208635. double currentRate = 0;
  208636. asioObject->getSampleRate (&currentRate);
  208637. if (currentRate <= 0.0 || currentRate > 192001.0)
  208638. {
  208639. log ("setting sample rate");
  208640. err = asioObject->setSampleRate (44100.0);
  208641. if (err != 0)
  208642. {
  208643. logError ("setting sample rate", err);
  208644. }
  208645. asioObject->getSampleRate (&currentRate);
  208646. }
  208647. currentSampleRate = currentRate;
  208648. postOutput = (asioObject->outputReady() == 0);
  208649. if (postOutput)
  208650. {
  208651. log ("ASIO outputReady = ok");
  208652. }
  208653. updateSampleRates();
  208654. // ..because cubase does it at this point
  208655. inputLatency = outputLatency = 0;
  208656. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  208657. {
  208658. log ("ASIO - no latencies");
  208659. }
  208660. log (String ("latencies: ")
  208661. + String ((int) inputLatency)
  208662. + T(", ") + String ((int) outputLatency));
  208663. // create some dummy buffers now.. because cubase does..
  208664. numActiveInputChans = 0;
  208665. numActiveOutputChans = 0;
  208666. ASIOBufferInfo* info = bufferInfos;
  208667. int i, numChans = 0;
  208668. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  208669. {
  208670. info->isInput = 1;
  208671. info->channelNum = i;
  208672. info->buffers[0] = info->buffers[1] = 0;
  208673. ++info;
  208674. ++numChans;
  208675. }
  208676. const int outputBufferIndex = numChans;
  208677. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  208678. {
  208679. info->isInput = 0;
  208680. info->channelNum = i;
  208681. info->buffers[0] = info->buffers[1] = 0;
  208682. ++info;
  208683. ++numChans;
  208684. }
  208685. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  208686. if (currentASIODev[0] == this)
  208687. {
  208688. callbacks.bufferSwitch = &bufferSwitchCallback0;
  208689. callbacks.asioMessage = &asioMessagesCallback0;
  208690. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  208691. }
  208692. else if (currentASIODev[1] == this)
  208693. {
  208694. callbacks.bufferSwitch = &bufferSwitchCallback1;
  208695. callbacks.asioMessage = &asioMessagesCallback1;
  208696. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  208697. }
  208698. else if (currentASIODev[2] == this)
  208699. {
  208700. callbacks.bufferSwitch = &bufferSwitchCallback2;
  208701. callbacks.asioMessage = &asioMessagesCallback2;
  208702. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  208703. }
  208704. else
  208705. {
  208706. jassertfalse
  208707. }
  208708. log (T("creating buffers (dummy): ") + String (numChans)
  208709. + T(", ") + String ((int) preferredSize));
  208710. if (preferredSize > 0)
  208711. {
  208712. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  208713. if (err != 0)
  208714. {
  208715. logError ("dummy buffers", err);
  208716. }
  208717. }
  208718. long newInps = 0, newOuts = 0;
  208719. asioObject->getChannels (&newInps, &newOuts);
  208720. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  208721. {
  208722. totalNumInputChans = newInps;
  208723. totalNumOutputChans = newOuts;
  208724. log (String ((int) totalNumInputChans) + T(" in; ")
  208725. + String ((int) totalNumOutputChans) + T(" out"));
  208726. }
  208727. updateSampleRates();
  208728. ASIOChannelInfo channelInfo;
  208729. channelInfo.type = 0;
  208730. for (i = 0; i < totalNumInputChans; ++i)
  208731. {
  208732. zerostruct (channelInfo);
  208733. channelInfo.channel = i;
  208734. channelInfo.isInput = 1;
  208735. asioObject->getChannelInfo (&channelInfo);
  208736. inputChannelNames.add (String (channelInfo.name));
  208737. }
  208738. for (i = 0; i < totalNumOutputChans; ++i)
  208739. {
  208740. zerostruct (channelInfo);
  208741. channelInfo.channel = i;
  208742. channelInfo.isInput = 0;
  208743. asioObject->getChannelInfo (&channelInfo);
  208744. outputChannelNames.add (String (channelInfo.name));
  208745. typeToFormatParameters (channelInfo.type,
  208746. outputChannelBitDepths[i],
  208747. outputChannelBytesPerSample[i],
  208748. outputChannelIsFloat[i],
  208749. outputChannelLittleEndian[i]);
  208750. if (i < 2)
  208751. {
  208752. // clear the channels that are used with the dummy stuff
  208753. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  208754. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  208755. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  208756. }
  208757. }
  208758. outputChannelNames.trim();
  208759. inputChannelNames.trim();
  208760. outputChannelNames.appendNumbersToDuplicates (false, true);
  208761. inputChannelNames.appendNumbersToDuplicates (false, true);
  208762. // start and stop because cubase does it..
  208763. asioObject->getLatencies (&inputLatency, &outputLatency);
  208764. if ((err = asioObject->start()) != 0)
  208765. {
  208766. // ignore an error here, as it might start later after setting other stuff up
  208767. logError ("ASIO start", err);
  208768. }
  208769. Thread::sleep (100);
  208770. asioObject->stop();
  208771. }
  208772. else
  208773. {
  208774. error = "Can't detect buffer sizes";
  208775. }
  208776. }
  208777. else
  208778. {
  208779. error = "Can't detect asio channels";
  208780. }
  208781. }
  208782. }
  208783. else
  208784. {
  208785. error = "No such device";
  208786. }
  208787. if (error.isNotEmpty())
  208788. {
  208789. logError (error, err);
  208790. if (asioObject != 0)
  208791. asioObject->disposeBuffers();
  208792. removeCurrentDriver();
  208793. isASIOOpen = false;
  208794. }
  208795. else
  208796. {
  208797. isASIOOpen = true;
  208798. log ("ASIO device open");
  208799. }
  208800. isOpen_ = false;
  208801. needToReset = false;
  208802. isReSync = false;
  208803. return error;
  208804. }
  208805. void callback (const long index) throw()
  208806. {
  208807. if (isStarted)
  208808. {
  208809. bufferIndex = index;
  208810. processBuffer();
  208811. }
  208812. else
  208813. {
  208814. if (postOutput && (asioObject != 0))
  208815. asioObject->outputReady();
  208816. }
  208817. calledback = true;
  208818. }
  208819. void processBuffer() throw()
  208820. {
  208821. const ASIOBufferInfo* const infos = bufferInfos;
  208822. const int bi = bufferIndex;
  208823. const ScopedLock sl (callbackLock);
  208824. if (needToReset)
  208825. {
  208826. needToReset = false;
  208827. if (isReSync)
  208828. {
  208829. log ("! ASIO resync");
  208830. isReSync = false;
  208831. }
  208832. else
  208833. {
  208834. startTimer (20);
  208835. }
  208836. }
  208837. if (bi >= 0)
  208838. {
  208839. const int samps = currentBlockSizeSamples;
  208840. if (currentCallback != 0)
  208841. {
  208842. int i;
  208843. for (i = 0; i < numActiveInputChans; ++i)
  208844. {
  208845. float* const dst = inBuffers[i];
  208846. jassert (dst != 0);
  208847. const char* const src = (const char*) (infos[i].buffers[bi]);
  208848. if (inputChannelIsFloat[i])
  208849. {
  208850. memcpy (dst, src, samps * sizeof (float));
  208851. }
  208852. else
  208853. {
  208854. jassert (dst == tempBuffer + (samps * i));
  208855. switch (inputChannelBitDepths[i])
  208856. {
  208857. case 16:
  208858. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  208859. samps, inputChannelLittleEndian[i]);
  208860. break;
  208861. case 24:
  208862. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  208863. samps, inputChannelLittleEndian[i]);
  208864. break;
  208865. case 32:
  208866. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  208867. samps, inputChannelLittleEndian[i]);
  208868. break;
  208869. case 64:
  208870. jassertfalse
  208871. break;
  208872. }
  208873. }
  208874. }
  208875. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  208876. numActiveInputChans,
  208877. outBuffers,
  208878. numActiveOutputChans,
  208879. samps);
  208880. for (i = 0; i < numActiveOutputChans; ++i)
  208881. {
  208882. float* const src = outBuffers[i];
  208883. jassert (src != 0);
  208884. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  208885. if (outputChannelIsFloat[i])
  208886. {
  208887. memcpy (dst, src, samps * sizeof (float));
  208888. }
  208889. else
  208890. {
  208891. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  208892. switch (outputChannelBitDepths[i])
  208893. {
  208894. case 16:
  208895. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  208896. samps, outputChannelLittleEndian[i]);
  208897. break;
  208898. case 24:
  208899. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  208900. samps, outputChannelLittleEndian[i]);
  208901. break;
  208902. case 32:
  208903. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  208904. samps, outputChannelLittleEndian[i]);
  208905. break;
  208906. case 64:
  208907. jassertfalse
  208908. break;
  208909. }
  208910. }
  208911. }
  208912. }
  208913. else
  208914. {
  208915. for (int i = 0; i < numActiveOutputChans; ++i)
  208916. {
  208917. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  208918. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  208919. }
  208920. }
  208921. }
  208922. if (postOutput)
  208923. asioObject->outputReady();
  208924. }
  208925. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  208926. {
  208927. if (currentASIODev[0] != 0)
  208928. currentASIODev[0]->callback (index);
  208929. return 0;
  208930. }
  208931. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  208932. {
  208933. if (currentASIODev[1] != 0)
  208934. currentASIODev[1]->callback (index);
  208935. return 0;
  208936. }
  208937. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  208938. {
  208939. if (currentASIODev[2] != 0)
  208940. currentASIODev[2]->callback (index);
  208941. return 0;
  208942. }
  208943. static void bufferSwitchCallback0 (long index, long) throw()
  208944. {
  208945. if (currentASIODev[0] != 0)
  208946. currentASIODev[0]->callback (index);
  208947. }
  208948. static void bufferSwitchCallback1 (long index, long) throw()
  208949. {
  208950. if (currentASIODev[1] != 0)
  208951. currentASIODev[1]->callback (index);
  208952. }
  208953. static void bufferSwitchCallback2 (long index, long) throw()
  208954. {
  208955. if (currentASIODev[2] != 0)
  208956. currentASIODev[2]->callback (index);
  208957. }
  208958. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  208959. {
  208960. return asioMessagesCallback (selector, value, 0);
  208961. }
  208962. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  208963. {
  208964. return asioMessagesCallback (selector, value, 1);
  208965. }
  208966. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  208967. {
  208968. return asioMessagesCallback (selector, value, 2);
  208969. }
  208970. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  208971. {
  208972. switch (selector)
  208973. {
  208974. case kAsioSelectorSupported:
  208975. if (value == kAsioResetRequest
  208976. || value == kAsioEngineVersion
  208977. || value == kAsioResyncRequest
  208978. || value == kAsioLatenciesChanged
  208979. || value == kAsioSupportsInputMonitor)
  208980. return 1;
  208981. break;
  208982. case kAsioBufferSizeChange:
  208983. break;
  208984. case kAsioResetRequest:
  208985. if (currentASIODev[deviceIndex] != 0)
  208986. currentASIODev[deviceIndex]->resetRequest();
  208987. return 1;
  208988. case kAsioResyncRequest:
  208989. if (currentASIODev[deviceIndex] != 0)
  208990. currentASIODev[deviceIndex]->resyncRequest();
  208991. return 1;
  208992. case kAsioLatenciesChanged:
  208993. return 1;
  208994. case kAsioEngineVersion:
  208995. return 2;
  208996. case kAsioSupportsTimeInfo:
  208997. case kAsioSupportsTimeCode:
  208998. return 0;
  208999. }
  209000. return 0;
  209001. }
  209002. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  209003. {
  209004. }
  209005. static void convertInt16ToFloat (const char* src,
  209006. float* dest,
  209007. const int srcStrideBytes,
  209008. int numSamples,
  209009. const bool littleEndian) throw()
  209010. {
  209011. const double g = 1.0 / 32768.0;
  209012. if (littleEndian)
  209013. {
  209014. while (--numSamples >= 0)
  209015. {
  209016. *dest++ = (float) (g * (short) littleEndianShort (src));
  209017. src += srcStrideBytes;
  209018. }
  209019. }
  209020. else
  209021. {
  209022. while (--numSamples >= 0)
  209023. {
  209024. *dest++ = (float) (g * (short) bigEndianShort (src));
  209025. src += srcStrideBytes;
  209026. }
  209027. }
  209028. }
  209029. static void convertFloatToInt16 (const float* src,
  209030. char* dest,
  209031. const int dstStrideBytes,
  209032. int numSamples,
  209033. const bool littleEndian) throw()
  209034. {
  209035. const double maxVal = (double) 0x7fff;
  209036. if (littleEndian)
  209037. {
  209038. while (--numSamples >= 0)
  209039. {
  209040. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209041. dest += dstStrideBytes;
  209042. }
  209043. }
  209044. else
  209045. {
  209046. while (--numSamples >= 0)
  209047. {
  209048. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209049. dest += dstStrideBytes;
  209050. }
  209051. }
  209052. }
  209053. static void convertInt24ToFloat (const char* src,
  209054. float* dest,
  209055. const int srcStrideBytes,
  209056. int numSamples,
  209057. const bool littleEndian) throw()
  209058. {
  209059. const double g = 1.0 / 0x7fffff;
  209060. if (littleEndian)
  209061. {
  209062. while (--numSamples >= 0)
  209063. {
  209064. *dest++ = (float) (g * littleEndian24Bit (src));
  209065. src += srcStrideBytes;
  209066. }
  209067. }
  209068. else
  209069. {
  209070. while (--numSamples >= 0)
  209071. {
  209072. *dest++ = (float) (g * bigEndian24Bit (src));
  209073. src += srcStrideBytes;
  209074. }
  209075. }
  209076. }
  209077. static void convertFloatToInt24 (const float* src,
  209078. char* dest,
  209079. const int dstStrideBytes,
  209080. int numSamples,
  209081. const bool littleEndian) throw()
  209082. {
  209083. const double maxVal = (double) 0x7fffff;
  209084. if (littleEndian)
  209085. {
  209086. while (--numSamples >= 0)
  209087. {
  209088. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209089. dest += dstStrideBytes;
  209090. }
  209091. }
  209092. else
  209093. {
  209094. while (--numSamples >= 0)
  209095. {
  209096. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  209097. dest += dstStrideBytes;
  209098. }
  209099. }
  209100. }
  209101. static void convertInt32ToFloat (const char* src,
  209102. float* dest,
  209103. const int srcStrideBytes,
  209104. int numSamples,
  209105. const bool littleEndian) throw()
  209106. {
  209107. const double g = 1.0 / 0x7fffffff;
  209108. if (littleEndian)
  209109. {
  209110. while (--numSamples >= 0)
  209111. {
  209112. *dest++ = (float) (g * (int) littleEndianInt (src));
  209113. src += srcStrideBytes;
  209114. }
  209115. }
  209116. else
  209117. {
  209118. while (--numSamples >= 0)
  209119. {
  209120. *dest++ = (float) (g * (int) bigEndianInt (src));
  209121. src += srcStrideBytes;
  209122. }
  209123. }
  209124. }
  209125. static void convertFloatToInt32 (const float* src,
  209126. char* dest,
  209127. const int dstStrideBytes,
  209128. int numSamples,
  209129. const bool littleEndian) throw()
  209130. {
  209131. const double maxVal = (double) 0x7fffffff;
  209132. if (littleEndian)
  209133. {
  209134. while (--numSamples >= 0)
  209135. {
  209136. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209137. dest += dstStrideBytes;
  209138. }
  209139. }
  209140. else
  209141. {
  209142. while (--numSamples >= 0)
  209143. {
  209144. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  209145. dest += dstStrideBytes;
  209146. }
  209147. }
  209148. }
  209149. static void typeToFormatParameters (const long type,
  209150. int& bitDepth,
  209151. int& byteStride,
  209152. bool& formatIsFloat,
  209153. bool& littleEndian) throw()
  209154. {
  209155. bitDepth = 0;
  209156. littleEndian = false;
  209157. formatIsFloat = false;
  209158. switch (type)
  209159. {
  209160. case ASIOSTInt16MSB:
  209161. case ASIOSTInt16LSB:
  209162. case ASIOSTInt32MSB16:
  209163. case ASIOSTInt32LSB16:
  209164. bitDepth = 16; break;
  209165. case ASIOSTFloat32MSB:
  209166. case ASIOSTFloat32LSB:
  209167. formatIsFloat = true;
  209168. bitDepth = 32; break;
  209169. case ASIOSTInt32MSB:
  209170. case ASIOSTInt32LSB:
  209171. bitDepth = 32; break;
  209172. case ASIOSTInt24MSB:
  209173. case ASIOSTInt24LSB:
  209174. case ASIOSTInt32MSB24:
  209175. case ASIOSTInt32LSB24:
  209176. case ASIOSTInt32MSB18:
  209177. case ASIOSTInt32MSB20:
  209178. case ASIOSTInt32LSB18:
  209179. case ASIOSTInt32LSB20:
  209180. bitDepth = 24; break;
  209181. case ASIOSTFloat64MSB:
  209182. case ASIOSTFloat64LSB:
  209183. default:
  209184. bitDepth = 64;
  209185. break;
  209186. }
  209187. switch (type)
  209188. {
  209189. case ASIOSTInt16MSB:
  209190. case ASIOSTInt32MSB16:
  209191. case ASIOSTFloat32MSB:
  209192. case ASIOSTFloat64MSB:
  209193. case ASIOSTInt32MSB:
  209194. case ASIOSTInt32MSB18:
  209195. case ASIOSTInt32MSB20:
  209196. case ASIOSTInt32MSB24:
  209197. case ASIOSTInt24MSB:
  209198. littleEndian = false; break;
  209199. case ASIOSTInt16LSB:
  209200. case ASIOSTInt32LSB16:
  209201. case ASIOSTFloat32LSB:
  209202. case ASIOSTFloat64LSB:
  209203. case ASIOSTInt32LSB:
  209204. case ASIOSTInt32LSB18:
  209205. case ASIOSTInt32LSB20:
  209206. case ASIOSTInt32LSB24:
  209207. case ASIOSTInt24LSB:
  209208. littleEndian = true; break;
  209209. default:
  209210. break;
  209211. }
  209212. switch (type)
  209213. {
  209214. case ASIOSTInt16LSB:
  209215. case ASIOSTInt16MSB:
  209216. byteStride = 2; break;
  209217. case ASIOSTInt24LSB:
  209218. case ASIOSTInt24MSB:
  209219. byteStride = 3; break;
  209220. case ASIOSTInt32MSB16:
  209221. case ASIOSTInt32LSB16:
  209222. case ASIOSTInt32MSB:
  209223. case ASIOSTInt32MSB18:
  209224. case ASIOSTInt32MSB20:
  209225. case ASIOSTInt32MSB24:
  209226. case ASIOSTInt32LSB:
  209227. case ASIOSTInt32LSB18:
  209228. case ASIOSTInt32LSB20:
  209229. case ASIOSTInt32LSB24:
  209230. case ASIOSTFloat32LSB:
  209231. case ASIOSTFloat32MSB:
  209232. byteStride = 4; break;
  209233. case ASIOSTFloat64MSB:
  209234. case ASIOSTFloat64LSB:
  209235. byteStride = 8; break;
  209236. default:
  209237. break;
  209238. }
  209239. }
  209240. };
  209241. class ASIOAudioIODeviceType : public AudioIODeviceType
  209242. {
  209243. public:
  209244. ASIOAudioIODeviceType()
  209245. : AudioIODeviceType (T("ASIO")),
  209246. classIds (2),
  209247. hasScanned (false)
  209248. {
  209249. CoInitialize (0);
  209250. }
  209251. ~ASIOAudioIODeviceType()
  209252. {
  209253. }
  209254. void scanForDevices()
  209255. {
  209256. hasScanned = true;
  209257. deviceNames.clear();
  209258. classIds.clear();
  209259. HKEY hk = 0;
  209260. int index = 0;
  209261. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  209262. {
  209263. for (;;)
  209264. {
  209265. char name [256];
  209266. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  209267. {
  209268. addDriverInfo (name, hk);
  209269. }
  209270. else
  209271. {
  209272. break;
  209273. }
  209274. }
  209275. RegCloseKey (hk);
  209276. }
  209277. }
  209278. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  209279. {
  209280. jassert (hasScanned); // need to call scanForDevices() before doing this
  209281. return deviceNames;
  209282. }
  209283. int getDefaultDeviceIndex (const bool) const
  209284. {
  209285. jassert (hasScanned); // need to call scanForDevices() before doing this
  209286. for (int i = deviceNames.size(); --i >= 0;)
  209287. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  209288. return i; // asio4all is a safe choice for a default..
  209289. #if JUCE_DEBUG
  209290. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  209291. return 1; // (the digi m-box driver crashes the app when you run
  209292. // it in the debugger, which can be a bit annoying)
  209293. #endif
  209294. return 0;
  209295. }
  209296. static int findFreeSlot()
  209297. {
  209298. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  209299. if (currentASIODev[i] == 0)
  209300. return i;
  209301. jassertfalse; // unfortunately you can only have a finite number
  209302. // of ASIO devices open at the same time..
  209303. return -1;
  209304. }
  209305. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  209306. {
  209307. jassert (hasScanned); // need to call scanForDevices() before doing this
  209308. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  209309. }
  209310. bool hasSeparateInputsAndOutputs() const { return false; }
  209311. AudioIODevice* createDevice (const String& outputDeviceName,
  209312. const String& inputDeviceName)
  209313. {
  209314. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  209315. (void) inputDeviceName;
  209316. jassert (hasScanned); // need to call scanForDevices() before doing this
  209317. const int index = deviceNames.indexOf (outputDeviceName);
  209318. if (index >= 0)
  209319. {
  209320. const int freeSlot = findFreeSlot();
  209321. if (freeSlot >= 0)
  209322. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  209323. }
  209324. return 0;
  209325. }
  209326. juce_UseDebuggingNewOperator
  209327. private:
  209328. StringArray deviceNames;
  209329. OwnedArray <CLSID> classIds;
  209330. bool hasScanned;
  209331. static bool checkClassIsOk (const String& classId)
  209332. {
  209333. HKEY hk = 0;
  209334. bool ok = false;
  209335. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  209336. {
  209337. int index = 0;
  209338. for (;;)
  209339. {
  209340. char buf [512];
  209341. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  209342. {
  209343. if (classId.equalsIgnoreCase (buf))
  209344. {
  209345. HKEY subKey, pathKey;
  209346. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209347. {
  209348. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  209349. {
  209350. char pathName [600];
  209351. DWORD dtype = REG_SZ;
  209352. DWORD dsize = sizeof (pathName);
  209353. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  209354. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  209355. {
  209356. OFSTRUCT of;
  209357. zerostruct (of);
  209358. of.cBytes = sizeof (of);
  209359. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  209360. }
  209361. RegCloseKey (pathKey);
  209362. }
  209363. RegCloseKey (subKey);
  209364. }
  209365. break;
  209366. }
  209367. }
  209368. else
  209369. {
  209370. break;
  209371. }
  209372. }
  209373. RegCloseKey (hk);
  209374. }
  209375. return ok;
  209376. }
  209377. void addDriverInfo (const String& keyName, HKEY hk)
  209378. {
  209379. HKEY subKey;
  209380. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  209381. {
  209382. char buf [256];
  209383. DWORD dtype = REG_SZ;
  209384. DWORD dsize = sizeof (buf);
  209385. zeromem (buf, dsize);
  209386. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209387. {
  209388. if (dsize > 0 && checkClassIsOk (buf))
  209389. {
  209390. wchar_t classIdStr [130];
  209391. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  209392. String deviceName;
  209393. CLSID classId;
  209394. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  209395. {
  209396. dtype = REG_SZ;
  209397. dsize = sizeof (buf);
  209398. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  209399. deviceName = buf;
  209400. else
  209401. deviceName = keyName;
  209402. log (T("found ") + deviceName);
  209403. deviceNames.add (deviceName);
  209404. classIds.add (new CLSID (classId));
  209405. }
  209406. }
  209407. RegCloseKey (subKey);
  209408. }
  209409. }
  209410. }
  209411. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  209412. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  209413. };
  209414. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  209415. {
  209416. return new ASIOAudioIODeviceType();
  209417. }
  209418. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  209419. void* guid,
  209420. const String& optionalDllForDirectLoading)
  209421. {
  209422. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  209423. if (freeSlot < 0)
  209424. return 0;
  209425. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  209426. }
  209427. #undef log
  209428. #endif
  209429. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  209430. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  209431. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209432. // compiled on its own).
  209433. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  209434. END_JUCE_NAMESPACE
  209435. extern "C"
  209436. {
  209437. // Declare just the minimum number of interfaces for the DSound objects that we need..
  209438. typedef struct typeDSBUFFERDESC
  209439. {
  209440. DWORD dwSize;
  209441. DWORD dwFlags;
  209442. DWORD dwBufferBytes;
  209443. DWORD dwReserved;
  209444. LPWAVEFORMATEX lpwfxFormat;
  209445. GUID guid3DAlgorithm;
  209446. } DSBUFFERDESC;
  209447. struct IDirectSoundBuffer;
  209448. #undef INTERFACE
  209449. #define INTERFACE IDirectSound
  209450. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  209451. {
  209452. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209453. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209454. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209455. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  209456. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209457. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  209458. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  209459. STDMETHOD(Compact) (THIS) PURE;
  209460. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  209461. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  209462. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209463. };
  209464. #undef INTERFACE
  209465. #define INTERFACE IDirectSoundBuffer
  209466. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  209467. {
  209468. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209469. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209470. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209471. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209472. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209473. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209474. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  209475. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  209476. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  209477. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209478. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  209479. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209480. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  209481. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  209482. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  209483. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  209484. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  209485. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  209486. STDMETHOD(Stop) (THIS) PURE;
  209487. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209488. STDMETHOD(Restore) (THIS) PURE;
  209489. };
  209490. typedef struct typeDSCBUFFERDESC
  209491. {
  209492. DWORD dwSize;
  209493. DWORD dwFlags;
  209494. DWORD dwBufferBytes;
  209495. DWORD dwReserved;
  209496. LPWAVEFORMATEX lpwfxFormat;
  209497. } DSCBUFFERDESC;
  209498. struct IDirectSoundCaptureBuffer;
  209499. #undef INTERFACE
  209500. #define INTERFACE IDirectSoundCapture
  209501. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  209502. {
  209503. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209504. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209505. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209506. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  209507. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209508. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  209509. };
  209510. #undef INTERFACE
  209511. #define INTERFACE IDirectSoundCaptureBuffer
  209512. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  209513. {
  209514. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  209515. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  209516. STDMETHOD_(ULONG,Release) (THIS) PURE;
  209517. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  209518. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  209519. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  209520. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  209521. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  209522. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  209523. STDMETHOD(Start) (THIS_ DWORD) PURE;
  209524. STDMETHOD(Stop) (THIS) PURE;
  209525. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  209526. };
  209527. };
  209528. BEGIN_JUCE_NAMESPACE
  209529. static const String getDSErrorMessage (HRESULT hr)
  209530. {
  209531. const char* result = 0;
  209532. switch (hr)
  209533. {
  209534. case MAKE_HRESULT(1, 0x878, 10):
  209535. result = "Device already allocated";
  209536. break;
  209537. case MAKE_HRESULT(1, 0x878, 30):
  209538. result = "Control unavailable";
  209539. break;
  209540. case E_INVALIDARG:
  209541. result = "Invalid parameter";
  209542. break;
  209543. case MAKE_HRESULT(1, 0x878, 50):
  209544. result = "Invalid call";
  209545. break;
  209546. case E_FAIL:
  209547. result = "Generic error";
  209548. break;
  209549. case MAKE_HRESULT(1, 0x878, 70):
  209550. result = "Priority level error";
  209551. break;
  209552. case E_OUTOFMEMORY:
  209553. result = "Out of memory";
  209554. break;
  209555. case MAKE_HRESULT(1, 0x878, 100):
  209556. result = "Bad format";
  209557. break;
  209558. case E_NOTIMPL:
  209559. result = "Unsupported function";
  209560. break;
  209561. case MAKE_HRESULT(1, 0x878, 120):
  209562. result = "No driver";
  209563. break;
  209564. case MAKE_HRESULT(1, 0x878, 130):
  209565. result = "Already initialised";
  209566. break;
  209567. case CLASS_E_NOAGGREGATION:
  209568. result = "No aggregation";
  209569. break;
  209570. case MAKE_HRESULT(1, 0x878, 150):
  209571. result = "Buffer lost";
  209572. break;
  209573. case MAKE_HRESULT(1, 0x878, 160):
  209574. result = "Another app has priority";
  209575. break;
  209576. case MAKE_HRESULT(1, 0x878, 170):
  209577. result = "Uninitialised";
  209578. break;
  209579. case E_NOINTERFACE:
  209580. result = "No interface";
  209581. break;
  209582. case S_OK:
  209583. result = "No error";
  209584. break;
  209585. default:
  209586. return "Unknown error: " + String ((int) hr);
  209587. }
  209588. return result;
  209589. }
  209590. #define DS_DEBUGGING 1
  209591. #ifdef DS_DEBUGGING
  209592. #define CATCH JUCE_CATCH_EXCEPTION
  209593. #undef log
  209594. #define log(a) Logger::writeToLog(a);
  209595. #undef logError
  209596. #define logError(a) logDSError(a, __LINE__);
  209597. static void logDSError (HRESULT hr, int lineNum)
  209598. {
  209599. if (hr != S_OK)
  209600. {
  209601. String error ("DS error at line ");
  209602. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  209603. log (error);
  209604. }
  209605. }
  209606. #else
  209607. #define CATCH JUCE_CATCH_ALL
  209608. #define log(a)
  209609. #define logError(a)
  209610. #endif
  209611. #define DSOUND_FUNCTION(functionName, params) \
  209612. typedef HRESULT (WINAPI *type##functionName) params; \
  209613. static type##functionName ds##functionName = 0;
  209614. #define DSOUND_FUNCTION_LOAD(functionName) \
  209615. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  209616. jassert (ds##functionName != 0);
  209617. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  209618. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  209619. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  209620. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  209621. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209622. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  209623. static void initialiseDSoundFunctions()
  209624. {
  209625. if (dsDirectSoundCreate == 0)
  209626. {
  209627. HMODULE h = LoadLibraryA ("dsound.dll");
  209628. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  209629. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  209630. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  209631. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  209632. }
  209633. }
  209634. class DSoundInternalOutChannel
  209635. {
  209636. String name;
  209637. LPGUID guid;
  209638. int sampleRate, bufferSizeSamples;
  209639. float* leftBuffer;
  209640. float* rightBuffer;
  209641. IDirectSound* pDirectSound;
  209642. IDirectSoundBuffer* pOutputBuffer;
  209643. DWORD writeOffset;
  209644. int totalBytesPerBuffer;
  209645. int bytesPerBuffer;
  209646. unsigned int lastPlayCursor;
  209647. public:
  209648. int bitDepth;
  209649. bool doneFlag;
  209650. DSoundInternalOutChannel (const String& name_,
  209651. LPGUID guid_,
  209652. int rate,
  209653. int bufferSize,
  209654. float* left,
  209655. float* right)
  209656. : name (name_),
  209657. guid (guid_),
  209658. sampleRate (rate),
  209659. bufferSizeSamples (bufferSize),
  209660. leftBuffer (left),
  209661. rightBuffer (right),
  209662. pDirectSound (0),
  209663. pOutputBuffer (0),
  209664. bitDepth (16)
  209665. {
  209666. }
  209667. ~DSoundInternalOutChannel()
  209668. {
  209669. close();
  209670. }
  209671. void close()
  209672. {
  209673. HRESULT hr;
  209674. if (pOutputBuffer != 0)
  209675. {
  209676. JUCE_TRY
  209677. {
  209678. log (T("closing dsound out: ") + name);
  209679. hr = pOutputBuffer->Stop();
  209680. logError (hr);
  209681. }
  209682. CATCH
  209683. JUCE_TRY
  209684. {
  209685. hr = pOutputBuffer->Release();
  209686. logError (hr);
  209687. }
  209688. CATCH
  209689. pOutputBuffer = 0;
  209690. }
  209691. if (pDirectSound != 0)
  209692. {
  209693. JUCE_TRY
  209694. {
  209695. hr = pDirectSound->Release();
  209696. logError (hr);
  209697. }
  209698. CATCH
  209699. pDirectSound = 0;
  209700. }
  209701. }
  209702. const String open()
  209703. {
  209704. log (T("opening dsound out device: ") + name
  209705. + T(" rate=") + String (sampleRate)
  209706. + T(" bits=") + String (bitDepth)
  209707. + T(" buf=") + String (bufferSizeSamples));
  209708. pDirectSound = 0;
  209709. pOutputBuffer = 0;
  209710. writeOffset = 0;
  209711. String error;
  209712. HRESULT hr = E_NOINTERFACE;
  209713. if (dsDirectSoundCreate != 0)
  209714. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  209715. if (hr == S_OK)
  209716. {
  209717. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  209718. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  209719. const int numChannels = 2;
  209720. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  209721. logError (hr);
  209722. if (hr == S_OK)
  209723. {
  209724. IDirectSoundBuffer* pPrimaryBuffer;
  209725. DSBUFFERDESC primaryDesc;
  209726. zerostruct (primaryDesc);
  209727. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209728. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  209729. primaryDesc.dwBufferBytes = 0;
  209730. primaryDesc.lpwfxFormat = 0;
  209731. log ("opening dsound out step 2");
  209732. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  209733. logError (hr);
  209734. if (hr == S_OK)
  209735. {
  209736. WAVEFORMATEX wfFormat;
  209737. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  209738. wfFormat.nChannels = (unsigned short) numChannels;
  209739. wfFormat.nSamplesPerSec = sampleRate;
  209740. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  209741. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  209742. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  209743. wfFormat.cbSize = 0;
  209744. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  209745. logError (hr);
  209746. if (hr == S_OK)
  209747. {
  209748. DSBUFFERDESC secondaryDesc;
  209749. zerostruct (secondaryDesc);
  209750. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  209751. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  209752. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  209753. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  209754. secondaryDesc.lpwfxFormat = &wfFormat;
  209755. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  209756. logError (hr);
  209757. if (hr == S_OK)
  209758. {
  209759. log ("opening dsound out step 3");
  209760. DWORD dwDataLen;
  209761. unsigned char* pDSBuffData;
  209762. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  209763. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  209764. logError (hr);
  209765. if (hr == S_OK)
  209766. {
  209767. zeromem (pDSBuffData, dwDataLen);
  209768. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  209769. if (hr == S_OK)
  209770. {
  209771. hr = pOutputBuffer->SetCurrentPosition (0);
  209772. if (hr == S_OK)
  209773. {
  209774. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  209775. if (hr == S_OK)
  209776. return String::empty;
  209777. }
  209778. }
  209779. }
  209780. }
  209781. }
  209782. }
  209783. }
  209784. }
  209785. error = getDSErrorMessage (hr);
  209786. close();
  209787. return error;
  209788. }
  209789. void synchronisePosition()
  209790. {
  209791. if (pOutputBuffer != 0)
  209792. {
  209793. DWORD playCursor;
  209794. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  209795. }
  209796. }
  209797. bool service()
  209798. {
  209799. if (pOutputBuffer == 0)
  209800. return true;
  209801. DWORD playCursor, writeCursor;
  209802. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  209803. if (hr != S_OK)
  209804. {
  209805. logError (hr);
  209806. jassertfalse
  209807. return true;
  209808. }
  209809. int playWriteGap = writeCursor - playCursor;
  209810. if (playWriteGap < 0)
  209811. playWriteGap += totalBytesPerBuffer;
  209812. int bytesEmpty = playCursor - writeOffset;
  209813. if (bytesEmpty < 0)
  209814. bytesEmpty += totalBytesPerBuffer;
  209815. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  209816. {
  209817. writeOffset = writeCursor;
  209818. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  209819. }
  209820. if (bytesEmpty >= bytesPerBuffer)
  209821. {
  209822. LPBYTE lpbuf1 = 0;
  209823. LPBYTE lpbuf2 = 0;
  209824. DWORD dwSize1 = 0;
  209825. DWORD dwSize2 = 0;
  209826. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  209827. bytesPerBuffer,
  209828. (void**) &lpbuf1, &dwSize1,
  209829. (void**) &lpbuf2, &dwSize2, 0);
  209830. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  209831. {
  209832. pOutputBuffer->Restore();
  209833. hr = pOutputBuffer->Lock (writeOffset,
  209834. bytesPerBuffer,
  209835. (void**) &lpbuf1, &dwSize1,
  209836. (void**) &lpbuf2, &dwSize2, 0);
  209837. }
  209838. if (hr == S_OK)
  209839. {
  209840. if (bitDepth == 16)
  209841. {
  209842. const float gainL = 32767.0f;
  209843. const float gainR = 32767.0f;
  209844. int* dest = (int*)lpbuf1;
  209845. const float* left = leftBuffer;
  209846. const float* right = rightBuffer;
  209847. int samples1 = dwSize1 >> 2;
  209848. int samples2 = dwSize2 >> 2;
  209849. if (left == 0)
  209850. {
  209851. while (--samples1 >= 0)
  209852. {
  209853. int r = roundFloatToInt (gainR * *right++);
  209854. if (r < -32768)
  209855. r = -32768;
  209856. else if (r > 32767)
  209857. r = 32767;
  209858. *dest++ = (r << 16);
  209859. }
  209860. dest = (int*)lpbuf2;
  209861. while (--samples2 >= 0)
  209862. {
  209863. int r = roundFloatToInt (gainR * *right++);
  209864. if (r < -32768)
  209865. r = -32768;
  209866. else if (r > 32767)
  209867. r = 32767;
  209868. *dest++ = (r << 16);
  209869. }
  209870. }
  209871. else if (right == 0)
  209872. {
  209873. while (--samples1 >= 0)
  209874. {
  209875. int l = roundFloatToInt (gainL * *left++);
  209876. if (l < -32768)
  209877. l = -32768;
  209878. else if (l > 32767)
  209879. l = 32767;
  209880. l &= 0xffff;
  209881. *dest++ = l;
  209882. }
  209883. dest = (int*)lpbuf2;
  209884. while (--samples2 >= 0)
  209885. {
  209886. int l = roundFloatToInt (gainL * *left++);
  209887. if (l < -32768)
  209888. l = -32768;
  209889. else if (l > 32767)
  209890. l = 32767;
  209891. l &= 0xffff;
  209892. *dest++ = l;
  209893. }
  209894. }
  209895. else
  209896. {
  209897. while (--samples1 >= 0)
  209898. {
  209899. int l = roundFloatToInt (gainL * *left++);
  209900. if (l < -32768)
  209901. l = -32768;
  209902. else if (l > 32767)
  209903. l = 32767;
  209904. l &= 0xffff;
  209905. int r = roundFloatToInt (gainR * *right++);
  209906. if (r < -32768)
  209907. r = -32768;
  209908. else if (r > 32767)
  209909. r = 32767;
  209910. *dest++ = (r << 16) | l;
  209911. }
  209912. dest = (int*)lpbuf2;
  209913. while (--samples2 >= 0)
  209914. {
  209915. int l = roundFloatToInt (gainL * *left++);
  209916. if (l < -32768)
  209917. l = -32768;
  209918. else if (l > 32767)
  209919. l = 32767;
  209920. l &= 0xffff;
  209921. int r = roundFloatToInt (gainR * *right++);
  209922. if (r < -32768)
  209923. r = -32768;
  209924. else if (r > 32767)
  209925. r = 32767;
  209926. *dest++ = (r << 16) | l;
  209927. }
  209928. }
  209929. }
  209930. else
  209931. {
  209932. jassertfalse
  209933. }
  209934. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  209935. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  209936. }
  209937. else
  209938. {
  209939. jassertfalse
  209940. logError (hr);
  209941. }
  209942. bytesEmpty -= bytesPerBuffer;
  209943. return true;
  209944. }
  209945. else
  209946. {
  209947. return false;
  209948. }
  209949. }
  209950. };
  209951. struct DSoundInternalInChannel
  209952. {
  209953. String name;
  209954. LPGUID guid;
  209955. int sampleRate, bufferSizeSamples;
  209956. float* leftBuffer;
  209957. float* rightBuffer;
  209958. IDirectSound* pDirectSound;
  209959. IDirectSoundCapture* pDirectSoundCapture;
  209960. IDirectSoundCaptureBuffer* pInputBuffer;
  209961. public:
  209962. unsigned int readOffset;
  209963. int bytesPerBuffer, totalBytesPerBuffer;
  209964. int bitDepth;
  209965. bool doneFlag;
  209966. DSoundInternalInChannel (const String& name_,
  209967. LPGUID guid_,
  209968. int rate,
  209969. int bufferSize,
  209970. float* left,
  209971. float* right)
  209972. : name (name_),
  209973. guid (guid_),
  209974. sampleRate (rate),
  209975. bufferSizeSamples (bufferSize),
  209976. leftBuffer (left),
  209977. rightBuffer (right),
  209978. pDirectSound (0),
  209979. pDirectSoundCapture (0),
  209980. pInputBuffer (0),
  209981. bitDepth (16)
  209982. {
  209983. }
  209984. ~DSoundInternalInChannel()
  209985. {
  209986. close();
  209987. }
  209988. void close()
  209989. {
  209990. HRESULT hr;
  209991. if (pInputBuffer != 0)
  209992. {
  209993. JUCE_TRY
  209994. {
  209995. log (T("closing dsound in: ") + name);
  209996. hr = pInputBuffer->Stop();
  209997. logError (hr);
  209998. }
  209999. CATCH
  210000. JUCE_TRY
  210001. {
  210002. hr = pInputBuffer->Release();
  210003. logError (hr);
  210004. }
  210005. CATCH
  210006. pInputBuffer = 0;
  210007. }
  210008. if (pDirectSoundCapture != 0)
  210009. {
  210010. JUCE_TRY
  210011. {
  210012. hr = pDirectSoundCapture->Release();
  210013. logError (hr);
  210014. }
  210015. CATCH
  210016. pDirectSoundCapture = 0;
  210017. }
  210018. if (pDirectSound != 0)
  210019. {
  210020. JUCE_TRY
  210021. {
  210022. hr = pDirectSound->Release();
  210023. logError (hr);
  210024. }
  210025. CATCH
  210026. pDirectSound = 0;
  210027. }
  210028. }
  210029. const String open()
  210030. {
  210031. log (T("opening dsound in device: ") + name
  210032. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  210033. pDirectSound = 0;
  210034. pDirectSoundCapture = 0;
  210035. pInputBuffer = 0;
  210036. readOffset = 0;
  210037. totalBytesPerBuffer = 0;
  210038. String error;
  210039. HRESULT hr = E_NOINTERFACE;
  210040. if (dsDirectSoundCaptureCreate != 0)
  210041. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  210042. logError (hr);
  210043. if (hr == S_OK)
  210044. {
  210045. const int numChannels = 2;
  210046. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  210047. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  210048. WAVEFORMATEX wfFormat;
  210049. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  210050. wfFormat.nChannels = (unsigned short)numChannels;
  210051. wfFormat.nSamplesPerSec = sampleRate;
  210052. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  210053. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  210054. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  210055. wfFormat.cbSize = 0;
  210056. DSCBUFFERDESC captureDesc;
  210057. zerostruct (captureDesc);
  210058. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  210059. captureDesc.dwFlags = 0;
  210060. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  210061. captureDesc.lpwfxFormat = &wfFormat;
  210062. log (T("opening dsound in step 2"));
  210063. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  210064. logError (hr);
  210065. if (hr == S_OK)
  210066. {
  210067. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  210068. logError (hr);
  210069. if (hr == S_OK)
  210070. return String::empty;
  210071. }
  210072. }
  210073. error = getDSErrorMessage (hr);
  210074. close();
  210075. return error;
  210076. }
  210077. void synchronisePosition()
  210078. {
  210079. if (pInputBuffer != 0)
  210080. {
  210081. DWORD capturePos;
  210082. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  210083. }
  210084. }
  210085. bool service()
  210086. {
  210087. if (pInputBuffer == 0)
  210088. return true;
  210089. DWORD capturePos, readPos;
  210090. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  210091. logError (hr);
  210092. if (hr != S_OK)
  210093. return true;
  210094. int bytesFilled = readPos - readOffset;
  210095. if (bytesFilled < 0)
  210096. bytesFilled += totalBytesPerBuffer;
  210097. if (bytesFilled >= bytesPerBuffer)
  210098. {
  210099. LPBYTE lpbuf1 = 0;
  210100. LPBYTE lpbuf2 = 0;
  210101. DWORD dwsize1 = 0;
  210102. DWORD dwsize2 = 0;
  210103. HRESULT hr = pInputBuffer->Lock (readOffset,
  210104. bytesPerBuffer,
  210105. (void**) &lpbuf1, &dwsize1,
  210106. (void**) &lpbuf2, &dwsize2, 0);
  210107. if (hr == S_OK)
  210108. {
  210109. if (bitDepth == 16)
  210110. {
  210111. const float g = 1.0f / 32768.0f;
  210112. float* destL = leftBuffer;
  210113. float* destR = rightBuffer;
  210114. int samples1 = dwsize1 >> 2;
  210115. int samples2 = dwsize2 >> 2;
  210116. const short* src = (const short*)lpbuf1;
  210117. if (destL == 0)
  210118. {
  210119. while (--samples1 >= 0)
  210120. {
  210121. ++src;
  210122. *destR++ = *src++ * g;
  210123. }
  210124. src = (const short*)lpbuf2;
  210125. while (--samples2 >= 0)
  210126. {
  210127. ++src;
  210128. *destR++ = *src++ * g;
  210129. }
  210130. }
  210131. else if (destR == 0)
  210132. {
  210133. while (--samples1 >= 0)
  210134. {
  210135. *destL++ = *src++ * g;
  210136. ++src;
  210137. }
  210138. src = (const short*)lpbuf2;
  210139. while (--samples2 >= 0)
  210140. {
  210141. *destL++ = *src++ * g;
  210142. ++src;
  210143. }
  210144. }
  210145. else
  210146. {
  210147. while (--samples1 >= 0)
  210148. {
  210149. *destL++ = *src++ * g;
  210150. *destR++ = *src++ * g;
  210151. }
  210152. src = (const short*)lpbuf2;
  210153. while (--samples2 >= 0)
  210154. {
  210155. *destL++ = *src++ * g;
  210156. *destR++ = *src++ * g;
  210157. }
  210158. }
  210159. }
  210160. else
  210161. {
  210162. jassertfalse
  210163. }
  210164. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  210165. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  210166. }
  210167. else
  210168. {
  210169. logError (hr);
  210170. jassertfalse
  210171. }
  210172. bytesFilled -= bytesPerBuffer;
  210173. return true;
  210174. }
  210175. else
  210176. {
  210177. return false;
  210178. }
  210179. }
  210180. };
  210181. class DSoundAudioIODevice : public AudioIODevice,
  210182. public Thread
  210183. {
  210184. public:
  210185. DSoundAudioIODevice (const String& deviceName,
  210186. const int outputDeviceIndex_,
  210187. const int inputDeviceIndex_)
  210188. : AudioIODevice (deviceName, "DirectSound"),
  210189. Thread ("Juce DSound"),
  210190. isOpen_ (false),
  210191. isStarted (false),
  210192. outputDeviceIndex (outputDeviceIndex_),
  210193. inputDeviceIndex (inputDeviceIndex_),
  210194. inChans (4),
  210195. outChans (4),
  210196. numInputBuffers (0),
  210197. numOutputBuffers (0),
  210198. totalSamplesOut (0),
  210199. sampleRate (0.0),
  210200. inputBuffers (0),
  210201. outputBuffers (0),
  210202. callback (0),
  210203. bufferSizeSamples (0)
  210204. {
  210205. if (outputDeviceIndex_ >= 0)
  210206. {
  210207. outChannels.add (TRANS("Left"));
  210208. outChannels.add (TRANS("Right"));
  210209. }
  210210. if (inputDeviceIndex_ >= 0)
  210211. {
  210212. inChannels.add (TRANS("Left"));
  210213. inChannels.add (TRANS("Right"));
  210214. }
  210215. }
  210216. ~DSoundAudioIODevice()
  210217. {
  210218. close();
  210219. }
  210220. const StringArray getOutputChannelNames()
  210221. {
  210222. return outChannels;
  210223. }
  210224. const StringArray getInputChannelNames()
  210225. {
  210226. return inChannels;
  210227. }
  210228. int getNumSampleRates()
  210229. {
  210230. return 4;
  210231. }
  210232. double getSampleRate (int index)
  210233. {
  210234. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210235. return samps [jlimit (0, 3, index)];
  210236. }
  210237. int getNumBufferSizesAvailable()
  210238. {
  210239. return 50;
  210240. }
  210241. int getBufferSizeSamples (int index)
  210242. {
  210243. int n = 64;
  210244. for (int i = 0; i < index; ++i)
  210245. n += (n < 512) ? 32
  210246. : ((n < 1024) ? 64
  210247. : ((n < 2048) ? 128 : 256));
  210248. return n;
  210249. }
  210250. int getDefaultBufferSize()
  210251. {
  210252. return 2560;
  210253. }
  210254. const String open (const BitArray& inputChannels,
  210255. const BitArray& outputChannels,
  210256. double sampleRate,
  210257. int bufferSizeSamples)
  210258. {
  210259. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  210260. isOpen_ = lastError.isEmpty();
  210261. return lastError;
  210262. }
  210263. void close()
  210264. {
  210265. stop();
  210266. if (isOpen_)
  210267. {
  210268. closeDevice();
  210269. isOpen_ = false;
  210270. }
  210271. }
  210272. bool isOpen()
  210273. {
  210274. return isOpen_ && isThreadRunning();
  210275. }
  210276. int getCurrentBufferSizeSamples()
  210277. {
  210278. return bufferSizeSamples;
  210279. }
  210280. double getCurrentSampleRate()
  210281. {
  210282. return sampleRate;
  210283. }
  210284. int getCurrentBitDepth()
  210285. {
  210286. int i, bits = 256;
  210287. for (i = inChans.size(); --i >= 0;)
  210288. bits = jmin (bits, inChans[i]->bitDepth);
  210289. for (i = outChans.size(); --i >= 0;)
  210290. bits = jmin (bits, outChans[i]->bitDepth);
  210291. if (bits > 32)
  210292. bits = 16;
  210293. return bits;
  210294. }
  210295. const BitArray getActiveOutputChannels() const
  210296. {
  210297. return enabledOutputs;
  210298. }
  210299. const BitArray getActiveInputChannels() const
  210300. {
  210301. return enabledInputs;
  210302. }
  210303. int getOutputLatencyInSamples()
  210304. {
  210305. return (int) (getCurrentBufferSizeSamples() * 1.5);
  210306. }
  210307. int getInputLatencyInSamples()
  210308. {
  210309. return getOutputLatencyInSamples();
  210310. }
  210311. void start (AudioIODeviceCallback* call)
  210312. {
  210313. if (isOpen_ && call != 0 && ! isStarted)
  210314. {
  210315. if (! isThreadRunning())
  210316. {
  210317. // something gone wrong and the thread's stopped..
  210318. isOpen_ = false;
  210319. return;
  210320. }
  210321. call->audioDeviceAboutToStart (this);
  210322. const ScopedLock sl (startStopLock);
  210323. callback = call;
  210324. isStarted = true;
  210325. }
  210326. }
  210327. void stop()
  210328. {
  210329. if (isStarted)
  210330. {
  210331. AudioIODeviceCallback* const callbackLocal = callback;
  210332. {
  210333. const ScopedLock sl (startStopLock);
  210334. isStarted = false;
  210335. }
  210336. if (callbackLocal != 0)
  210337. callbackLocal->audioDeviceStopped();
  210338. }
  210339. }
  210340. bool isPlaying()
  210341. {
  210342. return isStarted && isOpen_ && isThreadRunning();
  210343. }
  210344. const String getLastError()
  210345. {
  210346. return lastError;
  210347. }
  210348. juce_UseDebuggingNewOperator
  210349. StringArray inChannels, outChannels;
  210350. int outputDeviceIndex, inputDeviceIndex;
  210351. private:
  210352. bool isOpen_;
  210353. bool isStarted;
  210354. String lastError;
  210355. OwnedArray <DSoundInternalInChannel> inChans;
  210356. OwnedArray <DSoundInternalOutChannel> outChans;
  210357. WaitableEvent startEvent;
  210358. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  210359. int volatile totalSamplesOut;
  210360. int64 volatile lastBlockTime;
  210361. double sampleRate;
  210362. BitArray enabledInputs, enabledOutputs;
  210363. float** inputBuffers;
  210364. float** outputBuffers;
  210365. AudioIODeviceCallback* callback;
  210366. CriticalSection startStopLock;
  210367. DSoundAudioIODevice (const DSoundAudioIODevice&);
  210368. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  210369. const String openDevice (const BitArray& inputChannels,
  210370. const BitArray& outputChannels,
  210371. double sampleRate_,
  210372. int bufferSizeSamples_);
  210373. void closeDevice()
  210374. {
  210375. isStarted = false;
  210376. stopThread (5000);
  210377. inChans.clear();
  210378. outChans.clear();
  210379. int i;
  210380. for (i = 0; i < numInputBuffers; ++i)
  210381. juce_free (inputBuffers[i]);
  210382. delete[] inputBuffers;
  210383. inputBuffers = 0;
  210384. numInputBuffers = 0;
  210385. for (i = 0; i < numOutputBuffers; ++i)
  210386. juce_free (outputBuffers[i]);
  210387. delete[] outputBuffers;
  210388. outputBuffers = 0;
  210389. numOutputBuffers = 0;
  210390. }
  210391. void resync()
  210392. {
  210393. if (! threadShouldExit())
  210394. {
  210395. sleep (5);
  210396. int i;
  210397. for (i = 0; i < outChans.size(); ++i)
  210398. outChans.getUnchecked(i)->synchronisePosition();
  210399. for (i = 0; i < inChans.size(); ++i)
  210400. inChans.getUnchecked(i)->synchronisePosition();
  210401. }
  210402. }
  210403. public:
  210404. void run()
  210405. {
  210406. while (! threadShouldExit())
  210407. {
  210408. if (wait (100))
  210409. break;
  210410. }
  210411. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  210412. const int maxTimeMS = jmax (5, 3 * latencyMs);
  210413. while (! threadShouldExit())
  210414. {
  210415. int numToDo = 0;
  210416. uint32 startTime = Time::getMillisecondCounter();
  210417. int i;
  210418. for (i = inChans.size(); --i >= 0;)
  210419. {
  210420. inChans.getUnchecked(i)->doneFlag = false;
  210421. ++numToDo;
  210422. }
  210423. for (i = outChans.size(); --i >= 0;)
  210424. {
  210425. outChans.getUnchecked(i)->doneFlag = false;
  210426. ++numToDo;
  210427. }
  210428. if (numToDo > 0)
  210429. {
  210430. const int maxCount = 3;
  210431. int count = maxCount;
  210432. for (;;)
  210433. {
  210434. for (i = inChans.size(); --i >= 0;)
  210435. {
  210436. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  210437. if ((! in->doneFlag) && in->service())
  210438. {
  210439. in->doneFlag = true;
  210440. --numToDo;
  210441. }
  210442. }
  210443. for (i = outChans.size(); --i >= 0;)
  210444. {
  210445. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  210446. if ((! out->doneFlag) && out->service())
  210447. {
  210448. out->doneFlag = true;
  210449. --numToDo;
  210450. }
  210451. }
  210452. if (numToDo <= 0)
  210453. break;
  210454. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  210455. {
  210456. resync();
  210457. break;
  210458. }
  210459. if (--count <= 0)
  210460. {
  210461. Sleep (1);
  210462. count = maxCount;
  210463. }
  210464. if (threadShouldExit())
  210465. return;
  210466. }
  210467. }
  210468. else
  210469. {
  210470. sleep (1);
  210471. }
  210472. const ScopedLock sl (startStopLock);
  210473. if (isStarted)
  210474. {
  210475. JUCE_TRY
  210476. {
  210477. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  210478. numInputBuffers,
  210479. outputBuffers,
  210480. numOutputBuffers,
  210481. bufferSizeSamples);
  210482. }
  210483. JUCE_CATCH_EXCEPTION
  210484. totalSamplesOut += bufferSizeSamples;
  210485. }
  210486. else
  210487. {
  210488. for (i = 0; i < numOutputBuffers; ++i)
  210489. if (outputBuffers[i] != 0)
  210490. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  210491. totalSamplesOut = 0;
  210492. sleep (1);
  210493. }
  210494. }
  210495. }
  210496. };
  210497. class DSoundAudioIODeviceType : public AudioIODeviceType
  210498. {
  210499. public:
  210500. DSoundAudioIODeviceType()
  210501. : AudioIODeviceType (T("DirectSound")),
  210502. hasScanned (false)
  210503. {
  210504. initialiseDSoundFunctions();
  210505. }
  210506. ~DSoundAudioIODeviceType()
  210507. {
  210508. }
  210509. void scanForDevices()
  210510. {
  210511. hasScanned = true;
  210512. outputDeviceNames.clear();
  210513. outputGuids.clear();
  210514. inputDeviceNames.clear();
  210515. inputGuids.clear();
  210516. if (dsDirectSoundEnumerateW != 0)
  210517. {
  210518. dsDirectSoundEnumerateW (outputEnumProcW, this);
  210519. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  210520. }
  210521. }
  210522. const StringArray getDeviceNames (const bool wantInputNames) const
  210523. {
  210524. jassert (hasScanned); // need to call scanForDevices() before doing this
  210525. return wantInputNames ? inputDeviceNames
  210526. : outputDeviceNames;
  210527. }
  210528. int getDefaultDeviceIndex (const bool /*forInput*/) const
  210529. {
  210530. jassert (hasScanned); // need to call scanForDevices() before doing this
  210531. return 0;
  210532. }
  210533. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  210534. {
  210535. jassert (hasScanned); // need to call scanForDevices() before doing this
  210536. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  210537. if (d == 0)
  210538. return -1;
  210539. return asInput ? d->inputDeviceIndex
  210540. : d->outputDeviceIndex;
  210541. }
  210542. bool hasSeparateInputsAndOutputs() const { return true; }
  210543. AudioIODevice* createDevice (const String& outputDeviceName,
  210544. const String& inputDeviceName)
  210545. {
  210546. jassert (hasScanned); // need to call scanForDevices() before doing this
  210547. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  210548. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  210549. if (outputIndex >= 0 || inputIndex >= 0)
  210550. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  210551. : inputDeviceName,
  210552. outputIndex, inputIndex);
  210553. return 0;
  210554. }
  210555. juce_UseDebuggingNewOperator
  210556. StringArray outputDeviceNames;
  210557. OwnedArray <GUID> outputGuids;
  210558. StringArray inputDeviceNames;
  210559. OwnedArray <GUID> inputGuids;
  210560. private:
  210561. bool hasScanned;
  210562. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  210563. {
  210564. desc = desc.trim();
  210565. if (desc.isNotEmpty())
  210566. {
  210567. const String origDesc (desc);
  210568. int n = 2;
  210569. while (outputDeviceNames.contains (desc))
  210570. desc = origDesc + T(" (") + String (n++) + T(")");
  210571. outputDeviceNames.add (desc);
  210572. if (lpGUID != 0)
  210573. outputGuids.add (new GUID (*lpGUID));
  210574. else
  210575. outputGuids.add (0);
  210576. }
  210577. return TRUE;
  210578. }
  210579. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210580. {
  210581. return ((DSoundAudioIODeviceType*) object)
  210582. ->outputEnumProc (lpGUID, String (description));
  210583. }
  210584. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210585. {
  210586. return ((DSoundAudioIODeviceType*) object)
  210587. ->outputEnumProc (lpGUID, String (description));
  210588. }
  210589. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  210590. {
  210591. desc = desc.trim();
  210592. if (desc.isNotEmpty())
  210593. {
  210594. const String origDesc (desc);
  210595. int n = 2;
  210596. while (inputDeviceNames.contains (desc))
  210597. desc = origDesc + T(" (") + String (n++) + T(")");
  210598. inputDeviceNames.add (desc);
  210599. if (lpGUID != 0)
  210600. inputGuids.add (new GUID (*lpGUID));
  210601. else
  210602. inputGuids.add (0);
  210603. }
  210604. return TRUE;
  210605. }
  210606. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  210607. {
  210608. return ((DSoundAudioIODeviceType*) object)
  210609. ->inputEnumProc (lpGUID, String (description));
  210610. }
  210611. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  210612. {
  210613. return ((DSoundAudioIODeviceType*) object)
  210614. ->inputEnumProc (lpGUID, String (description));
  210615. }
  210616. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  210617. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  210618. };
  210619. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  210620. const BitArray& outputChannels,
  210621. double sampleRate_,
  210622. int bufferSizeSamples_)
  210623. {
  210624. closeDevice();
  210625. totalSamplesOut = 0;
  210626. sampleRate = sampleRate_;
  210627. if (bufferSizeSamples_ <= 0)
  210628. bufferSizeSamples_ = 960; // use as a default size if none is set.
  210629. bufferSizeSamples = bufferSizeSamples_ & ~7;
  210630. DSoundAudioIODeviceType dlh;
  210631. dlh.scanForDevices();
  210632. enabledInputs = inputChannels;
  210633. enabledInputs.setRange (inChannels.size(),
  210634. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  210635. false);
  210636. numInputBuffers = enabledInputs.countNumberOfSetBits();
  210637. inputBuffers = new float* [numInputBuffers + 2];
  210638. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  210639. int i, numIns = 0;
  210640. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  210641. {
  210642. float* left = 0;
  210643. float* right = 0;
  210644. if (enabledInputs[i])
  210645. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210646. if (enabledInputs[i + 1])
  210647. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210648. if (left != 0 || right != 0)
  210649. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  210650. dlh.inputGuids [inputDeviceIndex],
  210651. (int) sampleRate, bufferSizeSamples,
  210652. left, right));
  210653. }
  210654. enabledOutputs = outputChannels;
  210655. enabledOutputs.setRange (outChannels.size(),
  210656. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  210657. false);
  210658. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  210659. outputBuffers = new float* [numOutputBuffers + 2];
  210660. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  210661. int numOuts = 0;
  210662. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  210663. {
  210664. float* left = 0;
  210665. float* right = 0;
  210666. if (enabledOutputs[i])
  210667. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210668. if (enabledOutputs[i + 1])
  210669. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  210670. if (left != 0 || right != 0)
  210671. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  210672. dlh.outputGuids [outputDeviceIndex],
  210673. (int) sampleRate, bufferSizeSamples,
  210674. left, right));
  210675. }
  210676. String error;
  210677. // boost our priority while opening the devices to try to get better sync between them
  210678. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  210679. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  210680. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  210681. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  210682. for (i = 0; i < outChans.size(); ++i)
  210683. {
  210684. error = outChans[i]->open();
  210685. if (error.isNotEmpty())
  210686. {
  210687. error = T("Error opening ") + dlh.outputDeviceNames[i]
  210688. + T(": \"") + error + T("\"");
  210689. break;
  210690. }
  210691. }
  210692. if (error.isEmpty())
  210693. {
  210694. for (i = 0; i < inChans.size(); ++i)
  210695. {
  210696. error = inChans[i]->open();
  210697. if (error.isNotEmpty())
  210698. {
  210699. error = T("Error opening ") + dlh.inputDeviceNames[i]
  210700. + T(": \"") + error + T("\"");
  210701. break;
  210702. }
  210703. }
  210704. }
  210705. if (error.isEmpty())
  210706. {
  210707. totalSamplesOut = 0;
  210708. for (i = 0; i < outChans.size(); ++i)
  210709. outChans.getUnchecked(i)->synchronisePosition();
  210710. for (i = 0; i < inChans.size(); ++i)
  210711. inChans.getUnchecked(i)->synchronisePosition();
  210712. startThread (9);
  210713. sleep (10);
  210714. notify();
  210715. }
  210716. else
  210717. {
  210718. log (error);
  210719. }
  210720. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  210721. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  210722. return error;
  210723. }
  210724. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  210725. {
  210726. return new DSoundAudioIODeviceType();
  210727. }
  210728. #undef log
  210729. #endif
  210730. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  210731. /********* Start of inlined file: juce_win32_WASAPI.cpp *********/
  210732. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210733. // compiled on its own).
  210734. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  210735. #if 1
  210736. const String getAudioErrorDesc (HRESULT hr)
  210737. {
  210738. const char* e = 0;
  210739. switch (hr)
  210740. {
  210741. case E_POINTER: e = "E_POINTER"; break;
  210742. case E_INVALIDARG: e = "E_INVALIDARG"; break;
  210743. case AUDCLNT_E_NOT_INITIALIZED: e = "AUDCLNT_E_NOT_INITIALIZED"; break;
  210744. case AUDCLNT_E_ALREADY_INITIALIZED: e = "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  210745. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e = "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  210746. case AUDCLNT_E_DEVICE_INVALIDATED: e = "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  210747. case AUDCLNT_E_NOT_STOPPED: e = "AUDCLNT_E_NOT_STOPPED"; break;
  210748. case AUDCLNT_E_BUFFER_TOO_LARGE: e = "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  210749. case AUDCLNT_E_OUT_OF_ORDER: e = "AUDCLNT_E_OUT_OF_ORDER"; break;
  210750. case AUDCLNT_E_UNSUPPORTED_FORMAT: e = "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  210751. case AUDCLNT_E_INVALID_SIZE: e = "AUDCLNT_E_INVALID_SIZE"; break;
  210752. case AUDCLNT_E_DEVICE_IN_USE: e = "AUDCLNT_E_DEVICE_IN_USE"; break;
  210753. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e = "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  210754. case AUDCLNT_E_THREAD_NOT_REGISTERED: e = "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  210755. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  210756. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e = "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  210757. case AUDCLNT_E_SERVICE_NOT_RUNNING: e = "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  210758. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  210759. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  210760. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  210761. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e = "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  210762. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e = "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  210763. case AUDCLNT_E_BUFFER_SIZE_ERROR: e = "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  210764. case AUDCLNT_S_BUFFER_EMPTY: e = "AUDCLNT_S_BUFFER_EMPTY"; break;
  210765. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e = "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  210766. default: return String::toHexString ((int) hr);
  210767. }
  210768. return e;
  210769. }
  210770. #define logFailure(hr) { if (FAILED (hr)) { DBG ("WASAPI FAIL! " + getAudioErrorDesc (hr)); jassertfalse } }
  210771. #define OK(a) wasapi_checkResult(a)
  210772. static bool wasapi_checkResult (HRESULT hr)
  210773. {
  210774. logFailure (hr);
  210775. return SUCCEEDED (hr);
  210776. }
  210777. #else
  210778. #define logFailure(hr) {}
  210779. #define OK(a) SUCCEEDED(a)
  210780. #endif
  210781. static const String wasapi_getDeviceID (IMMDevice* const device)
  210782. {
  210783. String s;
  210784. WCHAR* deviceId = 0;
  210785. if (OK (device->GetId (&deviceId)))
  210786. {
  210787. s = String (deviceId);
  210788. CoTaskMemFree (deviceId);
  210789. }
  210790. return s;
  210791. }
  210792. static EDataFlow wasapi_getDataFlow (IMMDevice* const device)
  210793. {
  210794. EDataFlow flow = eRender;
  210795. ComSmartPtr <IMMEndpoint> endPoint;
  210796. if (OK (device->QueryInterface (__uuidof (IMMEndpoint), (void**) &endPoint)))
  210797. (void) OK (endPoint->GetDataFlow (&flow));
  210798. return flow;
  210799. }
  210800. static int wasapi_refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  210801. {
  210802. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  210803. }
  210804. static void wasapi_copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  210805. {
  210806. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  210807. : sizeof (WAVEFORMATEX));
  210808. }
  210809. class WASAPIDeviceBase
  210810. {
  210811. public:
  210812. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
  210813. : device (device_),
  210814. sampleRate (0),
  210815. numChannels (0),
  210816. actualNumChannels (0),
  210817. defaultSampleRate (0),
  210818. minBufferSize (0),
  210819. defaultBufferSize (0),
  210820. latencySamples (0)
  210821. {
  210822. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  210823. ComSmartPtr <IAudioClient> tempClient (createClient());
  210824. if (tempClient == 0)
  210825. return;
  210826. REFERENCE_TIME defaultPeriod, minPeriod;
  210827. if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  210828. return;
  210829. WAVEFORMATEX* mixFormat = 0;
  210830. if (! OK (tempClient->GetMixFormat (&mixFormat)))
  210831. return;
  210832. WAVEFORMATEXTENSIBLE format;
  210833. wasapi_copyWavFormat (format, mixFormat);
  210834. CoTaskMemFree (mixFormat);
  210835. actualNumChannels = numChannels = format.Format.nChannels;
  210836. defaultSampleRate = format.Format.nSamplesPerSec;
  210837. minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
  210838. defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);
  210839. FloatElementComparator<double> comparator;
  210840. rates.addSorted (comparator, defaultSampleRate);
  210841. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  210842. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  210843. {
  210844. if (ratesToTest[i] == defaultSampleRate)
  210845. continue;
  210846. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  210847. if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
  210848. if (! rates.contains (ratesToTest[i]))
  210849. rates.addSorted (comparator, ratesToTest[i]);
  210850. }
  210851. }
  210852. ~WASAPIDeviceBase()
  210853. {
  210854. device = 0;
  210855. CloseHandle (clientEvent);
  210856. }
  210857. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  210858. bool openClient (const double newSampleRate, const BitArray& newChannels)
  210859. {
  210860. sampleRate = newSampleRate;
  210861. channels = newChannels;
  210862. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  210863. numChannels = channels.getHighestBit() + 1;
  210864. if (numChannels == 0)
  210865. return true;
  210866. client = createClient();
  210867. if (client != 0
  210868. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  210869. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  210870. {
  210871. channelMaps.clear();
  210872. for (int i = 0; i <= channels.getHighestBit(); ++i)
  210873. if (channels[i])
  210874. channelMaps.add (i);
  210875. REFERENCE_TIME latency;
  210876. if (OK (client->GetStreamLatency (&latency)))
  210877. latencySamples = wasapi_refTimeToSamples (latency, sampleRate);
  210878. (void) OK (client->GetBufferSize (&actualBufferSize));
  210879. return OK (client->SetEventHandle (clientEvent));
  210880. }
  210881. return false;
  210882. }
  210883. void closeClient()
  210884. {
  210885. if (client != 0)
  210886. client->Stop();
  210887. client = 0;
  210888. ResetEvent (clientEvent);
  210889. }
  210890. ComSmartPtr <IMMDevice> device;
  210891. ComSmartPtr <IAudioClient> client;
  210892. double sampleRate, defaultSampleRate;
  210893. int numChannels, actualNumChannels;
  210894. int minBufferSize, defaultBufferSize, latencySamples;
  210895. Array <double> rates;
  210896. HANDLE clientEvent;
  210897. BitArray channels;
  210898. AudioDataConverters::DataFormat dataFormat;
  210899. Array <int> channelMaps;
  210900. UINT32 actualBufferSize;
  210901. int bytesPerSample;
  210902. private:
  210903. const ComSmartPtr <IAudioClient> createClient()
  210904. {
  210905. ComSmartPtr <IAudioClient> client;
  210906. if (device != 0)
  210907. {
  210908. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) &client);
  210909. logFailure (hr);
  210910. }
  210911. return client;
  210912. }
  210913. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  210914. {
  210915. WAVEFORMATEXTENSIBLE format;
  210916. zerostruct (format);
  210917. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  210918. {
  210919. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  210920. }
  210921. else
  210922. {
  210923. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  210924. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  210925. }
  210926. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  210927. format.Format.nChannels = (WORD) numChannels;
  210928. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  210929. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  210930. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  210931. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  210932. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  210933. switch (numChannels)
  210934. {
  210935. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  210936. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  210937. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210938. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  210939. 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;
  210940. default: break;
  210941. }
  210942. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  210943. HRESULT hr = client->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, (WAVEFORMATEX**) &nearestFormat);
  210944. logFailure (hr);
  210945. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  210946. {
  210947. wasapi_copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  210948. hr = S_OK;
  210949. }
  210950. CoTaskMemFree (nearestFormat);
  210951. GUID session;
  210952. if (hr == S_OK
  210953. && OK (client->Initialize (AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  210954. 0, 0, (WAVEFORMATEX*) &format, &session)))
  210955. {
  210956. actualNumChannels = format.Format.nChannels;
  210957. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  210958. bytesPerSample = format.Format.wBitsPerSample / 8;
  210959. dataFormat = isFloat ? AudioDataConverters::float32LE
  210960. : (bytesPerSample == 4 ? AudioDataConverters::int32LE
  210961. : ((bytesPerSample == 3 ? AudioDataConverters::int24LE
  210962. : AudioDataConverters::int16LE)));
  210963. return true;
  210964. }
  210965. return false;
  210966. }
  210967. };
  210968. class WASAPIInputDevice : public WASAPIDeviceBase
  210969. {
  210970. public:
  210971. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_)
  210972. : WASAPIDeviceBase (device_),
  210973. reservoir (1, 1)
  210974. {
  210975. }
  210976. ~WASAPIInputDevice()
  210977. {
  210978. close();
  210979. }
  210980. bool open (const double newSampleRate, const BitArray& newChannels)
  210981. {
  210982. reservoirSize = 0;
  210983. reservoirCapacity = 16384;
  210984. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  210985. return openClient (newSampleRate, newChannels)
  210986. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioCaptureClient), (void**) &captureClient)));
  210987. }
  210988. void close()
  210989. {
  210990. closeClient();
  210991. captureClient = 0;
  210992. reservoir.setSize (0);
  210993. }
  210994. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  210995. {
  210996. if (numChannels <= 0)
  210997. return;
  210998. int offset = 0;
  210999. while (bufferSize > 0)
  211000. {
  211001. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  211002. {
  211003. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  211004. for (int i = 0; i < numDestBuffers; ++i)
  211005. {
  211006. float* const dest = destBuffers[i] + offset;
  211007. const int srcChan = channelMaps.getUnchecked(i);
  211008. switch (dataFormat)
  211009. {
  211010. case AudioDataConverters::float32LE:
  211011. AudioDataConverters::convertFloat32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211012. break;
  211013. case AudioDataConverters::int32LE:
  211014. AudioDataConverters::convertInt32LEToFloat (((uint8*) reservoir.getData()) + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211015. break;
  211016. case AudioDataConverters::int24LE:
  211017. AudioDataConverters::convertInt24LEToFloat (((uint8*) reservoir.getData()) + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211018. break;
  211019. case AudioDataConverters::int16LE:
  211020. AudioDataConverters::convertInt16LEToFloat (((uint8*) reservoir.getData()) + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211021. break;
  211022. default: jassertfalse; break;
  211023. }
  211024. }
  211025. bufferSize -= samplesToDo;
  211026. offset += samplesToDo;
  211027. reservoirSize -= samplesToDo;
  211028. }
  211029. else
  211030. {
  211031. UINT32 packetLength = 0;
  211032. if (! OK (captureClient->GetNextPacketSize (&packetLength)))
  211033. break;
  211034. if (packetLength == 0)
  211035. {
  211036. if (thread.threadShouldExit())
  211037. break;
  211038. Thread::sleep (1);
  211039. continue;
  211040. }
  211041. uint8* inputData = 0;
  211042. UINT32 numSamplesAvailable;
  211043. DWORD flags;
  211044. if (OK (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  211045. {
  211046. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  211047. for (int i = 0; i < numDestBuffers; ++i)
  211048. {
  211049. float* const dest = destBuffers[i] + offset;
  211050. const int srcChan = channelMaps.getUnchecked(i);
  211051. switch (dataFormat)
  211052. {
  211053. case AudioDataConverters::float32LE:
  211054. AudioDataConverters::convertFloat32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211055. break;
  211056. case AudioDataConverters::int32LE:
  211057. AudioDataConverters::convertInt32LEToFloat (inputData + 4 * srcChan, dest, samplesToDo, 4 * actualNumChannels);
  211058. break;
  211059. case AudioDataConverters::int24LE:
  211060. AudioDataConverters::convertInt24LEToFloat (inputData + 3 * srcChan, dest, samplesToDo, 3 * actualNumChannels);
  211061. break;
  211062. case AudioDataConverters::int16LE:
  211063. AudioDataConverters::convertInt16LEToFloat (inputData + 2 * srcChan, dest, samplesToDo, 2 * actualNumChannels);
  211064. break;
  211065. default: jassertfalse; break;
  211066. }
  211067. }
  211068. bufferSize -= samplesToDo;
  211069. offset += samplesToDo;
  211070. if (samplesToDo < numSamplesAvailable)
  211071. {
  211072. reservoirSize = jmin (numSamplesAvailable - samplesToDo, reservoirCapacity);
  211073. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  211074. bytesPerSample * actualNumChannels * reservoirSize);
  211075. }
  211076. captureClient->ReleaseBuffer (numSamplesAvailable);
  211077. }
  211078. }
  211079. }
  211080. }
  211081. ComSmartPtr <IAudioCaptureClient> captureClient;
  211082. MemoryBlock reservoir;
  211083. int reservoirSize, reservoirCapacity;
  211084. };
  211085. class WASAPIOutputDevice : public WASAPIDeviceBase
  211086. {
  211087. public:
  211088. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_)
  211089. : WASAPIDeviceBase (device_)
  211090. {
  211091. }
  211092. ~WASAPIOutputDevice()
  211093. {
  211094. close();
  211095. }
  211096. bool open (const double newSampleRate, const BitArray& newChannels)
  211097. {
  211098. return openClient (newSampleRate, newChannels)
  211099. && (numChannels == 0 || OK (client->GetService (__uuidof (IAudioRenderClient), (void**) &renderClient)));
  211100. }
  211101. void close()
  211102. {
  211103. closeClient();
  211104. renderClient = 0;
  211105. }
  211106. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  211107. {
  211108. if (numChannels <= 0)
  211109. return;
  211110. int offset = 0;
  211111. while (bufferSize > 0)
  211112. {
  211113. UINT32 padding = 0;
  211114. if (! OK (client->GetCurrentPadding (&padding)))
  211115. return;
  211116. const int samplesToDo = jmin ((int) (actualBufferSize - padding), bufferSize);
  211117. if (samplesToDo <= 0)
  211118. {
  211119. if (thread.threadShouldExit())
  211120. break;
  211121. Thread::sleep (0);
  211122. continue;
  211123. }
  211124. uint8* outputData = 0;
  211125. if (OK (renderClient->GetBuffer (samplesToDo, &outputData)))
  211126. {
  211127. for (int i = 0; i < numSrcBuffers; ++i)
  211128. {
  211129. const float* const source = srcBuffers[i] + offset;
  211130. const int destChan = channelMaps.getUnchecked(i);
  211131. switch (dataFormat)
  211132. {
  211133. case AudioDataConverters::float32LE:
  211134. AudioDataConverters::convertFloatToFloat32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211135. break;
  211136. case AudioDataConverters::int32LE:
  211137. AudioDataConverters::convertFloatToInt32LE (source, outputData + 4 * destChan, samplesToDo, 4 * actualNumChannels);
  211138. break;
  211139. case AudioDataConverters::int24LE:
  211140. AudioDataConverters::convertFloatToInt24LE (source, outputData + 3 * destChan, samplesToDo, 3 * actualNumChannels);
  211141. break;
  211142. case AudioDataConverters::int16LE:
  211143. AudioDataConverters::convertFloatToInt16LE (source, outputData + 2 * destChan, samplesToDo, 2 * actualNumChannels);
  211144. break;
  211145. default: jassertfalse; break;
  211146. }
  211147. }
  211148. renderClient->ReleaseBuffer (samplesToDo, 0);
  211149. offset += samplesToDo;
  211150. bufferSize -= samplesToDo;
  211151. }
  211152. }
  211153. }
  211154. ComSmartPtr <IAudioRenderClient> renderClient;
  211155. };
  211156. class WASAPIAudioIODevice : public AudioIODevice,
  211157. public Thread
  211158. {
  211159. public:
  211160. WASAPIAudioIODevice (const String& deviceName,
  211161. const String& outputDeviceId_,
  211162. const String& inputDeviceId_)
  211163. : AudioIODevice (deviceName, "Windows Audio"),
  211164. Thread ("Juce WASAPI"),
  211165. isOpen_ (false),
  211166. isStarted (false),
  211167. outputDevice (0),
  211168. outputDeviceId (outputDeviceId_),
  211169. inputDevice (0),
  211170. inputDeviceId (inputDeviceId_),
  211171. currentBufferSizeSamples (0),
  211172. currentSampleRate (0),
  211173. callback (0)
  211174. {
  211175. }
  211176. ~WASAPIAudioIODevice()
  211177. {
  211178. close();
  211179. deleteAndZero (inputDevice);
  211180. deleteAndZero (outputDevice);
  211181. }
  211182. bool initialise()
  211183. {
  211184. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  211185. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  211186. latencyIn = latencyOut = 0;
  211187. Array <double> ratesIn, ratesOut;
  211188. if (createDevices())
  211189. {
  211190. jassert (inputDevice != 0 || outputDevice != 0);
  211191. if (inputDevice != 0 && outputDevice != 0)
  211192. {
  211193. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  211194. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  211195. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  211196. sampleRates = inputDevice->rates;
  211197. sampleRates.removeValuesNotIn (outputDevice->rates);
  211198. jassert (sampleRates.size() > 0); // in and out devices don't share any common sample rates!
  211199. }
  211200. else
  211201. {
  211202. WASAPIDeviceBase* const d = inputDevice != 0 ? (WASAPIDeviceBase*) inputDevice : (WASAPIDeviceBase*) outputDevice;
  211203. defaultSampleRate = d->defaultSampleRate;
  211204. minBufferSize = d->minBufferSize;
  211205. defaultBufferSize = d->defaultBufferSize;
  211206. sampleRates = d->rates;
  211207. }
  211208. IntegerElementComparator<int> comparator;
  211209. bufferSizes.addSorted (comparator, defaultBufferSize);
  211210. if (minBufferSize != defaultBufferSize)
  211211. bufferSizes.addSorted (comparator, minBufferSize);
  211212. int n = 64;
  211213. for (int i = 0; i < 40; ++i)
  211214. {
  211215. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  211216. bufferSizes.addSorted (comparator, n);
  211217. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  211218. }
  211219. return true;
  211220. }
  211221. return false;
  211222. }
  211223. const StringArray getOutputChannelNames()
  211224. {
  211225. StringArray outChannels;
  211226. if (outputDevice != 0)
  211227. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  211228. outChannels.add ("Output channel " + String (i));
  211229. return outChannels;
  211230. }
  211231. const StringArray getInputChannelNames()
  211232. {
  211233. StringArray inChannels;
  211234. if (inputDevice != 0)
  211235. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  211236. inChannels.add ("Input channel " + String (i));
  211237. return inChannels;
  211238. }
  211239. int getNumSampleRates() { return sampleRates.size(); }
  211240. double getSampleRate (int index) { return sampleRates [index]; }
  211241. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  211242. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  211243. int getDefaultBufferSize() { return defaultBufferSize; }
  211244. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  211245. double getCurrentSampleRate() { return currentSampleRate; }
  211246. int getCurrentBitDepth() { return 32; }
  211247. int getOutputLatencyInSamples() { return latencyOut; }
  211248. int getInputLatencyInSamples() { return latencyIn; }
  211249. const BitArray getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BitArray(); }
  211250. const BitArray getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BitArray(); }
  211251. const String getLastError() { return lastError; }
  211252. const String open (const BitArray& inputChannels, const BitArray& outputChannels,
  211253. double sampleRate, int bufferSizeSamples)
  211254. {
  211255. close();
  211256. lastError = String::empty;
  211257. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  211258. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  211259. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  211260. {
  211261. lastError = "Couldn't open the input device!";
  211262. return lastError;
  211263. }
  211264. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  211265. {
  211266. close();
  211267. lastError = "Couldn't open the output device!";
  211268. return lastError;
  211269. }
  211270. if (inputDevice != 0)
  211271. ResetEvent (inputDevice->clientEvent);
  211272. if (outputDevice != 0)
  211273. ResetEvent (outputDevice->clientEvent);
  211274. startThread (8);
  211275. Thread::sleep (5);
  211276. if (inputDevice != 0 && inputDevice->client != 0)
  211277. {
  211278. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  211279. HRESULT hr = inputDevice->client->Start();
  211280. logFailure (hr); //xxx handle this
  211281. }
  211282. if (outputDevice != 0 && outputDevice->client != 0)
  211283. {
  211284. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  211285. HRESULT hr = outputDevice->client->Start();
  211286. logFailure (hr); //xxx handle this
  211287. }
  211288. isOpen_ = true;
  211289. return lastError;
  211290. }
  211291. void close()
  211292. {
  211293. stop();
  211294. if (inputDevice != 0)
  211295. SetEvent (inputDevice->clientEvent);
  211296. if (outputDevice != 0)
  211297. SetEvent (outputDevice->clientEvent);
  211298. stopThread (5000);
  211299. if (inputDevice != 0)
  211300. inputDevice->close();
  211301. if (outputDevice != 0)
  211302. outputDevice->close();
  211303. isOpen_ = false;
  211304. }
  211305. bool isOpen() { return isOpen_ && isThreadRunning(); }
  211306. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  211307. void start (AudioIODeviceCallback* call)
  211308. {
  211309. if (isOpen_ && call != 0 && ! isStarted)
  211310. {
  211311. if (! isThreadRunning())
  211312. {
  211313. // something's gone wrong and the thread's stopped..
  211314. isOpen_ = false;
  211315. return;
  211316. }
  211317. call->audioDeviceAboutToStart (this);
  211318. const ScopedLock sl (startStopLock);
  211319. callback = call;
  211320. isStarted = true;
  211321. }
  211322. }
  211323. void stop()
  211324. {
  211325. if (isStarted)
  211326. {
  211327. AudioIODeviceCallback* const callbackLocal = callback;
  211328. {
  211329. const ScopedLock sl (startStopLock);
  211330. isStarted = false;
  211331. }
  211332. if (callbackLocal != 0)
  211333. callbackLocal->audioDeviceStopped();
  211334. }
  211335. }
  211336. void run()
  211337. {
  211338. const int bufferSize = currentBufferSizeSamples;
  211339. HANDLE events[2];
  211340. int numEvents = 0;
  211341. if (inputDevice != 0)
  211342. events [numEvents++] = inputDevice->clientEvent;
  211343. if (outputDevice != 0)
  211344. events [numEvents++] = outputDevice->clientEvent;
  211345. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  211346. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  211347. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  211348. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  211349. float** const inputBuffers = ins.getArrayOfChannels();
  211350. float** const outputBuffers = outs.getArrayOfChannels();
  211351. ins.clear();
  211352. while (! threadShouldExit())
  211353. {
  211354. const DWORD result = WaitForMultipleObjects (numEvents, events, true, 1000);
  211355. if (result == WAIT_TIMEOUT)
  211356. continue;
  211357. if (threadShouldExit())
  211358. break;
  211359. if (inputDevice != 0)
  211360. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  211361. // Make the callback..
  211362. {
  211363. const ScopedLock sl (startStopLock);
  211364. if (isStarted)
  211365. {
  211366. JUCE_TRY
  211367. {
  211368. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  211369. numInputBuffers,
  211370. outputBuffers,
  211371. numOutputBuffers,
  211372. bufferSize);
  211373. }
  211374. JUCE_CATCH_EXCEPTION
  211375. }
  211376. else
  211377. {
  211378. outs.clear();
  211379. }
  211380. }
  211381. if (outputDevice != 0)
  211382. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  211383. }
  211384. }
  211385. juce_UseDebuggingNewOperator
  211386. String outputDeviceId, inputDeviceId;
  211387. String lastError;
  211388. private:
  211389. // Device stats...
  211390. WASAPIInputDevice* inputDevice;
  211391. WASAPIOutputDevice* outputDevice;
  211392. double defaultSampleRate;
  211393. int minBufferSize, defaultBufferSize;
  211394. int latencyIn, latencyOut;
  211395. Array <double> sampleRates;
  211396. Array <int> bufferSizes;
  211397. // Active state...
  211398. bool isOpen_, isStarted;
  211399. int currentBufferSizeSamples;
  211400. double currentSampleRate;
  211401. AudioIODeviceCallback* callback;
  211402. CriticalSection startStopLock;
  211403. bool createDevices()
  211404. {
  211405. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211406. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211407. return false;
  211408. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211409. if (! OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection)))
  211410. return false;
  211411. UINT32 numDevices = 0;
  211412. if (! OK (deviceCollection->GetCount (&numDevices)))
  211413. return false;
  211414. for (UINT32 i = 0; i < numDevices; ++i)
  211415. {
  211416. ComSmartPtr <IMMDevice> device;
  211417. if (! OK (deviceCollection->Item (i, &device)))
  211418. continue;
  211419. const String deviceId (wasapi_getDeviceID (device));
  211420. if (deviceId.isEmpty())
  211421. continue;
  211422. const EDataFlow flow = wasapi_getDataFlow (device);
  211423. if (deviceId == inputDeviceId && flow == eCapture)
  211424. inputDevice = new WASAPIInputDevice (device);
  211425. else if (deviceId == outputDeviceId && flow == eRender)
  211426. outputDevice = new WASAPIOutputDevice (device);
  211427. }
  211428. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  211429. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  211430. }
  211431. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  211432. const WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  211433. };
  211434. class WASAPIAudioIODeviceType : public AudioIODeviceType
  211435. {
  211436. public:
  211437. WASAPIAudioIODeviceType()
  211438. : AudioIODeviceType (T("Windows Audio")),
  211439. hasScanned (false)
  211440. {
  211441. }
  211442. ~WASAPIAudioIODeviceType()
  211443. {
  211444. }
  211445. void scanForDevices()
  211446. {
  211447. hasScanned = true;
  211448. outputDeviceNames.clear();
  211449. inputDeviceNames.clear();
  211450. outputDeviceIds.clear();
  211451. inputDeviceIds.clear();
  211452. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  211453. if (! OK (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator), CLSCTX_INPROC_SERVER)))
  211454. return;
  211455. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  211456. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  211457. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  211458. UINT32 numDevices = 0;
  211459. if (! (OK (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, &deviceCollection))
  211460. && OK (deviceCollection->GetCount (&numDevices))))
  211461. return;
  211462. for (UINT32 i = 0; i < numDevices; ++i)
  211463. {
  211464. ComSmartPtr <IMMDevice> device;
  211465. if (! OK (deviceCollection->Item (i, &device)))
  211466. continue;
  211467. const String deviceId (wasapi_getDeviceID (device));
  211468. DWORD state = 0;
  211469. if (! OK (device->GetState (&state)))
  211470. continue;
  211471. if (state != DEVICE_STATE_ACTIVE)
  211472. continue;
  211473. String name;
  211474. {
  211475. ComSmartPtr <IPropertyStore> properties;
  211476. if (! OK (device->OpenPropertyStore (STGM_READ, &properties)))
  211477. continue;
  211478. PROPVARIANT value;
  211479. PropVariantInit (&value);
  211480. if (OK (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  211481. name = value.pwszVal;
  211482. PropVariantClear (&value);
  211483. }
  211484. const EDataFlow flow = wasapi_getDataFlow (device);
  211485. if (flow == eRender)
  211486. {
  211487. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  211488. outputDeviceIds.insert (index, deviceId);
  211489. outputDeviceNames.insert (index, name);
  211490. }
  211491. else if (flow == eCapture)
  211492. {
  211493. const int index = (deviceId == defaultCapture) ? 0 : -1;
  211494. inputDeviceIds.insert (index, deviceId);
  211495. inputDeviceNames.insert (index, name);
  211496. }
  211497. }
  211498. }
  211499. const StringArray getDeviceNames (const bool wantInputNames) const
  211500. {
  211501. jassert (hasScanned); // need to call scanForDevices() before doing this
  211502. return wantInputNames ? inputDeviceNames
  211503. : outputDeviceNames;
  211504. }
  211505. int getDefaultDeviceIndex (const bool /*forInput*/) const
  211506. {
  211507. jassert (hasScanned); // need to call scanForDevices() before doing this
  211508. return 0;
  211509. }
  211510. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  211511. {
  211512. jassert (hasScanned); // need to call scanForDevices() before doing this
  211513. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  211514. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  211515. : outputDeviceIds.indexOf (d->outputDeviceId));
  211516. }
  211517. bool hasSeparateInputsAndOutputs() const { return true; }
  211518. AudioIODevice* createDevice (const String& outputDeviceName,
  211519. const String& inputDeviceName)
  211520. {
  211521. jassert (hasScanned); // need to call scanForDevices() before doing this
  211522. WASAPIAudioIODevice* d = 0;
  211523. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  211524. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  211525. if (outputIndex >= 0 || inputIndex >= 0)
  211526. {
  211527. d = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  211528. : inputDeviceName,
  211529. outputDeviceIds [outputIndex],
  211530. inputDeviceIds [inputIndex]);
  211531. if (! d->initialise())
  211532. deleteAndZero (d);
  211533. }
  211534. return d;
  211535. }
  211536. juce_UseDebuggingNewOperator
  211537. StringArray outputDeviceNames, outputDeviceIds;
  211538. StringArray inputDeviceNames, inputDeviceIds;
  211539. private:
  211540. bool hasScanned;
  211541. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  211542. {
  211543. String s;
  211544. IMMDevice* dev = 0;
  211545. if (OK (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  211546. eMultimedia, &dev)))
  211547. {
  211548. WCHAR* deviceId = 0;
  211549. if (OK (dev->GetId (&deviceId)))
  211550. {
  211551. s = String (deviceId);
  211552. CoTaskMemFree (deviceId);
  211553. }
  211554. dev->Release();
  211555. }
  211556. return s;
  211557. }
  211558. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  211559. const WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  211560. };
  211561. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  211562. {
  211563. return new WASAPIAudioIODeviceType();
  211564. }
  211565. #undef logFailure
  211566. #undef OK
  211567. #endif
  211568. /********* End of inlined file: juce_win32_WASAPI.cpp *********/
  211569. /********* Start of inlined file: juce_win32_CameraDevice.cpp *********/
  211570. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  211571. // compiled on its own).
  211572. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  211573. class DShowCameraDeviceInteral : public ChangeBroadcaster
  211574. {
  211575. public:
  211576. DShowCameraDeviceInteral (CameraDevice* const owner_,
  211577. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  211578. const ComSmartPtr <IBaseFilter>& filter_,
  211579. int minWidth, int minHeight,
  211580. int maxWidth, int maxHeight)
  211581. : owner (owner_),
  211582. captureGraphBuilder (captureGraphBuilder_),
  211583. filter (filter_),
  211584. ok (false),
  211585. imageNeedsFlipping (false),
  211586. width (0),
  211587. height (0),
  211588. activeUsers (0),
  211589. recordNextFrameTime (false)
  211590. {
  211591. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph, CLSCTX_INPROC);
  211592. if (FAILED (hr))
  211593. return;
  211594. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  211595. if (FAILED (hr))
  211596. return;
  211597. hr = graphBuilder->QueryInterface (IID_IMediaControl, (void**) &mediaControl);
  211598. if (FAILED (hr))
  211599. return;
  211600. {
  211601. ComSmartPtr <IAMStreamConfig> streamConfig;
  211602. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE,
  211603. 0,
  211604. filter,
  211605. IID_IAMStreamConfig,
  211606. (void**) &streamConfig);
  211607. if (streamConfig != 0)
  211608. {
  211609. getVideoSizes (streamConfig);
  211610. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  211611. return;
  211612. }
  211613. }
  211614. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  211615. if (FAILED (hr))
  211616. return;
  211617. hr = smartTee.CoCreateInstance (CLSID_SmartTee, CLSCTX_INPROC_SERVER);
  211618. if (FAILED (hr))
  211619. return;
  211620. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  211621. if (FAILED (hr))
  211622. return;
  211623. if (! connectFilters (filter, smartTee))
  211624. return;
  211625. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  211626. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber, CLSCTX_INPROC_SERVER);
  211627. if (FAILED (hr))
  211628. return;
  211629. hr = sampleGrabberBase->QueryInterface (IID_ISampleGrabber, (void**) &sampleGrabber);
  211630. if (FAILED (hr))
  211631. return;
  211632. AM_MEDIA_TYPE mt;
  211633. zerostruct (mt);
  211634. mt.majortype = MEDIATYPE_Video;
  211635. mt.subtype = MEDIASUBTYPE_RGB24;
  211636. mt.formattype = FORMAT_VideoInfo;
  211637. sampleGrabber->SetMediaType (&mt);
  211638. callback = new GrabberCallback (*this);
  211639. sampleGrabber->SetCallback (callback, 1);
  211640. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  211641. if (FAILED (hr))
  211642. return;
  211643. ComSmartPtr <IPin> grabberInputPin;
  211644. if (! (getPin (smartTee, PINDIR_OUTPUT, &smartTeeCaptureOutputPin, "capture")
  211645. && getPin (smartTee, PINDIR_OUTPUT, &smartTeePreviewOutputPin, "preview")
  211646. && getPin (sampleGrabberBase, PINDIR_INPUT, &grabberInputPin)))
  211647. return;
  211648. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  211649. if (FAILED (hr))
  211650. return;
  211651. zerostruct (mt);
  211652. hr = sampleGrabber->GetConnectedMediaType (&mt);
  211653. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  211654. width = pVih->bmiHeader.biWidth;
  211655. height = pVih->bmiHeader.biHeight;
  211656. ComSmartPtr <IBaseFilter> nullFilter;
  211657. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer, CLSCTX_INPROC_SERVER);
  211658. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  211659. if (connectFilters (sampleGrabberBase, nullFilter)
  211660. && addGraphToRot())
  211661. {
  211662. activeImage = new Image (Image::RGB, width, height, true);
  211663. loadingImage = new Image (Image::RGB, width, height, true);
  211664. ok = true;
  211665. }
  211666. }
  211667. ~DShowCameraDeviceInteral()
  211668. {
  211669. mediaControl->Stop();
  211670. removeGraphFromRot();
  211671. for (int i = viewerComps.size(); --i >= 0;)
  211672. ((DShowCaptureViewerComp*) viewerComps.getUnchecked(i))->ownerDeleted();
  211673. callback = 0;
  211674. graphBuilder = 0;
  211675. sampleGrabber = 0;
  211676. mediaControl = 0;
  211677. filter = 0;
  211678. captureGraphBuilder = 0;
  211679. smartTee = 0;
  211680. smartTeePreviewOutputPin = 0;
  211681. smartTeeCaptureOutputPin = 0;
  211682. mux = 0;
  211683. fileWriter = 0;
  211684. delete activeImage;
  211685. delete loadingImage;
  211686. }
  211687. void addUser()
  211688. {
  211689. if (ok && activeUsers++ == 0)
  211690. mediaControl->Run();
  211691. }
  211692. void removeUser()
  211693. {
  211694. if (ok && --activeUsers == 0)
  211695. mediaControl->Stop();
  211696. }
  211697. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  211698. {
  211699. if (recordNextFrameTime)
  211700. {
  211701. firstRecordedTime = Time::getCurrentTime();
  211702. recordNextFrameTime = false;
  211703. }
  211704. imageSwapLock.enter();
  211705. int ls, ps;
  211706. const int lineStride = width * 3;
  211707. uint8* const dest = loadingImage->lockPixelDataReadWrite (0, 0, width, height, ls, ps);
  211708. for (int i = 0; i < height; ++i)
  211709. memcpy (dest + ls * ((height - 1) - i),
  211710. buffer + lineStride * i,
  211711. lineStride);
  211712. loadingImage->releasePixelDataReadWrite (dest);
  211713. imageNeedsFlipping = true;
  211714. imageSwapLock.exit();
  211715. callListeners (*loadingImage);
  211716. sendChangeMessage (this);
  211717. }
  211718. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  211719. {
  211720. if (imageNeedsFlipping)
  211721. {
  211722. imageSwapLock.enter();
  211723. swapVariables (loadingImage, activeImage);
  211724. imageNeedsFlipping = false;
  211725. imageSwapLock.exit();
  211726. }
  211727. RectanglePlacement rp (RectanglePlacement::centred);
  211728. double dx = 0, dy = 0, dw = width, dh = height;
  211729. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  211730. const int rx = roundDoubleToInt (dx), ry = roundDoubleToInt (dy);
  211731. const int rw = roundDoubleToInt (dw), rh = roundDoubleToInt (dh);
  211732. g.saveState();
  211733. g.excludeClipRegion (rx, ry, rw, rh);
  211734. g.fillAll (Colours::black);
  211735. g.restoreState();
  211736. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  211737. }
  211738. bool createFileCaptureFilter (const File& file)
  211739. {
  211740. removeFileCaptureFilter();
  211741. file.deleteFile();
  211742. mediaControl->Stop();
  211743. firstRecordedTime = Time();
  211744. recordNextFrameTime = true;
  211745. HRESULT hr = mux.CoCreateInstance (CLSID_AviDest, CLSCTX_INPROC_SERVER);
  211746. if (SUCCEEDED (hr))
  211747. {
  211748. hr = graphBuilder->AddFilter (mux, _T("AVI Mux"));
  211749. if (SUCCEEDED (hr))
  211750. {
  211751. fileWriter.CoCreateInstance (CLSID_FileWriter, CLSCTX_INPROC_SERVER);
  211752. if (SUCCEEDED (hr))
  211753. {
  211754. ComSmartPtr <IFileSinkFilter> fileSink;
  211755. hr = fileWriter->QueryInterface (IID_IFileSinkFilter, (void**) &fileSink);
  211756. if (SUCCEEDED (hr))
  211757. {
  211758. AM_MEDIA_TYPE mt;
  211759. zerostruct (mt);
  211760. mt.majortype = MEDIATYPE_Stream;
  211761. mt.subtype = MEDIASUBTYPE_Avi;
  211762. mt.formattype = FORMAT_VideoInfo;
  211763. hr = fileSink->SetFileName (file.getFullPathName(), &mt);
  211764. if (SUCCEEDED (hr))
  211765. {
  211766. hr = graphBuilder->AddFilter (fileWriter, _T("File Writer"));
  211767. if (SUCCEEDED (hr))
  211768. {
  211769. ComSmartPtr <IPin> muxInputPin, muxOutputPin, writerInput;
  211770. if (getPin (mux, PINDIR_INPUT, &muxInputPin)
  211771. && getPin (mux, PINDIR_OUTPUT, &muxOutputPin)
  211772. && getPin (fileWriter, PINDIR_INPUT, &writerInput))
  211773. {
  211774. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, muxInputPin);
  211775. if (SUCCEEDED (hr))
  211776. {
  211777. hr = graphBuilder->Connect (muxOutputPin, writerInput);
  211778. if (SUCCEEDED (hr))
  211779. {
  211780. if (ok && activeUsers > 0)
  211781. mediaControl->Run();
  211782. return true;
  211783. }
  211784. }
  211785. }
  211786. }
  211787. }
  211788. }
  211789. }
  211790. }
  211791. }
  211792. removeFileCaptureFilter();
  211793. if (ok && activeUsers > 0)
  211794. mediaControl->Run();
  211795. return false;
  211796. }
  211797. void removeFileCaptureFilter()
  211798. {
  211799. mediaControl->Stop();
  211800. if (mux != 0)
  211801. {
  211802. graphBuilder->RemoveFilter (mux);
  211803. mux = 0;
  211804. }
  211805. if (fileWriter != 0)
  211806. {
  211807. graphBuilder->RemoveFilter (fileWriter);
  211808. fileWriter = 0;
  211809. }
  211810. if (ok && activeUsers > 0)
  211811. mediaControl->Run();
  211812. }
  211813. void addListener (CameraImageListener* listenerToAdd)
  211814. {
  211815. const ScopedLock sl (listenerLock);
  211816. if (listeners.size() == 0)
  211817. addUser();
  211818. listeners.addIfNotAlreadyThere (listenerToAdd);
  211819. }
  211820. void removeListener (CameraImageListener* listenerToRemove)
  211821. {
  211822. const ScopedLock sl (listenerLock);
  211823. listeners.removeValue (listenerToRemove);
  211824. if (listeners.size() == 0)
  211825. removeUser();
  211826. }
  211827. void callListeners (Image& image)
  211828. {
  211829. const ScopedLock sl (listenerLock);
  211830. for (int i = listeners.size(); --i >= 0;)
  211831. {
  211832. CameraImageListener* l = (CameraImageListener*) listeners[i];
  211833. if (l != 0)
  211834. l->imageReceived (image);
  211835. }
  211836. }
  211837. class DShowCaptureViewerComp : public Component,
  211838. public ChangeListener
  211839. {
  211840. public:
  211841. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  211842. : owner (owner_)
  211843. {
  211844. setOpaque (true);
  211845. owner->addChangeListener (this);
  211846. owner->addUser();
  211847. owner->viewerComps.add (this);
  211848. setSize (owner_->width, owner_->height);
  211849. }
  211850. ~DShowCaptureViewerComp()
  211851. {
  211852. if (owner != 0)
  211853. {
  211854. owner->viewerComps.removeValue (this);
  211855. owner->removeUser();
  211856. owner->removeChangeListener (this);
  211857. }
  211858. }
  211859. void ownerDeleted()
  211860. {
  211861. owner = 0;
  211862. }
  211863. void paint (Graphics& g)
  211864. {
  211865. g.setColour (Colours::black);
  211866. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  211867. if (owner != 0)
  211868. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  211869. else
  211870. g.fillAll (Colours::black);
  211871. }
  211872. void changeListenerCallback (void*)
  211873. {
  211874. repaint();
  211875. }
  211876. private:
  211877. DShowCameraDeviceInteral* owner;
  211878. };
  211879. bool ok;
  211880. int width, height;
  211881. Time firstRecordedTime;
  211882. VoidArray viewerComps;
  211883. private:
  211884. CameraDevice* const owner;
  211885. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  211886. ComSmartPtr <IBaseFilter> filter;
  211887. ComSmartPtr <IBaseFilter> smartTee;
  211888. ComSmartPtr <IGraphBuilder> graphBuilder;
  211889. ComSmartPtr <ISampleGrabber> sampleGrabber;
  211890. ComSmartPtr <IMediaControl> mediaControl;
  211891. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  211892. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  211893. ComSmartPtr <IBaseFilter> mux, fileWriter;
  211894. int activeUsers;
  211895. Array <int> widths, heights;
  211896. DWORD graphRegistrationID;
  211897. CriticalSection imageSwapLock;
  211898. bool imageNeedsFlipping;
  211899. Image* loadingImage;
  211900. Image* activeImage;
  211901. bool recordNextFrameTime;
  211902. void getVideoSizes (IAMStreamConfig* const streamConfig)
  211903. {
  211904. widths.clear();
  211905. heights.clear();
  211906. int count = 0, size = 0;
  211907. streamConfig->GetNumberOfCapabilities (&count, &size);
  211908. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211909. {
  211910. for (int i = 0; i < count; ++i)
  211911. {
  211912. VIDEO_STREAM_CONFIG_CAPS scc;
  211913. AM_MEDIA_TYPE* config;
  211914. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211915. if (SUCCEEDED (hr))
  211916. {
  211917. const int w = scc.InputSize.cx;
  211918. const int h = scc.InputSize.cy;
  211919. bool duplicate = false;
  211920. for (int j = widths.size(); --j >= 0;)
  211921. {
  211922. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  211923. {
  211924. duplicate = true;
  211925. break;
  211926. }
  211927. }
  211928. if (! duplicate)
  211929. {
  211930. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  211931. widths.add (w);
  211932. heights.add (h);
  211933. }
  211934. deleteMediaType (config);
  211935. }
  211936. }
  211937. }
  211938. }
  211939. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  211940. const int minWidth, const int minHeight,
  211941. const int maxWidth, const int maxHeight)
  211942. {
  211943. int count = 0, size = 0;
  211944. streamConfig->GetNumberOfCapabilities (&count, &size);
  211945. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  211946. {
  211947. for (int i = 0; i < count; ++i)
  211948. {
  211949. VIDEO_STREAM_CONFIG_CAPS scc;
  211950. AM_MEDIA_TYPE* config;
  211951. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  211952. if (SUCCEEDED (hr))
  211953. {
  211954. if (scc.InputSize.cx >= minWidth
  211955. && scc.InputSize.cy >= minHeight
  211956. && scc.InputSize.cx <= maxWidth
  211957. && scc.InputSize.cy <= maxHeight)
  211958. {
  211959. hr = streamConfig->SetFormat (config);
  211960. deleteMediaType (config);
  211961. return SUCCEEDED (hr);
  211962. }
  211963. deleteMediaType (config);
  211964. }
  211965. }
  211966. }
  211967. return false;
  211968. }
  211969. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, IPin** result, const char* pinName = 0)
  211970. {
  211971. ComSmartPtr <IEnumPins> enumerator;
  211972. ComSmartPtr <IPin> pin;
  211973. filter->EnumPins (&enumerator);
  211974. while (enumerator->Next (1, &pin, 0) == S_OK)
  211975. {
  211976. PIN_DIRECTION dir;
  211977. pin->QueryDirection (&dir);
  211978. if (wantedDirection == dir)
  211979. {
  211980. PIN_INFO info;
  211981. zerostruct (info);
  211982. pin->QueryPinInfo (&info);
  211983. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  211984. {
  211985. pin.p->AddRef();
  211986. *result = pin;
  211987. return true;
  211988. }
  211989. }
  211990. }
  211991. return false;
  211992. }
  211993. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  211994. {
  211995. ComSmartPtr <IPin> in, out;
  211996. return getPin (first, PINDIR_OUTPUT, &out)
  211997. && getPin (second, PINDIR_INPUT, &in)
  211998. && SUCCEEDED (graphBuilder->Connect (out, in));
  211999. }
  212000. bool addGraphToRot()
  212001. {
  212002. ComSmartPtr <IRunningObjectTable> rot;
  212003. if (FAILED (GetRunningObjectTable (0, &rot)))
  212004. return false;
  212005. ComSmartPtr <IMoniker> moniker;
  212006. WCHAR buffer[128];
  212007. HRESULT hr = CreateItemMoniker (_T("!"), buffer, &moniker);
  212008. if (FAILED (hr))
  212009. return false;
  212010. graphRegistrationID = 0;
  212011. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  212012. }
  212013. void removeGraphFromRot()
  212014. {
  212015. ComSmartPtr <IRunningObjectTable> rot;
  212016. if (SUCCEEDED (GetRunningObjectTable (0, &rot)))
  212017. rot->Revoke (graphRegistrationID);
  212018. }
  212019. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  212020. {
  212021. if (pmt->cbFormat != 0)
  212022. CoTaskMemFree ((PVOID) pmt->pbFormat);
  212023. if (pmt->pUnk != 0)
  212024. pmt->pUnk->Release();
  212025. CoTaskMemFree (pmt);
  212026. }
  212027. class GrabberCallback : public ISampleGrabberCB
  212028. {
  212029. public:
  212030. GrabberCallback (DShowCameraDeviceInteral& owner_)
  212031. : owner (owner_)
  212032. {
  212033. }
  212034. HRESULT __stdcall QueryInterface (REFIID id, void** result)
  212035. {
  212036. if (id == IID_IUnknown)
  212037. *result = dynamic_cast <IUnknown*> (this);
  212038. else if (id == IID_ISampleGrabberCB)
  212039. *result = dynamic_cast <ISampleGrabberCB*> (this);
  212040. else
  212041. {
  212042. *result = 0;
  212043. return E_NOINTERFACE;
  212044. }
  212045. AddRef();
  212046. return S_OK;
  212047. }
  212048. ULONG __stdcall AddRef() { return ++refCount; }
  212049. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  212050. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  212051. {
  212052. return E_FAIL;
  212053. }
  212054. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  212055. {
  212056. owner.handleFrame (time, buffer, bufferSize);
  212057. return S_OK;
  212058. }
  212059. private:
  212060. int refCount;
  212061. DShowCameraDeviceInteral& owner;
  212062. GrabberCallback (const GrabberCallback&);
  212063. const GrabberCallback& operator= (const GrabberCallback&);
  212064. };
  212065. ComSmartPtr <GrabberCallback> callback;
  212066. VoidArray listeners;
  212067. CriticalSection listenerLock;
  212068. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  212069. const DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  212070. };
  212071. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  212072. : name (name_)
  212073. {
  212074. isRecording = false;
  212075. }
  212076. CameraDevice::~CameraDevice()
  212077. {
  212078. stopRecording();
  212079. delete (DShowCameraDeviceInteral*) internal;
  212080. internal = 0;
  212081. }
  212082. Component* CameraDevice::createViewerComponent()
  212083. {
  212084. return new DShowCameraDeviceInteral::DShowCaptureViewerComp ((DShowCameraDeviceInteral*) internal);
  212085. }
  212086. const String CameraDevice::getFileExtension()
  212087. {
  212088. return ".avi";
  212089. }
  212090. void CameraDevice::startRecordingToFile (const File& file)
  212091. {
  212092. stopRecording();
  212093. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212094. d->addUser();
  212095. isRecording = d->createFileCaptureFilter (file);
  212096. }
  212097. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  212098. {
  212099. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212100. return d->firstRecordedTime;
  212101. }
  212102. void CameraDevice::stopRecording()
  212103. {
  212104. if (isRecording)
  212105. {
  212106. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212107. d->removeFileCaptureFilter();
  212108. d->removeUser();
  212109. isRecording = false;
  212110. }
  212111. }
  212112. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  212113. {
  212114. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212115. if (listenerToAdd != 0)
  212116. d->addListener (listenerToAdd);
  212117. }
  212118. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  212119. {
  212120. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  212121. if (listenerToRemove != 0)
  212122. d->removeListener (listenerToRemove);
  212123. }
  212124. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  212125. const int deviceIndexToOpen,
  212126. String& name)
  212127. {
  212128. int index = 0;
  212129. ComSmartPtr <IBaseFilter> result;
  212130. ComSmartPtr <ICreateDevEnum> pDevEnum;
  212131. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum, CLSCTX_INPROC);
  212132. if (SUCCEEDED (hr))
  212133. {
  212134. ComSmartPtr <IEnumMoniker> enumerator;
  212135. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, &enumerator, 0);
  212136. if (SUCCEEDED (hr) && enumerator != 0)
  212137. {
  212138. ComSmartPtr <IBaseFilter> captureFilter;
  212139. ComSmartPtr <IMoniker> moniker;
  212140. ULONG fetched;
  212141. while (enumerator->Next (1, &moniker, &fetched) == S_OK)
  212142. {
  212143. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) &captureFilter);
  212144. if (SUCCEEDED (hr))
  212145. {
  212146. ComSmartPtr <IPropertyBag> propertyBag;
  212147. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) &propertyBag);
  212148. if (SUCCEEDED (hr))
  212149. {
  212150. VARIANT var;
  212151. var.vt = VT_BSTR;
  212152. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  212153. propertyBag = 0;
  212154. if (SUCCEEDED (hr))
  212155. {
  212156. if (names != 0)
  212157. names->add (var.bstrVal);
  212158. if (index == deviceIndexToOpen)
  212159. {
  212160. name = var.bstrVal;
  212161. result = captureFilter;
  212162. captureFilter = 0;
  212163. break;
  212164. }
  212165. ++index;
  212166. }
  212167. moniker = 0;
  212168. }
  212169. captureFilter = 0;
  212170. }
  212171. }
  212172. }
  212173. }
  212174. return result;
  212175. }
  212176. const StringArray CameraDevice::getAvailableDevices()
  212177. {
  212178. StringArray devs;
  212179. String dummy;
  212180. enumerateCameras (&devs, -1, dummy);
  212181. return devs;
  212182. }
  212183. CameraDevice* CameraDevice::openDevice (int index,
  212184. int minWidth, int minHeight,
  212185. int maxWidth, int maxHeight)
  212186. {
  212187. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  212188. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2, CLSCTX_INPROC);
  212189. if (SUCCEEDED (hr))
  212190. {
  212191. String name;
  212192. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  212193. if (filter != 0)
  212194. {
  212195. CameraDevice* const cam = new CameraDevice (name, index);
  212196. DShowCameraDeviceInteral* const intern
  212197. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  212198. minWidth, minHeight, maxWidth, maxHeight);
  212199. cam->internal = intern;
  212200. if (intern->ok)
  212201. return cam;
  212202. else
  212203. delete cam;
  212204. }
  212205. }
  212206. return 0;
  212207. }
  212208. #endif
  212209. /********* End of inlined file: juce_win32_CameraDevice.cpp *********/
  212210. #endif
  212211. // Auto-link the other win32 libs that are needed by library calls..
  212212. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  212213. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212214. // Auto-links to various win32 libs that are needed by library calls..
  212215. #pragma comment(lib, "kernel32.lib")
  212216. #pragma comment(lib, "user32.lib")
  212217. #pragma comment(lib, "shell32.lib")
  212218. #pragma comment(lib, "gdi32.lib")
  212219. #pragma comment(lib, "vfw32.lib")
  212220. #pragma comment(lib, "comdlg32.lib")
  212221. #pragma comment(lib, "winmm.lib")
  212222. #pragma comment(lib, "wininet.lib")
  212223. #pragma comment(lib, "ole32.lib")
  212224. #pragma comment(lib, "advapi32.lib")
  212225. #pragma comment(lib, "ws2_32.lib")
  212226. #pragma comment(lib, "comsupp.lib")
  212227. #pragma comment(lib, "version.lib")
  212228. #if JUCE_OPENGL
  212229. #pragma comment(lib, "OpenGL32.Lib")
  212230. #pragma comment(lib, "GlU32.Lib")
  212231. #endif
  212232. #if JUCE_QUICKTIME
  212233. #pragma comment (lib, "QTMLClient.lib")
  212234. #endif
  212235. #if JUCE_USE_CAMERA
  212236. #pragma comment (lib, "Strmiids.lib")
  212237. #endif
  212238. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  212239. #endif
  212240. END_JUCE_NAMESPACE
  212241. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  212242. #endif
  212243. #if JUCE_LINUX
  212244. /********* Start of inlined file: juce_linux_NativeCode.cpp *********/
  212245. /*
  212246. This file wraps together all the mac-specific code, so that
  212247. we can include all the native headers just once, and compile all our
  212248. platform-specific stuff in one big lump, keeping it out of the way of
  212249. the rest of the codebase.
  212250. */
  212251. BEGIN_JUCE_NAMESPACE
  212252. /* Remove this macro if you're having problems compiling the cpu affinity
  212253. calls (the API for these has changed about quite a bit in various Linux
  212254. versions, and a lot of distros seem to ship with obsolete versions)
  212255. */
  212256. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  212257. #define SUPPORT_AFFINITIES 1
  212258. #endif
  212259. #define JUCE_INCLUDED_FILE 1
  212260. // Now include the actual code files..
  212261. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  212262. /*
  212263. This file contains posix routines that are common to both the Linux and Mac builds.
  212264. It gets included directly in the cpp files for these platforms.
  212265. */
  212266. CriticalSection::CriticalSection() throw()
  212267. {
  212268. pthread_mutexattr_t atts;
  212269. pthread_mutexattr_init (&atts);
  212270. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  212271. pthread_mutex_init (&internal, &atts);
  212272. }
  212273. CriticalSection::~CriticalSection() throw()
  212274. {
  212275. pthread_mutex_destroy (&internal);
  212276. }
  212277. void CriticalSection::enter() const throw()
  212278. {
  212279. pthread_mutex_lock (&internal);
  212280. }
  212281. bool CriticalSection::tryEnter() const throw()
  212282. {
  212283. return pthread_mutex_trylock (&internal) == 0;
  212284. }
  212285. void CriticalSection::exit() const throw()
  212286. {
  212287. pthread_mutex_unlock (&internal);
  212288. }
  212289. struct EventStruct
  212290. {
  212291. pthread_cond_t condition;
  212292. pthread_mutex_t mutex;
  212293. bool triggered;
  212294. };
  212295. WaitableEvent::WaitableEvent() throw()
  212296. {
  212297. EventStruct* const es = new EventStruct();
  212298. es->triggered = false;
  212299. pthread_cond_init (&es->condition, 0);
  212300. pthread_mutex_init (&es->mutex, 0);
  212301. internal = es;
  212302. }
  212303. WaitableEvent::~WaitableEvent() throw()
  212304. {
  212305. EventStruct* const es = (EventStruct*) internal;
  212306. pthread_cond_destroy (&es->condition);
  212307. pthread_mutex_destroy (&es->mutex);
  212308. delete es;
  212309. }
  212310. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  212311. {
  212312. EventStruct* const es = (EventStruct*) internal;
  212313. bool ok = true;
  212314. pthread_mutex_lock (&es->mutex);
  212315. if (timeOutMillisecs < 0)
  212316. {
  212317. while (! es->triggered)
  212318. pthread_cond_wait (&es->condition, &es->mutex);
  212319. }
  212320. else
  212321. {
  212322. while (! es->triggered)
  212323. {
  212324. struct timeval t;
  212325. gettimeofday (&t, 0);
  212326. struct timespec time;
  212327. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  212328. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  212329. if (time.tv_nsec >= 1000000000)
  212330. {
  212331. time.tv_nsec -= 1000000000;
  212332. time.tv_sec++;
  212333. }
  212334. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  212335. {
  212336. ok = false;
  212337. break;
  212338. }
  212339. }
  212340. }
  212341. es->triggered = false;
  212342. pthread_mutex_unlock (&es->mutex);
  212343. return ok;
  212344. }
  212345. void WaitableEvent::signal() const throw()
  212346. {
  212347. EventStruct* const es = (EventStruct*) internal;
  212348. pthread_mutex_lock (&es->mutex);
  212349. es->triggered = true;
  212350. pthread_cond_broadcast (&es->condition);
  212351. pthread_mutex_unlock (&es->mutex);
  212352. }
  212353. void WaitableEvent::reset() const throw()
  212354. {
  212355. EventStruct* const es = (EventStruct*) internal;
  212356. pthread_mutex_lock (&es->mutex);
  212357. es->triggered = false;
  212358. pthread_mutex_unlock (&es->mutex);
  212359. }
  212360. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  212361. {
  212362. struct timespec time;
  212363. time.tv_sec = millisecs / 1000;
  212364. time.tv_nsec = (millisecs % 1000) * 1000000;
  212365. nanosleep (&time, 0);
  212366. }
  212367. const tchar File::separator = T('/');
  212368. const tchar* File::separatorString = T("/");
  212369. bool juce_copyFile (const String& s, const String& d) throw();
  212370. static bool juce_stat (const String& fileName, struct stat& info) throw()
  212371. {
  212372. return fileName.isNotEmpty()
  212373. && (stat (fileName.toUTF8(), &info) == 0);
  212374. }
  212375. bool juce_isDirectory (const String& fileName) throw()
  212376. {
  212377. struct stat info;
  212378. return fileName.isEmpty()
  212379. || (juce_stat (fileName, info)
  212380. && ((info.st_mode & S_IFDIR) != 0));
  212381. }
  212382. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  212383. {
  212384. if (fileName.isEmpty())
  212385. return false;
  212386. const char* const fileNameUTF8 = fileName.toUTF8();
  212387. bool exists = access (fileNameUTF8, F_OK) == 0;
  212388. if (exists && dontCountDirectories)
  212389. {
  212390. struct stat info;
  212391. const int res = stat (fileNameUTF8, &info);
  212392. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  212393. exists = false;
  212394. }
  212395. return exists;
  212396. }
  212397. int64 juce_getFileSize (const String& fileName) throw()
  212398. {
  212399. struct stat info;
  212400. return juce_stat (fileName, info) ? info.st_size : 0;
  212401. }
  212402. bool juce_canWriteToFile (const String& fileName) throw()
  212403. {
  212404. return access (fileName.toUTF8(), W_OK) == 0;
  212405. }
  212406. bool juce_deleteFile (const String& fileName) throw()
  212407. {
  212408. if (juce_isDirectory (fileName))
  212409. return rmdir ((const char*) fileName.toUTF8()) == 0;
  212410. else
  212411. return remove ((const char*) fileName.toUTF8()) == 0;
  212412. }
  212413. bool juce_moveFile (const String& source, const String& dest) throw()
  212414. {
  212415. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  212416. return true;
  212417. if (juce_canWriteToFile (source)
  212418. && juce_copyFile (source, dest))
  212419. {
  212420. if (juce_deleteFile (source))
  212421. return true;
  212422. juce_deleteFile (dest);
  212423. }
  212424. return false;
  212425. }
  212426. void juce_createDirectory (const String& fileName) throw()
  212427. {
  212428. mkdir (fileName.toUTF8(), 0777);
  212429. }
  212430. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  212431. {
  212432. int flags = O_RDONLY;
  212433. if (forWriting)
  212434. {
  212435. if (juce_fileExists (fileName, false))
  212436. {
  212437. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  212438. if (f != -1)
  212439. lseek (f, 0, SEEK_END);
  212440. return (void*) f;
  212441. }
  212442. else
  212443. {
  212444. flags = O_RDWR + O_CREAT;
  212445. }
  212446. }
  212447. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  212448. }
  212449. void juce_fileClose (void* handle) throw()
  212450. {
  212451. if (handle != 0)
  212452. close ((int) (pointer_sized_int) handle);
  212453. }
  212454. int juce_fileRead (void* handle, void* buffer, int size) throw()
  212455. {
  212456. if (handle != 0)
  212457. return read ((int) (pointer_sized_int) handle, buffer, size);
  212458. return 0;
  212459. }
  212460. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  212461. {
  212462. if (handle != 0)
  212463. return write ((int) (pointer_sized_int) handle, buffer, size);
  212464. return 0;
  212465. }
  212466. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  212467. {
  212468. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  212469. return pos;
  212470. return -1;
  212471. }
  212472. int64 juce_fileGetPosition (void* handle) throw()
  212473. {
  212474. if (handle != 0)
  212475. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  212476. else
  212477. return -1;
  212478. }
  212479. void juce_fileFlush (void* handle) throw()
  212480. {
  212481. if (handle != 0)
  212482. fsync ((int) (pointer_sized_int) handle);
  212483. }
  212484. const File juce_getExecutableFile()
  212485. {
  212486. Dl_info exeInfo;
  212487. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  212488. return File (exeInfo.dli_fname);
  212489. }
  212490. // if this file doesn't exist, find a parent of it that does..
  212491. static bool doStatFS (const File* file, struct statfs& result) throw()
  212492. {
  212493. File f (*file);
  212494. for (int i = 5; --i >= 0;)
  212495. {
  212496. if (f.exists())
  212497. break;
  212498. f = f.getParentDirectory();
  212499. }
  212500. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  212501. }
  212502. int64 File::getBytesFreeOnVolume() const throw()
  212503. {
  212504. struct statfs buf;
  212505. if (doStatFS (this, buf))
  212506. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  212507. return 0;
  212508. }
  212509. int64 File::getVolumeTotalSize() const throw()
  212510. {
  212511. struct statfs buf;
  212512. if (doStatFS (this, buf))
  212513. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  212514. return 0;
  212515. }
  212516. const String juce_getVolumeLabel (const String& filenameOnVolume,
  212517. int& volumeSerialNumber) throw()
  212518. {
  212519. volumeSerialNumber = 0;
  212520. #if JUCE_MAC
  212521. struct VolAttrBuf
  212522. {
  212523. u_int32_t length;
  212524. attrreference_t mountPointRef;
  212525. char mountPointSpace [MAXPATHLEN];
  212526. } attrBuf;
  212527. struct attrlist attrList;
  212528. zerostruct (attrList);
  212529. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  212530. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  212531. File f (filenameOnVolume);
  212532. for (;;)
  212533. {
  212534. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  212535. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  212536. {
  212537. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  212538. (int) attrBuf.mountPointRef.attr_length);
  212539. }
  212540. const File parent (f.getParentDirectory());
  212541. if (f == parent)
  212542. break;
  212543. f = parent;
  212544. }
  212545. #endif
  212546. return String::empty;
  212547. }
  212548. void juce_runSystemCommand (const String& command)
  212549. {
  212550. int result = system ((const char*) command.toUTF8());
  212551. (void) result;
  212552. }
  212553. const String juce_getOutputFromCommand (const String& command)
  212554. {
  212555. // slight bodge here, as we just pipe the output into a temp file and read it...
  212556. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  212557. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  212558. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  212559. String result (tempFile.loadFileAsString());
  212560. tempFile.deleteFile();
  212561. return result;
  212562. }
  212563. #if JUCE_64BIT
  212564. #define filedesc ((long long) internal)
  212565. #else
  212566. #define filedesc ((int) internal)
  212567. #endif
  212568. InterProcessLock::InterProcessLock (const String& name_) throw()
  212569. : internal (0),
  212570. name (name_),
  212571. reentrancyLevel (0)
  212572. {
  212573. #if JUCE_MAC
  212574. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  212575. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  212576. #else
  212577. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  212578. #endif
  212579. temp.create();
  212580. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  212581. }
  212582. InterProcessLock::~InterProcessLock() throw()
  212583. {
  212584. while (reentrancyLevel > 0)
  212585. this->exit();
  212586. close (filedesc);
  212587. }
  212588. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  212589. {
  212590. if (internal == 0)
  212591. return false;
  212592. if (reentrancyLevel != 0)
  212593. return true;
  212594. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  212595. struct flock fl;
  212596. zerostruct (fl);
  212597. fl.l_whence = SEEK_SET;
  212598. fl.l_type = F_WRLCK;
  212599. for (;;)
  212600. {
  212601. const int result = fcntl (filedesc, F_SETLK, &fl);
  212602. if (result >= 0)
  212603. {
  212604. ++reentrancyLevel;
  212605. return true;
  212606. }
  212607. if (errno != EINTR)
  212608. {
  212609. if (timeOutMillisecs == 0
  212610. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  212611. break;
  212612. Thread::sleep (10);
  212613. }
  212614. }
  212615. return false;
  212616. }
  212617. void InterProcessLock::exit() throw()
  212618. {
  212619. if (reentrancyLevel > 0 && internal != 0)
  212620. {
  212621. --reentrancyLevel;
  212622. struct flock fl;
  212623. zerostruct (fl);
  212624. fl.l_whence = SEEK_SET;
  212625. fl.l_type = F_UNLCK;
  212626. for (;;)
  212627. {
  212628. const int result = fcntl (filedesc, F_SETLKW, &fl);
  212629. if (result >= 0 || errno != EINTR)
  212630. break;
  212631. }
  212632. }
  212633. }
  212634. /********* End of inlined file: juce_posix_SharedCode.h *********/
  212635. /********* Start of inlined file: juce_linux_Files.cpp *********/
  212636. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  212637. // compiled on its own).
  212638. #ifdef JUCE_INCLUDED_FILE
  212639. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  212640. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  212641. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  212642. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  212643. void juce_getFileTimes (const String& fileName,
  212644. int64& modificationTime,
  212645. int64& accessTime,
  212646. int64& creationTime) throw()
  212647. {
  212648. modificationTime = 0;
  212649. accessTime = 0;
  212650. creationTime = 0;
  212651. struct stat info;
  212652. const int res = stat (fileName.toUTF8(), &info);
  212653. if (res == 0)
  212654. {
  212655. modificationTime = (int64) info.st_mtime * 1000;
  212656. accessTime = (int64) info.st_atime * 1000;
  212657. creationTime = (int64) info.st_ctime * 1000;
  212658. }
  212659. }
  212660. bool juce_setFileTimes (const String& fileName,
  212661. int64 modificationTime,
  212662. int64 accessTime,
  212663. int64 creationTime) throw()
  212664. {
  212665. struct utimbuf times;
  212666. times.actime = (time_t) (accessTime / 1000);
  212667. times.modtime = (time_t) (modificationTime / 1000);
  212668. return utime (fileName.toUTF8(), &times) == 0;
  212669. }
  212670. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  212671. {
  212672. struct stat info;
  212673. const int res = stat (fileName.toUTF8(), &info);
  212674. if (res != 0)
  212675. return false;
  212676. info.st_mode &= 0777; // Just permissions
  212677. if( isReadOnly )
  212678. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  212679. else
  212680. // Give everybody write permission?
  212681. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  212682. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  212683. }
  212684. bool juce_copyFile (const String& s, const String& d) throw()
  212685. {
  212686. const File source (s), dest (d);
  212687. FileInputStream* in = source.createInputStream();
  212688. bool ok = false;
  212689. if (in != 0)
  212690. {
  212691. if (dest.deleteFile())
  212692. {
  212693. FileOutputStream* const out = dest.createOutputStream();
  212694. if (out != 0)
  212695. {
  212696. const int bytesCopied = out->writeFromInputStream (*in, -1);
  212697. delete out;
  212698. ok = (bytesCopied == source.getSize());
  212699. if (! ok)
  212700. dest.deleteFile();
  212701. }
  212702. }
  212703. delete in;
  212704. }
  212705. return ok;
  212706. }
  212707. const StringArray juce_getFileSystemRoots() throw()
  212708. {
  212709. StringArray s;
  212710. s.add (T("/"));
  212711. return s;
  212712. }
  212713. bool File::isOnCDRomDrive() const throw()
  212714. {
  212715. struct statfs buf;
  212716. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212717. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  212718. // Assume not if this fails for some reason
  212719. return false;
  212720. }
  212721. bool File::isOnHardDisk() const throw()
  212722. {
  212723. struct statfs buf;
  212724. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  212725. {
  212726. switch (buf.f_type)
  212727. {
  212728. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  212729. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  212730. case U_NFS_SUPER_MAGIC: // Network NFS
  212731. case U_SMB_SUPER_MAGIC: // Network Samba
  212732. return false;
  212733. default:
  212734. // Assume anything else is a hard-disk (but note it could
  212735. // be a RAM disk. There isn't a good way of determining
  212736. // this for sure)
  212737. return true;
  212738. }
  212739. }
  212740. // Assume so if this fails for some reason
  212741. return true;
  212742. }
  212743. bool File::isOnRemovableDrive() const throw()
  212744. {
  212745. jassertfalse // xxx not implemented for linux!
  212746. return false;
  212747. }
  212748. bool File::isHidden() const throw()
  212749. {
  212750. return getFileName().startsWithChar (T('.'));
  212751. }
  212752. const File File::getSpecialLocation (const SpecialLocationType type)
  212753. {
  212754. switch (type)
  212755. {
  212756. case userHomeDirectory:
  212757. {
  212758. const char* homeDir = getenv ("HOME");
  212759. if (homeDir == 0)
  212760. {
  212761. struct passwd* const pw = getpwuid (getuid());
  212762. if (pw != 0)
  212763. homeDir = pw->pw_dir;
  212764. }
  212765. return File (String::fromUTF8 ((const uint8*) homeDir));
  212766. }
  212767. case userDocumentsDirectory:
  212768. case userMusicDirectory:
  212769. case userMoviesDirectory:
  212770. case userApplicationDataDirectory:
  212771. return File ("~");
  212772. case userDesktopDirectory:
  212773. return File ("~/Desktop");
  212774. case commonApplicationDataDirectory:
  212775. return File ("/var");
  212776. case globalApplicationsDirectory:
  212777. return File ("/usr");
  212778. case tempDirectory:
  212779. {
  212780. File tmp ("/var/tmp");
  212781. if (! tmp.isDirectory())
  212782. {
  212783. tmp = T("/tmp");
  212784. if (! tmp.isDirectory())
  212785. tmp = File::getCurrentWorkingDirectory();
  212786. }
  212787. return tmp;
  212788. }
  212789. case currentExecutableFile:
  212790. case currentApplicationFile:
  212791. return juce_getExecutableFile();
  212792. default:
  212793. jassertfalse // unknown type?
  212794. break;
  212795. }
  212796. return File::nonexistent;
  212797. }
  212798. const File File::getCurrentWorkingDirectory() throw()
  212799. {
  212800. char buf [2048];
  212801. return File (String::fromUTF8 ((const uint8*) getcwd (buf, sizeof (buf))));
  212802. }
  212803. bool File::setAsCurrentWorkingDirectory() const throw()
  212804. {
  212805. return chdir (getFullPathName().toUTF8()) == 0;
  212806. }
  212807. const String File::getVersion() const throw()
  212808. {
  212809. return String::empty; // xxx not yet implemented
  212810. }
  212811. const File File::getLinkedTarget() const throw()
  212812. {
  212813. char buffer [4096];
  212814. size_t numChars = readlink ((const char*) getFullPathName().toUTF8(),
  212815. buffer, sizeof (buffer));
  212816. if (numChars > 0 && numChars <= sizeof (buffer))
  212817. return File (String::fromUTF8 ((const uint8*) buffer, (int) numChars));
  212818. return *this;
  212819. }
  212820. bool File::moveToTrash() const throw()
  212821. {
  212822. if (! exists())
  212823. return true;
  212824. File trashCan (T("~/.Trash"));
  212825. if (! trashCan.isDirectory())
  212826. trashCan = T("~/.local/share/Trash/files");
  212827. if (! trashCan.isDirectory())
  212828. return false;
  212829. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  212830. getFileExtension()));
  212831. }
  212832. struct FindFileStruct
  212833. {
  212834. String parentDir, wildCard;
  212835. DIR* dir;
  212836. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  212837. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  212838. {
  212839. const char* const wildcardUTF8 = wildCard.toUTF8();
  212840. for (;;)
  212841. {
  212842. struct dirent* const de = readdir (dir);
  212843. if (de == 0)
  212844. break;
  212845. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  212846. {
  212847. result = String::fromUTF8 ((const uint8*) de->d_name);
  212848. const String path (parentDir + result);
  212849. if (isDir != 0 || fileSize != 0)
  212850. {
  212851. struct stat info;
  212852. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  212853. if (isDir != 0)
  212854. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  212855. if (isHidden != 0)
  212856. *isHidden = (de->d_name[0] == '.');
  212857. if (fileSize != 0)
  212858. *fileSize = statOk ? info.st_size : 0;
  212859. }
  212860. if (modTime != 0 || creationTime != 0)
  212861. {
  212862. int64 m, a, c;
  212863. juce_getFileTimes (path, m, a, c);
  212864. if (modTime != 0)
  212865. *modTime = m;
  212866. if (creationTime != 0)
  212867. *creationTime = c;
  212868. }
  212869. if (isReadOnly != 0)
  212870. *isReadOnly = ! juce_canWriteToFile (path);
  212871. return true;
  212872. }
  212873. }
  212874. return false;
  212875. }
  212876. };
  212877. // returns 0 on failure
  212878. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  212879. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  212880. Time* creationTime, bool* isReadOnly) throw()
  212881. {
  212882. DIR* d = opendir (directory.toUTF8());
  212883. if (d != 0)
  212884. {
  212885. FindFileStruct* ff = new FindFileStruct();
  212886. ff->parentDir = directory;
  212887. if (!ff->parentDir.endsWithChar (File::separator))
  212888. ff->parentDir += File::separator;
  212889. ff->wildCard = wildCard;
  212890. if (wildCard == T("*.*"))
  212891. ff->wildCard = T("*");
  212892. ff->dir = d;
  212893. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  212894. {
  212895. return ff;
  212896. }
  212897. else
  212898. {
  212899. firstResultFile = String::empty;
  212900. isDir = false;
  212901. isHidden = false;
  212902. closedir (d);
  212903. delete ff;
  212904. }
  212905. }
  212906. return 0;
  212907. }
  212908. bool juce_findFileNext (void* handle, String& resultFile,
  212909. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  212910. {
  212911. FindFileStruct* const ff = (FindFileStruct*) handle;
  212912. if (ff != 0)
  212913. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  212914. return false;
  212915. }
  212916. void juce_findFileClose (void* handle) throw()
  212917. {
  212918. FindFileStruct* const ff = (FindFileStruct*) handle;
  212919. if (ff != 0)
  212920. {
  212921. closedir (ff->dir);
  212922. delete ff;
  212923. }
  212924. }
  212925. bool juce_launchFile (const String& fileName,
  212926. const String& parameters) throw()
  212927. {
  212928. String cmdString (fileName);
  212929. cmdString << " " << parameters;
  212930. if (URL::isProbablyAWebsiteURL (fileName)
  212931. || URL::isProbablyAnEmailAddress (fileName))
  212932. {
  212933. // create a command that tries to launch a bunch of likely browsers
  212934. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  212935. StringArray cmdLines;
  212936. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  212937. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  212938. cmdString = cmdLines.joinIntoString (T(" || "));
  212939. }
  212940. if (cmdString.startsWithIgnoreCase (T("file:")))
  212941. cmdString = cmdString.substring (5);
  212942. const char* const argv[4] = { "/bin/sh", "-c", (const char*) cmdString.toUTF8(), 0 };
  212943. const int cpid = fork();
  212944. if (cpid == 0)
  212945. {
  212946. setsid();
  212947. // Child process
  212948. execve (argv[0], (char**) argv, environ);
  212949. exit (0);
  212950. }
  212951. return cpid >= 0;
  212952. }
  212953. #endif
  212954. /********* End of inlined file: juce_linux_Files.cpp *********/
  212955. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  212956. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  212957. // compiled on its own).
  212958. #if JUCE_INCLUDED_FILE
  212959. struct NamedPipeInternal
  212960. {
  212961. String pipeInName, pipeOutName;
  212962. int pipeIn, pipeOut;
  212963. bool volatile createdPipe, blocked, stopReadOperation;
  212964. static void signalHandler (int) {}
  212965. };
  212966. void NamedPipe::cancelPendingReads()
  212967. {
  212968. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  212969. {
  212970. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212971. intern->stopReadOperation = true;
  212972. char buffer [1] = { 0 };
  212973. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  212974. (void) bytesWritten;
  212975. int timeout = 2000;
  212976. while (intern->blocked && --timeout >= 0)
  212977. Thread::sleep (2);
  212978. intern->stopReadOperation = false;
  212979. }
  212980. }
  212981. void NamedPipe::close()
  212982. {
  212983. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  212984. if (intern != 0)
  212985. {
  212986. internal = 0;
  212987. if (intern->pipeIn != -1)
  212988. ::close (intern->pipeIn);
  212989. if (intern->pipeOut != -1)
  212990. ::close (intern->pipeOut);
  212991. if (intern->createdPipe)
  212992. {
  212993. unlink (intern->pipeInName);
  212994. unlink (intern->pipeOutName);
  212995. }
  212996. delete intern;
  212997. }
  212998. }
  212999. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  213000. {
  213001. close();
  213002. NamedPipeInternal* const intern = new NamedPipeInternal();
  213003. internal = intern;
  213004. intern->createdPipe = createPipe;
  213005. intern->blocked = false;
  213006. intern->stopReadOperation = false;
  213007. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  213008. siginterrupt (SIGPIPE, 1);
  213009. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  213010. intern->pipeInName = pipePath + T("_in");
  213011. intern->pipeOutName = pipePath + T("_out");
  213012. intern->pipeIn = -1;
  213013. intern->pipeOut = -1;
  213014. if (createPipe)
  213015. {
  213016. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  213017. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  213018. {
  213019. delete intern;
  213020. internal = 0;
  213021. return false;
  213022. }
  213023. }
  213024. return true;
  213025. }
  213026. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  213027. {
  213028. int bytesRead = -1;
  213029. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213030. if (intern != 0)
  213031. {
  213032. intern->blocked = true;
  213033. if (intern->pipeIn == -1)
  213034. {
  213035. if (intern->createdPipe)
  213036. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  213037. else
  213038. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  213039. if (intern->pipeIn == -1)
  213040. {
  213041. intern->blocked = false;
  213042. return -1;
  213043. }
  213044. }
  213045. bytesRead = 0;
  213046. char* p = (char*) destBuffer;
  213047. while (bytesRead < maxBytesToRead)
  213048. {
  213049. const int bytesThisTime = maxBytesToRead - bytesRead;
  213050. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  213051. if (numRead <= 0 || intern->stopReadOperation)
  213052. {
  213053. bytesRead = -1;
  213054. break;
  213055. }
  213056. bytesRead += numRead;
  213057. p += bytesRead;
  213058. }
  213059. intern->blocked = false;
  213060. }
  213061. return bytesRead;
  213062. }
  213063. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  213064. {
  213065. int bytesWritten = -1;
  213066. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  213067. if (intern != 0)
  213068. {
  213069. if (intern->pipeOut == -1)
  213070. {
  213071. if (intern->createdPipe)
  213072. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  213073. else
  213074. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  213075. if (intern->pipeOut == -1)
  213076. {
  213077. return -1;
  213078. }
  213079. }
  213080. const char* p = (const char*) sourceBuffer;
  213081. bytesWritten = 0;
  213082. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  213083. while (bytesWritten < numBytesToWrite
  213084. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  213085. {
  213086. const int bytesThisTime = numBytesToWrite - bytesWritten;
  213087. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  213088. if (numWritten <= 0)
  213089. {
  213090. bytesWritten = -1;
  213091. break;
  213092. }
  213093. bytesWritten += numWritten;
  213094. p += bytesWritten;
  213095. }
  213096. }
  213097. return bytesWritten;
  213098. }
  213099. #endif
  213100. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  213101. /********* Start of inlined file: juce_linux_Network.cpp *********/
  213102. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213103. // compiled on its own).
  213104. #ifdef JUCE_INCLUDED_FILE
  213105. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  213106. {
  213107. int numResults = 0;
  213108. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  213109. if (s != -1)
  213110. {
  213111. char buf [1024];
  213112. struct ifconf ifc;
  213113. ifc.ifc_len = sizeof (buf);
  213114. ifc.ifc_buf = buf;
  213115. ioctl (s, SIOCGIFCONF, &ifc);
  213116. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  213117. {
  213118. struct ifreq ifr;
  213119. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  213120. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  213121. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  213122. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  213123. && numResults < maxNum)
  213124. {
  213125. int64 a = 0;
  213126. for (int j = 6; --j >= 0;)
  213127. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  213128. *addresses++ = a;
  213129. ++numResults;
  213130. }
  213131. }
  213132. close (s);
  213133. }
  213134. return numResults;
  213135. }
  213136. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  213137. const String& emailSubject,
  213138. const String& bodyText,
  213139. const StringArray& filesToAttach)
  213140. {
  213141. jassertfalse // xxx todo
  213142. return false;
  213143. }
  213144. /** A HTTP input stream that uses sockets.
  213145. */
  213146. class JUCE_HTTPSocketStream
  213147. {
  213148. public:
  213149. JUCE_HTTPSocketStream()
  213150. : readPosition (0),
  213151. socketHandle (-1),
  213152. levelsOfRedirection (0),
  213153. timeoutSeconds (15)
  213154. {
  213155. }
  213156. ~JUCE_HTTPSocketStream()
  213157. {
  213158. closeSocket();
  213159. }
  213160. bool open (const String& url,
  213161. const String& headers,
  213162. const MemoryBlock& postData,
  213163. const bool isPost,
  213164. URL::OpenStreamProgressCallback* callback,
  213165. void* callbackContext,
  213166. int timeOutMs)
  213167. {
  213168. closeSocket();
  213169. uint32 timeOutTime = Time::getMillisecondCounter();
  213170. if (timeOutMs == 0)
  213171. timeOutTime += 60000;
  213172. else if (timeOutMs < 0)
  213173. timeOutTime = 0xffffffff;
  213174. else
  213175. timeOutTime += timeOutMs;
  213176. String hostName, hostPath;
  213177. int hostPort;
  213178. if (! decomposeURL (url, hostName, hostPath, hostPort))
  213179. return false;
  213180. const struct hostent* host = 0;
  213181. int port = 0;
  213182. String proxyName, proxyPath;
  213183. int proxyPort = 0;
  213184. String proxyURL (getenv ("http_proxy"));
  213185. if (proxyURL.startsWithIgnoreCase (T("http://")))
  213186. {
  213187. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  213188. return false;
  213189. host = gethostbyname ((const char*) proxyName.toUTF8());
  213190. port = proxyPort;
  213191. }
  213192. else
  213193. {
  213194. host = gethostbyname ((const char*) hostName.toUTF8());
  213195. port = hostPort;
  213196. }
  213197. if (host == 0)
  213198. return false;
  213199. struct sockaddr_in address;
  213200. zerostruct (address);
  213201. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  213202. address.sin_family = host->h_addrtype;
  213203. address.sin_port = htons (port);
  213204. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  213205. if (socketHandle == -1)
  213206. return false;
  213207. int receiveBufferSize = 16384;
  213208. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  213209. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  213210. #if JUCE_MAC
  213211. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  213212. #endif
  213213. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  213214. {
  213215. closeSocket();
  213216. return false;
  213217. }
  213218. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  213219. proxyName, proxyPort,
  213220. hostPath, url,
  213221. headers, postData,
  213222. isPost));
  213223. int totalHeaderSent = 0;
  213224. while (totalHeaderSent < requestHeader.getSize())
  213225. {
  213226. if (Time::getMillisecondCounter() > timeOutTime)
  213227. {
  213228. closeSocket();
  213229. return false;
  213230. }
  213231. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  213232. if (send (socketHandle,
  213233. ((const char*) requestHeader.getData()) + totalHeaderSent,
  213234. numToSend, 0)
  213235. != numToSend)
  213236. {
  213237. closeSocket();
  213238. return false;
  213239. }
  213240. totalHeaderSent += numToSend;
  213241. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  213242. {
  213243. closeSocket();
  213244. return false;
  213245. }
  213246. }
  213247. const String responseHeader (readResponse (timeOutTime));
  213248. if (responseHeader.isNotEmpty())
  213249. {
  213250. //DBG (responseHeader);
  213251. StringArray lines;
  213252. lines.addLines (responseHeader);
  213253. // NB - using charToString() here instead of just T(" "), because that was
  213254. // causing a mysterious gcc internal compiler error...
  213255. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  213256. .substring (0, 3).getIntValue();
  213257. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  213258. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  213259. String location (findHeaderItem (lines, T("Location:")));
  213260. if (statusCode >= 300 && statusCode < 400
  213261. && location.isNotEmpty())
  213262. {
  213263. if (! location.startsWithIgnoreCase (T("http://")))
  213264. location = T("http://") + location;
  213265. if (levelsOfRedirection++ < 3)
  213266. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  213267. }
  213268. else
  213269. {
  213270. levelsOfRedirection = 0;
  213271. return true;
  213272. }
  213273. }
  213274. closeSocket();
  213275. return false;
  213276. }
  213277. int read (void* buffer, int bytesToRead)
  213278. {
  213279. fd_set readbits;
  213280. FD_ZERO (&readbits);
  213281. FD_SET (socketHandle, &readbits);
  213282. struct timeval tv;
  213283. tv.tv_sec = timeoutSeconds;
  213284. tv.tv_usec = 0;
  213285. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213286. return 0; // (timeout)
  213287. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  213288. readPosition += bytesRead;
  213289. return bytesRead;
  213290. }
  213291. int readPosition;
  213292. juce_UseDebuggingNewOperator
  213293. private:
  213294. int socketHandle, levelsOfRedirection;
  213295. const int timeoutSeconds;
  213296. void closeSocket()
  213297. {
  213298. if (socketHandle >= 0)
  213299. close (socketHandle);
  213300. socketHandle = -1;
  213301. }
  213302. const MemoryBlock createRequestHeader (const String& hostName,
  213303. const int hostPort,
  213304. const String& proxyName,
  213305. const int proxyPort,
  213306. const String& hostPath,
  213307. const String& originalURL,
  213308. const String& headers,
  213309. const MemoryBlock& postData,
  213310. const bool isPost)
  213311. {
  213312. String header (isPost ? "POST " : "GET ");
  213313. if (proxyName.isEmpty())
  213314. {
  213315. header << hostPath << " HTTP/1.0\r\nHost: "
  213316. << hostName << ':' << hostPort;
  213317. }
  213318. else
  213319. {
  213320. header << originalURL << " HTTP/1.0\r\nHost: "
  213321. << proxyName << ':' << proxyPort;
  213322. }
  213323. header << "\r\nUser-Agent: JUCE/"
  213324. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  213325. << "\r\nConnection: Close\r\nContent-Length: "
  213326. << postData.getSize() << "\r\n"
  213327. << headers << "\r\n";
  213328. MemoryBlock mb;
  213329. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  213330. mb.append (postData.getData(), postData.getSize());
  213331. return mb;
  213332. }
  213333. const String readResponse (const uint32 timeOutTime)
  213334. {
  213335. int bytesRead = 0, numConsecutiveLFs = 0;
  213336. MemoryBlock buffer (1024, true);
  213337. while (numConsecutiveLFs < 2 && bytesRead < 32768
  213338. && Time::getMillisecondCounter() <= timeOutTime)
  213339. {
  213340. fd_set readbits;
  213341. FD_ZERO (&readbits);
  213342. FD_SET (socketHandle, &readbits);
  213343. struct timeval tv;
  213344. tv.tv_sec = timeoutSeconds;
  213345. tv.tv_usec = 0;
  213346. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  213347. return String::empty; // (timeout)
  213348. buffer.ensureSize (bytesRead + 8, true);
  213349. char* const dest = (char*) buffer.getData() + bytesRead;
  213350. if (recv (socketHandle, dest, 1, 0) == -1)
  213351. return String::empty;
  213352. const char lastByte = *dest;
  213353. ++bytesRead;
  213354. if (lastByte == '\n')
  213355. ++numConsecutiveLFs;
  213356. else if (lastByte != '\r')
  213357. numConsecutiveLFs = 0;
  213358. }
  213359. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  213360. if (header.startsWithIgnoreCase (T("HTTP/")))
  213361. return header.trimEnd();
  213362. return String::empty;
  213363. }
  213364. static bool decomposeURL (const String& url,
  213365. String& host, String& path, int& port)
  213366. {
  213367. if (! url.startsWithIgnoreCase (T("http://")))
  213368. return false;
  213369. const int nextSlash = url.indexOfChar (7, '/');
  213370. int nextColon = url.indexOfChar (7, ':');
  213371. if (nextColon > nextSlash && nextSlash > 0)
  213372. nextColon = -1;
  213373. if (nextColon >= 0)
  213374. {
  213375. host = url.substring (7, nextColon);
  213376. if (nextSlash >= 0)
  213377. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  213378. else
  213379. port = url.substring (nextColon + 1).getIntValue();
  213380. }
  213381. else
  213382. {
  213383. port = 80;
  213384. if (nextSlash >= 0)
  213385. host = url.substring (7, nextSlash);
  213386. else
  213387. host = url.substring (7);
  213388. }
  213389. if (nextSlash >= 0)
  213390. path = url.substring (nextSlash);
  213391. else
  213392. path = T("/");
  213393. return true;
  213394. }
  213395. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  213396. {
  213397. for (int i = 0; i < lines.size(); ++i)
  213398. if (lines[i].startsWithIgnoreCase (itemName))
  213399. return lines[i].substring (itemName.length()).trim();
  213400. return String::empty;
  213401. }
  213402. };
  213403. bool juce_isOnLine()
  213404. {
  213405. return true;
  213406. }
  213407. void* juce_openInternetFile (const String& url,
  213408. const String& headers,
  213409. const MemoryBlock& postData,
  213410. const bool isPost,
  213411. URL::OpenStreamProgressCallback* callback,
  213412. void* callbackContext,
  213413. int timeOutMs)
  213414. {
  213415. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  213416. if (s->open (url, headers, postData, isPost,
  213417. callback, callbackContext, timeOutMs))
  213418. return s;
  213419. delete s;
  213420. return 0;
  213421. }
  213422. void juce_closeInternetFile (void* handle)
  213423. {
  213424. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213425. if (s != 0)
  213426. delete s;
  213427. }
  213428. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  213429. {
  213430. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213431. if (s != 0)
  213432. return s->read (buffer, bytesToRead);
  213433. return 0;
  213434. }
  213435. int64 juce_getInternetFileContentLength (void* handle)
  213436. {
  213437. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213438. if (s != 0)
  213439. {
  213440. //xxx todo
  213441. jassertfalse
  213442. }
  213443. return -1;
  213444. }
  213445. int juce_seekInInternetFile (void* handle, int newPosition)
  213446. {
  213447. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  213448. if (s != 0)
  213449. return s->readPosition;
  213450. return 0;
  213451. }
  213452. #endif
  213453. /********* End of inlined file: juce_linux_Network.cpp *********/
  213454. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  213455. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213456. // compiled on its own).
  213457. #ifdef JUCE_INCLUDED_FILE
  213458. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  213459. {
  213460. unsigned int cpu = 0;
  213461. unsigned int ext = 0;
  213462. unsigned int family = 0;
  213463. unsigned int dummy = 0;
  213464. #if JUCE_64BIT
  213465. __asm__ ("cpuid"
  213466. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213467. #else
  213468. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  213469. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  213470. #endif
  213471. if (familyModel != 0)
  213472. *familyModel = family;
  213473. if (extFeatures != 0)
  213474. *extFeatures = ext;
  213475. return cpu;
  213476. }*/
  213477. void Logger::outputDebugString (const String& text) throw()
  213478. {
  213479. fputs (text.toUTF8(), stdout);
  213480. fputs ("\n", stdout);
  213481. }
  213482. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  213483. {
  213484. String text;
  213485. va_list args;
  213486. va_start (args, format);
  213487. text.vprintf(format, args);
  213488. outputDebugString(text);
  213489. }
  213490. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  213491. {
  213492. return Linux;
  213493. }
  213494. const String SystemStats::getOperatingSystemName() throw()
  213495. {
  213496. return T("Linux");
  213497. }
  213498. bool SystemStats::isOperatingSystem64Bit() throw()
  213499. {
  213500. #if JUCE_64BIT
  213501. return true;
  213502. #else
  213503. //xxx not sure how to find this out?..
  213504. return false;
  213505. #endif
  213506. }
  213507. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  213508. {
  213509. String info;
  213510. char buf [256];
  213511. FILE* f = fopen ("/proc/cpuinfo", "r");
  213512. while (f != 0 && fgets (buf, sizeof(buf), f))
  213513. {
  213514. if (strncmp (buf, key, strlen (key)) == 0)
  213515. {
  213516. char* p = buf;
  213517. while (*p && *p != '\n')
  213518. ++p;
  213519. if (*p != 0)
  213520. *p = 0;
  213521. p = buf;
  213522. while (*p != 0 && *p != ':')
  213523. ++p;
  213524. if (*p != 0 && *(p + 1) != 0)
  213525. info = p + 2;
  213526. if (! lastOne)
  213527. break;
  213528. }
  213529. }
  213530. fclose (f);
  213531. return info;
  213532. }
  213533. bool SystemStats::hasMMX() throw()
  213534. {
  213535. return getCpuInfo ("flags").contains (T("mmx"));
  213536. }
  213537. bool SystemStats::hasSSE() throw()
  213538. {
  213539. return getCpuInfo ("flags").contains (T("sse"));
  213540. }
  213541. bool SystemStats::hasSSE2() throw()
  213542. {
  213543. return getCpuInfo ("flags").contains (T("sse2"));
  213544. }
  213545. bool SystemStats::has3DNow() throw()
  213546. {
  213547. return getCpuInfo ("flags").contains (T("3dnow"));
  213548. }
  213549. const String SystemStats::getCpuVendor() throw()
  213550. {
  213551. return getCpuInfo ("vendor_id");
  213552. }
  213553. int SystemStats::getCpuSpeedInMegaherz() throw()
  213554. {
  213555. const String speed (getCpuInfo ("cpu MHz"));
  213556. return (int) (speed.getFloatValue() + 0.5f);
  213557. }
  213558. int SystemStats::getMemorySizeInMegabytes() throw()
  213559. {
  213560. struct sysinfo sysi;
  213561. if (sysinfo (&sysi) == 0)
  213562. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  213563. return 0;
  213564. }
  213565. uint32 juce_millisecondsSinceStartup() throw()
  213566. {
  213567. static unsigned int calibrate = 0;
  213568. static bool calibrated = false;
  213569. timeval t;
  213570. unsigned int ret = 0;
  213571. if (! gettimeofday (&t, 0))
  213572. {
  213573. if (! calibrated)
  213574. {
  213575. struct sysinfo sysi;
  213576. if (sysinfo (&sysi) == 0)
  213577. // Safe to assume system was not brought up earlier than 1970!
  213578. calibrate = t.tv_sec - sysi.uptime;
  213579. calibrated = true;
  213580. }
  213581. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  213582. }
  213583. return ret;
  213584. }
  213585. double Time::getMillisecondCounterHiRes() throw()
  213586. {
  213587. return getHighResolutionTicks() * 0.001;
  213588. }
  213589. int64 Time::getHighResolutionTicks() throw()
  213590. {
  213591. timeval t;
  213592. if (gettimeofday (&t, 0))
  213593. return 0;
  213594. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  213595. }
  213596. int64 Time::getHighResolutionTicksPerSecond() throw()
  213597. {
  213598. // Microseconds
  213599. return 1000000;
  213600. }
  213601. bool Time::setSystemTimeToThisTime() const throw()
  213602. {
  213603. timeval t;
  213604. t.tv_sec = millisSinceEpoch % 1000000;
  213605. t.tv_usec = millisSinceEpoch - t.tv_sec;
  213606. return settimeofday (&t, NULL) ? false : true;
  213607. }
  213608. int SystemStats::getPageSize() throw()
  213609. {
  213610. static int systemPageSize = 0;
  213611. if (systemPageSize == 0)
  213612. systemPageSize = sysconf (_SC_PAGESIZE);
  213613. return systemPageSize;
  213614. }
  213615. int SystemStats::getNumCpus() throw()
  213616. {
  213617. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  213618. return lastCpu + 1;
  213619. }
  213620. void SystemStats::initialiseStats() throw()
  213621. {
  213622. // Process starts off as root when running suid
  213623. Process::lowerPrivilege();
  213624. String s (SystemStats::getJUCEVersion());
  213625. }
  213626. void PlatformUtilities::fpuReset()
  213627. {
  213628. }
  213629. #endif
  213630. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  213631. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  213632. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213633. // compiled on its own).
  213634. #ifdef JUCE_INCLUDED_FILE
  213635. /*
  213636. Note that a lot of methods that you'd expect to find in this file actually
  213637. live in juce_posix_SharedCode.h!
  213638. */
  213639. void JUCE_API juce_threadEntryPoint (void*);
  213640. void* threadEntryProc (void* value) throw()
  213641. {
  213642. // New threads start off as root when running suid
  213643. Process::lowerPrivilege();
  213644. juce_threadEntryPoint (value);
  213645. return 0;
  213646. }
  213647. void* juce_createThread (void* userData) throw()
  213648. {
  213649. pthread_t handle = 0;
  213650. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  213651. {
  213652. pthread_detach (handle);
  213653. return (void*)handle;
  213654. }
  213655. return 0;
  213656. }
  213657. void juce_killThread (void* handle) throw()
  213658. {
  213659. if (handle != 0)
  213660. pthread_cancel ((pthread_t)handle);
  213661. }
  213662. void juce_setCurrentThreadName (const String& /*name*/) throw()
  213663. {
  213664. }
  213665. Thread::ThreadID Thread::getCurrentThreadId() throw()
  213666. {
  213667. return (ThreadID) pthread_self();
  213668. }
  213669. /*
  213670. * This is all a bit non-ideal... the trouble is that on Linux you
  213671. * need to call setpriority to affect the dynamic priority for
  213672. * non-realtime processes, but this requires the pid, which is not
  213673. * accessible from the pthread_t. We could get it by calling getpid
  213674. * once each thread has started, but then we would need a list of
  213675. * running threads etc etc.
  213676. * Also there is no such thing as IDLE priority on Linux.
  213677. * For the moment, map idle, low and normal process priorities to
  213678. * SCHED_OTHER, with the thread priority ignored for these classes.
  213679. * Map high priority processes to the lower half of the SCHED_RR
  213680. * range, and realtime to the upper half
  213681. */
  213682. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  213683. // priority of the current thread
  213684. bool juce_setThreadPriority (void* handle, int priority) throw()
  213685. {
  213686. struct sched_param param;
  213687. int policy, maxp, minp, pri;
  213688. if (handle == 0)
  213689. handle = (void*) pthread_self();
  213690. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  213691. && policy != SCHED_OTHER)
  213692. {
  213693. minp = sched_get_priority_min(policy);
  213694. maxp = sched_get_priority_max(policy);
  213695. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  213696. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  213697. // Realtime process priority
  213698. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  213699. else
  213700. // High process priority
  213701. param.__sched_priority = minp + pri;
  213702. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  213703. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  213704. }
  213705. return false;
  213706. }
  213707. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  213708. {
  213709. #if SUPPORT_AFFINITIES
  213710. cpu_set_t affinity;
  213711. CPU_ZERO (&affinity);
  213712. for (int i = 0; i < 32; ++i)
  213713. if ((affinityMask & (1 << i)) != 0)
  213714. CPU_SET (i, &affinity);
  213715. /*
  213716. N.B. If this line causes a compile error, then you've probably not got the latest
  213717. version of glibc installed.
  213718. If you don't want to update your copy of glibc and don't care about cpu affinities,
  213719. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  213720. from the linuxincludes.h file.
  213721. */
  213722. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  213723. sched_yield();
  213724. #else
  213725. /* affinities aren't supported because either the appropriate header files weren't found,
  213726. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  213727. */
  213728. jassertfalse
  213729. #endif
  213730. }
  213731. void Thread::yield() throw()
  213732. {
  213733. sched_yield();
  213734. }
  213735. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  213736. void Process::setPriority (ProcessPriority prior)
  213737. {
  213738. struct sched_param param;
  213739. int policy, maxp, minp;
  213740. const int p = (int) prior;
  213741. if (p <= 1)
  213742. policy = SCHED_OTHER;
  213743. else
  213744. policy = SCHED_RR;
  213745. minp = sched_get_priority_min (policy);
  213746. maxp = sched_get_priority_max (policy);
  213747. if (p < 2)
  213748. param.__sched_priority = 0;
  213749. else if (p == 2 )
  213750. // Set to middle of lower realtime priority range
  213751. param.__sched_priority = minp + (maxp - minp) / 4;
  213752. else
  213753. // Set to middle of higher realtime priority range
  213754. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  213755. pthread_setschedparam (pthread_self(), policy, &param);
  213756. }
  213757. void Process::terminate()
  213758. {
  213759. exit (0);
  213760. }
  213761. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  213762. {
  213763. static char testResult = 0;
  213764. if (testResult == 0)
  213765. {
  213766. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  213767. if (testResult >= 0)
  213768. {
  213769. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  213770. testResult = 1;
  213771. }
  213772. }
  213773. return testResult < 0;
  213774. }
  213775. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  213776. {
  213777. return juce_isRunningUnderDebugger();
  213778. }
  213779. void Process::raisePrivilege()
  213780. {
  213781. // If running suid root, change effective user
  213782. // to root
  213783. if (geteuid() != 0 && getuid() == 0)
  213784. {
  213785. setreuid (geteuid(), getuid());
  213786. setregid (getegid(), getgid());
  213787. }
  213788. }
  213789. void Process::lowerPrivilege()
  213790. {
  213791. // If runing suid root, change effective user
  213792. // back to real user
  213793. if (geteuid() == 0 && getuid() != 0)
  213794. {
  213795. setreuid (geteuid(), getuid());
  213796. setregid (getegid(), getgid());
  213797. }
  213798. }
  213799. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213800. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  213801. {
  213802. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  213803. }
  213804. void PlatformUtilities::freeDynamicLibrary (void* handle)
  213805. {
  213806. dlclose(handle);
  213807. }
  213808. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  213809. {
  213810. return dlsym (libraryHandle, (const char*) procedureName);
  213811. }
  213812. #endif
  213813. #endif
  213814. /********* End of inlined file: juce_linux_Threads.cpp *********/
  213815. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  213816. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  213817. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  213818. // compiled on its own).
  213819. #ifdef JUCE_INCLUDED_FILE
  213820. #ifdef JUCE_DEBUG
  213821. #define JUCE_DEBUG_XERRORS 1
  213822. #endif
  213823. Display* display = 0; // This is also referenced from WindowDriver.cpp
  213824. static Window juce_messageWindowHandle = None;
  213825. #define SpecialAtom "JUCESpecialAtom"
  213826. #define BroadcastAtom "JUCEBroadcastAtom"
  213827. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  213828. static Atom specialId;
  213829. static Atom broadcastId;
  213830. static Atom specialCallbackId;
  213831. // This is referenced from WindowDriver.cpp
  213832. XContext improbableNumber;
  213833. // Defined in WindowDriver.cpp
  213834. extern void juce_windowMessageReceive (XEvent* event);
  213835. struct MessageThreadFuncCall
  213836. {
  213837. MessageCallbackFunction* func;
  213838. void* parameter;
  213839. void* result;
  213840. CriticalSection lock;
  213841. WaitableEvent event;
  213842. };
  213843. static bool errorCondition = false;
  213844. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  213845. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  213846. // (defined in another file to avoid problems including certain headers in this one)
  213847. extern bool juce_isRunningAsApplication();
  213848. // Usually happens when client-server connection is broken
  213849. static int ioErrorHandler (Display* display)
  213850. {
  213851. DBG (T("ERROR: connection to X server broken.. terminating."));
  213852. errorCondition = true;
  213853. if (juce_isRunningAsApplication())
  213854. Process::terminate();
  213855. return 0;
  213856. }
  213857. // A protocol error has occurred
  213858. static int errorHandler (Display* display, XErrorEvent* event)
  213859. {
  213860. #ifdef JUCE_DEBUG_XERRORS
  213861. char errorStr[64] = { 0 };
  213862. char requestStr[64] = { 0 };
  213863. XGetErrorText (display, event->error_code, errorStr, 64);
  213864. XGetErrorDatabaseText (display,
  213865. "XRequest",
  213866. (const char*) String (event->request_code),
  213867. "Unknown",
  213868. requestStr,
  213869. 64);
  213870. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  213871. #endif
  213872. return 0;
  213873. }
  213874. static bool breakIn = false;
  213875. // Breakin from keyboard
  213876. static void sig_handler (int sig)
  213877. {
  213878. if (sig == SIGINT)
  213879. {
  213880. breakIn = true;
  213881. return;
  213882. }
  213883. static bool reentrant = false;
  213884. if (reentrant == false)
  213885. {
  213886. reentrant = true;
  213887. // Illegal instruction
  213888. fflush (stdout);
  213889. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  213890. errorCondition = true;
  213891. if (juce_isRunningAsApplication())
  213892. Process::terminate();
  213893. }
  213894. else
  213895. {
  213896. if (juce_isRunningAsApplication())
  213897. exit(0);
  213898. }
  213899. }
  213900. void MessageManager::doPlatformSpecificInitialisation()
  213901. {
  213902. // Initialise xlib for multiple thread support
  213903. static bool initThreadCalled = false;
  213904. if (! initThreadCalled)
  213905. {
  213906. if (! XInitThreads())
  213907. {
  213908. // This is fatal! Print error and closedown
  213909. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  213910. if (juce_isRunningAsApplication())
  213911. Process::terminate();
  213912. return;
  213913. }
  213914. initThreadCalled = true;
  213915. }
  213916. // This is called if the client/server connection is broken
  213917. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  213918. // This is called if a protocol error occurs
  213919. oldErrorHandler = XSetErrorHandler (errorHandler);
  213920. // Install signal handler for break-in
  213921. struct sigaction saction;
  213922. sigset_t maskSet;
  213923. sigemptyset (&maskSet);
  213924. saction.sa_handler = sig_handler;
  213925. saction.sa_mask = maskSet;
  213926. saction.sa_flags = 0;
  213927. sigaction (SIGINT, &saction, NULL);
  213928. #ifndef _DEBUG
  213929. // Setup signal handlers for various fatal errors
  213930. sigaction (SIGILL, &saction, NULL);
  213931. sigaction (SIGBUS, &saction, NULL);
  213932. sigaction (SIGFPE, &saction, NULL);
  213933. sigaction (SIGSEGV, &saction, NULL);
  213934. sigaction (SIGSYS, &saction, NULL);
  213935. #endif
  213936. String displayName (getenv ("DISPLAY"));
  213937. if (displayName.isEmpty())
  213938. displayName = T(":0.0");
  213939. display = XOpenDisplay (displayName);
  213940. if (display == 0)
  213941. {
  213942. // This is fatal! Print error and closedown
  213943. Logger::outputDebugString ("Failed to open the X display.");
  213944. if (juce_isRunningAsApplication())
  213945. Process::terminate();
  213946. return;
  213947. }
  213948. // Get defaults for various properties
  213949. int screen = DefaultScreen (display);
  213950. Window root = RootWindow (display, screen);
  213951. Visual* visual = DefaultVisual (display, screen);
  213952. // Create atoms for our ClientMessages (these cannot be deleted)
  213953. specialId = XInternAtom (display, SpecialAtom, false);
  213954. broadcastId = XInternAtom (display, BroadcastAtom, false);
  213955. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  213956. // Create a context to store user data associated with Windows we
  213957. // create in WindowDriver
  213958. improbableNumber = XUniqueContext();
  213959. // We're only interested in client messages for this window
  213960. // which are always sent
  213961. XSetWindowAttributes swa;
  213962. swa.event_mask = NoEventMask;
  213963. // Create our message window (this will never be mapped)
  213964. juce_messageWindowHandle = XCreateWindow (display, root,
  213965. 0, 0, 1, 1, 0, 0, InputOnly,
  213966. visual, CWEventMask, &swa);
  213967. }
  213968. void MessageManager::doPlatformSpecificShutdown()
  213969. {
  213970. if (errorCondition == false)
  213971. {
  213972. XDestroyWindow (display, juce_messageWindowHandle);
  213973. XCloseDisplay (display);
  213974. // reset pointers
  213975. juce_messageWindowHandle = 0;
  213976. display = 0;
  213977. // Restore original error handlers
  213978. XSetIOErrorHandler (oldIOErrorHandler);
  213979. oldIOErrorHandler = 0;
  213980. XSetErrorHandler (oldErrorHandler);
  213981. oldErrorHandler = 0;
  213982. }
  213983. }
  213984. bool juce_postMessageToSystemQueue (void* message)
  213985. {
  213986. if (errorCondition)
  213987. return false;
  213988. XClientMessageEvent clientMsg;
  213989. clientMsg.display = display;
  213990. clientMsg.window = juce_messageWindowHandle;
  213991. clientMsg.type = ClientMessage;
  213992. clientMsg.format = 32;
  213993. clientMsg.message_type = specialId;
  213994. #if JUCE_64BIT
  213995. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  213996. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  213997. #else
  213998. clientMsg.data.l[0] = (long) message;
  213999. #endif
  214000. XSendEvent (display, juce_messageWindowHandle, false,
  214001. NoEventMask, (XEvent*) &clientMsg);
  214002. XFlush (display); // This is necessary to ensure the event is delivered
  214003. return true;
  214004. }
  214005. void MessageManager::broadcastMessage (const String& value) throw()
  214006. {
  214007. }
  214008. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  214009. void* parameter)
  214010. {
  214011. void* retVal = 0;
  214012. if (! errorCondition)
  214013. {
  214014. if (! isThisTheMessageThread())
  214015. {
  214016. static MessageThreadFuncCall messageFuncCallContext;
  214017. const ScopedLock sl (messageFuncCallContext.lock);
  214018. XClientMessageEvent clientMsg;
  214019. clientMsg.display = display;
  214020. clientMsg.window = juce_messageWindowHandle;
  214021. clientMsg.type = ClientMessage;
  214022. clientMsg.format = 32;
  214023. clientMsg.message_type = specialCallbackId;
  214024. #if JUCE_64BIT
  214025. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  214026. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  214027. #else
  214028. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  214029. #endif
  214030. messageFuncCallContext.func = func;
  214031. messageFuncCallContext.parameter = parameter;
  214032. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  214033. return 0;
  214034. XFlush (display); // This is necessary to ensure the event is delivered
  214035. // Wait for it to complete before continuing
  214036. messageFuncCallContext.event.wait();
  214037. retVal = messageFuncCallContext.result;
  214038. }
  214039. else
  214040. {
  214041. // Just call the function directly
  214042. retVal = func (parameter);
  214043. }
  214044. }
  214045. return retVal;
  214046. }
  214047. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  214048. {
  214049. if (errorCondition)
  214050. return false;
  214051. if (breakIn)
  214052. {
  214053. errorCondition = true;
  214054. if (juce_isRunningAsApplication())
  214055. Process::terminate();
  214056. return false;
  214057. }
  214058. if (returnIfNoPendingMessages && ! XPending (display))
  214059. return false;
  214060. XEvent evt;
  214061. XNextEvent (display, &evt);
  214062. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  214063. {
  214064. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  214065. if (clientMsg->format != 32)
  214066. {
  214067. jassertfalse
  214068. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  214069. }
  214070. else
  214071. {
  214072. JUCE_TRY
  214073. {
  214074. #if JUCE_64BIT
  214075. void* const messagePtr
  214076. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  214077. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  214078. #else
  214079. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  214080. #endif
  214081. if (clientMsg->message_type == specialId)
  214082. {
  214083. MessageManager::getInstance()->deliverMessage (messagePtr);
  214084. }
  214085. else if (clientMsg->message_type == specialCallbackId)
  214086. {
  214087. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  214088. MessageCallbackFunction* func = call->func;
  214089. call->result = (*func) (call->parameter);
  214090. call->event.signal();
  214091. }
  214092. else if (clientMsg->message_type == broadcastId)
  214093. {
  214094. #if 0
  214095. TCHAR buffer[8192];
  214096. zeromem (buffer, sizeof (buffer));
  214097. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  214098. mq->deliverBroadcastMessage (String (buffer));
  214099. #endif
  214100. }
  214101. else
  214102. {
  214103. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  214104. }
  214105. }
  214106. JUCE_CATCH_ALL
  214107. }
  214108. }
  214109. else if (evt.xany.window != juce_messageWindowHandle)
  214110. {
  214111. juce_windowMessageReceive (&evt);
  214112. }
  214113. return true;
  214114. }
  214115. #endif
  214116. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  214117. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  214118. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214119. // compiled on its own).
  214120. #ifdef JUCE_INCLUDED_FILE
  214121. class FreeTypeFontFace
  214122. {
  214123. public:
  214124. enum FontStyle
  214125. {
  214126. Plain = 0,
  214127. Bold = 1,
  214128. Italic = 2
  214129. };
  214130. struct FontNameIndex
  214131. {
  214132. String fileName;
  214133. int faceIndex;
  214134. };
  214135. FreeTypeFontFace (const String& familyName)
  214136. : hasSerif (false),
  214137. monospaced (false)
  214138. {
  214139. family = familyName;
  214140. }
  214141. void setFileName (const String& name,
  214142. const int faceIndex,
  214143. FontStyle style)
  214144. {
  214145. if (names[(int) style].fileName.isEmpty())
  214146. {
  214147. names[(int) style].fileName = name;
  214148. names[(int) style].faceIndex = faceIndex;
  214149. }
  214150. }
  214151. const String& getFamilyName() const throw()
  214152. {
  214153. return family;
  214154. }
  214155. const String& getFileName (int style, int* faceIndex) const throw()
  214156. {
  214157. *faceIndex = names [style].faceIndex;
  214158. return names[style].fileName;
  214159. }
  214160. void setMonospaced (bool mono) { monospaced = mono; }
  214161. bool getMonospaced () const throw() { return monospaced; }
  214162. void setSerif (const bool serif) { hasSerif = serif; }
  214163. bool getSerif () const throw() { return hasSerif; }
  214164. private:
  214165. String family;
  214166. FontNameIndex names[4];
  214167. bool hasSerif, monospaced;
  214168. };
  214169. class FreeTypeInterface : public DeletedAtShutdown
  214170. {
  214171. public:
  214172. FreeTypeInterface() throw()
  214173. : lastFace (0),
  214174. lastBold (false),
  214175. lastItalic (false)
  214176. {
  214177. if (FT_Init_FreeType (&ftLib) != 0)
  214178. {
  214179. ftLib = 0;
  214180. DBG (T("Failed to initialize FreeType"));
  214181. }
  214182. StringArray fontDirs;
  214183. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  214184. fontDirs.removeEmptyStrings (true);
  214185. if (fontDirs.size() == 0)
  214186. {
  214187. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  214188. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  214189. if (fontsInfo != 0)
  214190. {
  214191. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  214192. {
  214193. fontDirs.add (e->getAllSubText().trim());
  214194. }
  214195. delete fontsInfo;
  214196. }
  214197. }
  214198. if (fontDirs.size() == 0)
  214199. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  214200. for (int i = 0; i < fontDirs.size(); ++i)
  214201. enumerateFaces (fontDirs[i]);
  214202. }
  214203. ~FreeTypeInterface() throw()
  214204. {
  214205. if (lastFace != 0)
  214206. FT_Done_Face (lastFace);
  214207. if (ftLib != 0)
  214208. FT_Done_FreeType (ftLib);
  214209. clearSingletonInstance();
  214210. }
  214211. FreeTypeFontFace* findOrCreate (const String& familyName,
  214212. const bool create = false) throw()
  214213. {
  214214. for (int i = 0; i < faces.size(); i++)
  214215. if (faces[i]->getFamilyName() == familyName)
  214216. return faces[i];
  214217. if (! create)
  214218. return NULL;
  214219. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  214220. faces.add (newFace);
  214221. return newFace;
  214222. }
  214223. // Enumerate all font faces available in a given directory
  214224. void enumerateFaces (const String& path) throw()
  214225. {
  214226. File dirPath (path);
  214227. if (path.isEmpty() || ! dirPath.isDirectory())
  214228. return;
  214229. DirectoryIterator di (dirPath, true);
  214230. while (di.next())
  214231. {
  214232. File possible (di.getFile());
  214233. if (possible.hasFileExtension (T("ttf"))
  214234. || possible.hasFileExtension (T("pfb"))
  214235. || possible.hasFileExtension (T("pcf")))
  214236. {
  214237. FT_Face face;
  214238. int faceIndex = 0;
  214239. int numFaces = 0;
  214240. do
  214241. {
  214242. if (FT_New_Face (ftLib,
  214243. possible.getFullPathName(),
  214244. faceIndex,
  214245. &face) == 0)
  214246. {
  214247. if (faceIndex == 0)
  214248. numFaces = face->num_faces;
  214249. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  214250. {
  214251. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  214252. int style = (int) FreeTypeFontFace::Plain;
  214253. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  214254. style |= (int) FreeTypeFontFace::Bold;
  214255. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  214256. style |= (int) FreeTypeFontFace::Italic;
  214257. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  214258. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  214259. newFace->setMonospaced (true);
  214260. else
  214261. newFace->setMonospaced (false);
  214262. // Surely there must be a better way to do this?
  214263. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  214264. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  214265. || String (face->family_name).containsIgnoreCase (T("Arial")))
  214266. {
  214267. newFace->setSerif (false);
  214268. }
  214269. else
  214270. {
  214271. newFace->setSerif (true);
  214272. }
  214273. }
  214274. FT_Done_Face (face);
  214275. }
  214276. ++faceIndex;
  214277. }
  214278. while (faceIndex < numFaces);
  214279. }
  214280. }
  214281. }
  214282. // Create a FreeType face object for a given font
  214283. FT_Face createFT_Face (const String& fontName,
  214284. const bool bold,
  214285. const bool italic) throw()
  214286. {
  214287. FT_Face face = NULL;
  214288. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  214289. {
  214290. face = lastFace;
  214291. }
  214292. else
  214293. {
  214294. if (lastFace)
  214295. {
  214296. FT_Done_Face (lastFace);
  214297. lastFace = NULL;
  214298. }
  214299. lastFontName = fontName;
  214300. lastBold = bold;
  214301. lastItalic = italic;
  214302. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  214303. if (ftFace != 0)
  214304. {
  214305. int style = (int) FreeTypeFontFace::Plain;
  214306. if (bold)
  214307. style |= (int) FreeTypeFontFace::Bold;
  214308. if (italic)
  214309. style |= (int) FreeTypeFontFace::Italic;
  214310. int faceIndex;
  214311. String fileName (ftFace->getFileName (style, &faceIndex));
  214312. if (fileName.isEmpty())
  214313. {
  214314. style ^= (int) FreeTypeFontFace::Bold;
  214315. fileName = ftFace->getFileName (style, &faceIndex);
  214316. if (fileName.isEmpty())
  214317. {
  214318. style ^= (int) FreeTypeFontFace::Bold;
  214319. style ^= (int) FreeTypeFontFace::Italic;
  214320. fileName = ftFace->getFileName (style, &faceIndex);
  214321. if (! fileName.length())
  214322. {
  214323. style ^= (int) FreeTypeFontFace::Bold;
  214324. fileName = ftFace->getFileName (style, &faceIndex);
  214325. }
  214326. }
  214327. }
  214328. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  214329. {
  214330. face = lastFace;
  214331. // If there isn't a unicode charmap then select the first one.
  214332. if (FT_Select_Charmap (face, ft_encoding_unicode))
  214333. FT_Set_Charmap (face, face->charmaps[0]);
  214334. }
  214335. }
  214336. }
  214337. return face;
  214338. }
  214339. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  214340. {
  214341. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  214342. const float height = (float) (face->ascender - face->descender);
  214343. const float scaleX = 1.0f / height;
  214344. const float scaleY = -1.0f / height;
  214345. Path destShape;
  214346. #define CONVERTX(val) (scaleX * (val).x)
  214347. #define CONVERTY(val) (scaleY * (val).y)
  214348. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  214349. | FT_LOAD_NO_BITMAP
  214350. | FT_LOAD_IGNORE_TRANSFORM) != 0
  214351. || face->glyph->format != ft_glyph_format_outline)
  214352. {
  214353. return false;
  214354. }
  214355. const FT_Outline* const outline = &face->glyph->outline;
  214356. const short* const contours = outline->contours;
  214357. const char* const tags = outline->tags;
  214358. FT_Vector* const points = outline->points;
  214359. for (int c = 0; c < outline->n_contours; c++)
  214360. {
  214361. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  214362. const int endPoint = contours[c];
  214363. for (int p = startPoint; p <= endPoint; p++)
  214364. {
  214365. const float x = CONVERTX (points[p]);
  214366. const float y = CONVERTY (points[p]);
  214367. if (p == startPoint)
  214368. {
  214369. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214370. {
  214371. float x2 = CONVERTX (points [endPoint]);
  214372. float y2 = CONVERTY (points [endPoint]);
  214373. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  214374. {
  214375. x2 = (x + x2) * 0.5f;
  214376. y2 = (y + y2) * 0.5f;
  214377. }
  214378. destShape.startNewSubPath (x2, y2);
  214379. }
  214380. else
  214381. {
  214382. destShape.startNewSubPath (x, y);
  214383. }
  214384. }
  214385. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  214386. {
  214387. if (p != startPoint)
  214388. destShape.lineTo (x, y);
  214389. }
  214390. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  214391. {
  214392. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  214393. float x2 = CONVERTX (points [nextIndex]);
  214394. float y2 = CONVERTY (points [nextIndex]);
  214395. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  214396. {
  214397. x2 = (x + x2) * 0.5f;
  214398. y2 = (y + y2) * 0.5f;
  214399. }
  214400. else
  214401. {
  214402. ++p;
  214403. }
  214404. destShape.quadraticTo (x, y, x2, y2);
  214405. }
  214406. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  214407. {
  214408. if (p >= endPoint)
  214409. return false;
  214410. const int next1 = p + 1;
  214411. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  214412. const float x2 = CONVERTX (points [next1]);
  214413. const float y2 = CONVERTY (points [next1]);
  214414. const float x3 = CONVERTX (points [next2]);
  214415. const float y3 = CONVERTY (points [next2]);
  214416. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  214417. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  214418. return false;
  214419. destShape.cubicTo (x, y, x2, y2, x3, y3);
  214420. p += 2;
  214421. }
  214422. }
  214423. destShape.closeSubPath();
  214424. }
  214425. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  214426. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  214427. addKerning (face, dest, character, glyphIndex);
  214428. return true;
  214429. }
  214430. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  214431. {
  214432. const float height = (float) (face->ascender - face->descender);
  214433. uint32 rightGlyphIndex;
  214434. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  214435. while (rightGlyphIndex != 0)
  214436. {
  214437. FT_Vector kerning;
  214438. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  214439. {
  214440. if (kerning.x != 0)
  214441. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  214442. }
  214443. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  214444. }
  214445. }
  214446. // Add a glyph to a font
  214447. bool addGlyphToFont (const uint32 character,
  214448. const tchar* fontName, bool bold, bool italic,
  214449. Typeface& dest) throw()
  214450. {
  214451. FT_Face face = createFT_Face (fontName, bold, italic);
  214452. if (face != 0)
  214453. return addGlyph (face, dest, character);
  214454. return false;
  214455. }
  214456. // Create a Typeface object for given name/style
  214457. bool createTypeface (const String& fontName,
  214458. const bool bold, const bool italic,
  214459. Typeface& dest,
  214460. const bool addAllGlyphs) throw()
  214461. {
  214462. dest.clear();
  214463. dest.setName (fontName);
  214464. dest.setBold (bold);
  214465. dest.setItalic (italic);
  214466. FT_Face face = createFT_Face (fontName, bold, italic);
  214467. if (face == 0)
  214468. {
  214469. #ifdef JUCE_DEBUG
  214470. String msg (T("Failed to create typeface: "));
  214471. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  214472. DBG (msg);
  214473. #endif
  214474. return face;
  214475. }
  214476. const float height = (float) (face->ascender - face->descender);
  214477. dest.setAscent (face->ascender / height);
  214478. dest.setDefaultCharacter (L' ');
  214479. if (addAllGlyphs)
  214480. {
  214481. uint32 glyphIndex;
  214482. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  214483. while (glyphIndex != 0)
  214484. {
  214485. addGlyph (face, dest, charCode);
  214486. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  214487. }
  214488. }
  214489. return true;
  214490. }
  214491. void getFamilyNames (StringArray& familyNames) const throw()
  214492. {
  214493. for (int i = 0; i < faces.size(); i++)
  214494. familyNames.add (faces[i]->getFamilyName());
  214495. }
  214496. void getMonospacedNames (StringArray& monoSpaced) const throw()
  214497. {
  214498. for (int i = 0; i < faces.size(); i++)
  214499. if (faces[i]->getMonospaced())
  214500. monoSpaced.add (faces[i]->getFamilyName());
  214501. }
  214502. void getSerifNames (StringArray& serif) const throw()
  214503. {
  214504. for (int i = 0; i < faces.size(); i++)
  214505. if (faces[i]->getSerif())
  214506. serif.add (faces[i]->getFamilyName());
  214507. }
  214508. void getSansSerifNames (StringArray& sansSerif) const throw()
  214509. {
  214510. for (int i = 0; i < faces.size(); i++)
  214511. if (! faces[i]->getSerif())
  214512. sansSerif.add (faces[i]->getFamilyName());
  214513. }
  214514. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  214515. private:
  214516. FT_Library ftLib;
  214517. FT_Face lastFace;
  214518. String lastFontName;
  214519. bool lastBold, lastItalic;
  214520. OwnedArray<FreeTypeFontFace> faces;
  214521. };
  214522. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  214523. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  214524. bool bold, bool italic,
  214525. bool addAllGlyphsToFont) throw()
  214526. {
  214527. FreeTypeInterface::getInstance()
  214528. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  214529. }
  214530. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  214531. {
  214532. return FreeTypeInterface::getInstance()
  214533. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  214534. }
  214535. const StringArray Font::findAllTypefaceNames() throw()
  214536. {
  214537. StringArray s;
  214538. FreeTypeInterface::getInstance()->getFamilyNames (s);
  214539. s.sort (true);
  214540. return s;
  214541. }
  214542. static const String pickBestFont (const StringArray& names,
  214543. const char* const choicesString)
  214544. {
  214545. StringArray choices;
  214546. choices.addTokens (String (choicesString), T(","), 0);
  214547. choices.trim();
  214548. choices.removeEmptyStrings();
  214549. int i, j;
  214550. for (j = 0; j < choices.size(); ++j)
  214551. if (names.contains (choices[j], true))
  214552. return choices[j];
  214553. for (j = 0; j < choices.size(); ++j)
  214554. for (i = 0; i < names.size(); i++)
  214555. if (names[i].startsWithIgnoreCase (choices[j]))
  214556. return names[i];
  214557. for (j = 0; j < choices.size(); ++j)
  214558. for (i = 0; i < names.size(); i++)
  214559. if (names[i].containsIgnoreCase (choices[j]))
  214560. return names[i];
  214561. return names[0];
  214562. }
  214563. static const String linux_getDefaultSansSerifFontName()
  214564. {
  214565. StringArray allFonts;
  214566. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  214567. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  214568. }
  214569. static const String linux_getDefaultSerifFontName()
  214570. {
  214571. StringArray allFonts;
  214572. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  214573. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  214574. }
  214575. static const String linux_getDefaultMonospacedFontName()
  214576. {
  214577. StringArray allFonts;
  214578. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  214579. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  214580. }
  214581. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  214582. {
  214583. defaultSans = linux_getDefaultSansSerifFontName();
  214584. defaultSerif = linux_getDefaultSerifFontName();
  214585. defaultFixed = linux_getDefaultMonospacedFontName();
  214586. }
  214587. #endif
  214588. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  214589. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  214590. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  214591. // compiled on its own).
  214592. #ifdef JUCE_INCLUDED_FILE
  214593. #define TAKE_FOCUS 0
  214594. #define DELETE_WINDOW 1
  214595. #define SYSTEM_TRAY_REQUEST_DOCK 0
  214596. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  214597. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  214598. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  214599. static Atom wm_ChangeState = None;
  214600. static Atom wm_State = None;
  214601. static Atom wm_Protocols = None;
  214602. static Atom wm_ProtocolList [2] = { None, None };
  214603. static Atom wm_ActiveWin = None;
  214604. #define ourDndVersion 3
  214605. static Atom XA_XdndAware = None;
  214606. static Atom XA_XdndEnter = None;
  214607. static Atom XA_XdndLeave = None;
  214608. static Atom XA_XdndPosition = None;
  214609. static Atom XA_XdndStatus = None;
  214610. static Atom XA_XdndDrop = None;
  214611. static Atom XA_XdndFinished = None;
  214612. static Atom XA_XdndSelection = None;
  214613. static Atom XA_XdndProxy = None;
  214614. static Atom XA_XdndTypeList = None;
  214615. static Atom XA_XdndActionList = None;
  214616. static Atom XA_XdndActionDescription = None;
  214617. static Atom XA_XdndActionCopy = None;
  214618. static Atom XA_XdndActionMove = None;
  214619. static Atom XA_XdndActionLink = None;
  214620. static Atom XA_XdndActionAsk = None;
  214621. static Atom XA_XdndActionPrivate = None;
  214622. static Atom XA_JXSelectionWindowProperty = None;
  214623. static Atom XA_MimeTextPlain = None;
  214624. static Atom XA_MimeTextUriList = None;
  214625. static Atom XA_MimeRootDrop = None;
  214626. static XErrorHandler oldHandler = 0;
  214627. static int trappedErrorCode = 0;
  214628. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  214629. {
  214630. trappedErrorCode = err->error_code;
  214631. return 0;
  214632. }
  214633. static void trapErrors()
  214634. {
  214635. trappedErrorCode = 0;
  214636. oldHandler = XSetErrorHandler (errorTrapHandler);
  214637. }
  214638. static bool untrapErrors()
  214639. {
  214640. XSetErrorHandler (oldHandler);
  214641. return (trappedErrorCode == 0);
  214642. }
  214643. static bool isActiveApplication = false;
  214644. bool Process::isForegroundProcess() throw()
  214645. {
  214646. return isActiveApplication;
  214647. }
  214648. // (used in the messaging code, declared here for build reasons)
  214649. bool juce_isRunningAsApplication()
  214650. {
  214651. return JUCEApplication::getInstance() != 0;
  214652. }
  214653. // These are defined in juce_linux_Messaging.cpp
  214654. extern Display* display;
  214655. extern XContext improbableNumber;
  214656. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  214657. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  214658. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  214659. static int pointerMap[5];
  214660. static int lastMousePosX = 0, lastMousePosY = 0;
  214661. enum MouseButtons
  214662. {
  214663. NoButton = 0,
  214664. LeftButton = 1,
  214665. MiddleButton = 2,
  214666. RightButton = 3,
  214667. WheelUp = 4,
  214668. WheelDown = 5
  214669. };
  214670. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  214671. {
  214672. Window root, child;
  214673. int winx, winy;
  214674. unsigned int mask;
  214675. mouseMods = 0;
  214676. if (XQueryPointer (display,
  214677. RootWindow (display, DefaultScreen (display)),
  214678. &root, &child,
  214679. &x, &y, &winx, &winy, &mask) == False)
  214680. {
  214681. // Pointer not on the default screen
  214682. x = y = -1;
  214683. }
  214684. else
  214685. {
  214686. if ((mask & Button1Mask) != 0)
  214687. mouseMods |= ModifierKeys::leftButtonModifier;
  214688. if ((mask & Button2Mask) != 0)
  214689. mouseMods |= ModifierKeys::middleButtonModifier;
  214690. if ((mask & Button3Mask) != 0)
  214691. mouseMods |= ModifierKeys::rightButtonModifier;
  214692. }
  214693. }
  214694. static int AltMask = 0;
  214695. static int NumLockMask = 0;
  214696. static bool numLock = 0;
  214697. static bool capsLock = 0;
  214698. static char keyStates [32];
  214699. static void updateKeyStates (const int keycode, const bool press) throw()
  214700. {
  214701. const int keybyte = keycode >> 3;
  214702. const int keybit = (1 << (keycode & 7));
  214703. if (press)
  214704. keyStates [keybyte] |= keybit;
  214705. else
  214706. keyStates [keybyte] &= ~keybit;
  214707. }
  214708. static bool keyDown (const int keycode) throw()
  214709. {
  214710. const int keybyte = keycode >> 3;
  214711. const int keybit = (1 << (keycode & 7));
  214712. return (keyStates [keybyte] & keybit) != 0;
  214713. }
  214714. static const int extendedKeyModifier = 0x10000000;
  214715. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  214716. {
  214717. int keysym;
  214718. if (keyCode & extendedKeyModifier)
  214719. {
  214720. keysym = 0xff00 | (keyCode & 0xff);
  214721. }
  214722. else
  214723. {
  214724. keysym = keyCode;
  214725. if (keysym == (XK_Tab & 0xff)
  214726. || keysym == (XK_Return & 0xff)
  214727. || keysym == (XK_Escape & 0xff)
  214728. || keysym == (XK_BackSpace & 0xff))
  214729. {
  214730. keysym |= 0xff00;
  214731. }
  214732. }
  214733. return keyDown (XKeysymToKeycode (display, keysym));
  214734. }
  214735. // Alt and Num lock are not defined by standard X
  214736. // modifier constants: check what they're mapped to
  214737. static void getModifierMapping() throw()
  214738. {
  214739. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  214740. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  214741. AltMask = 0;
  214742. NumLockMask = 0;
  214743. XModifierKeymap* mapping = XGetModifierMapping (display);
  214744. if (mapping)
  214745. {
  214746. for (int i = 0; i < 8; i++)
  214747. {
  214748. if (mapping->modifiermap [i << 1] == altLeftCode)
  214749. AltMask = 1 << i;
  214750. else if (mapping->modifiermap [i << 1] == numLockCode)
  214751. NumLockMask = 1 << i;
  214752. }
  214753. XFreeModifiermap (mapping);
  214754. }
  214755. }
  214756. static int currentModifiers = 0;
  214757. void ModifierKeys::updateCurrentModifiers() throw()
  214758. {
  214759. currentModifierFlags = currentModifiers;
  214760. }
  214761. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  214762. {
  214763. int x, y, mouseMods;
  214764. getMousePos (x, y, mouseMods);
  214765. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  214766. currentModifiers |= mouseMods;
  214767. return ModifierKeys (currentModifiers);
  214768. }
  214769. static void updateKeyModifiers (const int status) throw()
  214770. {
  214771. currentModifiers &= ~(ModifierKeys::shiftModifier
  214772. | ModifierKeys::ctrlModifier
  214773. | ModifierKeys::altModifier);
  214774. if (status & ShiftMask)
  214775. currentModifiers |= ModifierKeys::shiftModifier;
  214776. if (status & ControlMask)
  214777. currentModifiers |= ModifierKeys::ctrlModifier;
  214778. if (status & AltMask)
  214779. currentModifiers |= ModifierKeys::altModifier;
  214780. numLock = ((status & NumLockMask) != 0);
  214781. capsLock = ((status & LockMask) != 0);
  214782. }
  214783. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  214784. {
  214785. int modifier = 0;
  214786. bool isModifier = true;
  214787. switch (sym)
  214788. {
  214789. case XK_Shift_L:
  214790. case XK_Shift_R:
  214791. modifier = ModifierKeys::shiftModifier;
  214792. break;
  214793. case XK_Control_L:
  214794. case XK_Control_R:
  214795. modifier = ModifierKeys::ctrlModifier;
  214796. break;
  214797. case XK_Alt_L:
  214798. case XK_Alt_R:
  214799. modifier = ModifierKeys::altModifier;
  214800. break;
  214801. case XK_Num_Lock:
  214802. if (press)
  214803. numLock = ! numLock;
  214804. break;
  214805. case XK_Caps_Lock:
  214806. if (press)
  214807. capsLock = ! capsLock;
  214808. break;
  214809. case XK_Scroll_Lock:
  214810. break;
  214811. default:
  214812. isModifier = false;
  214813. break;
  214814. }
  214815. if (modifier != 0)
  214816. {
  214817. if (press)
  214818. currentModifiers |= modifier;
  214819. else
  214820. currentModifiers &= ~modifier;
  214821. }
  214822. return isModifier;
  214823. }
  214824. #if JUCE_USE_XSHM
  214825. static bool isShmAvailable() throw()
  214826. {
  214827. static bool isChecked = false;
  214828. static bool isAvailable = false;
  214829. if (! isChecked)
  214830. {
  214831. isChecked = true;
  214832. int major, minor;
  214833. Bool pixmaps;
  214834. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  214835. {
  214836. trapErrors();
  214837. XShmSegmentInfo segmentInfo;
  214838. zerostruct (segmentInfo);
  214839. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  214840. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  214841. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214842. xImage->bytes_per_line * xImage->height,
  214843. IPC_CREAT | 0777)) >= 0)
  214844. {
  214845. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214846. if (segmentInfo.shmaddr != (void*) -1)
  214847. {
  214848. segmentInfo.readOnly = False;
  214849. xImage->data = segmentInfo.shmaddr;
  214850. XSync (display, False);
  214851. if (XShmAttach (display, &segmentInfo) != 0)
  214852. {
  214853. XSync (display, False);
  214854. XShmDetach (display, &segmentInfo);
  214855. isAvailable = true;
  214856. }
  214857. }
  214858. XFlush (display);
  214859. XDestroyImage (xImage);
  214860. shmdt (segmentInfo.shmaddr);
  214861. }
  214862. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214863. isAvailable &= untrapErrors();
  214864. }
  214865. }
  214866. return isAvailable;
  214867. }
  214868. #endif
  214869. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  214870. {
  214871. const int width = image.getWidth();
  214872. const int height = image.getHeight();
  214873. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  214874. int index = 0;
  214875. for (int y = 0; y < height; ++y)
  214876. for (int x = 0; x < width; ++x)
  214877. colour[index++] = image.getPixelAt (x, y).getARGB();
  214878. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  214879. 0, (char*) colour, width, height, 32, 0);
  214880. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  214881. width, height, 24);
  214882. GC gc = XCreateGC (display, pixmap, 0, 0);
  214883. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  214884. XFreeGC (display, gc);
  214885. juce_free (colour);
  214886. return pixmap;
  214887. }
  214888. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  214889. {
  214890. const int width = image.getWidth();
  214891. const int height = image.getHeight();
  214892. const int stride = (width + 7) >> 3;
  214893. uint8* const mask = (uint8*) juce_calloc (stride * height);
  214894. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  214895. for (int y = 0; y < height; ++y)
  214896. {
  214897. for (int x = 0; x < width; ++x)
  214898. {
  214899. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  214900. const int offset = y * stride + (x >> 3);
  214901. if (image.getPixelAt (x, y).getAlpha() >= 128)
  214902. mask[offset] |= bit;
  214903. }
  214904. }
  214905. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  214906. (char*) mask, width, height, 1, 0, 1);
  214907. juce_free (mask);
  214908. return pixmap;
  214909. }
  214910. class XBitmapImage : public Image
  214911. {
  214912. public:
  214913. XBitmapImage (const PixelFormat format_, const int w, const int h,
  214914. const bool clearImage, const bool is16Bit_)
  214915. : Image (format_, w, h),
  214916. is16Bit (is16Bit_)
  214917. {
  214918. jassert (format_ == RGB || format_ == ARGB);
  214919. pixelStride = (format_ == RGB) ? 3 : 4;
  214920. lineStride = ((w * pixelStride + 3) & ~3);
  214921. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  214922. #if JUCE_USE_XSHM
  214923. usingXShm = false;
  214924. if ((! is16Bit) && isShmAvailable())
  214925. {
  214926. zerostruct (segmentInfo);
  214927. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  214928. if (xImage != 0)
  214929. {
  214930. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  214931. xImage->bytes_per_line * xImage->height,
  214932. IPC_CREAT | 0777)) >= 0)
  214933. {
  214934. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  214935. if (segmentInfo.shmaddr != (void*) -1)
  214936. {
  214937. segmentInfo.readOnly = False;
  214938. xImage->data = segmentInfo.shmaddr;
  214939. imageData = (uint8*) segmentInfo.shmaddr;
  214940. XSync (display, False);
  214941. if (XShmAttach (display, &segmentInfo) != 0)
  214942. {
  214943. XSync (display, False);
  214944. usingXShm = true;
  214945. }
  214946. else
  214947. {
  214948. jassertfalse
  214949. }
  214950. }
  214951. else
  214952. {
  214953. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  214954. }
  214955. }
  214956. }
  214957. }
  214958. if (! usingXShm)
  214959. #endif
  214960. {
  214961. imageData = (uint8*) juce_malloc (lineStride * h);
  214962. if (format_ == ARGB && clearImage)
  214963. zeromem (imageData, h * lineStride);
  214964. xImage = (XImage*) juce_calloc (sizeof (XImage));
  214965. xImage->width = w;
  214966. xImage->height = h;
  214967. xImage->xoffset = 0;
  214968. xImage->format = ZPixmap;
  214969. xImage->data = (char*) imageData;
  214970. xImage->byte_order = ImageByteOrder (display);
  214971. xImage->bitmap_unit = BitmapUnit (display);
  214972. xImage->bitmap_bit_order = BitmapBitOrder (display);
  214973. xImage->bitmap_pad = 32;
  214974. xImage->depth = pixelStride * 8;
  214975. xImage->bytes_per_line = lineStride;
  214976. xImage->bits_per_pixel = pixelStride * 8;
  214977. xImage->red_mask = 0x00FF0000;
  214978. xImage->green_mask = 0x0000FF00;
  214979. xImage->blue_mask = 0x000000FF;
  214980. if (is16Bit)
  214981. {
  214982. const int pixelStride = 2;
  214983. const int lineStride = ((w * pixelStride + 3) & ~3);
  214984. xImage->data = (char*) juce_malloc (lineStride * h);
  214985. xImage->bitmap_pad = 16;
  214986. xImage->depth = pixelStride * 8;
  214987. xImage->bytes_per_line = lineStride;
  214988. xImage->bits_per_pixel = pixelStride * 8;
  214989. xImage->red_mask = visual->red_mask;
  214990. xImage->green_mask = visual->green_mask;
  214991. xImage->blue_mask = visual->blue_mask;
  214992. }
  214993. if (! XInitImage (xImage))
  214994. {
  214995. jassertfalse
  214996. }
  214997. }
  214998. }
  214999. ~XBitmapImage()
  215000. {
  215001. #if JUCE_USE_XSHM
  215002. if (usingXShm)
  215003. {
  215004. XShmDetach (display, &segmentInfo);
  215005. XFlush (display);
  215006. XDestroyImage (xImage);
  215007. shmdt (segmentInfo.shmaddr);
  215008. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  215009. }
  215010. else
  215011. #endif
  215012. {
  215013. juce_free (xImage->data);
  215014. xImage->data = 0;
  215015. XDestroyImage (xImage);
  215016. }
  215017. if (! is16Bit)
  215018. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  215019. }
  215020. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  215021. {
  215022. static GC gc = 0;
  215023. if (gc == 0)
  215024. gc = DefaultGC (display, DefaultScreen (display));
  215025. if (is16Bit)
  215026. {
  215027. const uint32 rMask = xImage->red_mask;
  215028. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  215029. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  215030. const uint32 gMask = xImage->green_mask;
  215031. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  215032. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  215033. const uint32 bMask = xImage->blue_mask;
  215034. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  215035. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  215036. int ls, ps;
  215037. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  215038. for (int y = sy; y < sy + dh; ++y)
  215039. {
  215040. const uint8* p = pixels + y * ls + sx * ps;
  215041. for (int x = sx; x < sx + dw; ++x)
  215042. {
  215043. const PixelRGB* const pixel = (const PixelRGB*) p;
  215044. p += ps;
  215045. XPutPixel (xImage, x, y,
  215046. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  215047. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  215048. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  215049. }
  215050. }
  215051. releasePixelDataReadOnly (pixels);
  215052. }
  215053. // blit results to screen.
  215054. #if JUCE_USE_XSHM
  215055. if (usingXShm)
  215056. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  215057. else
  215058. #endif
  215059. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  215060. }
  215061. juce_UseDebuggingNewOperator
  215062. private:
  215063. XImage* xImage;
  215064. const bool is16Bit;
  215065. #if JUCE_USE_XSHM
  215066. XShmSegmentInfo segmentInfo;
  215067. bool usingXShm;
  215068. #endif
  215069. static int getShiftNeeded (const uint32 mask) throw()
  215070. {
  215071. for (int i = 32; --i >= 0;)
  215072. if (((mask >> i) & 1) != 0)
  215073. return i - 7;
  215074. jassertfalse
  215075. return 0;
  215076. }
  215077. };
  215078. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  215079. class LinuxComponentPeer : public ComponentPeer
  215080. {
  215081. public:
  215082. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  215083. : ComponentPeer (component, windowStyleFlags),
  215084. windowH (0),
  215085. parentWindow (0),
  215086. wx (0),
  215087. wy (0),
  215088. ww (0),
  215089. wh (0),
  215090. taskbarImage (0),
  215091. fullScreen (false),
  215092. entered (false),
  215093. mapped (false)
  215094. {
  215095. // it's dangerous to create a window on a thread other than the message thread..
  215096. checkMessageManagerIsLocked
  215097. repainter = new LinuxRepaintManager (this);
  215098. createWindow();
  215099. setTitle (component->getName());
  215100. }
  215101. ~LinuxComponentPeer()
  215102. {
  215103. // it's dangerous to delete a window on a thread other than the message thread..
  215104. checkMessageManagerIsLocked
  215105. deleteTaskBarIcon();
  215106. deleteIconPixmaps();
  215107. destroyWindow();
  215108. windowH = 0;
  215109. delete repainter;
  215110. }
  215111. void* getNativeHandle() const
  215112. {
  215113. return (void*) windowH;
  215114. }
  215115. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  215116. {
  215117. XPointer peer = 0;
  215118. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  215119. {
  215120. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  215121. peer = 0;
  215122. }
  215123. return (LinuxComponentPeer*) peer;
  215124. }
  215125. void setVisible (bool shouldBeVisible)
  215126. {
  215127. if (shouldBeVisible)
  215128. XMapWindow (display, windowH);
  215129. else
  215130. XUnmapWindow (display, windowH);
  215131. }
  215132. void setTitle (const String& title)
  215133. {
  215134. setWindowTitle (windowH, title);
  215135. }
  215136. void setPosition (int x, int y)
  215137. {
  215138. setBounds (x, y, ww, wh, false);
  215139. }
  215140. void setSize (int w, int h)
  215141. {
  215142. setBounds (wx, wy, w, h, false);
  215143. }
  215144. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  215145. {
  215146. fullScreen = isNowFullScreen;
  215147. if (windowH != 0)
  215148. {
  215149. const ComponentDeletionWatcher deletionChecker (component);
  215150. wx = x;
  215151. wy = y;
  215152. ww = jmax (1, w);
  215153. wh = jmax (1, h);
  215154. // Make sure the Window manager does what we want
  215155. XSizeHints* hints = XAllocSizeHints();
  215156. hints->flags = USSize | USPosition;
  215157. hints->width = ww;
  215158. hints->height = wh;
  215159. hints->x = wx;
  215160. hints->y = wy;
  215161. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  215162. {
  215163. hints->min_width = hints->max_width = hints->width;
  215164. hints->min_height = hints->max_height = hints->height;
  215165. hints->flags |= PMinSize | PMaxSize;
  215166. }
  215167. XSetWMNormalHints (display, windowH, hints);
  215168. XFree (hints);
  215169. XMoveResizeWindow (display, windowH,
  215170. wx - windowBorder.getLeft(),
  215171. wy - windowBorder.getTop(), ww, wh);
  215172. if (! deletionChecker.hasBeenDeleted())
  215173. {
  215174. updateBorderSize();
  215175. handleMovedOrResized();
  215176. }
  215177. }
  215178. }
  215179. void getBounds (int& x, int& y, int& w, int& h) const
  215180. {
  215181. x = wx;
  215182. y = wy;
  215183. w = ww;
  215184. h = wh;
  215185. }
  215186. int getScreenX() const
  215187. {
  215188. return wx;
  215189. }
  215190. int getScreenY() const
  215191. {
  215192. return wy;
  215193. }
  215194. void relativePositionToGlobal (int& x, int& y)
  215195. {
  215196. x += wx;
  215197. y += wy;
  215198. }
  215199. void globalPositionToRelative (int& x, int& y)
  215200. {
  215201. x -= wx;
  215202. y -= wy;
  215203. }
  215204. void setMinimised (bool shouldBeMinimised)
  215205. {
  215206. if (shouldBeMinimised)
  215207. {
  215208. Window root = RootWindow (display, DefaultScreen (display));
  215209. XClientMessageEvent clientMsg;
  215210. clientMsg.display = display;
  215211. clientMsg.window = windowH;
  215212. clientMsg.type = ClientMessage;
  215213. clientMsg.format = 32;
  215214. clientMsg.message_type = wm_ChangeState;
  215215. clientMsg.data.l[0] = IconicState;
  215216. XSendEvent (display, root, false,
  215217. SubstructureRedirectMask | SubstructureNotifyMask,
  215218. (XEvent*) &clientMsg);
  215219. }
  215220. else
  215221. {
  215222. setVisible (true);
  215223. }
  215224. }
  215225. bool isMinimised() const
  215226. {
  215227. bool minimised = false;
  215228. unsigned char* stateProp;
  215229. unsigned long nitems, bytesLeft;
  215230. Atom actualType;
  215231. int actualFormat;
  215232. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  215233. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  215234. &stateProp) == Success
  215235. && actualType == wm_State
  215236. && actualFormat == 32
  215237. && nitems > 0)
  215238. {
  215239. if (((unsigned long*) stateProp)[0] == IconicState)
  215240. minimised = true;
  215241. XFree (stateProp);
  215242. }
  215243. return minimised;
  215244. }
  215245. void setFullScreen (const bool shouldBeFullScreen)
  215246. {
  215247. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  215248. setMinimised (false);
  215249. if (fullScreen != shouldBeFullScreen)
  215250. {
  215251. if (shouldBeFullScreen)
  215252. r = Desktop::getInstance().getMainMonitorArea();
  215253. if (! r.isEmpty())
  215254. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  215255. getComponent()->repaint();
  215256. }
  215257. }
  215258. bool isFullScreen() const
  215259. {
  215260. return fullScreen;
  215261. }
  215262. bool isChildWindowOf (Window possibleParent) const
  215263. {
  215264. Window* windowList = 0;
  215265. uint32 windowListSize = 0;
  215266. Window parent, root;
  215267. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  215268. {
  215269. if (windowList != 0)
  215270. XFree (windowList);
  215271. return parent == possibleParent;
  215272. }
  215273. return false;
  215274. }
  215275. bool isFrontWindow() const
  215276. {
  215277. Window* windowList = 0;
  215278. uint32 windowListSize = 0;
  215279. bool result = false;
  215280. Window parent, root = RootWindow (display, DefaultScreen (display));
  215281. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  215282. {
  215283. for (int i = windowListSize; --i >= 0;)
  215284. {
  215285. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  215286. if (peer != 0)
  215287. {
  215288. result = (peer == this);
  215289. break;
  215290. }
  215291. }
  215292. }
  215293. if (windowList != 0)
  215294. XFree (windowList);
  215295. return result;
  215296. }
  215297. bool contains (int x, int y, bool trueIfInAChildWindow) const
  215298. {
  215299. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  215300. if (((unsigned int) x) >= (unsigned int) ww
  215301. || ((unsigned int) y) >= (unsigned int) wh)
  215302. return false;
  215303. bool inFront = false;
  215304. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  215305. {
  215306. Component* const c = Desktop::getInstance().getComponent (i);
  215307. if (inFront)
  215308. {
  215309. if (c->contains (x + wx - c->getScreenX(),
  215310. y + wy - c->getScreenY()))
  215311. {
  215312. return false;
  215313. }
  215314. }
  215315. else if (c == getComponent())
  215316. {
  215317. inFront = true;
  215318. }
  215319. }
  215320. if (trueIfInAChildWindow)
  215321. return true;
  215322. ::Window root, child;
  215323. unsigned int bw, depth;
  215324. int wx, wy, w, h;
  215325. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  215326. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  215327. &bw, &depth))
  215328. {
  215329. return false;
  215330. }
  215331. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  215332. return false;
  215333. return child == None;
  215334. }
  215335. const BorderSize getFrameSize() const
  215336. {
  215337. return BorderSize();
  215338. }
  215339. bool setAlwaysOnTop (bool alwaysOnTop)
  215340. {
  215341. if (windowH != 0)
  215342. {
  215343. const bool wasVisible = component->isVisible();
  215344. if (wasVisible)
  215345. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  215346. XSetWindowAttributes swa;
  215347. swa.override_redirect = alwaysOnTop ? True : False;
  215348. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  215349. if (wasVisible)
  215350. setVisible (true);
  215351. }
  215352. return true;
  215353. }
  215354. void toFront (bool makeActive)
  215355. {
  215356. if (makeActive)
  215357. {
  215358. setVisible (true);
  215359. grabFocus();
  215360. }
  215361. XEvent ev;
  215362. ev.xclient.type = ClientMessage;
  215363. ev.xclient.serial = 0;
  215364. ev.xclient.send_event = True;
  215365. ev.xclient.message_type = wm_ActiveWin;
  215366. ev.xclient.window = windowH;
  215367. ev.xclient.format = 32;
  215368. ev.xclient.data.l[0] = 2;
  215369. ev.xclient.data.l[1] = CurrentTime;
  215370. ev.xclient.data.l[2] = 0;
  215371. ev.xclient.data.l[3] = 0;
  215372. ev.xclient.data.l[4] = 0;
  215373. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  215374. False,
  215375. SubstructureRedirectMask | SubstructureNotifyMask,
  215376. &ev);
  215377. XWindowAttributes attr;
  215378. XGetWindowAttributes (display, windowH, &attr);
  215379. if (attr.override_redirect)
  215380. XRaiseWindow (display, windowH);
  215381. XSync (display, False);
  215382. handleBroughtToFront();
  215383. }
  215384. void toBehind (ComponentPeer* other)
  215385. {
  215386. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  215387. jassert (otherPeer != 0); // wrong type of window?
  215388. if (otherPeer != 0)
  215389. {
  215390. setMinimised (false);
  215391. Window newStack[] = { otherPeer->windowH, windowH };
  215392. XRestackWindows (display, newStack, 2);
  215393. }
  215394. }
  215395. bool isFocused() const
  215396. {
  215397. int revert;
  215398. Window focusedWindow = 0;
  215399. XGetInputFocus (display, &focusedWindow, &revert);
  215400. return focusedWindow == windowH;
  215401. }
  215402. void grabFocus()
  215403. {
  215404. XWindowAttributes atts;
  215405. if (windowH != 0
  215406. && XGetWindowAttributes (display, windowH, &atts)
  215407. && atts.map_state == IsViewable
  215408. && ! isFocused())
  215409. {
  215410. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  215411. isActiveApplication = true;
  215412. }
  215413. }
  215414. void textInputRequired (int /*x*/, int /*y*/)
  215415. {
  215416. }
  215417. void repaint (int x, int y, int w, int h)
  215418. {
  215419. if (Rectangle::intersectRectangles (x, y, w, h,
  215420. 0, 0,
  215421. getComponent()->getWidth(),
  215422. getComponent()->getHeight()))
  215423. {
  215424. repainter->repaint (x, y, w, h);
  215425. }
  215426. }
  215427. void performAnyPendingRepaintsNow()
  215428. {
  215429. repainter->performAnyPendingRepaintsNow();
  215430. }
  215431. void setIcon (const Image& newIcon)
  215432. {
  215433. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  215434. unsigned long* const data = (unsigned long*) juce_malloc (dataSize * sizeof (uint32));
  215435. int index = 0;
  215436. data[index++] = newIcon.getWidth();
  215437. data[index++] = newIcon.getHeight();
  215438. for (int y = 0; y < newIcon.getHeight(); ++y)
  215439. for (int x = 0; x < newIcon.getWidth(); ++x)
  215440. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  215441. XChangeProperty (display, windowH,
  215442. XInternAtom (display, "_NET_WM_ICON", False),
  215443. XA_CARDINAL, 32, PropModeReplace,
  215444. (unsigned char*) data, dataSize);
  215445. juce_free (data);
  215446. deleteIconPixmaps();
  215447. XWMHints* wmHints = XGetWMHints (display, windowH);
  215448. if (wmHints == 0)
  215449. wmHints = XAllocWMHints();
  215450. wmHints->flags |= IconPixmapHint | IconMaskHint;
  215451. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  215452. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  215453. XSetWMHints (display, windowH, wmHints);
  215454. XFree (wmHints);
  215455. XSync (display, False);
  215456. }
  215457. void deleteIconPixmaps()
  215458. {
  215459. XWMHints* wmHints = XGetWMHints (display, windowH);
  215460. if (wmHints != 0)
  215461. {
  215462. if ((wmHints->flags & IconPixmapHint) != 0)
  215463. {
  215464. wmHints->flags &= ~IconPixmapHint;
  215465. XFreePixmap (display, wmHints->icon_pixmap);
  215466. }
  215467. if ((wmHints->flags & IconMaskHint) != 0)
  215468. {
  215469. wmHints->flags &= ~IconMaskHint;
  215470. XFreePixmap (display, wmHints->icon_mask);
  215471. }
  215472. XSetWMHints (display, windowH, wmHints);
  215473. XFree (wmHints);
  215474. }
  215475. }
  215476. void handleWindowMessage (XEvent* event)
  215477. {
  215478. switch (event->xany.type)
  215479. {
  215480. case 2: // 'KeyPress'
  215481. {
  215482. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  215483. updateKeyStates (keyEvent->keycode, true);
  215484. char utf8 [64];
  215485. zeromem (utf8, sizeof (utf8));
  215486. KeySym sym;
  215487. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  215488. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  215489. int keyCode = (int) unicodeChar;
  215490. if (keyCode < 0x20)
  215491. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  215492. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  215493. const int oldMods = currentModifiers;
  215494. bool keyPressed = false;
  215495. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  215496. if ((sym & 0xff00) == 0xff00)
  215497. {
  215498. // Translate keypad
  215499. if (sym == XK_KP_Divide)
  215500. keyCode = XK_slash;
  215501. else if (sym == XK_KP_Multiply)
  215502. keyCode = XK_asterisk;
  215503. else if (sym == XK_KP_Subtract)
  215504. keyCode = XK_hyphen;
  215505. else if (sym == XK_KP_Add)
  215506. keyCode = XK_plus;
  215507. else if (sym == XK_KP_Enter)
  215508. keyCode = XK_Return;
  215509. else if (sym == XK_KP_Decimal)
  215510. keyCode = numLock ? XK_period : XK_Delete;
  215511. else if (sym == XK_KP_0)
  215512. keyCode = numLock ? XK_0 : XK_Insert;
  215513. else if (sym == XK_KP_1)
  215514. keyCode = numLock ? XK_1 : XK_End;
  215515. else if (sym == XK_KP_2)
  215516. keyCode = numLock ? XK_2 : XK_Down;
  215517. else if (sym == XK_KP_3)
  215518. keyCode = numLock ? XK_3 : XK_Page_Down;
  215519. else if (sym == XK_KP_4)
  215520. keyCode = numLock ? XK_4 : XK_Left;
  215521. else if (sym == XK_KP_5)
  215522. keyCode = XK_5;
  215523. else if (sym == XK_KP_6)
  215524. keyCode = numLock ? XK_6 : XK_Right;
  215525. else if (sym == XK_KP_7)
  215526. keyCode = numLock ? XK_7 : XK_Home;
  215527. else if (sym == XK_KP_8)
  215528. keyCode = numLock ? XK_8 : XK_Up;
  215529. else if (sym == XK_KP_9)
  215530. keyCode = numLock ? XK_9 : XK_Page_Up;
  215531. switch (sym)
  215532. {
  215533. case XK_Left:
  215534. case XK_Right:
  215535. case XK_Up:
  215536. case XK_Down:
  215537. case XK_Page_Up:
  215538. case XK_Page_Down:
  215539. case XK_End:
  215540. case XK_Home:
  215541. case XK_Delete:
  215542. case XK_Insert:
  215543. keyPressed = true;
  215544. keyCode = (sym & 0xff) | extendedKeyModifier;
  215545. break;
  215546. case XK_Tab:
  215547. case XK_Return:
  215548. case XK_Escape:
  215549. case XK_BackSpace:
  215550. keyPressed = true;
  215551. keyCode &= 0xff;
  215552. break;
  215553. default:
  215554. {
  215555. if (sym >= XK_F1 && sym <= XK_F16)
  215556. {
  215557. keyPressed = true;
  215558. keyCode = (sym & 0xff) | extendedKeyModifier;
  215559. }
  215560. break;
  215561. }
  215562. }
  215563. }
  215564. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  215565. keyPressed = true;
  215566. if (oldMods != currentModifiers)
  215567. handleModifierKeysChange();
  215568. if (keyDownChange)
  215569. handleKeyUpOrDown (true);
  215570. if (keyPressed)
  215571. handleKeyPress (keyCode, unicodeChar);
  215572. break;
  215573. }
  215574. case KeyRelease:
  215575. {
  215576. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  215577. updateKeyStates (keyEvent->keycode, false);
  215578. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  215579. const int oldMods = currentModifiers;
  215580. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  215581. if (oldMods != currentModifiers)
  215582. handleModifierKeysChange();
  215583. if (keyDownChange)
  215584. handleKeyUpOrDown (false);
  215585. break;
  215586. }
  215587. case ButtonPress:
  215588. {
  215589. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  215590. bool buttonMsg = false;
  215591. bool wheelUpMsg = false;
  215592. bool wheelDownMsg = false;
  215593. const int map = pointerMap [buttonPressEvent->button - Button1];
  215594. if (map == LeftButton)
  215595. {
  215596. currentModifiers |= ModifierKeys::leftButtonModifier;
  215597. buttonMsg = true;
  215598. }
  215599. else if (map == RightButton)
  215600. {
  215601. currentModifiers |= ModifierKeys::rightButtonModifier;
  215602. buttonMsg = true;
  215603. }
  215604. else if (map == MiddleButton)
  215605. {
  215606. currentModifiers |= ModifierKeys::middleButtonModifier;
  215607. buttonMsg = true;
  215608. }
  215609. else if (map == WheelUp)
  215610. {
  215611. wheelUpMsg = true;
  215612. }
  215613. else if (map == WheelDown)
  215614. {
  215615. wheelDownMsg = true;
  215616. }
  215617. updateKeyModifiers (buttonPressEvent->state);
  215618. if (buttonMsg)
  215619. {
  215620. toFront (true);
  215621. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  215622. getEventTime (buttonPressEvent->time));
  215623. }
  215624. else if (wheelUpMsg || wheelDownMsg)
  215625. {
  215626. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  215627. getEventTime (buttonPressEvent->time));
  215628. }
  215629. lastMousePosX = lastMousePosY = 0x100000;
  215630. break;
  215631. }
  215632. case ButtonRelease:
  215633. {
  215634. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  215635. const int oldModifiers = currentModifiers;
  215636. const int map = pointerMap [buttonRelEvent->button - Button1];
  215637. if (map == LeftButton)
  215638. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  215639. else if (map == RightButton)
  215640. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  215641. else if (map == MiddleButton)
  215642. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  215643. updateKeyModifiers (buttonRelEvent->state);
  215644. handleMouseUp (oldModifiers,
  215645. buttonRelEvent->x, buttonRelEvent->y,
  215646. getEventTime (buttonRelEvent->time));
  215647. lastMousePosX = lastMousePosY = 0x100000;
  215648. break;
  215649. }
  215650. case MotionNotify:
  215651. {
  215652. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  215653. updateKeyModifiers (movedEvent->state);
  215654. int x, y, mouseMods;
  215655. getMousePos (x, y, mouseMods);
  215656. if (lastMousePosX != x || lastMousePosY != y)
  215657. {
  215658. lastMousePosX = x;
  215659. lastMousePosY = y;
  215660. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  215661. {
  215662. Window wRoot = 0, wParent = 0;
  215663. Window* wChild = 0;
  215664. unsigned int numChildren;
  215665. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  215666. if (wParent != 0
  215667. && wParent != windowH
  215668. && wParent != wRoot)
  215669. {
  215670. parentWindow = wParent;
  215671. updateBounds();
  215672. x -= getScreenX();
  215673. y -= getScreenY();
  215674. }
  215675. else
  215676. {
  215677. parentWindow = 0;
  215678. x -= getScreenX();
  215679. y -= getScreenY();
  215680. }
  215681. }
  215682. else
  215683. {
  215684. x -= getScreenX();
  215685. y -= getScreenY();
  215686. }
  215687. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  215688. handleMouseMove (x, y, getEventTime (movedEvent->time));
  215689. else
  215690. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  215691. }
  215692. break;
  215693. }
  215694. case EnterNotify:
  215695. {
  215696. lastMousePosX = lastMousePosY = 0x100000;
  215697. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  215698. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215699. && ! entered)
  215700. {
  215701. updateKeyModifiers (enterEvent->state);
  215702. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  215703. entered = true;
  215704. }
  215705. break;
  215706. }
  215707. case LeaveNotify:
  215708. {
  215709. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  215710. // Suppress the normal leave if we've got a pointer grab, or if
  215711. // it's a bogus one caused by clicking a mouse button when running
  215712. // in a Window manager
  215713. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  215714. && leaveEvent->mode == NotifyNormal)
  215715. || leaveEvent->mode == NotifyUngrab)
  215716. {
  215717. updateKeyModifiers (leaveEvent->state);
  215718. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  215719. entered = false;
  215720. }
  215721. break;
  215722. }
  215723. case FocusIn:
  215724. {
  215725. isActiveApplication = true;
  215726. if (isFocused())
  215727. handleFocusGain();
  215728. break;
  215729. }
  215730. case FocusOut:
  215731. {
  215732. isActiveApplication = false;
  215733. if (! isFocused())
  215734. handleFocusLoss();
  215735. break;
  215736. }
  215737. case Expose:
  215738. {
  215739. // Batch together all pending expose events
  215740. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  215741. XEvent nextEvent;
  215742. if (exposeEvent->window != windowH)
  215743. {
  215744. Window child;
  215745. XTranslateCoordinates (display, exposeEvent->window, windowH,
  215746. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  215747. &child);
  215748. }
  215749. repaint (exposeEvent->x, exposeEvent->y,
  215750. exposeEvent->width, exposeEvent->height);
  215751. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  215752. {
  215753. XPeekEvent (display, (XEvent*) &nextEvent);
  215754. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  215755. break;
  215756. XNextEvent (display, (XEvent*) &nextEvent);
  215757. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  215758. repaint (nextExposeEvent->x, nextExposeEvent->y,
  215759. nextExposeEvent->width, nextExposeEvent->height);
  215760. }
  215761. break;
  215762. }
  215763. case CirculateNotify:
  215764. case CreateNotify:
  215765. case DestroyNotify:
  215766. // Think we can ignore these
  215767. break;
  215768. case ConfigureNotify:
  215769. {
  215770. updateBounds();
  215771. updateBorderSize();
  215772. handleMovedOrResized();
  215773. // if the native title bar is dragged, need to tell any active menus, etc.
  215774. if ((styleFlags & windowHasTitleBar) != 0
  215775. && component->isCurrentlyBlockedByAnotherModalComponent())
  215776. {
  215777. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  215778. if (currentModalComp != 0)
  215779. currentModalComp->inputAttemptWhenModal();
  215780. }
  215781. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  215782. if (confEvent->window == windowH
  215783. && confEvent->above != 0
  215784. && isFrontWindow())
  215785. {
  215786. handleBroughtToFront();
  215787. }
  215788. break;
  215789. }
  215790. case ReparentNotify:
  215791. case GravityNotify:
  215792. {
  215793. parentWindow = 0;
  215794. Window wRoot = 0;
  215795. Window* wChild = 0;
  215796. unsigned int numChildren;
  215797. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  215798. if (parentWindow == windowH || parentWindow == wRoot)
  215799. parentWindow = 0;
  215800. updateBounds();
  215801. updateBorderSize();
  215802. handleMovedOrResized();
  215803. break;
  215804. }
  215805. case MapNotify:
  215806. mapped = true;
  215807. handleBroughtToFront();
  215808. break;
  215809. case UnmapNotify:
  215810. mapped = false;
  215811. break;
  215812. case MappingNotify:
  215813. {
  215814. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  215815. if (mappingEvent->request != MappingPointer)
  215816. {
  215817. // Deal with modifier/keyboard mapping
  215818. XRefreshKeyboardMapping (mappingEvent);
  215819. getModifierMapping();
  215820. }
  215821. break;
  215822. }
  215823. case ClientMessage:
  215824. {
  215825. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  215826. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  215827. {
  215828. const Atom atom = (Atom) clientMsg->data.l[0];
  215829. if (atom == wm_ProtocolList [TAKE_FOCUS])
  215830. {
  215831. XWindowAttributes atts;
  215832. if (clientMsg->window != 0
  215833. && XGetWindowAttributes (display, clientMsg->window, &atts))
  215834. {
  215835. if (atts.map_state == IsViewable)
  215836. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  215837. }
  215838. }
  215839. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  215840. {
  215841. handleUserClosingWindow();
  215842. }
  215843. }
  215844. else if (clientMsg->message_type == XA_XdndEnter)
  215845. {
  215846. handleDragAndDropEnter (clientMsg);
  215847. }
  215848. else if (clientMsg->message_type == XA_XdndLeave)
  215849. {
  215850. resetDragAndDrop();
  215851. }
  215852. else if (clientMsg->message_type == XA_XdndPosition)
  215853. {
  215854. handleDragAndDropPosition (clientMsg);
  215855. }
  215856. else if (clientMsg->message_type == XA_XdndDrop)
  215857. {
  215858. handleDragAndDropDrop (clientMsg);
  215859. }
  215860. else if (clientMsg->message_type == XA_XdndStatus)
  215861. {
  215862. handleDragAndDropStatus (clientMsg);
  215863. }
  215864. else if (clientMsg->message_type == XA_XdndFinished)
  215865. {
  215866. resetDragAndDrop();
  215867. }
  215868. break;
  215869. }
  215870. case SelectionNotify:
  215871. handleDragAndDropSelection (event);
  215872. break;
  215873. case SelectionClear:
  215874. case SelectionRequest:
  215875. break;
  215876. default:
  215877. break;
  215878. }
  215879. }
  215880. void showMouseCursor (Cursor cursor) throw()
  215881. {
  215882. XDefineCursor (display, windowH, cursor);
  215883. }
  215884. void setTaskBarIcon (const Image& image)
  215885. {
  215886. deleteTaskBarIcon();
  215887. taskbarImage = image.createCopy();
  215888. Screen* const screen = XDefaultScreenOfDisplay (display);
  215889. const int screenNumber = XScreenNumberOfScreen (screen);
  215890. char screenAtom[32];
  215891. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  215892. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  215893. XGrabServer (display);
  215894. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  215895. if (managerWin != None)
  215896. XSelectInput (display, managerWin, StructureNotifyMask);
  215897. XUngrabServer (display);
  215898. XFlush (display);
  215899. if (managerWin != None)
  215900. {
  215901. XEvent ev;
  215902. zerostruct (ev);
  215903. ev.xclient.type = ClientMessage;
  215904. ev.xclient.window = managerWin;
  215905. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  215906. ev.xclient.format = 32;
  215907. ev.xclient.data.l[0] = CurrentTime;
  215908. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  215909. ev.xclient.data.l[2] = windowH;
  215910. ev.xclient.data.l[3] = 0;
  215911. ev.xclient.data.l[4] = 0;
  215912. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  215913. XSync (display, False);
  215914. }
  215915. // For older KDE's ...
  215916. long atomData = 1;
  215917. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  215918. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  215919. // For more recent KDE's...
  215920. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  215921. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  215922. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  215923. XSizeHints* hints = XAllocSizeHints();
  215924. hints->flags = PMinSize;
  215925. hints->min_width = 22;
  215926. hints->min_height = 22;
  215927. XSetWMNormalHints (display, windowH, hints);
  215928. XFree (hints);
  215929. }
  215930. void deleteTaskBarIcon()
  215931. {
  215932. deleteAndZero (taskbarImage);
  215933. }
  215934. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  215935. juce_UseDebuggingNewOperator
  215936. bool dontRepaint;
  215937. private:
  215938. class LinuxRepaintManager : public Timer
  215939. {
  215940. public:
  215941. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  215942. : peer (peer_),
  215943. image (0),
  215944. lastTimeImageUsed (0)
  215945. {
  215946. #if JUCE_USE_XSHM
  215947. useARGBImagesForRendering = isShmAvailable();
  215948. if (useARGBImagesForRendering)
  215949. {
  215950. XShmSegmentInfo segmentinfo;
  215951. XImage* const testImage
  215952. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  215953. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  215954. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  215955. XDestroyImage (testImage);
  215956. }
  215957. #endif
  215958. }
  215959. ~LinuxRepaintManager()
  215960. {
  215961. delete image;
  215962. }
  215963. void timerCallback()
  215964. {
  215965. if (! regionsNeedingRepaint.isEmpty())
  215966. {
  215967. stopTimer();
  215968. performAnyPendingRepaintsNow();
  215969. }
  215970. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  215971. {
  215972. stopTimer();
  215973. deleteAndZero (image);
  215974. }
  215975. }
  215976. void repaint (int x, int y, int w, int h)
  215977. {
  215978. if (! isTimerRunning())
  215979. startTimer (repaintTimerPeriod);
  215980. regionsNeedingRepaint.add (x, y, w, h);
  215981. }
  215982. void performAnyPendingRepaintsNow()
  215983. {
  215984. peer->clearMaskedRegion();
  215985. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  215986. if (! totalArea.isEmpty())
  215987. {
  215988. if (image == 0 || image->getWidth() < totalArea.getWidth()
  215989. || image->getHeight() < totalArea.getHeight())
  215990. {
  215991. delete image;
  215992. #if JUCE_USE_XSHM
  215993. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  215994. : Image::RGB,
  215995. #else
  215996. image = new XBitmapImage (Image::RGB,
  215997. #endif
  215998. (totalArea.getWidth() + 31) & ~31,
  215999. (totalArea.getHeight() + 31) & ~31,
  216000. false,
  216001. peer->depthIs16Bit);
  216002. }
  216003. startTimer (repaintTimerPeriod);
  216004. LowLevelGraphicsSoftwareRenderer context (*image);
  216005. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  216006. if (context.reduceClipRegion (regionsNeedingRepaint))
  216007. peer->handlePaint (context);
  216008. if (! peer->maskedRegion.isEmpty())
  216009. regionsNeedingRepaint.subtract (peer->maskedRegion);
  216010. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  216011. {
  216012. const Rectangle& r = *i.getRectangle();
  216013. image->blitToWindow (peer->windowH,
  216014. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  216015. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  216016. }
  216017. }
  216018. regionsNeedingRepaint.clear();
  216019. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  216020. startTimer (repaintTimerPeriod);
  216021. }
  216022. private:
  216023. LinuxComponentPeer* const peer;
  216024. XBitmapImage* image;
  216025. uint32 lastTimeImageUsed;
  216026. RectangleList regionsNeedingRepaint;
  216027. #if JUCE_USE_XSHM
  216028. bool useARGBImagesForRendering;
  216029. #endif
  216030. LinuxRepaintManager (const LinuxRepaintManager&);
  216031. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  216032. };
  216033. LinuxRepaintManager* repainter;
  216034. friend class LinuxRepaintManager;
  216035. Window windowH, parentWindow;
  216036. int wx, wy, ww, wh;
  216037. Image* taskbarImage;
  216038. bool fullScreen, entered, mapped, depthIs16Bit;
  216039. BorderSize windowBorder;
  216040. void removeWindowDecorations (Window wndH)
  216041. {
  216042. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216043. if (hints != None)
  216044. {
  216045. typedef struct
  216046. {
  216047. unsigned long flags;
  216048. unsigned long functions;
  216049. unsigned long decorations;
  216050. long input_mode;
  216051. unsigned long status;
  216052. } MotifWmHints;
  216053. MotifWmHints motifHints;
  216054. zerostruct (motifHints);
  216055. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  216056. motifHints.decorations = 0;
  216057. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216058. (unsigned char*) &motifHints, 4);
  216059. }
  216060. hints = XInternAtom (display, "_WIN_HINTS", True);
  216061. if (hints != None)
  216062. {
  216063. long gnomeHints = 0;
  216064. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216065. (unsigned char*) &gnomeHints, 1);
  216066. }
  216067. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  216068. if (hints != None)
  216069. {
  216070. long kwmHints = 2; /*KDE_tinyDecoration*/
  216071. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  216072. (unsigned char*) &kwmHints, 1);
  216073. }
  216074. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  216075. if (hints != None)
  216076. {
  216077. int netHints [2];
  216078. int numHints = 0;
  216079. if ((styleFlags & windowIsTemporary) != 0)
  216080. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  216081. else
  216082. netHints [numHints] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  216083. if (netHints [numHints] != 0)
  216084. ++numHints;
  216085. netHints[numHints] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  216086. if (netHints [numHints] != 0)
  216087. ++numHints;
  216088. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216089. (unsigned char*) &netHints, numHints);
  216090. }
  216091. }
  216092. void addWindowButtons (Window wndH)
  216093. {
  216094. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  216095. if (hints != None)
  216096. {
  216097. typedef struct
  216098. {
  216099. unsigned long flags;
  216100. unsigned long functions;
  216101. unsigned long decorations;
  216102. long input_mode;
  216103. unsigned long status;
  216104. } MotifWmHints;
  216105. MotifWmHints motifHints;
  216106. zerostruct (motifHints);
  216107. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  216108. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  216109. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  216110. if ((styleFlags & windowHasCloseButton) != 0)
  216111. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  216112. if ((styleFlags & windowHasMinimiseButton) != 0)
  216113. {
  216114. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  216115. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  216116. }
  216117. if ((styleFlags & windowHasMaximiseButton) != 0)
  216118. {
  216119. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  216120. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  216121. }
  216122. if ((styleFlags & windowIsResizable) != 0)
  216123. {
  216124. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  216125. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  216126. }
  216127. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  216128. }
  216129. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  216130. if (hints != None)
  216131. {
  216132. int netHints [6];
  216133. int num = 0;
  216134. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  216135. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  216136. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  216137. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  216138. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  216139. (unsigned char*) &netHints, num);
  216140. }
  216141. }
  216142. void createWindow()
  216143. {
  216144. static bool atomsInitialised = false;
  216145. if (! atomsInitialised)
  216146. {
  216147. atomsInitialised = true;
  216148. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  216149. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  216150. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  216151. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  216152. wm_State = XInternAtom (display, "WM_STATE", 1);
  216153. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  216154. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  216155. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  216156. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  216157. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  216158. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  216159. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  216160. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  216161. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  216162. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  216163. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  216164. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  216165. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  216166. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  216167. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  216168. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  216169. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  216170. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  216171. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  216172. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  216173. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  216174. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  216175. }
  216176. resetDragAndDrop();
  216177. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  216178. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  216179. allowedMimeTypeAtoms [1] = XA_OtherMime;
  216180. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  216181. allowedActions [0] = XA_XdndActionMove;
  216182. allowedActions [1] = XA_XdndActionCopy;
  216183. allowedActions [2] = XA_XdndActionLink;
  216184. allowedActions [3] = XA_XdndActionAsk;
  216185. allowedActions [4] = XA_XdndActionPrivate;
  216186. // Get defaults for various properties
  216187. const int screen = DefaultScreen (display);
  216188. Window root = RootWindow (display, screen);
  216189. // Attempt to create a 24-bit window on the default screen. If this is not
  216190. // possible then exit
  216191. XVisualInfo desiredVisual;
  216192. desiredVisual.screen = screen;
  216193. desiredVisual.depth = 24;
  216194. depthIs16Bit = false;
  216195. int numVisuals;
  216196. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216197. &desiredVisual, &numVisuals);
  216198. if (numVisuals < 1 || visuals == 0)
  216199. {
  216200. XFree (visuals);
  216201. desiredVisual.depth = 16;
  216202. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  216203. &desiredVisual, &numVisuals);
  216204. if (numVisuals < 1 || visuals == 0)
  216205. {
  216206. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  216207. Process::terminate();
  216208. }
  216209. depthIs16Bit = true;
  216210. }
  216211. XFree (visuals);
  216212. // Set up the window attributes
  216213. XSetWindowAttributes swa;
  216214. swa.border_pixel = 0;
  216215. swa.background_pixmap = None;
  216216. swa.colormap = DefaultColormap (display, screen);
  216217. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  216218. swa.event_mask = eventMask;
  216219. Window wndH = XCreateWindow (display, root,
  216220. 0, 0, 1, 1,
  216221. 0, 0, InputOutput, (Visual*) CopyFromParent,
  216222. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  216223. &swa);
  216224. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  216225. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  216226. GrabModeAsync, GrabModeAsync, None, None);
  216227. // Set the window context to identify the window handle object
  216228. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  216229. {
  216230. // Failed
  216231. jassertfalse
  216232. Logger::outputDebugString ("Failed to create context information for window.\n");
  216233. XDestroyWindow (display, wndH);
  216234. wndH = 0;
  216235. }
  216236. // Set window manager hints
  216237. XWMHints* wmHints = XAllocWMHints();
  216238. wmHints->flags = InputHint | StateHint;
  216239. wmHints->input = True; // Locally active input model
  216240. wmHints->initial_state = NormalState;
  216241. XSetWMHints (display, wndH, wmHints);
  216242. XFree (wmHints);
  216243. if ((styleFlags & windowIsSemiTransparent) != 0)
  216244. {
  216245. //xxx
  216246. }
  216247. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  216248. {
  216249. //xxx
  216250. }
  216251. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  216252. if ((styleFlags & windowHasTitleBar) == 0)
  216253. removeWindowDecorations (wndH);
  216254. else
  216255. addWindowButtons (wndH);
  216256. // Set window manager protocols
  216257. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  216258. (unsigned char*) wm_ProtocolList, 2);
  216259. // Set drag and drop flags
  216260. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  216261. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  216262. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  216263. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  216264. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  216265. (const unsigned char*) "", 0);
  216266. unsigned long dndVersion = ourDndVersion;
  216267. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  216268. (const unsigned char*) &dndVersion, 1);
  216269. // Set window name
  216270. setWindowTitle (wndH, getComponent()->getName());
  216271. // Initialise the pointer and keyboard mapping
  216272. // This is not the same as the logical pointer mapping the X server uses:
  216273. // we don't mess with this.
  216274. static bool mappingInitialised = false;
  216275. if (! mappingInitialised)
  216276. {
  216277. mappingInitialised = true;
  216278. const int numButtons = XGetPointerMapping (display, 0, 0);
  216279. if (numButtons == 2)
  216280. {
  216281. pointerMap[0] = LeftButton;
  216282. pointerMap[1] = RightButton;
  216283. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  216284. }
  216285. else if (numButtons >= 3)
  216286. {
  216287. pointerMap[0] = LeftButton;
  216288. pointerMap[1] = MiddleButton;
  216289. pointerMap[2] = RightButton;
  216290. if (numButtons >= 5)
  216291. {
  216292. pointerMap[3] = WheelUp;
  216293. pointerMap[4] = WheelDown;
  216294. }
  216295. }
  216296. getModifierMapping();
  216297. }
  216298. windowH = wndH;
  216299. }
  216300. void destroyWindow()
  216301. {
  216302. XPointer handlePointer;
  216303. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  216304. XDeleteContext (display, (XID) windowH, improbableNumber);
  216305. XDestroyWindow (display, windowH);
  216306. // Wait for it to complete and then remove any events for this
  216307. // window from the event queue.
  216308. XSync (display, false);
  216309. XEvent event;
  216310. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  216311. {}
  216312. }
  216313. static int64 getEventTime (::Time t) throw()
  216314. {
  216315. static int64 eventTimeOffset = 0x12345678;
  216316. const int64 thisMessageTime = t;
  216317. if (eventTimeOffset == 0x12345678)
  216318. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  216319. return eventTimeOffset + thisMessageTime;
  216320. }
  216321. static void setWindowTitle (Window xwin, const char* const title) throw()
  216322. {
  216323. XTextProperty nameProperty;
  216324. char* strings[] = { (char*) title };
  216325. if (XStringListToTextProperty (strings, 1, &nameProperty))
  216326. {
  216327. XSetWMName (display, xwin, &nameProperty);
  216328. XSetWMIconName (display, xwin, &nameProperty);
  216329. XFree (nameProperty.value);
  216330. }
  216331. }
  216332. void updateBorderSize()
  216333. {
  216334. if ((styleFlags & windowHasTitleBar) == 0)
  216335. {
  216336. windowBorder = BorderSize (0);
  216337. }
  216338. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  216339. {
  216340. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  216341. if (hints != None)
  216342. {
  216343. unsigned char* data = 0;
  216344. unsigned long nitems, bytesLeft;
  216345. Atom actualType;
  216346. int actualFormat;
  216347. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  216348. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216349. &data) == Success)
  216350. {
  216351. const unsigned long* const sizes = (const unsigned long*) data;
  216352. if (actualFormat == 32)
  216353. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  216354. (int) sizes[3], (int) sizes[1]);
  216355. XFree (data);
  216356. }
  216357. }
  216358. }
  216359. }
  216360. void updateBounds()
  216361. {
  216362. jassert (windowH != 0);
  216363. if (windowH != 0)
  216364. {
  216365. Window root, child;
  216366. unsigned int bw, depth;
  216367. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  216368. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  216369. &bw, &depth))
  216370. {
  216371. wx = wy = ww = wh = 0;
  216372. }
  216373. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  216374. {
  216375. wx = wy = 0;
  216376. }
  216377. }
  216378. }
  216379. void resetDragAndDrop()
  216380. {
  216381. dragAndDropFiles.clear();
  216382. lastDropX = lastDropY = -1;
  216383. dragAndDropCurrentMimeType = 0;
  216384. dragAndDropSourceWindow = 0;
  216385. srcMimeTypeAtomList.clear();
  216386. }
  216387. void sendDragAndDropMessage (XClientMessageEvent& msg)
  216388. {
  216389. msg.type = ClientMessage;
  216390. msg.display = display;
  216391. msg.window = dragAndDropSourceWindow;
  216392. msg.format = 32;
  216393. msg.data.l[0] = windowH;
  216394. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  216395. }
  216396. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  216397. {
  216398. XClientMessageEvent msg;
  216399. zerostruct (msg);
  216400. msg.message_type = XA_XdndStatus;
  216401. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  216402. msg.data.l[4] = dropAction;
  216403. sendDragAndDropMessage (msg);
  216404. }
  216405. void sendDragAndDropLeave()
  216406. {
  216407. XClientMessageEvent msg;
  216408. zerostruct (msg);
  216409. msg.message_type = XA_XdndLeave;
  216410. sendDragAndDropMessage (msg);
  216411. }
  216412. void sendDragAndDropFinish()
  216413. {
  216414. XClientMessageEvent msg;
  216415. zerostruct (msg);
  216416. msg.message_type = XA_XdndFinished;
  216417. sendDragAndDropMessage (msg);
  216418. }
  216419. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  216420. {
  216421. if ((clientMsg->data.l[1] & 1) == 0)
  216422. {
  216423. sendDragAndDropLeave();
  216424. if (dragAndDropFiles.size() > 0)
  216425. handleFileDragExit (dragAndDropFiles);
  216426. dragAndDropFiles.clear();
  216427. }
  216428. }
  216429. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  216430. {
  216431. if (dragAndDropSourceWindow == 0)
  216432. return;
  216433. dragAndDropSourceWindow = clientMsg->data.l[0];
  216434. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  216435. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  216436. if (lastDropX != dropX || lastDropY != dropY)
  216437. {
  216438. lastDropX = dropX;
  216439. lastDropY = dropY;
  216440. dragAndDropTimestamp = clientMsg->data.l[3];
  216441. Atom targetAction = XA_XdndActionCopy;
  216442. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  216443. {
  216444. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  216445. {
  216446. targetAction = allowedActions[i];
  216447. break;
  216448. }
  216449. }
  216450. sendDragAndDropStatus (true, targetAction);
  216451. if (dragAndDropFiles.size() == 0)
  216452. updateDraggedFileList (clientMsg);
  216453. if (dragAndDropFiles.size() > 0)
  216454. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  216455. }
  216456. }
  216457. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  216458. {
  216459. if (dragAndDropFiles.size() == 0)
  216460. updateDraggedFileList (clientMsg);
  216461. const StringArray files (dragAndDropFiles);
  216462. const int lastX = lastDropX, lastY = lastDropY;
  216463. sendDragAndDropFinish();
  216464. resetDragAndDrop();
  216465. if (files.size() > 0)
  216466. handleFileDragDrop (files, lastX, lastY);
  216467. }
  216468. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  216469. {
  216470. dragAndDropFiles.clear();
  216471. srcMimeTypeAtomList.clear();
  216472. dragAndDropCurrentMimeType = 0;
  216473. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  216474. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  216475. {
  216476. dragAndDropSourceWindow = 0;
  216477. return;
  216478. }
  216479. dragAndDropSourceWindow = clientMsg->data.l[0];
  216480. if ((clientMsg->data.l[1] & 1) != 0)
  216481. {
  216482. Atom actual;
  216483. int format;
  216484. unsigned long count = 0, remaining = 0;
  216485. unsigned char* data = 0;
  216486. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  216487. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  216488. &count, &remaining, &data);
  216489. if (data != 0)
  216490. {
  216491. if (actual == XA_ATOM && format == 32 && count != 0)
  216492. {
  216493. const unsigned long* const types = (const unsigned long*) data;
  216494. for (unsigned int i = 0; i < count; ++i)
  216495. if (types[i] != None)
  216496. srcMimeTypeAtomList.add (types[i]);
  216497. }
  216498. XFree (data);
  216499. }
  216500. }
  216501. if (srcMimeTypeAtomList.size() == 0)
  216502. {
  216503. for (int i = 2; i < 5; ++i)
  216504. if (clientMsg->data.l[i] != None)
  216505. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  216506. if (srcMimeTypeAtomList.size() == 0)
  216507. {
  216508. dragAndDropSourceWindow = 0;
  216509. return;
  216510. }
  216511. }
  216512. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  216513. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  216514. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  216515. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  216516. handleDragAndDropPosition (clientMsg);
  216517. }
  216518. void handleDragAndDropSelection (const XEvent* const evt)
  216519. {
  216520. dragAndDropFiles.clear();
  216521. if (evt->xselection.property != 0)
  216522. {
  216523. StringArray lines;
  216524. {
  216525. MemoryBlock dropData;
  216526. for (;;)
  216527. {
  216528. Atom actual;
  216529. uint8* data = 0;
  216530. unsigned long count = 0, remaining = 0;
  216531. int format = 0;
  216532. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  216533. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  216534. &format, &count, &remaining, &data) == Success)
  216535. {
  216536. dropData.append (data, count * format / 8);
  216537. XFree (data);
  216538. if (remaining == 0)
  216539. break;
  216540. }
  216541. else
  216542. {
  216543. XFree (data);
  216544. break;
  216545. }
  216546. }
  216547. lines.addLines (dropData.toString());
  216548. }
  216549. for (int i = 0; i < lines.size(); ++i)
  216550. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  216551. dragAndDropFiles.trim();
  216552. dragAndDropFiles.removeEmptyStrings();
  216553. }
  216554. }
  216555. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  216556. {
  216557. dragAndDropFiles.clear();
  216558. if (dragAndDropSourceWindow != None
  216559. && dragAndDropCurrentMimeType != 0)
  216560. {
  216561. dragAndDropTimestamp = clientMsg->data.l[2];
  216562. XConvertSelection (display,
  216563. XA_XdndSelection,
  216564. dragAndDropCurrentMimeType,
  216565. XA_JXSelectionWindowProperty,
  216566. windowH,
  216567. dragAndDropTimestamp);
  216568. }
  216569. }
  216570. StringArray dragAndDropFiles;
  216571. int dragAndDropTimestamp, lastDropX, lastDropY;
  216572. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  216573. Window dragAndDropSourceWindow;
  216574. unsigned int allowedActions [5];
  216575. unsigned int allowedMimeTypeAtoms [3];
  216576. Array <Atom> srcMimeTypeAtomList;
  216577. };
  216578. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  216579. {
  216580. if (enableOrDisable)
  216581. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  216582. }
  216583. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  216584. {
  216585. return new LinuxComponentPeer (this, styleFlags);
  216586. }
  216587. // (this callback is hooked up in the messaging code)
  216588. void juce_windowMessageReceive (XEvent* event)
  216589. {
  216590. if (event->xany.window != None)
  216591. {
  216592. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  216593. if (ComponentPeer::isValidPeer (peer))
  216594. peer->handleWindowMessage (event);
  216595. }
  216596. else
  216597. {
  216598. switch (event->xany.type)
  216599. {
  216600. case KeymapNotify:
  216601. {
  216602. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  216603. memcpy (keyStates, keymapEvent->key_vector, 32);
  216604. break;
  216605. }
  216606. default:
  216607. break;
  216608. }
  216609. }
  216610. }
  216611. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  216612. {
  216613. #if JUCE_USE_XINERAMA
  216614. int major_opcode, first_event, first_error;
  216615. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  216616. && XineramaIsActive (display))
  216617. {
  216618. int numMonitors = 0;
  216619. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  216620. if (screens != 0)
  216621. {
  216622. for (int i = numMonitors; --i >= 0;)
  216623. {
  216624. int index = screens[i].screen_number;
  216625. if (index >= 0)
  216626. {
  216627. while (monitorCoords.size() < index)
  216628. monitorCoords.add (Rectangle (0, 0, 0, 0));
  216629. monitorCoords.set (index, Rectangle (screens[i].x_org,
  216630. screens[i].y_org,
  216631. screens[i].width,
  216632. screens[i].height));
  216633. }
  216634. }
  216635. XFree (screens);
  216636. }
  216637. }
  216638. if (monitorCoords.size() == 0)
  216639. #endif
  216640. {
  216641. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  216642. if (hints != None)
  216643. {
  216644. const int numMonitors = ScreenCount (display);
  216645. for (int i = 0; i < numMonitors; ++i)
  216646. {
  216647. Window root = RootWindow (display, i);
  216648. unsigned long nitems, bytesLeft;
  216649. Atom actualType;
  216650. int actualFormat;
  216651. unsigned char* data = 0;
  216652. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  216653. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  216654. &data) == Success)
  216655. {
  216656. const long* const position = (const long*) data;
  216657. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  216658. monitorCoords.add (Rectangle (position[0], position[1],
  216659. position[2], position[3]));
  216660. XFree (data);
  216661. }
  216662. }
  216663. }
  216664. if (monitorCoords.size() == 0)
  216665. {
  216666. monitorCoords.add (Rectangle (0, 0,
  216667. DisplayWidth (display, DefaultScreen (display)),
  216668. DisplayHeight (display, DefaultScreen (display))));
  216669. }
  216670. }
  216671. }
  216672. bool Desktop::canUseSemiTransparentWindows() throw()
  216673. {
  216674. return false;
  216675. }
  216676. void Desktop::getMousePosition (int& x, int& y) throw()
  216677. {
  216678. int mouseMods;
  216679. getMousePos (x, y, mouseMods);
  216680. }
  216681. void Desktop::setMousePosition (int x, int y) throw()
  216682. {
  216683. Window root = RootWindow (display, DefaultScreen (display));
  216684. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  216685. }
  216686. static bool screenSaverAllowed = true;
  216687. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  216688. {
  216689. if (screenSaverAllowed != isEnabled)
  216690. {
  216691. screenSaverAllowed = isEnabled;
  216692. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  216693. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  216694. if (xScreenSaverSuspend == 0)
  216695. {
  216696. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  216697. if (h != 0)
  216698. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  216699. }
  216700. if (xScreenSaverSuspend != 0)
  216701. xScreenSaverSuspend (display, ! isEnabled);
  216702. }
  216703. }
  216704. bool Desktop::isScreenSaverEnabled() throw()
  216705. {
  216706. return screenSaverAllowed;
  216707. }
  216708. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  216709. {
  216710. Window root = RootWindow (display, DefaultScreen (display));
  216711. const unsigned int imageW = image.getWidth();
  216712. const unsigned int imageH = image.getHeight();
  216713. unsigned int cursorW, cursorH;
  216714. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  216715. return 0;
  216716. Image im (Image::ARGB, cursorW, cursorH, true);
  216717. Graphics g (im);
  216718. if (imageW > cursorW || imageH > cursorH)
  216719. {
  216720. hotspotX = (hotspotX * cursorW) / imageW;
  216721. hotspotY = (hotspotY * cursorH) / imageH;
  216722. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  216723. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  216724. false);
  216725. }
  216726. else
  216727. {
  216728. g.drawImageAt (&image, 0, 0);
  216729. }
  216730. const int stride = (cursorW + 7) >> 3;
  216731. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  216732. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  216733. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  216734. for (int y = cursorH; --y >= 0;)
  216735. {
  216736. for (int x = cursorW; --x >= 0;)
  216737. {
  216738. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  216739. const int offset = y * stride + (x >> 3);
  216740. const Colour c (im.getPixelAt (x, y));
  216741. if (c.getAlpha() >= 128)
  216742. maskPlane[offset] |= mask;
  216743. if (c.getBrightness() >= 0.5f)
  216744. sourcePlane[offset] |= mask;
  216745. }
  216746. }
  216747. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  216748. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  216749. juce_free (maskPlane);
  216750. juce_free (sourcePlane);
  216751. XColor white, black;
  216752. black.red = black.green = black.blue = 0;
  216753. white.red = white.green = white.blue = 0xffff;
  216754. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  216755. XFreePixmap (display, sourcePixmap);
  216756. XFreePixmap (display, maskPixmap);
  216757. return result;
  216758. }
  216759. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  216760. {
  216761. if (cursorHandle != None)
  216762. XFreeCursor (display, (Cursor) cursorHandle);
  216763. }
  216764. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  216765. {
  216766. unsigned int shape;
  216767. switch (type)
  216768. {
  216769. case MouseCursor::NoCursor:
  216770. {
  216771. const Image im (Image::ARGB, 16, 16, true);
  216772. return juce_createMouseCursorFromImage (im, 0, 0);
  216773. }
  216774. case MouseCursor::NormalCursor:
  216775. return (void*) None; // Use parent cursor
  216776. case MouseCursor::DraggingHandCursor:
  216777. {
  216778. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  216779. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  216780. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  216781. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  216782. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  216783. const int dragHandDataSize = 99;
  216784. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  216785. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  216786. delete im;
  216787. return dragHandCursor;
  216788. }
  216789. case MouseCursor::CopyingCursor:
  216790. {
  216791. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  216792. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  216793. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  216794. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  216795. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  216796. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  216797. const int copyCursorSize = 119;
  216798. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  216799. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  216800. delete im;
  216801. return copyCursor;
  216802. }
  216803. case MouseCursor::WaitCursor:
  216804. shape = XC_watch;
  216805. break;
  216806. case MouseCursor::IBeamCursor:
  216807. shape = XC_xterm;
  216808. break;
  216809. case MouseCursor::PointingHandCursor:
  216810. shape = XC_hand2;
  216811. break;
  216812. case MouseCursor::LeftRightResizeCursor:
  216813. shape = XC_sb_h_double_arrow;
  216814. break;
  216815. case MouseCursor::UpDownResizeCursor:
  216816. shape = XC_sb_v_double_arrow;
  216817. break;
  216818. case MouseCursor::UpDownLeftRightResizeCursor:
  216819. shape = XC_fleur;
  216820. break;
  216821. case MouseCursor::TopEdgeResizeCursor:
  216822. shape = XC_top_side;
  216823. break;
  216824. case MouseCursor::BottomEdgeResizeCursor:
  216825. shape = XC_bottom_side;
  216826. break;
  216827. case MouseCursor::LeftEdgeResizeCursor:
  216828. shape = XC_left_side;
  216829. break;
  216830. case MouseCursor::RightEdgeResizeCursor:
  216831. shape = XC_right_side;
  216832. break;
  216833. case MouseCursor::TopLeftCornerResizeCursor:
  216834. shape = XC_top_left_corner;
  216835. break;
  216836. case MouseCursor::TopRightCornerResizeCursor:
  216837. shape = XC_top_right_corner;
  216838. break;
  216839. case MouseCursor::BottomLeftCornerResizeCursor:
  216840. shape = XC_bottom_left_corner;
  216841. break;
  216842. case MouseCursor::BottomRightCornerResizeCursor:
  216843. shape = XC_bottom_right_corner;
  216844. break;
  216845. case MouseCursor::CrosshairCursor:
  216846. shape = XC_crosshair;
  216847. break;
  216848. default:
  216849. return (void*) None; // Use parent cursor
  216850. }
  216851. return (void*) XCreateFontCursor (display, shape);
  216852. }
  216853. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  216854. {
  216855. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  216856. if (lp != 0)
  216857. lp->showMouseCursor ((Cursor) getHandle());
  216858. }
  216859. void MouseCursor::showInAllWindows() const throw()
  216860. {
  216861. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  216862. showInWindow (ComponentPeer::getPeer (i));
  216863. }
  216864. Image* juce_createIconForFile (const File& file)
  216865. {
  216866. return 0;
  216867. }
  216868. #if JUCE_OPENGL
  216869. class WindowedGLContext : public OpenGLContext
  216870. {
  216871. public:
  216872. WindowedGLContext (Component* const component,
  216873. const OpenGLPixelFormat& pixelFormat_,
  216874. GLXContext sharedContext)
  216875. : renderContext (0),
  216876. embeddedWindow (0),
  216877. pixelFormat (pixelFormat_)
  216878. {
  216879. jassert (component != 0);
  216880. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  216881. if (peer == 0)
  216882. return;
  216883. XSync (display, False);
  216884. GLint attribs [64];
  216885. int n = 0;
  216886. attribs[n++] = GLX_RGBA;
  216887. attribs[n++] = GLX_DOUBLEBUFFER;
  216888. attribs[n++] = GLX_RED_SIZE;
  216889. attribs[n++] = pixelFormat.redBits;
  216890. attribs[n++] = GLX_GREEN_SIZE;
  216891. attribs[n++] = pixelFormat.greenBits;
  216892. attribs[n++] = GLX_BLUE_SIZE;
  216893. attribs[n++] = pixelFormat.blueBits;
  216894. attribs[n++] = GLX_ALPHA_SIZE;
  216895. attribs[n++] = pixelFormat.alphaBits;
  216896. attribs[n++] = GLX_DEPTH_SIZE;
  216897. attribs[n++] = pixelFormat.depthBufferBits;
  216898. attribs[n++] = GLX_STENCIL_SIZE;
  216899. attribs[n++] = pixelFormat.stencilBufferBits;
  216900. attribs[n++] = GLX_ACCUM_RED_SIZE;
  216901. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  216902. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  216903. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  216904. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  216905. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  216906. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  216907. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  216908. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  216909. attribs[n++] = None;
  216910. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  216911. if (bestVisual == 0)
  216912. return;
  216913. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  216914. Window windowH = (Window) peer->getNativeHandle();
  216915. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  216916. XSetWindowAttributes swa;
  216917. swa.colormap = colourMap;
  216918. swa.border_pixel = 0;
  216919. swa.event_mask = ExposureMask | StructureNotifyMask;
  216920. embeddedWindow = XCreateWindow (display, windowH,
  216921. 0, 0, 1, 1, 0,
  216922. bestVisual->depth,
  216923. InputOutput,
  216924. bestVisual->visual,
  216925. CWBorderPixel | CWColormap | CWEventMask,
  216926. &swa);
  216927. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  216928. XMapWindow (display, embeddedWindow);
  216929. XFreeColormap (display, colourMap);
  216930. XFree (bestVisual);
  216931. XSync (display, False);
  216932. }
  216933. ~WindowedGLContext()
  216934. {
  216935. makeInactive();
  216936. glXDestroyContext (display, renderContext);
  216937. XUnmapWindow (display, embeddedWindow);
  216938. XDestroyWindow (display, embeddedWindow);
  216939. }
  216940. bool makeActive() const throw()
  216941. {
  216942. jassert (renderContext != 0);
  216943. return glXMakeCurrent (display, embeddedWindow, renderContext)
  216944. && XSync (display, False);
  216945. }
  216946. bool makeInactive() const throw()
  216947. {
  216948. return (! isActive()) || glXMakeCurrent (display, None, 0);
  216949. }
  216950. bool isActive() const throw()
  216951. {
  216952. return glXGetCurrentContext() == renderContext;
  216953. }
  216954. const OpenGLPixelFormat getPixelFormat() const
  216955. {
  216956. return pixelFormat;
  216957. }
  216958. void* getRawContext() const throw()
  216959. {
  216960. return renderContext;
  216961. }
  216962. void updateWindowPosition (int x, int y, int w, int h, int)
  216963. {
  216964. XMoveResizeWindow (display, embeddedWindow,
  216965. x, y, jmax (1, w), jmax (1, h));
  216966. }
  216967. void swapBuffers()
  216968. {
  216969. glXSwapBuffers (display, embeddedWindow);
  216970. }
  216971. bool setSwapInterval (const int numFramesPerSwap)
  216972. {
  216973. // xxx needs doing..
  216974. return false;
  216975. }
  216976. int getSwapInterval() const
  216977. {
  216978. // xxx needs doing..
  216979. return 0;
  216980. }
  216981. void repaint()
  216982. {
  216983. }
  216984. juce_UseDebuggingNewOperator
  216985. GLXContext renderContext;
  216986. private:
  216987. Window embeddedWindow;
  216988. OpenGLPixelFormat pixelFormat;
  216989. WindowedGLContext (const WindowedGLContext&);
  216990. const WindowedGLContext& operator= (const WindowedGLContext&);
  216991. };
  216992. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  216993. const OpenGLPixelFormat& pixelFormat,
  216994. const OpenGLContext* const contextToShareWith)
  216995. {
  216996. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  216997. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  216998. if (c->renderContext == 0)
  216999. deleteAndZero (c);
  217000. return c;
  217001. }
  217002. void juce_glViewport (const int w, const int h)
  217003. {
  217004. glViewport (0, 0, w, h);
  217005. }
  217006. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  217007. OwnedArray <OpenGLPixelFormat>& results)
  217008. {
  217009. results.add (new OpenGLPixelFormat()); // xxx
  217010. }
  217011. #endif
  217012. static void initClipboard (Window root, Atom* cutBuffers) throw()
  217013. {
  217014. static bool init = false;
  217015. if (! init)
  217016. {
  217017. init = true;
  217018. // Make sure all cut buffers exist before use
  217019. for (int i = 0; i < 8; i++)
  217020. {
  217021. XChangeProperty (display, root, cutBuffers[i],
  217022. XA_STRING, 8, PropModeAppend, NULL, 0);
  217023. }
  217024. }
  217025. }
  217026. // Clipboard implemented currently using cut buffers
  217027. // rather than the more powerful selection method
  217028. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  217029. {
  217030. Window root = RootWindow (display, DefaultScreen (display));
  217031. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217032. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217033. initClipboard (root, cutBuffers);
  217034. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  217035. XChangeProperty (display, root, cutBuffers[0],
  217036. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  217037. clipText.length());
  217038. }
  217039. const String SystemClipboard::getTextFromClipboard() throw()
  217040. {
  217041. const int bufSize = 64; // in words
  217042. String returnData;
  217043. int byteOffset = 0;
  217044. Window root = RootWindow (display, DefaultScreen (display));
  217045. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  217046. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  217047. initClipboard (root, cutBuffers);
  217048. for (;;)
  217049. {
  217050. unsigned long bytesLeft = 0, nitems = 0;
  217051. unsigned char* clipData = 0;
  217052. int actualFormat = 0;
  217053. Atom actualType;
  217054. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  217055. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  217056. &clipData) == Success)
  217057. {
  217058. if (actualType == XA_STRING && actualFormat == 8)
  217059. {
  217060. byteOffset += nitems;
  217061. returnData += String ((const char*) clipData, nitems);
  217062. }
  217063. else
  217064. {
  217065. bytesLeft = 0;
  217066. }
  217067. if (clipData != 0)
  217068. XFree (clipData);
  217069. }
  217070. if (bytesLeft == 0)
  217071. break;
  217072. }
  217073. return returnData;
  217074. }
  217075. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  217076. {
  217077. jassertfalse // not implemented!
  217078. return false;
  217079. }
  217080. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  217081. {
  217082. jassertfalse // not implemented!
  217083. return false;
  217084. }
  217085. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  217086. {
  217087. if (! isOnDesktop ())
  217088. addToDesktop (0);
  217089. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217090. if (wp != 0)
  217091. {
  217092. wp->setTaskBarIcon (newImage);
  217093. setVisible (true);
  217094. toFront (false);
  217095. repaint();
  217096. }
  217097. }
  217098. void SystemTrayIconComponent::paint (Graphics& g)
  217099. {
  217100. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  217101. if (wp != 0)
  217102. {
  217103. const Image* const image = wp->getTaskbarIcon();
  217104. if (image != 0)
  217105. {
  217106. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  217107. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  217108. false);
  217109. }
  217110. }
  217111. }
  217112. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  217113. {
  217114. // xxx not yet implemented!
  217115. }
  217116. void PlatformUtilities::beep()
  217117. {
  217118. fprintf (stdout, "\a");
  217119. fflush (stdout);
  217120. }
  217121. bool AlertWindow::showNativeDialogBox (const String& title,
  217122. const String& bodyText,
  217123. bool isOkCancel)
  217124. {
  217125. // xxx this is supposed to pop up an alert!
  217126. Logger::outputDebugString (title + ": " + bodyText);
  217127. // use a non-native one for the time being..
  217128. if (isOkCancel)
  217129. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  217130. else
  217131. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  217132. return true;
  217133. }
  217134. const int KeyPress::spaceKey = XK_space & 0xff;
  217135. const int KeyPress::returnKey = XK_Return & 0xff;
  217136. const int KeyPress::escapeKey = XK_Escape & 0xff;
  217137. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  217138. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  217139. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  217140. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  217141. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  217142. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  217143. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  217144. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  217145. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  217146. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  217147. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  217148. const int KeyPress::tabKey = XK_Tab & 0xff;
  217149. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  217150. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  217151. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  217152. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  217153. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  217154. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  217155. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  217156. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  217157. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  217158. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  217159. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  217160. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  217161. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  217162. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  217163. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  217164. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  217165. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  217166. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  217167. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  217168. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  217169. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  217170. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  217171. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  217172. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  217173. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  217174. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  217175. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  217176. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  217177. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  217178. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  217179. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  217180. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  217181. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  217182. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  217183. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  217184. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  217185. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  217186. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  217187. #endif
  217188. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  217189. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  217190. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217191. // compiled on its own).
  217192. #ifdef JUCE_INCLUDED_FILE && JUCE_ALSA
  217193. static const int maxNumChans = 64;
  217194. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  217195. {
  217196. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  217197. snd_pcm_hw_params_t* hwParams;
  217198. snd_pcm_hw_params_alloca (&hwParams);
  217199. for (int i = 0; ratesToTry[i] != 0; ++i)
  217200. {
  217201. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  217202. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  217203. {
  217204. rates.addIfNotAlreadyThere (ratesToTry[i]);
  217205. }
  217206. }
  217207. }
  217208. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  217209. {
  217210. snd_pcm_hw_params_t *params;
  217211. snd_pcm_hw_params_alloca (&params);
  217212. if (snd_pcm_hw_params_any (handle, params) >= 0)
  217213. {
  217214. snd_pcm_hw_params_get_channels_min (params, minChans);
  217215. snd_pcm_hw_params_get_channels_max (params, maxChans);
  217216. }
  217217. }
  217218. static void getDeviceProperties (const String& id,
  217219. unsigned int& minChansOut,
  217220. unsigned int& maxChansOut,
  217221. unsigned int& minChansIn,
  217222. unsigned int& maxChansIn,
  217223. Array <int>& rates)
  217224. {
  217225. if (id.isEmpty())
  217226. return;
  217227. snd_ctl_t* handle;
  217228. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  217229. {
  217230. snd_pcm_info_t* info;
  217231. snd_pcm_info_alloca (&info);
  217232. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  217233. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  217234. snd_pcm_info_set_subdevice (info, 0);
  217235. if (snd_ctl_pcm_info (handle, info) >= 0)
  217236. {
  217237. snd_pcm_t* pcmHandle;
  217238. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217239. {
  217240. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  217241. getDeviceSampleRates (pcmHandle, rates);
  217242. snd_pcm_close (pcmHandle);
  217243. }
  217244. }
  217245. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  217246. if (snd_ctl_pcm_info (handle, info) >= 0)
  217247. {
  217248. snd_pcm_t* pcmHandle;
  217249. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217250. {
  217251. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  217252. if (rates.size() == 0)
  217253. getDeviceSampleRates (pcmHandle, rates);
  217254. snd_pcm_close (pcmHandle);
  217255. }
  217256. }
  217257. snd_ctl_close (handle);
  217258. }
  217259. }
  217260. class ALSADevice
  217261. {
  217262. public:
  217263. ALSADevice (const String& id,
  217264. const bool forInput)
  217265. : handle (0),
  217266. bitDepth (16),
  217267. numChannelsRunning (0),
  217268. isInput (forInput),
  217269. sampleFormat (AudioDataConverters::int16LE)
  217270. {
  217271. failed (snd_pcm_open (&handle, id,
  217272. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  217273. SND_PCM_ASYNC));
  217274. }
  217275. ~ALSADevice()
  217276. {
  217277. if (handle != 0)
  217278. snd_pcm_close (handle);
  217279. }
  217280. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  217281. {
  217282. if (handle == 0)
  217283. return false;
  217284. snd_pcm_hw_params_t* hwParams;
  217285. snd_pcm_hw_params_alloca (&hwParams);
  217286. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  217287. return false;
  217288. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  217289. isInterleaved = false;
  217290. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  217291. isInterleaved = true;
  217292. else
  217293. {
  217294. jassertfalse
  217295. return false;
  217296. }
  217297. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  217298. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  217299. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  217300. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  217301. SND_PCM_FORMAT_S24_3LE, 24, AudioDataConverters::int24LE,
  217302. SND_PCM_FORMAT_S24_3BE, 24, AudioDataConverters::int24BE,
  217303. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  217304. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  217305. bitDepth = 0;
  217306. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  217307. {
  217308. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  217309. {
  217310. bitDepth = formatsToTry [i + 1];
  217311. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  217312. break;
  217313. }
  217314. }
  217315. if (bitDepth == 0)
  217316. {
  217317. error = "device doesn't support a compatible PCM format";
  217318. DBG (T("ALSA error: ") + error + T("\n"));
  217319. return false;
  217320. }
  217321. int dir = 0;
  217322. unsigned int periods = 4;
  217323. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  217324. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  217325. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  217326. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  217327. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  217328. || failed (snd_pcm_hw_params (handle, hwParams)))
  217329. {
  217330. return false;
  217331. }
  217332. snd_pcm_sw_params_t* swParams;
  217333. snd_pcm_sw_params_alloca (&swParams);
  217334. snd_pcm_uframes_t boundary;
  217335. if (failed (snd_pcm_sw_params_current (handle, swParams))
  217336. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  217337. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  217338. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  217339. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  217340. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  217341. || failed (snd_pcm_sw_params (handle, swParams)))
  217342. {
  217343. return false;
  217344. }
  217345. /*
  217346. #ifdef JUCE_DEBUG
  217347. // enable this to dump the config of the devices that get opened
  217348. snd_output_t* out;
  217349. snd_output_stdio_attach (&out, stderr, 0);
  217350. snd_pcm_hw_params_dump (hwParams, out);
  217351. snd_pcm_sw_params_dump (swParams, out);
  217352. #endif
  217353. */
  217354. numChannelsRunning = numChannels;
  217355. return true;
  217356. }
  217357. bool write (float** const data, const int numSamples)
  217358. {
  217359. if (isInterleaved)
  217360. {
  217361. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217362. float* interleaved = (float*) scratch;
  217363. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  217364. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217365. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  217366. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217367. return false;
  217368. }
  217369. else
  217370. {
  217371. for (int i = 0; i < numChannelsRunning; ++i)
  217372. if (data[i] != 0)
  217373. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  217374. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  217375. if (failed (num))
  217376. {
  217377. if (num == -EPIPE)
  217378. {
  217379. if (failed (snd_pcm_prepare (handle)))
  217380. return false;
  217381. }
  217382. else if (num != -ESTRPIPE)
  217383. return false;
  217384. }
  217385. }
  217386. return true;
  217387. }
  217388. bool read (float** const data, const int numSamples)
  217389. {
  217390. if (isInterleaved)
  217391. {
  217392. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  217393. float* interleaved = (float*) scratch;
  217394. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  217395. if (failed (num))
  217396. {
  217397. if (num == -EPIPE)
  217398. {
  217399. if (failed (snd_pcm_prepare (handle)))
  217400. return false;
  217401. }
  217402. else if (num != -ESTRPIPE)
  217403. return false;
  217404. }
  217405. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  217406. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  217407. }
  217408. else
  217409. {
  217410. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  217411. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  217412. return false;
  217413. for (int i = 0; i < numChannelsRunning; ++i)
  217414. if (data[i] != 0)
  217415. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  217416. }
  217417. return true;
  217418. }
  217419. juce_UseDebuggingNewOperator
  217420. snd_pcm_t* handle;
  217421. String error;
  217422. int bitDepth, numChannelsRunning;
  217423. private:
  217424. const bool isInput;
  217425. bool isInterleaved;
  217426. MemoryBlock scratch;
  217427. AudioDataConverters::DataFormat sampleFormat;
  217428. bool failed (const int errorNum)
  217429. {
  217430. if (errorNum >= 0)
  217431. return false;
  217432. error = snd_strerror (errorNum);
  217433. DBG (T("ALSA error: ") + error + T("\n"));
  217434. return true;
  217435. }
  217436. };
  217437. class ALSAThread : public Thread
  217438. {
  217439. public:
  217440. ALSAThread (const String& inputId_,
  217441. const String& outputId_)
  217442. : Thread ("Juce ALSA"),
  217443. sampleRate (0),
  217444. bufferSize (0),
  217445. callback (0),
  217446. inputId (inputId_),
  217447. outputId (outputId_),
  217448. outputDevice (0),
  217449. inputDevice (0),
  217450. numCallbacks (0),
  217451. totalNumInputChannels (0),
  217452. totalNumOutputChannels (0)
  217453. {
  217454. zeromem (outputChannelData, sizeof (outputChannelData));
  217455. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217456. zeromem (inputChannelData, sizeof (inputChannelData));
  217457. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217458. initialiseRatesAndChannels();
  217459. }
  217460. ~ALSAThread()
  217461. {
  217462. close();
  217463. }
  217464. void open (BitArray inputChannels,
  217465. BitArray outputChannels,
  217466. const double sampleRate_,
  217467. const int bufferSize_)
  217468. {
  217469. close();
  217470. error = String::empty;
  217471. sampleRate = sampleRate_;
  217472. bufferSize = bufferSize_;
  217473. currentInputChans.clear();
  217474. currentOutputChans.clear();
  217475. if (inputChannels.getHighestBit() >= 0)
  217476. {
  217477. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), minChansIn); ++i)
  217478. {
  217479. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217480. if (inputChannels[i])
  217481. {
  217482. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  217483. currentInputChans.setBit (i);
  217484. }
  217485. }
  217486. }
  217487. if (outputChannels.getHighestBit() >= 0)
  217488. {
  217489. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), minChansOut); ++i)
  217490. {
  217491. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  217492. if (outputChannels[i])
  217493. {
  217494. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  217495. currentOutputChans.setBit (i);
  217496. }
  217497. }
  217498. }
  217499. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  217500. {
  217501. outputDevice = new ALSADevice (outputId, false);
  217502. if (outputDevice->error.isNotEmpty())
  217503. {
  217504. error = outputDevice->error;
  217505. deleteAndZero (outputDevice);
  217506. return;
  217507. }
  217508. currentOutputChans.setRange (0, minChansOut, true);
  217509. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  217510. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  217511. bufferSize))
  217512. {
  217513. error = outputDevice->error;
  217514. deleteAndZero (outputDevice);
  217515. return;
  217516. }
  217517. }
  217518. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  217519. {
  217520. inputDevice = new ALSADevice (inputId, true);
  217521. if (inputDevice->error.isNotEmpty())
  217522. {
  217523. error = inputDevice->error;
  217524. deleteAndZero (inputDevice);
  217525. return;
  217526. }
  217527. currentInputChans.setRange (0, minChansIn, true);
  217528. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  217529. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  217530. bufferSize))
  217531. {
  217532. error = inputDevice->error;
  217533. deleteAndZero (inputDevice);
  217534. return;
  217535. }
  217536. }
  217537. if (outputDevice == 0 && inputDevice == 0)
  217538. {
  217539. error = "no channels";
  217540. return;
  217541. }
  217542. if (outputDevice != 0 && inputDevice != 0)
  217543. {
  217544. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  217545. }
  217546. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  217547. return;
  217548. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  217549. return;
  217550. startThread (9);
  217551. int count = 1000;
  217552. while (numCallbacks == 0)
  217553. {
  217554. sleep (5);
  217555. if (--count < 0 || ! isThreadRunning())
  217556. {
  217557. error = "device didn't start";
  217558. break;
  217559. }
  217560. }
  217561. }
  217562. void close()
  217563. {
  217564. stopThread (6000);
  217565. deleteAndZero (inputDevice);
  217566. deleteAndZero (outputDevice);
  217567. for (int i = 0; i < maxNumChans; ++i)
  217568. {
  217569. juce_free (inputChannelData [i]);
  217570. juce_free (outputChannelData [i]);
  217571. }
  217572. zeromem (outputChannelData, sizeof (outputChannelData));
  217573. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  217574. zeromem (inputChannelData, sizeof (inputChannelData));
  217575. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  217576. totalNumOutputChannels = 0;
  217577. totalNumInputChannels = 0;
  217578. numCallbacks = 0;
  217579. }
  217580. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  217581. {
  217582. const ScopedLock sl (callbackLock);
  217583. callback = newCallback;
  217584. }
  217585. void run()
  217586. {
  217587. while (! threadShouldExit())
  217588. {
  217589. if (inputDevice != 0)
  217590. {
  217591. if (! inputDevice->read (inputChannelData, bufferSize))
  217592. {
  217593. DBG ("ALSA: read failure");
  217594. break;
  217595. }
  217596. }
  217597. if (threadShouldExit())
  217598. break;
  217599. {
  217600. const ScopedLock sl (callbackLock);
  217601. ++numCallbacks;
  217602. if (callback != 0)
  217603. {
  217604. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  217605. totalNumInputChannels,
  217606. outputChannelDataForCallback,
  217607. totalNumOutputChannels,
  217608. bufferSize);
  217609. }
  217610. else
  217611. {
  217612. for (int i = 0; i < totalNumOutputChannels; ++i)
  217613. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  217614. }
  217615. }
  217616. if (outputDevice != 0)
  217617. {
  217618. failed (snd_pcm_wait (outputDevice->handle, 2000));
  217619. if (threadShouldExit())
  217620. break;
  217621. failed (snd_pcm_avail_update (outputDevice->handle));
  217622. if (! outputDevice->write (outputChannelData, bufferSize))
  217623. {
  217624. DBG ("ALSA: write failure");
  217625. break;
  217626. }
  217627. }
  217628. }
  217629. }
  217630. int getBitDepth() const throw()
  217631. {
  217632. if (outputDevice != 0)
  217633. return outputDevice->bitDepth;
  217634. if (inputDevice != 0)
  217635. return inputDevice->bitDepth;
  217636. return 16;
  217637. }
  217638. juce_UseDebuggingNewOperator
  217639. String error;
  217640. double sampleRate;
  217641. int bufferSize;
  217642. BitArray currentInputChans, currentOutputChans;
  217643. Array <int> sampleRates;
  217644. StringArray channelNamesOut, channelNamesIn;
  217645. AudioIODeviceCallback* callback;
  217646. private:
  217647. const String inputId, outputId;
  217648. ALSADevice* outputDevice;
  217649. ALSADevice* inputDevice;
  217650. int numCallbacks;
  217651. CriticalSection callbackLock;
  217652. float* outputChannelData [maxNumChans];
  217653. float* outputChannelDataForCallback [maxNumChans];
  217654. int totalNumInputChannels;
  217655. float* inputChannelData [maxNumChans];
  217656. float* inputChannelDataForCallback [maxNumChans];
  217657. int totalNumOutputChannels;
  217658. unsigned int minChansOut, maxChansOut;
  217659. unsigned int minChansIn, maxChansIn;
  217660. bool failed (const int errorNum) throw()
  217661. {
  217662. if (errorNum >= 0)
  217663. return false;
  217664. error = snd_strerror (errorNum);
  217665. DBG (T("ALSA error: ") + error + T("\n"));
  217666. return true;
  217667. }
  217668. void initialiseRatesAndChannels() throw()
  217669. {
  217670. sampleRates.clear();
  217671. channelNamesOut.clear();
  217672. channelNamesIn.clear();
  217673. minChansOut = 0;
  217674. maxChansOut = 0;
  217675. minChansIn = 0;
  217676. maxChansIn = 0;
  217677. unsigned int dummy = 0;
  217678. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  217679. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  217680. unsigned int i;
  217681. for (i = 0; i < maxChansOut; ++i)
  217682. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  217683. for (i = 0; i < maxChansIn; ++i)
  217684. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  217685. }
  217686. };
  217687. class ALSAAudioIODevice : public AudioIODevice
  217688. {
  217689. public:
  217690. ALSAAudioIODevice (const String& deviceName,
  217691. const String& inputId_,
  217692. const String& outputId_)
  217693. : AudioIODevice (deviceName, T("ALSA")),
  217694. inputId (inputId_),
  217695. outputId (outputId_),
  217696. isOpen_ (false),
  217697. isStarted (false),
  217698. internal (0)
  217699. {
  217700. internal = new ALSAThread (inputId, outputId);
  217701. }
  217702. ~ALSAAudioIODevice()
  217703. {
  217704. delete internal;
  217705. }
  217706. const StringArray getOutputChannelNames()
  217707. {
  217708. return internal->channelNamesOut;
  217709. }
  217710. const StringArray getInputChannelNames()
  217711. {
  217712. return internal->channelNamesIn;
  217713. }
  217714. int getNumSampleRates()
  217715. {
  217716. return internal->sampleRates.size();
  217717. }
  217718. double getSampleRate (int index)
  217719. {
  217720. return internal->sampleRates [index];
  217721. }
  217722. int getNumBufferSizesAvailable()
  217723. {
  217724. return 50;
  217725. }
  217726. int getBufferSizeSamples (int index)
  217727. {
  217728. int n = 16;
  217729. for (int i = 0; i < index; ++i)
  217730. n += n < 64 ? 16
  217731. : (n < 512 ? 32
  217732. : (n < 1024 ? 64
  217733. : (n < 2048 ? 128 : 256)));
  217734. return n;
  217735. }
  217736. int getDefaultBufferSize()
  217737. {
  217738. return 512;
  217739. }
  217740. const String open (const BitArray& inputChannels,
  217741. const BitArray& outputChannels,
  217742. double sampleRate,
  217743. int bufferSizeSamples)
  217744. {
  217745. close();
  217746. if (bufferSizeSamples <= 0)
  217747. bufferSizeSamples = getDefaultBufferSize();
  217748. if (sampleRate <= 0)
  217749. {
  217750. for (int i = 0; i < getNumSampleRates(); ++i)
  217751. {
  217752. if (getSampleRate (i) >= 44100)
  217753. {
  217754. sampleRate = getSampleRate (i);
  217755. break;
  217756. }
  217757. }
  217758. }
  217759. internal->open (inputChannels, outputChannels,
  217760. sampleRate, bufferSizeSamples);
  217761. isOpen_ = internal->error.isEmpty();
  217762. return internal->error;
  217763. }
  217764. void close()
  217765. {
  217766. stop();
  217767. internal->close();
  217768. isOpen_ = false;
  217769. }
  217770. bool isOpen()
  217771. {
  217772. return isOpen_;
  217773. }
  217774. int getCurrentBufferSizeSamples()
  217775. {
  217776. return internal->bufferSize;
  217777. }
  217778. double getCurrentSampleRate()
  217779. {
  217780. return internal->sampleRate;
  217781. }
  217782. int getCurrentBitDepth()
  217783. {
  217784. return internal->getBitDepth();
  217785. }
  217786. const BitArray getActiveOutputChannels() const
  217787. {
  217788. return internal->currentOutputChans;
  217789. }
  217790. const BitArray getActiveInputChannels() const
  217791. {
  217792. return internal->currentInputChans;
  217793. }
  217794. int getOutputLatencyInSamples()
  217795. {
  217796. return 0;
  217797. }
  217798. int getInputLatencyInSamples()
  217799. {
  217800. return 0;
  217801. }
  217802. void start (AudioIODeviceCallback* callback)
  217803. {
  217804. if (! isOpen_)
  217805. callback = 0;
  217806. internal->setCallback (callback);
  217807. if (callback != 0)
  217808. callback->audioDeviceAboutToStart (this);
  217809. isStarted = (callback != 0);
  217810. }
  217811. void stop()
  217812. {
  217813. AudioIODeviceCallback* const oldCallback = internal->callback;
  217814. start (0);
  217815. if (oldCallback != 0)
  217816. oldCallback->audioDeviceStopped();
  217817. }
  217818. bool isPlaying()
  217819. {
  217820. return isStarted && internal->error.isEmpty();
  217821. }
  217822. const String getLastError()
  217823. {
  217824. return internal->error;
  217825. }
  217826. String inputId, outputId;
  217827. private:
  217828. bool isOpen_, isStarted;
  217829. ALSAThread* internal;
  217830. };
  217831. class ALSAAudioIODeviceType : public AudioIODeviceType
  217832. {
  217833. public:
  217834. ALSAAudioIODeviceType()
  217835. : AudioIODeviceType (T("ALSA")),
  217836. hasScanned (false)
  217837. {
  217838. }
  217839. ~ALSAAudioIODeviceType()
  217840. {
  217841. }
  217842. void scanForDevices()
  217843. {
  217844. if (hasScanned)
  217845. return;
  217846. hasScanned = true;
  217847. inputNames.clear();
  217848. inputIds.clear();
  217849. outputNames.clear();
  217850. outputIds.clear();
  217851. snd_ctl_t* handle;
  217852. snd_ctl_card_info_t* info;
  217853. snd_ctl_card_info_alloca (&info);
  217854. int cardNum = -1;
  217855. while (outputIds.size() + inputIds.size() <= 32)
  217856. {
  217857. snd_card_next (&cardNum);
  217858. if (cardNum < 0)
  217859. break;
  217860. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  217861. {
  217862. if (snd_ctl_card_info (handle, info) >= 0)
  217863. {
  217864. String cardId (snd_ctl_card_info_get_id (info));
  217865. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  217866. cardId = String (cardNum);
  217867. int device = -1;
  217868. for (;;)
  217869. {
  217870. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  217871. break;
  217872. String id, name;
  217873. id << "hw:" << cardId << ',' << device;
  217874. bool isInput, isOutput;
  217875. if (testDevice (id, isInput, isOutput))
  217876. {
  217877. name << snd_ctl_card_info_get_name (info);
  217878. if (name.isEmpty())
  217879. name = id;
  217880. if (isInput)
  217881. {
  217882. inputNames.add (name);
  217883. inputIds.add (id);
  217884. }
  217885. if (isOutput)
  217886. {
  217887. outputNames.add (name);
  217888. outputIds.add (id);
  217889. }
  217890. }
  217891. }
  217892. }
  217893. snd_ctl_close (handle);
  217894. }
  217895. }
  217896. inputNames.appendNumbersToDuplicates (false, true);
  217897. outputNames.appendNumbersToDuplicates (false, true);
  217898. }
  217899. const StringArray getDeviceNames (const bool wantInputNames) const
  217900. {
  217901. jassert (hasScanned); // need to call scanForDevices() before doing this
  217902. return wantInputNames ? inputNames : outputNames;
  217903. }
  217904. int getDefaultDeviceIndex (const bool forInput) const
  217905. {
  217906. jassert (hasScanned); // need to call scanForDevices() before doing this
  217907. return 0;
  217908. }
  217909. bool hasSeparateInputsAndOutputs() const { return true; }
  217910. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  217911. {
  217912. jassert (hasScanned); // need to call scanForDevices() before doing this
  217913. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  217914. if (d == 0)
  217915. return -1;
  217916. return asInput ? inputIds.indexOf (d->inputId)
  217917. : outputIds.indexOf (d->outputId);
  217918. }
  217919. AudioIODevice* createDevice (const String& outputDeviceName,
  217920. const String& inputDeviceName)
  217921. {
  217922. jassert (hasScanned); // need to call scanForDevices() before doing this
  217923. const int inputIndex = inputNames.indexOf (inputDeviceName);
  217924. const int outputIndex = outputNames.indexOf (outputDeviceName);
  217925. String deviceName (outputDeviceName);
  217926. if (deviceName.isEmpty())
  217927. deviceName = inputDeviceName;
  217928. if (index >= 0)
  217929. return new ALSAAudioIODevice (deviceName,
  217930. inputIds [inputIndex],
  217931. outputIds [outputIndex]);
  217932. return 0;
  217933. }
  217934. juce_UseDebuggingNewOperator
  217935. private:
  217936. StringArray inputNames, outputNames, inputIds, outputIds;
  217937. bool hasScanned;
  217938. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  217939. {
  217940. unsigned int minChansOut = 0, maxChansOut = 0;
  217941. unsigned int minChansIn = 0, maxChansIn = 0;
  217942. Array <int> rates;
  217943. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  217944. DBG (T("ALSA device: ") + id
  217945. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  217946. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  217947. + T(" rates=") + String (rates.size()));
  217948. isInput = maxChansIn > 0;
  217949. isOutput = maxChansOut > 0;
  217950. return (isInput || isOutput) && rates.size() > 0;
  217951. }
  217952. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  217953. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  217954. };
  217955. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  217956. {
  217957. return new ALSAAudioIODeviceType();
  217958. }
  217959. #endif
  217960. /********* End of inlined file: juce_linux_Audio.cpp *********/
  217961. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  217962. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217963. // compiled on its own).
  217964. #ifdef JUCE_INCLUDED_FILE
  217965. #if JUCE_ALSA
  217966. static snd_seq_t* iterateDevices (const bool forInput,
  217967. StringArray& deviceNamesFound,
  217968. const int deviceIndexToOpen)
  217969. {
  217970. snd_seq_t* returnedHandle = 0;
  217971. snd_seq_t* seqHandle;
  217972. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  217973. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  217974. {
  217975. snd_seq_system_info_t* systemInfo;
  217976. snd_seq_client_info_t* clientInfo;
  217977. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  217978. {
  217979. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  217980. && snd_seq_client_info_malloc (&clientInfo) == 0)
  217981. {
  217982. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  217983. while (--numClients >= 0 && returnedHandle == 0)
  217984. {
  217985. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  217986. {
  217987. snd_seq_port_info_t* portInfo;
  217988. if (snd_seq_port_info_malloc (&portInfo) == 0)
  217989. {
  217990. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  217991. const int client = snd_seq_client_info_get_client (clientInfo);
  217992. snd_seq_port_info_set_client (portInfo, client);
  217993. snd_seq_port_info_set_port (portInfo, -1);
  217994. while (--numPorts >= 0)
  217995. {
  217996. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  217997. && (snd_seq_port_info_get_capability (portInfo)
  217998. & (forInput ? SND_SEQ_PORT_CAP_READ
  217999. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  218000. {
  218001. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  218002. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  218003. {
  218004. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  218005. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  218006. if (sourcePort != -1)
  218007. {
  218008. snd_seq_set_client_name (seqHandle,
  218009. forInput ? "Juce Midi Input"
  218010. : "Juce Midi Output");
  218011. const int portId
  218012. = snd_seq_create_simple_port (seqHandle,
  218013. forInput ? "Juce Midi In Port"
  218014. : "Juce Midi Out Port",
  218015. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218016. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218017. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218018. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  218019. returnedHandle = seqHandle;
  218020. }
  218021. }
  218022. }
  218023. }
  218024. snd_seq_port_info_free (portInfo);
  218025. }
  218026. }
  218027. }
  218028. snd_seq_client_info_free (clientInfo);
  218029. }
  218030. snd_seq_system_info_free (systemInfo);
  218031. }
  218032. if (returnedHandle == 0)
  218033. snd_seq_close (seqHandle);
  218034. }
  218035. deviceNamesFound.appendNumbersToDuplicates (true, true);
  218036. return returnedHandle;
  218037. }
  218038. static snd_seq_t* createDevice (const bool forInput,
  218039. const String& deviceNameToOpen)
  218040. {
  218041. snd_seq_t* seqHandle = 0;
  218042. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  218043. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  218044. {
  218045. snd_seq_set_client_name (seqHandle,
  218046. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  218047. : (deviceNameToOpen + T(" Output"))));
  218048. const int portId
  218049. = snd_seq_create_simple_port (seqHandle,
  218050. forInput ? "in"
  218051. : "out",
  218052. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  218053. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  218054. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  218055. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  218056. if (portId < 0)
  218057. {
  218058. snd_seq_close (seqHandle);
  218059. seqHandle = 0;
  218060. }
  218061. }
  218062. return seqHandle;
  218063. }
  218064. class MidiOutputDevice
  218065. {
  218066. public:
  218067. MidiOutputDevice (MidiOutput* const midiOutput_,
  218068. snd_seq_t* const seqHandle_)
  218069. :
  218070. midiOutput (midiOutput_),
  218071. seqHandle (seqHandle_),
  218072. maxEventSize (16 * 1024)
  218073. {
  218074. jassert (seqHandle != 0 && midiOutput != 0);
  218075. snd_midi_event_new (maxEventSize, &midiParser);
  218076. }
  218077. ~MidiOutputDevice()
  218078. {
  218079. snd_midi_event_free (midiParser);
  218080. snd_seq_close (seqHandle);
  218081. }
  218082. void sendMessageNow (const MidiMessage& message)
  218083. {
  218084. if (message.getRawDataSize() > maxEventSize)
  218085. {
  218086. maxEventSize = message.getRawDataSize();
  218087. snd_midi_event_free (midiParser);
  218088. snd_midi_event_new (maxEventSize, &midiParser);
  218089. }
  218090. snd_seq_event_t event;
  218091. snd_seq_ev_clear (&event);
  218092. snd_midi_event_encode (midiParser,
  218093. message.getRawData(),
  218094. message.getRawDataSize(),
  218095. &event);
  218096. snd_midi_event_reset_encode (midiParser);
  218097. snd_seq_ev_set_source (&event, 0);
  218098. snd_seq_ev_set_subs (&event);
  218099. snd_seq_ev_set_direct (&event);
  218100. snd_seq_event_output (seqHandle, &event);
  218101. snd_seq_drain_output (seqHandle);
  218102. }
  218103. juce_UseDebuggingNewOperator
  218104. private:
  218105. MidiOutput* const midiOutput;
  218106. snd_seq_t* const seqHandle;
  218107. snd_midi_event_t* midiParser;
  218108. int maxEventSize;
  218109. };
  218110. const StringArray MidiOutput::getDevices()
  218111. {
  218112. StringArray devices;
  218113. iterateDevices (false, devices, -1);
  218114. return devices;
  218115. }
  218116. int MidiOutput::getDefaultDeviceIndex()
  218117. {
  218118. return 0;
  218119. }
  218120. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  218121. {
  218122. MidiOutput* newDevice = 0;
  218123. StringArray devices;
  218124. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  218125. if (handle != 0)
  218126. {
  218127. newDevice = new MidiOutput();
  218128. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218129. }
  218130. return newDevice;
  218131. }
  218132. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  218133. {
  218134. MidiOutput* newDevice = 0;
  218135. snd_seq_t* const handle = createDevice (false, deviceName);
  218136. if (handle != 0)
  218137. {
  218138. newDevice = new MidiOutput();
  218139. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  218140. }
  218141. return newDevice;
  218142. }
  218143. MidiOutput::~MidiOutput()
  218144. {
  218145. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  218146. delete device;
  218147. }
  218148. void MidiOutput::reset()
  218149. {
  218150. }
  218151. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  218152. {
  218153. return false;
  218154. }
  218155. void MidiOutput::setVolume (float leftVol, float rightVol)
  218156. {
  218157. }
  218158. void MidiOutput::sendMessageNow (const MidiMessage& message)
  218159. {
  218160. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  218161. }
  218162. class MidiInputThread : public Thread
  218163. {
  218164. public:
  218165. MidiInputThread (MidiInput* const midiInput_,
  218166. snd_seq_t* const seqHandle_,
  218167. MidiInputCallback* const callback_)
  218168. : Thread (T("Juce MIDI Input")),
  218169. midiInput (midiInput_),
  218170. seqHandle (seqHandle_),
  218171. callback (callback_)
  218172. {
  218173. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  218174. }
  218175. ~MidiInputThread()
  218176. {
  218177. snd_seq_close (seqHandle);
  218178. }
  218179. void run()
  218180. {
  218181. const int maxEventSize = 16 * 1024;
  218182. snd_midi_event_t* midiParser;
  218183. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  218184. {
  218185. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  218186. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  218187. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  218188. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  218189. while (! threadShouldExit())
  218190. {
  218191. if (poll (pfd, numPfds, 500) > 0)
  218192. {
  218193. snd_seq_event_t* inputEvent = 0;
  218194. snd_seq_nonblock (seqHandle, 1);
  218195. do
  218196. {
  218197. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  218198. {
  218199. // xxx what about SYSEXes that are too big for the buffer?
  218200. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  218201. snd_midi_event_reset_decode (midiParser);
  218202. if (numBytes > 0)
  218203. {
  218204. const MidiMessage message ((const uint8*) buffer,
  218205. numBytes,
  218206. Time::getMillisecondCounter() * 0.001);
  218207. callback->handleIncomingMidiMessage (midiInput, message);
  218208. }
  218209. snd_seq_free_event (inputEvent);
  218210. }
  218211. }
  218212. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  218213. snd_seq_free_event (inputEvent);
  218214. }
  218215. }
  218216. snd_midi_event_free (midiParser);
  218217. juce_free (buffer);
  218218. }
  218219. };
  218220. juce_UseDebuggingNewOperator
  218221. private:
  218222. MidiInput* const midiInput;
  218223. snd_seq_t* const seqHandle;
  218224. MidiInputCallback* const callback;
  218225. };
  218226. MidiInput::MidiInput (const String& name_)
  218227. : name (name_),
  218228. internal (0)
  218229. {
  218230. }
  218231. MidiInput::~MidiInput()
  218232. {
  218233. stop();
  218234. MidiInputThread* const thread = (MidiInputThread*) internal;
  218235. delete thread;
  218236. }
  218237. void MidiInput::start()
  218238. {
  218239. ((MidiInputThread*) internal)->startThread();
  218240. }
  218241. void MidiInput::stop()
  218242. {
  218243. ((MidiInputThread*) internal)->stopThread (3000);
  218244. }
  218245. int MidiInput::getDefaultDeviceIndex()
  218246. {
  218247. return 0;
  218248. }
  218249. const StringArray MidiInput::getDevices()
  218250. {
  218251. StringArray devices;
  218252. iterateDevices (true, devices, -1);
  218253. return devices;
  218254. }
  218255. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  218256. {
  218257. MidiInput* newDevice = 0;
  218258. StringArray devices;
  218259. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  218260. if (handle != 0)
  218261. {
  218262. newDevice = new MidiInput (devices [deviceIndex]);
  218263. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218264. }
  218265. return newDevice;
  218266. }
  218267. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  218268. {
  218269. MidiInput* newDevice = 0;
  218270. snd_seq_t* const handle = createDevice (true, deviceName);
  218271. if (handle != 0)
  218272. {
  218273. newDevice = new MidiInput (deviceName);
  218274. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  218275. }
  218276. return newDevice;
  218277. }
  218278. #else
  218279. // (These are just stub functions if ALSA is unavailable...)
  218280. const StringArray MidiOutput::getDevices() { return StringArray(); }
  218281. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  218282. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  218283. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  218284. MidiOutput::~MidiOutput() {}
  218285. void MidiOutput::reset() {}
  218286. bool MidiOutput::getVolume (float&, float&) { return false; }
  218287. void MidiOutput::setVolume (float, float) {}
  218288. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  218289. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  218290. MidiInput::~MidiInput() {}
  218291. void MidiInput::start() {}
  218292. void MidiInput::stop() {}
  218293. int MidiInput::getDefaultDeviceIndex() { return 0; }
  218294. const StringArray MidiInput::getDevices() { return StringArray(); }
  218295. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  218296. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  218297. #endif
  218298. #endif
  218299. /********* End of inlined file: juce_linux_Midi.cpp *********/
  218300. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  218301. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218302. // compiled on its own).
  218303. #ifdef JUCE_INCLUDED_FILE
  218304. AudioCDReader::AudioCDReader()
  218305. : AudioFormatReader (0, T("CD Audio"))
  218306. {
  218307. }
  218308. const StringArray AudioCDReader::getAvailableCDNames()
  218309. {
  218310. StringArray names;
  218311. return names;
  218312. }
  218313. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  218314. {
  218315. return 0;
  218316. }
  218317. AudioCDReader::~AudioCDReader()
  218318. {
  218319. }
  218320. void AudioCDReader::refreshTrackLengths()
  218321. {
  218322. }
  218323. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  218324. int64 startSampleInFile, int numSamples)
  218325. {
  218326. return false;
  218327. }
  218328. bool AudioCDReader::isCDStillPresent() const
  218329. {
  218330. return false;
  218331. }
  218332. int AudioCDReader::getNumTracks() const
  218333. {
  218334. return 0;
  218335. }
  218336. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  218337. {
  218338. return 0;
  218339. }
  218340. bool AudioCDReader::isTrackAudio (int trackNum) const
  218341. {
  218342. return false;
  218343. }
  218344. void AudioCDReader::enableIndexScanning (bool b)
  218345. {
  218346. }
  218347. int AudioCDReader::getLastIndex() const
  218348. {
  218349. return 0;
  218350. }
  218351. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  218352. {
  218353. return Array<int>();
  218354. }
  218355. int AudioCDReader::getCDDBId()
  218356. {
  218357. return 0;
  218358. }
  218359. #endif
  218360. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  218361. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  218362. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218363. // compiled on its own).
  218364. #ifdef JUCE_INCLUDED_FILE
  218365. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218366. const String& title,
  218367. const File& file,
  218368. const String& filters,
  218369. bool isDirectory,
  218370. bool isSave,
  218371. bool warnAboutOverwritingExistingFiles,
  218372. bool selectMultipleFiles,
  218373. FilePreviewComponent* previewComponent)
  218374. {
  218375. //xxx ain't got one!
  218376. jassertfalse
  218377. }
  218378. #endif
  218379. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  218380. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218381. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218382. // compiled on its own).
  218383. #ifdef JUCE_INCLUDED_FILE
  218384. #if JUCE_WEB_BROWSER
  218385. /*
  218386. Sorry.. This class isn't implemented on Linux!
  218387. */
  218388. WebBrowserComponent::WebBrowserComponent()
  218389. : browser (0),
  218390. blankPageShown (false)
  218391. {
  218392. setOpaque (true);
  218393. }
  218394. WebBrowserComponent::~WebBrowserComponent()
  218395. {
  218396. }
  218397. void WebBrowserComponent::goToURL (const String& url,
  218398. const StringArray* headers,
  218399. const MemoryBlock* postData)
  218400. {
  218401. lastURL = url;
  218402. lastHeaders.clear();
  218403. if (headers != 0)
  218404. lastHeaders = *headers;
  218405. lastPostData.setSize (0);
  218406. if (postData != 0)
  218407. lastPostData = *postData;
  218408. blankPageShown = false;
  218409. }
  218410. void WebBrowserComponent::stop()
  218411. {
  218412. }
  218413. void WebBrowserComponent::goBack()
  218414. {
  218415. lastURL = String::empty;
  218416. blankPageShown = false;
  218417. }
  218418. void WebBrowserComponent::goForward()
  218419. {
  218420. lastURL = String::empty;
  218421. }
  218422. void WebBrowserComponent::refresh()
  218423. {
  218424. }
  218425. void WebBrowserComponent::paint (Graphics& g)
  218426. {
  218427. g.fillAll (Colours::white);
  218428. }
  218429. void WebBrowserComponent::checkWindowAssociation()
  218430. {
  218431. }
  218432. void WebBrowserComponent::reloadLastURL()
  218433. {
  218434. if (lastURL.isNotEmpty())
  218435. {
  218436. goToURL (lastURL, &lastHeaders, &lastPostData);
  218437. lastURL = String::empty;
  218438. }
  218439. }
  218440. void WebBrowserComponent::parentHierarchyChanged()
  218441. {
  218442. checkWindowAssociation();
  218443. }
  218444. void WebBrowserComponent::resized()
  218445. {
  218446. }
  218447. void WebBrowserComponent::visibilityChanged()
  218448. {
  218449. checkWindowAssociation();
  218450. }
  218451. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218452. {
  218453. return true;
  218454. }
  218455. #endif
  218456. #endif
  218457. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  218458. #endif
  218459. END_JUCE_NAMESPACE
  218460. /********* End of inlined file: juce_linux_NativeCode.cpp *********/
  218461. #endif
  218462. #if JUCE_MAC
  218463. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  218464. /*
  218465. This file wraps together all the mac-specific code, so that
  218466. we can include all the native headers just once, and compile all our
  218467. platform-specific stuff in one big lump, keeping it out of the way of
  218468. the rest of the codebase.
  218469. */
  218470. BEGIN_JUCE_NAMESPACE
  218471. #undef Point
  218472. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  218473. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  218474. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  218475. cross-linked so that when you make a call to a class that you thought was private, it ends up
  218476. actually calling into a similarly named class in the other module's address space.
  218477. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  218478. have unique names, and should avoid this problem.
  218479. If you're using the amalgamated version, you can just set this macro to something unique before
  218480. you include juce_amalgamated.cpp.
  218481. */
  218482. #ifndef JUCE_ObjCExtraSuffix
  218483. #define JUCE_ObjCExtraSuffix 3
  218484. #endif
  218485. #define appendMacro1(a, b, c, d) a ## _ ## b ## _ ## c ## _ ## d
  218486. #define appendMacro2(a, b, c, d) appendMacro1(a, b, c, d)
  218487. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_ObjCExtraSuffix)
  218488. #define JUCE_INCLUDED_FILE 1
  218489. // Now include the actual code files..
  218490. /********* Start of inlined file: juce_mac_Strings.mm *********/
  218491. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218492. // compiled on its own).
  218493. #ifdef JUCE_INCLUDED_FILE
  218494. static const String nsStringToJuce (NSString* s)
  218495. {
  218496. return String::fromUTF8 ((uint8*) [s UTF8String]);
  218497. }
  218498. static NSString* juceStringToNS (const String& s)
  218499. {
  218500. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  218501. }
  218502. static const String convertUTF16ToString (const UniChar* utf16)
  218503. {
  218504. String s;
  218505. while (*utf16 != 0)
  218506. s += (juce_wchar) *utf16++;
  218507. return s;
  218508. }
  218509. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  218510. {
  218511. String result;
  218512. if (cfString != 0)
  218513. {
  218514. #if JUCE_STRINGS_ARE_UNICODE
  218515. CFRange range = { 0, CFStringGetLength (cfString) };
  218516. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  218517. CFStringGetCharacters (cfString, range, u);
  218518. u[range.length] = 0;
  218519. result = convertUTF16ToString (u);
  218520. juce_free (u);
  218521. #else
  218522. const int len = CFStringGetLength (cfString);
  218523. char* buffer = (char*) juce_malloc (len + 1);
  218524. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  218525. result = buffer;
  218526. juce_free (buffer);
  218527. #endif
  218528. }
  218529. return result;
  218530. }
  218531. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  218532. {
  218533. #if JUCE_STRINGS_ARE_UNICODE
  218534. const int len = s.length();
  218535. const juce_wchar* t = (const juce_wchar*) s;
  218536. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  218537. for (int i = 0; i <= len; ++i)
  218538. temp[i] = t[i];
  218539. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  218540. juce_free (temp);
  218541. return result;
  218542. #else
  218543. return CFStringCreateWithCString (kCFAllocatorDefault,
  218544. (const char*) s,
  218545. CFStringGetSystemEncoding());
  218546. #endif
  218547. }
  218548. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  218549. {
  218550. UnicodeMapping map;
  218551. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218552. kUnicodeNoSubset,
  218553. kTextEncodingDefaultFormat);
  218554. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  218555. kUnicodeCanonicalCompVariant,
  218556. kTextEncodingDefaultFormat);
  218557. map.mappingVersion = kUnicodeUseLatestMapping;
  218558. UnicodeToTextInfo conversionInfo = 0;
  218559. String result;
  218560. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  218561. {
  218562. const int len = s.length();
  218563. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218564. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  218565. for (int i = 0; i <= len; ++i)
  218566. tempIn[i] = s[i];
  218567. ByteCount bytesRead = 0;
  218568. ByteCount outputBufferSize = 0;
  218569. if (ConvertFromUnicodeToText (conversionInfo,
  218570. len * sizeof (UniChar), tempIn,
  218571. kUnicodeDefaultDirectionMask,
  218572. 0, 0, 0, 0,
  218573. len * sizeof (UniChar), &bytesRead,
  218574. &outputBufferSize, tempOut) == noErr)
  218575. {
  218576. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  218577. tchar* t = const_cast <tchar*> ((const tchar*) result);
  218578. unsigned int i;
  218579. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  218580. t[i] = (tchar) tempOut[i];
  218581. t[i] = 0;
  218582. }
  218583. juce_free (tempIn);
  218584. juce_free (tempOut);
  218585. DisposeUnicodeToTextInfo (&conversionInfo);
  218586. }
  218587. return result;
  218588. }
  218589. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218590. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  218591. {
  218592. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  218593. owner: nil];
  218594. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  218595. forType: NSStringPboardType];
  218596. }
  218597. const String SystemClipboard::getTextFromClipboard() throw()
  218598. {
  218599. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  218600. return text == 0 ? String::empty
  218601. : nsStringToJuce (text);
  218602. }
  218603. #endif
  218604. #endif
  218605. /********* End of inlined file: juce_mac_Strings.mm *********/
  218606. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  218607. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218608. // compiled on its own).
  218609. #ifdef JUCE_INCLUDED_FILE
  218610. static int64 highResTimerFrequency;
  218611. #if JUCE_INTEL
  218612. static void juce_getCpuVendor (char* const v) throw()
  218613. {
  218614. int vendor[4];
  218615. zerostruct (vendor);
  218616. int dummy = 0;
  218617. asm ("mov %%ebx, %%esi \n\t"
  218618. "cpuid \n\t"
  218619. "xchg %%esi, %%ebx"
  218620. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  218621. memcpy (v, vendor, 16);
  218622. }
  218623. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  218624. {
  218625. unsigned int cpu = 0;
  218626. unsigned int ext = 0;
  218627. unsigned int family = 0;
  218628. unsigned int dummy = 0;
  218629. asm ("mov %%ebx, %%esi \n\t"
  218630. "cpuid \n\t"
  218631. "xchg %%esi, %%ebx"
  218632. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  218633. familyModel = family;
  218634. extFeatures = ext;
  218635. return cpu;
  218636. }
  218637. struct CPUFlags
  218638. {
  218639. bool hasMMX : 1;
  218640. bool hasSSE : 1;
  218641. bool hasSSE2 : 1;
  218642. bool has3DNow : 1;
  218643. };
  218644. static CPUFlags cpuFlags;
  218645. #endif
  218646. void SystemStats::initialiseStats() throw()
  218647. {
  218648. static bool initialised = false;
  218649. if (! initialised)
  218650. {
  218651. initialised = true;
  218652. // extremely annoying: adding this line stops the apple menu items from working. Of
  218653. // course, not adding it means that carbon windows (e.g. in plugins) won't get
  218654. // any events.
  218655. //NSApplicationLoad();
  218656. [NSApplication sharedApplication];
  218657. #if JUCE_INTEL
  218658. {
  218659. unsigned int familyModel, extFeatures;
  218660. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  218661. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  218662. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  218663. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  218664. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  218665. }
  218666. #endif
  218667. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  218668. String s (SystemStats::getJUCEVersion());
  218669. rlimit lim;
  218670. getrlimit (RLIMIT_NOFILE, &lim);
  218671. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  218672. setrlimit (RLIMIT_NOFILE, &lim);
  218673. }
  218674. }
  218675. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  218676. {
  218677. return MacOSX;
  218678. }
  218679. const String SystemStats::getOperatingSystemName() throw()
  218680. {
  218681. return T("Mac OS X");
  218682. }
  218683. bool SystemStats::isOperatingSystem64Bit() throw()
  218684. {
  218685. #if JUCE_64BIT
  218686. return true;
  218687. #else
  218688. //xxx not sure how to find this out?..
  218689. return false;
  218690. #endif
  218691. }
  218692. int SystemStats::getMemorySizeInMegabytes() throw()
  218693. {
  218694. uint64 mem = 0;
  218695. size_t memSize = sizeof (mem);
  218696. int mib[] = { CTL_HW, HW_MEMSIZE };
  218697. sysctl (mib, 2, &mem, &memSize, 0, 0);
  218698. return mem / (1024 * 1024);
  218699. }
  218700. bool SystemStats::hasMMX() throw()
  218701. {
  218702. #if JUCE_INTEL
  218703. return cpuFlags.hasMMX;
  218704. #else
  218705. return false;
  218706. #endif
  218707. }
  218708. bool SystemStats::hasSSE() throw()
  218709. {
  218710. #if JUCE_INTEL
  218711. return cpuFlags.hasSSE;
  218712. #else
  218713. return false;
  218714. #endif
  218715. }
  218716. bool SystemStats::hasSSE2() throw()
  218717. {
  218718. #if JUCE_INTEL
  218719. return cpuFlags.hasSSE2;
  218720. #else
  218721. return false;
  218722. #endif
  218723. }
  218724. bool SystemStats::has3DNow() throw()
  218725. {
  218726. #if JUCE_INTEL
  218727. return cpuFlags.has3DNow;
  218728. #else
  218729. return false;
  218730. #endif
  218731. }
  218732. const String SystemStats::getCpuVendor() throw()
  218733. {
  218734. #if JUCE_INTEL
  218735. char v [16];
  218736. juce_getCpuVendor (v);
  218737. return String (v, 16);
  218738. #else
  218739. return String::empty;
  218740. #endif
  218741. }
  218742. int SystemStats::getCpuSpeedInMegaherz() throw()
  218743. {
  218744. uint64 speedHz = 0;
  218745. size_t speedSize = sizeof (speedHz);
  218746. int mib[] = { CTL_HW, HW_CPU_FREQ };
  218747. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  218748. #if JUCE_BIG_ENDIAN
  218749. if (speedSize == 4)
  218750. speedHz >>= 32;
  218751. #endif
  218752. return speedHz / 1000000;
  218753. }
  218754. int SystemStats::getNumCpus() throw()
  218755. {
  218756. #if MACOS_10_4_OR_EARLIER
  218757. return MPProcessors();
  218758. #else
  218759. return [[NSProcessInfo processInfo] activeProcessorCount];
  218760. #endif
  218761. }
  218762. static int64 juce_getMicroseconds() throw()
  218763. {
  218764. UnsignedWide t;
  218765. Microseconds (&t);
  218766. return (((int64) t.hi) << 32) | t.lo;
  218767. }
  218768. uint32 juce_millisecondsSinceStartup() throw()
  218769. {
  218770. return (uint32) (juce_getMicroseconds() / 1000);
  218771. }
  218772. double Time::getMillisecondCounterHiRes() throw()
  218773. {
  218774. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  218775. return juce_getMicroseconds() * 0.001;
  218776. }
  218777. int64 Time::getHighResolutionTicks() throw()
  218778. {
  218779. return (int64) AudioGetCurrentHostTime();
  218780. }
  218781. int64 Time::getHighResolutionTicksPerSecond() throw()
  218782. {
  218783. return highResTimerFrequency;
  218784. }
  218785. int64 SystemStats::getClockCycleCounter() throw()
  218786. {
  218787. return (int64) AudioGetCurrentHostTime();
  218788. }
  218789. bool Time::setSystemTimeToThisTime() const throw()
  218790. {
  218791. jassertfalse
  218792. return false;
  218793. }
  218794. int SystemStats::getPageSize() throw()
  218795. {
  218796. return NSPageSize();
  218797. }
  218798. void PlatformUtilities::fpuReset()
  218799. {
  218800. }
  218801. #endif
  218802. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  218803. /********* Start of inlined file: juce_mac_Network.mm *********/
  218804. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218805. // compiled on its own).
  218806. #if JUCE_INCLUDED_FILE
  218807. static bool getEthernetIterator (io_iterator_t* matchingServices) throw()
  218808. {
  218809. mach_port_t masterPort;
  218810. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  218811. {
  218812. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  218813. if (dict != 0)
  218814. {
  218815. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  218816. 0,
  218817. &kCFTypeDictionaryKeyCallBacks,
  218818. &kCFTypeDictionaryValueCallBacks);
  218819. if (propDict != 0)
  218820. {
  218821. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  218822. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  218823. CFRelease (propDict);
  218824. }
  218825. }
  218826. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  218827. }
  218828. return false;
  218829. }
  218830. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  218831. {
  218832. int numResults = 0;
  218833. io_iterator_t it;
  218834. if (getEthernetIterator (&it))
  218835. {
  218836. io_object_t i;
  218837. while ((i = IOIteratorNext (it)) != 0)
  218838. {
  218839. io_object_t controller;
  218840. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  218841. {
  218842. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  218843. CFSTR (kIOMACAddress),
  218844. kCFAllocatorDefault,
  218845. 0);
  218846. if (data != 0)
  218847. {
  218848. UInt8 addr [kIOEthernetAddressSize];
  218849. zeromem (addr, sizeof (addr));
  218850. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  218851. CFRelease (data);
  218852. int64 a = 0;
  218853. for (int i = 6; --i >= 0;)
  218854. a = (a << 8) | addr[i];
  218855. if (! littleEndian)
  218856. a = (int64) swapByteOrder ((uint64) a);
  218857. if (numResults < maxNum)
  218858. {
  218859. *addresses++ = a;
  218860. ++numResults;
  218861. }
  218862. }
  218863. IOObjectRelease (controller);
  218864. }
  218865. IOObjectRelease (i);
  218866. }
  218867. IOObjectRelease (it);
  218868. }
  218869. return numResults;
  218870. }
  218871. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218872. const String& emailSubject,
  218873. const String& bodyText,
  218874. const StringArray& filesToAttach)
  218875. {
  218876. const ScopedAutoReleasePool pool;
  218877. String script;
  218878. script << "tell application \"Mail\"\r\n"
  218879. "set newMessage to make new outgoing message with properties {subject:\""
  218880. << emailSubject.replace (T("\""), T("\\\""))
  218881. << "\", content:\""
  218882. << bodyText.replace (T("\""), T("\\\""))
  218883. << "\" & return & return}\r\n"
  218884. "tell newMessage\r\n"
  218885. "set visible to true\r\n"
  218886. "set sender to \"sdfsdfsdfewf\"\r\n"
  218887. "make new to recipient at end of to recipients with properties {address:\""
  218888. << targetEmailAddress
  218889. << "\"}\r\n";
  218890. for (int i = 0; i < filesToAttach.size(); ++i)
  218891. {
  218892. script << "tell content\r\n"
  218893. "make new attachment with properties {file name:\""
  218894. << filesToAttach[i].replace (T("\""), T("\\\""))
  218895. << "\"} at after the last paragraph\r\n"
  218896. "end tell\r\n";
  218897. }
  218898. script << "end tell\r\n"
  218899. "end tell\r\n";
  218900. NSAppleScript* s = [[NSAppleScript alloc]
  218901. initWithSource: juceStringToNS (script)];
  218902. NSDictionary* error = 0;
  218903. const bool ok = [s executeAndReturnError: &error] != nil;
  218904. [s release];
  218905. return ok;
  218906. }
  218907. END_JUCE_NAMESPACE
  218908. using namespace JUCE_NAMESPACE;
  218909. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  218910. @interface JuceURLConnection : NSObject
  218911. {
  218912. @public
  218913. NSURLRequest* request;
  218914. NSURLConnection* connection;
  218915. NSMutableData* data;
  218916. Thread* runLoopThread;
  218917. bool initialised, hasFailed, hasFinished;
  218918. int position;
  218919. int64 contentLength;
  218920. NSLock* dataLock;
  218921. }
  218922. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  218923. - (void) dealloc;
  218924. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  218925. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  218926. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  218927. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  218928. - (BOOL) isOpen;
  218929. - (int) read: (char*) dest numBytes: (int) num;
  218930. - (int) readPosition;
  218931. - (void) stop;
  218932. - (void) createConnection;
  218933. @end
  218934. class JuceURLConnectionMessageThread : public Thread
  218935. {
  218936. JuceURLConnection* owner;
  218937. public:
  218938. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  218939. : Thread (T("http connection")),
  218940. owner (owner_)
  218941. {
  218942. }
  218943. ~JuceURLConnectionMessageThread()
  218944. {
  218945. stopThread (10000);
  218946. }
  218947. void run()
  218948. {
  218949. [owner createConnection];
  218950. while (! threadShouldExit())
  218951. {
  218952. const ScopedAutoReleasePool pool;
  218953. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  218954. }
  218955. }
  218956. };
  218957. @implementation JuceURLConnection
  218958. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  218959. withCallback: (URL::OpenStreamProgressCallback*) callback
  218960. withContext: (void*) context;
  218961. {
  218962. [super init];
  218963. request = req;
  218964. [request retain];
  218965. data = [[NSMutableData data] retain];
  218966. dataLock = [[NSLock alloc] init];
  218967. connection = 0;
  218968. initialised = false;
  218969. hasFailed = false;
  218970. hasFinished = false;
  218971. contentLength = -1;
  218972. runLoopThread = new JuceURLConnectionMessageThread (self);
  218973. runLoopThread->startThread();
  218974. while (runLoopThread->isThreadRunning() && ! initialised)
  218975. {
  218976. if (callback != 0)
  218977. callback (context, -1, [[request HTTPBody] length]);
  218978. Thread::sleep (1);
  218979. }
  218980. return self;
  218981. }
  218982. - (void) dealloc
  218983. {
  218984. [self stop];
  218985. delete runLoopThread;
  218986. [connection release];
  218987. [data release];
  218988. [dataLock release];
  218989. [request release];
  218990. [super dealloc];
  218991. }
  218992. - (void) createConnection
  218993. {
  218994. connection = [[NSURLConnection alloc] initWithRequest: request
  218995. delegate: [self retain]];
  218996. if (connection == nil)
  218997. runLoopThread->signalThreadShouldExit();
  218998. }
  218999. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  219000. {
  219001. [dataLock lock];
  219002. [data setLength: 0];
  219003. [dataLock unlock];
  219004. initialised = true;
  219005. contentLength = [response expectedContentLength];
  219006. }
  219007. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  219008. {
  219009. DBG (nsStringToJuce ([error description]));
  219010. hasFailed = true;
  219011. initialised = true;
  219012. runLoopThread->signalThreadShouldExit();
  219013. }
  219014. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  219015. {
  219016. [dataLock lock];
  219017. [data appendData: newData];
  219018. [dataLock unlock];
  219019. initialised = true;
  219020. }
  219021. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  219022. {
  219023. hasFinished = true;
  219024. initialised = true;
  219025. runLoopThread->signalThreadShouldExit();
  219026. }
  219027. - (BOOL) isOpen
  219028. {
  219029. return connection != 0 && ! hasFailed;
  219030. }
  219031. - (int) readPosition
  219032. {
  219033. return position;
  219034. }
  219035. - (int) read: (char*) dest numBytes: (int) numNeeded
  219036. {
  219037. int numDone = 0;
  219038. while (numNeeded > 0)
  219039. {
  219040. int available = jmin (numNeeded, [data length]);
  219041. if (available > 0)
  219042. {
  219043. [dataLock lock];
  219044. [data getBytes: dest length: available];
  219045. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  219046. [dataLock unlock];
  219047. numDone += available;
  219048. numNeeded -= available;
  219049. dest += available;
  219050. }
  219051. else
  219052. {
  219053. if (hasFailed || hasFinished)
  219054. break;
  219055. Thread::sleep (1);
  219056. }
  219057. }
  219058. position += numDone;
  219059. return numDone;
  219060. }
  219061. - (void) stop
  219062. {
  219063. [connection cancel];
  219064. runLoopThread->stopThread (10000);
  219065. }
  219066. @end
  219067. BEGIN_JUCE_NAMESPACE
  219068. bool juce_isOnLine()
  219069. {
  219070. return true;
  219071. }
  219072. void* juce_openInternetFile (const String& url,
  219073. const String& headers,
  219074. const MemoryBlock& postData,
  219075. const bool isPost,
  219076. URL::OpenStreamProgressCallback* callback,
  219077. void* callbackContext,
  219078. int timeOutMs)
  219079. {
  219080. const ScopedAutoReleasePool pool;
  219081. NSMutableURLRequest* req = [NSMutableURLRequest
  219082. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  219083. cachePolicy: NSURLRequestUseProtocolCachePolicy
  219084. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  219085. if (req == nil)
  219086. return 0;
  219087. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  219088. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  219089. StringArray headerLines;
  219090. headerLines.addLines (headers);
  219091. headerLines.removeEmptyStrings (true);
  219092. for (int i = 0; i < headerLines.size(); ++i)
  219093. {
  219094. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  219095. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  219096. if (key.isNotEmpty() && value.isNotEmpty())
  219097. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  219098. }
  219099. if (isPost && postData.getSize() > 0)
  219100. {
  219101. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  219102. length: postData.getSize()]];
  219103. }
  219104. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  219105. withCallback: callback
  219106. withContext: callbackContext];
  219107. if ([s isOpen])
  219108. return s;
  219109. [s release];
  219110. return 0;
  219111. }
  219112. void juce_closeInternetFile (void* handle)
  219113. {
  219114. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219115. if (s != 0)
  219116. {
  219117. const ScopedAutoReleasePool pool;
  219118. [s stop];
  219119. [s release];
  219120. }
  219121. }
  219122. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  219123. {
  219124. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219125. if (s != 0)
  219126. {
  219127. const ScopedAutoReleasePool pool;
  219128. return [s read: (char*) buffer numBytes: bytesToRead];
  219129. }
  219130. return 0;
  219131. }
  219132. int64 juce_getInternetFileContentLength (void* handle)
  219133. {
  219134. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219135. if (s != 0)
  219136. return s->contentLength;
  219137. return -1;
  219138. }
  219139. int juce_seekInInternetFile (void* handle, int newPosition)
  219140. {
  219141. JuceURLConnection* const s = (JuceURLConnection*) handle;
  219142. if (s != 0)
  219143. return [s readPosition];
  219144. return 0;
  219145. }
  219146. #endif
  219147. /********* End of inlined file: juce_mac_Network.mm *********/
  219148. /********* Start of inlined file: juce_posix_NamedPipe.cpp *********/
  219149. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219150. // compiled on its own).
  219151. #if JUCE_INCLUDED_FILE
  219152. struct NamedPipeInternal
  219153. {
  219154. String pipeInName, pipeOutName;
  219155. int pipeIn, pipeOut;
  219156. bool volatile createdPipe, blocked, stopReadOperation;
  219157. static void signalHandler (int) {}
  219158. };
  219159. void NamedPipe::cancelPendingReads()
  219160. {
  219161. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  219162. {
  219163. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219164. intern->stopReadOperation = true;
  219165. char buffer [1] = { 0 };
  219166. int bytesWritten = ::write (intern->pipeIn, buffer, 1);
  219167. (void) bytesWritten;
  219168. int timeout = 2000;
  219169. while (intern->blocked && --timeout >= 0)
  219170. Thread::sleep (2);
  219171. intern->stopReadOperation = false;
  219172. }
  219173. }
  219174. void NamedPipe::close()
  219175. {
  219176. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219177. if (intern != 0)
  219178. {
  219179. internal = 0;
  219180. if (intern->pipeIn != -1)
  219181. ::close (intern->pipeIn);
  219182. if (intern->pipeOut != -1)
  219183. ::close (intern->pipeOut);
  219184. if (intern->createdPipe)
  219185. {
  219186. unlink (intern->pipeInName);
  219187. unlink (intern->pipeOutName);
  219188. }
  219189. delete intern;
  219190. }
  219191. }
  219192. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  219193. {
  219194. close();
  219195. NamedPipeInternal* const intern = new NamedPipeInternal();
  219196. internal = intern;
  219197. intern->createdPipe = createPipe;
  219198. intern->blocked = false;
  219199. intern->stopReadOperation = false;
  219200. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  219201. siginterrupt (SIGPIPE, 1);
  219202. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  219203. intern->pipeInName = pipePath + T("_in");
  219204. intern->pipeOutName = pipePath + T("_out");
  219205. intern->pipeIn = -1;
  219206. intern->pipeOut = -1;
  219207. if (createPipe)
  219208. {
  219209. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  219210. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  219211. {
  219212. delete intern;
  219213. internal = 0;
  219214. return false;
  219215. }
  219216. }
  219217. return true;
  219218. }
  219219. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  219220. {
  219221. int bytesRead = -1;
  219222. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219223. if (intern != 0)
  219224. {
  219225. intern->blocked = true;
  219226. if (intern->pipeIn == -1)
  219227. {
  219228. if (intern->createdPipe)
  219229. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  219230. else
  219231. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  219232. if (intern->pipeIn == -1)
  219233. {
  219234. intern->blocked = false;
  219235. return -1;
  219236. }
  219237. }
  219238. bytesRead = 0;
  219239. char* p = (char*) destBuffer;
  219240. while (bytesRead < maxBytesToRead)
  219241. {
  219242. const int bytesThisTime = maxBytesToRead - bytesRead;
  219243. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  219244. if (numRead <= 0 || intern->stopReadOperation)
  219245. {
  219246. bytesRead = -1;
  219247. break;
  219248. }
  219249. bytesRead += numRead;
  219250. p += bytesRead;
  219251. }
  219252. intern->blocked = false;
  219253. }
  219254. return bytesRead;
  219255. }
  219256. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  219257. {
  219258. int bytesWritten = -1;
  219259. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  219260. if (intern != 0)
  219261. {
  219262. if (intern->pipeOut == -1)
  219263. {
  219264. if (intern->createdPipe)
  219265. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  219266. else
  219267. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  219268. if (intern->pipeOut == -1)
  219269. {
  219270. return -1;
  219271. }
  219272. }
  219273. const char* p = (const char*) sourceBuffer;
  219274. bytesWritten = 0;
  219275. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  219276. while (bytesWritten < numBytesToWrite
  219277. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  219278. {
  219279. const int bytesThisTime = numBytesToWrite - bytesWritten;
  219280. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  219281. if (numWritten <= 0)
  219282. {
  219283. bytesWritten = -1;
  219284. break;
  219285. }
  219286. bytesWritten += numWritten;
  219287. p += bytesWritten;
  219288. }
  219289. }
  219290. return bytesWritten;
  219291. }
  219292. #endif
  219293. /********* End of inlined file: juce_posix_NamedPipe.cpp *********/
  219294. /********* Start of inlined file: juce_mac_Threads.mm *********/
  219295. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219296. // compiled on its own).
  219297. #ifdef JUCE_INCLUDED_FILE
  219298. /*
  219299. Note that a lot of methods that you'd expect to find in this file actually
  219300. live in juce_posix_SharedCode.h!
  219301. */
  219302. void JUCE_API juce_threadEntryPoint (void*);
  219303. void* threadEntryProc (void* userData) throw()
  219304. {
  219305. const ScopedAutoReleasePool pool;
  219306. juce_threadEntryPoint (userData);
  219307. return 0;
  219308. }
  219309. void* juce_createThread (void* userData) throw()
  219310. {
  219311. pthread_t handle = 0;
  219312. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  219313. {
  219314. pthread_detach (handle);
  219315. return (void*) handle;
  219316. }
  219317. return 0;
  219318. }
  219319. void juce_killThread (void* handle) throw()
  219320. {
  219321. if (handle != 0)
  219322. pthread_cancel ((pthread_t) handle);
  219323. }
  219324. void juce_setCurrentThreadName (const String& /*name*/) throw()
  219325. {
  219326. }
  219327. Thread::ThreadID Thread::getCurrentThreadId() throw()
  219328. {
  219329. return (ThreadID) pthread_self();
  219330. }
  219331. bool juce_setThreadPriority (void* handle, int priority) throw()
  219332. {
  219333. if (handle == 0)
  219334. handle = (void*) pthread_self();
  219335. struct sched_param param;
  219336. int policy;
  219337. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  219338. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  219339. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  219340. }
  219341. void Thread::yield() throw()
  219342. {
  219343. sched_yield();
  219344. }
  219345. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  219346. {
  219347. // xxx
  219348. jassertfalse
  219349. }
  219350. bool Process::isForegroundProcess() throw()
  219351. {
  219352. return [NSApp isActive];
  219353. }
  219354. void Process::raisePrivilege()
  219355. {
  219356. jassertfalse
  219357. }
  219358. void Process::lowerPrivilege()
  219359. {
  219360. jassertfalse
  219361. }
  219362. void Process::terminate()
  219363. {
  219364. exit (0);
  219365. }
  219366. void Process::setPriority (ProcessPriority p)
  219367. {
  219368. // xxx
  219369. }
  219370. #endif
  219371. /********* End of inlined file: juce_mac_Threads.mm *********/
  219372. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  219373. /*
  219374. This file contains posix routines that are common to both the Linux and Mac builds.
  219375. It gets included directly in the cpp files for these platforms.
  219376. */
  219377. CriticalSection::CriticalSection() throw()
  219378. {
  219379. pthread_mutexattr_t atts;
  219380. pthread_mutexattr_init (&atts);
  219381. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  219382. pthread_mutex_init (&internal, &atts);
  219383. }
  219384. CriticalSection::~CriticalSection() throw()
  219385. {
  219386. pthread_mutex_destroy (&internal);
  219387. }
  219388. void CriticalSection::enter() const throw()
  219389. {
  219390. pthread_mutex_lock (&internal);
  219391. }
  219392. bool CriticalSection::tryEnter() const throw()
  219393. {
  219394. return pthread_mutex_trylock (&internal) == 0;
  219395. }
  219396. void CriticalSection::exit() const throw()
  219397. {
  219398. pthread_mutex_unlock (&internal);
  219399. }
  219400. struct EventStruct
  219401. {
  219402. pthread_cond_t condition;
  219403. pthread_mutex_t mutex;
  219404. bool triggered;
  219405. };
  219406. WaitableEvent::WaitableEvent() throw()
  219407. {
  219408. EventStruct* const es = new EventStruct();
  219409. es->triggered = false;
  219410. pthread_cond_init (&es->condition, 0);
  219411. pthread_mutex_init (&es->mutex, 0);
  219412. internal = es;
  219413. }
  219414. WaitableEvent::~WaitableEvent() throw()
  219415. {
  219416. EventStruct* const es = (EventStruct*) internal;
  219417. pthread_cond_destroy (&es->condition);
  219418. pthread_mutex_destroy (&es->mutex);
  219419. delete es;
  219420. }
  219421. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  219422. {
  219423. EventStruct* const es = (EventStruct*) internal;
  219424. bool ok = true;
  219425. pthread_mutex_lock (&es->mutex);
  219426. if (timeOutMillisecs < 0)
  219427. {
  219428. while (! es->triggered)
  219429. pthread_cond_wait (&es->condition, &es->mutex);
  219430. }
  219431. else
  219432. {
  219433. while (! es->triggered)
  219434. {
  219435. struct timeval t;
  219436. gettimeofday (&t, 0);
  219437. struct timespec time;
  219438. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  219439. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  219440. if (time.tv_nsec >= 1000000000)
  219441. {
  219442. time.tv_nsec -= 1000000000;
  219443. time.tv_sec++;
  219444. }
  219445. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  219446. {
  219447. ok = false;
  219448. break;
  219449. }
  219450. }
  219451. }
  219452. es->triggered = false;
  219453. pthread_mutex_unlock (&es->mutex);
  219454. return ok;
  219455. }
  219456. void WaitableEvent::signal() const throw()
  219457. {
  219458. EventStruct* const es = (EventStruct*) internal;
  219459. pthread_mutex_lock (&es->mutex);
  219460. es->triggered = true;
  219461. pthread_cond_broadcast (&es->condition);
  219462. pthread_mutex_unlock (&es->mutex);
  219463. }
  219464. void WaitableEvent::reset() const throw()
  219465. {
  219466. EventStruct* const es = (EventStruct*) internal;
  219467. pthread_mutex_lock (&es->mutex);
  219468. es->triggered = false;
  219469. pthread_mutex_unlock (&es->mutex);
  219470. }
  219471. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  219472. {
  219473. struct timespec time;
  219474. time.tv_sec = millisecs / 1000;
  219475. time.tv_nsec = (millisecs % 1000) * 1000000;
  219476. nanosleep (&time, 0);
  219477. }
  219478. const tchar File::separator = T('/');
  219479. const tchar* File::separatorString = T("/");
  219480. bool juce_copyFile (const String& s, const String& d) throw();
  219481. static bool juce_stat (const String& fileName, struct stat& info) throw()
  219482. {
  219483. return fileName.isNotEmpty()
  219484. && (stat (fileName.toUTF8(), &info) == 0);
  219485. }
  219486. bool juce_isDirectory (const String& fileName) throw()
  219487. {
  219488. struct stat info;
  219489. return fileName.isEmpty()
  219490. || (juce_stat (fileName, info)
  219491. && ((info.st_mode & S_IFDIR) != 0));
  219492. }
  219493. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  219494. {
  219495. if (fileName.isEmpty())
  219496. return false;
  219497. const char* const fileNameUTF8 = fileName.toUTF8();
  219498. bool exists = access (fileNameUTF8, F_OK) == 0;
  219499. if (exists && dontCountDirectories)
  219500. {
  219501. struct stat info;
  219502. const int res = stat (fileNameUTF8, &info);
  219503. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  219504. exists = false;
  219505. }
  219506. return exists;
  219507. }
  219508. int64 juce_getFileSize (const String& fileName) throw()
  219509. {
  219510. struct stat info;
  219511. return juce_stat (fileName, info) ? info.st_size : 0;
  219512. }
  219513. bool juce_canWriteToFile (const String& fileName) throw()
  219514. {
  219515. return access (fileName.toUTF8(), W_OK) == 0;
  219516. }
  219517. bool juce_deleteFile (const String& fileName) throw()
  219518. {
  219519. if (juce_isDirectory (fileName))
  219520. return rmdir ((const char*) fileName.toUTF8()) == 0;
  219521. else
  219522. return remove ((const char*) fileName.toUTF8()) == 0;
  219523. }
  219524. bool juce_moveFile (const String& source, const String& dest) throw()
  219525. {
  219526. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  219527. return true;
  219528. if (juce_canWriteToFile (source)
  219529. && juce_copyFile (source, dest))
  219530. {
  219531. if (juce_deleteFile (source))
  219532. return true;
  219533. juce_deleteFile (dest);
  219534. }
  219535. return false;
  219536. }
  219537. void juce_createDirectory (const String& fileName) throw()
  219538. {
  219539. mkdir (fileName.toUTF8(), 0777);
  219540. }
  219541. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  219542. {
  219543. int flags = O_RDONLY;
  219544. if (forWriting)
  219545. {
  219546. if (juce_fileExists (fileName, false))
  219547. {
  219548. const int f = open ((const char*) fileName.toUTF8(), O_RDWR, 00644);
  219549. if (f != -1)
  219550. lseek (f, 0, SEEK_END);
  219551. return (void*) f;
  219552. }
  219553. else
  219554. {
  219555. flags = O_RDWR + O_CREAT;
  219556. }
  219557. }
  219558. return (void*) open ((const char*) fileName.toUTF8(), flags, 00644);
  219559. }
  219560. void juce_fileClose (void* handle) throw()
  219561. {
  219562. if (handle != 0)
  219563. close ((int) (pointer_sized_int) handle);
  219564. }
  219565. int juce_fileRead (void* handle, void* buffer, int size) throw()
  219566. {
  219567. if (handle != 0)
  219568. return read ((int) (pointer_sized_int) handle, buffer, size);
  219569. return 0;
  219570. }
  219571. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  219572. {
  219573. if (handle != 0)
  219574. return write ((int) (pointer_sized_int) handle, buffer, size);
  219575. return 0;
  219576. }
  219577. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  219578. {
  219579. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  219580. return pos;
  219581. return -1;
  219582. }
  219583. int64 juce_fileGetPosition (void* handle) throw()
  219584. {
  219585. if (handle != 0)
  219586. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  219587. else
  219588. return -1;
  219589. }
  219590. void juce_fileFlush (void* handle) throw()
  219591. {
  219592. if (handle != 0)
  219593. fsync ((int) (pointer_sized_int) handle);
  219594. }
  219595. const File juce_getExecutableFile()
  219596. {
  219597. Dl_info exeInfo;
  219598. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  219599. return File (exeInfo.dli_fname);
  219600. }
  219601. // if this file doesn't exist, find a parent of it that does..
  219602. static bool doStatFS (const File* file, struct statfs& result) throw()
  219603. {
  219604. File f (*file);
  219605. for (int i = 5; --i >= 0;)
  219606. {
  219607. if (f.exists())
  219608. break;
  219609. f = f.getParentDirectory();
  219610. }
  219611. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  219612. }
  219613. int64 File::getBytesFreeOnVolume() const throw()
  219614. {
  219615. struct statfs buf;
  219616. if (doStatFS (this, buf))
  219617. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  219618. return 0;
  219619. }
  219620. int64 File::getVolumeTotalSize() const throw()
  219621. {
  219622. struct statfs buf;
  219623. if (doStatFS (this, buf))
  219624. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  219625. return 0;
  219626. }
  219627. const String juce_getVolumeLabel (const String& filenameOnVolume,
  219628. int& volumeSerialNumber) throw()
  219629. {
  219630. volumeSerialNumber = 0;
  219631. #if JUCE_MAC
  219632. struct VolAttrBuf
  219633. {
  219634. u_int32_t length;
  219635. attrreference_t mountPointRef;
  219636. char mountPointSpace [MAXPATHLEN];
  219637. } attrBuf;
  219638. struct attrlist attrList;
  219639. zerostruct (attrList);
  219640. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  219641. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  219642. File f (filenameOnVolume);
  219643. for (;;)
  219644. {
  219645. if (getattrlist ((const char*) f.getFullPathName().toUTF8(),
  219646. &attrList, &attrBuf, sizeof(attrBuf), 0) == 0)
  219647. {
  219648. return String::fromUTF8 (((const uint8*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  219649. (int) attrBuf.mountPointRef.attr_length);
  219650. }
  219651. const File parent (f.getParentDirectory());
  219652. if (f == parent)
  219653. break;
  219654. f = parent;
  219655. }
  219656. #endif
  219657. return String::empty;
  219658. }
  219659. void juce_runSystemCommand (const String& command)
  219660. {
  219661. int result = system ((const char*) command.toUTF8());
  219662. (void) result;
  219663. }
  219664. const String juce_getOutputFromCommand (const String& command)
  219665. {
  219666. // slight bodge here, as we just pipe the output into a temp file and read it...
  219667. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  219668. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  219669. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  219670. String result (tempFile.loadFileAsString());
  219671. tempFile.deleteFile();
  219672. return result;
  219673. }
  219674. #if JUCE_64BIT
  219675. #define filedesc ((long long) internal)
  219676. #else
  219677. #define filedesc ((int) internal)
  219678. #endif
  219679. InterProcessLock::InterProcessLock (const String& name_) throw()
  219680. : internal (0),
  219681. name (name_),
  219682. reentrancyLevel (0)
  219683. {
  219684. #if JUCE_MAC
  219685. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  219686. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  219687. #else
  219688. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  219689. #endif
  219690. temp.create();
  219691. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  219692. }
  219693. InterProcessLock::~InterProcessLock() throw()
  219694. {
  219695. while (reentrancyLevel > 0)
  219696. this->exit();
  219697. close (filedesc);
  219698. }
  219699. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  219700. {
  219701. if (internal == 0)
  219702. return false;
  219703. if (reentrancyLevel != 0)
  219704. return true;
  219705. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  219706. struct flock fl;
  219707. zerostruct (fl);
  219708. fl.l_whence = SEEK_SET;
  219709. fl.l_type = F_WRLCK;
  219710. for (;;)
  219711. {
  219712. const int result = fcntl (filedesc, F_SETLK, &fl);
  219713. if (result >= 0)
  219714. {
  219715. ++reentrancyLevel;
  219716. return true;
  219717. }
  219718. if (errno != EINTR)
  219719. {
  219720. if (timeOutMillisecs == 0
  219721. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  219722. break;
  219723. Thread::sleep (10);
  219724. }
  219725. }
  219726. return false;
  219727. }
  219728. void InterProcessLock::exit() throw()
  219729. {
  219730. if (reentrancyLevel > 0 && internal != 0)
  219731. {
  219732. --reentrancyLevel;
  219733. struct flock fl;
  219734. zerostruct (fl);
  219735. fl.l_whence = SEEK_SET;
  219736. fl.l_type = F_UNLCK;
  219737. for (;;)
  219738. {
  219739. const int result = fcntl (filedesc, F_SETLKW, &fl);
  219740. if (result >= 0 || errno != EINTR)
  219741. break;
  219742. }
  219743. }
  219744. }
  219745. /********* End of inlined file: juce_posix_SharedCode.h *********/
  219746. /********* Start of inlined file: juce_mac_Files.mm *********/
  219747. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  219748. // compiled on its own).
  219749. #ifdef JUCE_INCLUDED_FILE
  219750. /*
  219751. Note that a lot of methods that you'd expect to find in this file actually
  219752. live in juce_posix_SharedCode.h!
  219753. */
  219754. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  219755. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  219756. {
  219757. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  219758. return 0;
  219759. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  219760. + ((d.fraction * 1000) >> 16)
  219761. - 2082844800000ll;
  219762. }
  219763. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  219764. {
  219765. if (t != 0)
  219766. t += 2082844800000ll;
  219767. d.highSeconds = (t / 1000) >> 32;
  219768. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  219769. d.fraction = ((t % 1000) << 16) / 1000;
  219770. }
  219771. void juce_getFileTimes (const String& fileName,
  219772. int64& modificationTime,
  219773. int64& accessTime,
  219774. int64& creationTime) throw()
  219775. {
  219776. modificationTime = 0;
  219777. accessTime = 0;
  219778. creationTime = 0;
  219779. FSRef fileRef;
  219780. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219781. {
  219782. FSRefParam info;
  219783. zerostruct (info);
  219784. info.ref = &fileRef;
  219785. info.whichInfo = kFSCatInfoAllDates;
  219786. FSCatalogInfo catInfo;
  219787. info.catInfo = &catInfo;
  219788. if (PBGetCatalogInfoSync (&info) == noErr)
  219789. {
  219790. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  219791. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  219792. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  219793. }
  219794. }
  219795. }
  219796. bool juce_setFileTimes (const String& fileName,
  219797. int64 modificationTime,
  219798. int64 accessTime,
  219799. int64 creationTime) throw()
  219800. {
  219801. FSRef fileRef;
  219802. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  219803. {
  219804. FSRefParam info;
  219805. zerostruct (info);
  219806. info.ref = &fileRef;
  219807. info.whichInfo = kFSCatInfoAllDates;
  219808. FSCatalogInfo catInfo;
  219809. info.catInfo = &catInfo;
  219810. if (PBGetCatalogInfoSync (&info) == noErr)
  219811. {
  219812. if (creationTime != 0)
  219813. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  219814. if (modificationTime != 0)
  219815. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  219816. if (accessTime != 0)
  219817. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  219818. return PBSetCatalogInfoSync (&info) == noErr;
  219819. }
  219820. }
  219821. return false;
  219822. }
  219823. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  219824. {
  219825. const char* const fileNameUTF8 = fileName.toUTF8();
  219826. struct stat info;
  219827. const int res = stat (fileNameUTF8, &info);
  219828. bool ok = false;
  219829. if (res == 0)
  219830. {
  219831. info.st_mode &= 0777; // Just permissions
  219832. if (isReadOnly)
  219833. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  219834. else
  219835. // Give everybody write permission?
  219836. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  219837. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  219838. }
  219839. return ok;
  219840. }
  219841. bool juce_copyFile (const String& src, const String& dst) throw()
  219842. {
  219843. const ScopedAutoReleasePool pool;
  219844. NSFileManager* fm = [NSFileManager defaultManager];
  219845. return [fm fileExistsAtPath: juceStringToNS (src)]
  219846. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  219847. && [fm copyItemAtPath: juceStringToNS (src)
  219848. toPath: juceStringToNS (dst)
  219849. error: nil];
  219850. #else
  219851. && [fm copyPath: juceStringToNS (src)
  219852. toPath: juceStringToNS (dst)
  219853. handler: nil];
  219854. #endif
  219855. }
  219856. const StringArray juce_getFileSystemRoots() throw()
  219857. {
  219858. StringArray s;
  219859. s.add (T("/"));
  219860. return s;
  219861. }
  219862. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  219863. {
  219864. struct statfs buf;
  219865. if (doStatFS (f, buf))
  219866. {
  219867. const String type (buf.f_fstypename);
  219868. while (*types != 0)
  219869. if (type.equalsIgnoreCase (*types++))
  219870. return true;
  219871. }
  219872. return false;
  219873. }
  219874. bool File::isOnCDRomDrive() const throw()
  219875. {
  219876. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  219877. return isFileOnDriveType (this, (const char**) cdTypes);
  219878. }
  219879. bool File::isOnHardDisk() const throw()
  219880. {
  219881. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  219882. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  219883. }
  219884. bool File::isOnRemovableDrive() const throw()
  219885. {
  219886. const ScopedAutoReleasePool pool;
  219887. BOOL removable = false;
  219888. [[NSWorkspace sharedWorkspace]
  219889. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  219890. isRemovable: &removable
  219891. isWritable: nil
  219892. isUnmountable: nil
  219893. description: nil
  219894. type: nil];
  219895. return removable;
  219896. }
  219897. static bool juce_isHiddenFile (const String& path) throw()
  219898. {
  219899. FSRef ref;
  219900. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  219901. return false;
  219902. FSCatalogInfo info;
  219903. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  219904. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  219905. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219906. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  219907. }
  219908. bool File::isHidden() const throw()
  219909. {
  219910. return juce_isHiddenFile (getFullPathName());
  219911. }
  219912. const File File::getSpecialLocation (const SpecialLocationType type)
  219913. {
  219914. const ScopedAutoReleasePool pool;
  219915. String resultPath;
  219916. switch (type)
  219917. {
  219918. case userHomeDirectory:
  219919. resultPath = nsStringToJuce (NSHomeDirectory());
  219920. break;
  219921. case userDocumentsDirectory:
  219922. resultPath = "~/Documents";
  219923. break;
  219924. case userDesktopDirectory:
  219925. resultPath = "~/Desktop";
  219926. break;
  219927. case userApplicationDataDirectory:
  219928. resultPath = "~/Library";
  219929. break;
  219930. case commonApplicationDataDirectory:
  219931. resultPath = "/Library";
  219932. break;
  219933. case globalApplicationsDirectory:
  219934. resultPath = "/Applications";
  219935. break;
  219936. case userMusicDirectory:
  219937. resultPath = "~/Music";
  219938. break;
  219939. case userMoviesDirectory:
  219940. resultPath = "~/Movies";
  219941. break;
  219942. case tempDirectory:
  219943. {
  219944. File tmp (T("~/Library/Caches/") + juce_getExecutableFile().getFileNameWithoutExtension());
  219945. tmp.createDirectory();
  219946. return tmp.getFullPathName();
  219947. }
  219948. case currentExecutableFile:
  219949. return juce_getExecutableFile();
  219950. case currentApplicationFile:
  219951. {
  219952. const File exe (juce_getExecutableFile());
  219953. const File parent (exe.getParentDirectory());
  219954. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  219955. ? parent.getParentDirectory().getParentDirectory()
  219956. : exe;
  219957. }
  219958. default:
  219959. jassertfalse // unknown type?
  219960. break;
  219961. }
  219962. if (resultPath != 0)
  219963. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  219964. return File::nonexistent;
  219965. }
  219966. const File File::getCurrentWorkingDirectory() throw()
  219967. {
  219968. char buf [2048];
  219969. getcwd (buf, sizeof(buf));
  219970. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  219971. }
  219972. bool File::setAsCurrentWorkingDirectory() const throw()
  219973. {
  219974. return chdir (getFullPathName().toUTF8()) == 0;
  219975. }
  219976. const String File::getVersion() const throw()
  219977. {
  219978. const ScopedAutoReleasePool pool;
  219979. String result;
  219980. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  219981. if (bundle != 0)
  219982. {
  219983. NSDictionary* info = [bundle infoDictionary];
  219984. if (info != 0)
  219985. {
  219986. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  219987. if (name != nil)
  219988. result = nsStringToJuce (name);
  219989. }
  219990. }
  219991. return result;
  219992. }
  219993. const File File::getLinkedTarget() const throw()
  219994. {
  219995. FSRef ref;
  219996. Boolean targetIsAFolder, wasAliased;
  219997. if (PlatformUtilities::makeFSRefFromPath (&ref, getFullPathName())
  219998. && (FSResolveAliasFileWithMountFlags (&ref, true, &targetIsAFolder, &wasAliased, 0) == noErr)
  219999. && wasAliased)
  220000. {
  220001. return File (PlatformUtilities::makePathFromFSRef (&ref));
  220002. }
  220003. return *this;
  220004. }
  220005. bool File::moveToTrash() const throw()
  220006. {
  220007. if (! exists())
  220008. return true;
  220009. const ScopedAutoReleasePool pool;
  220010. NSString* p = juceStringToNS (getFullPathName());
  220011. return [[NSWorkspace sharedWorkspace]
  220012. performFileOperation: NSWorkspaceRecycleOperation
  220013. source: [p stringByDeletingLastPathComponent]
  220014. destination: @""
  220015. files: [NSArray arrayWithObject: [p lastPathComponent]]
  220016. tag: nil ];
  220017. }
  220018. struct FindFileStruct
  220019. {
  220020. String parentDir, wildCard;
  220021. DIR* dir;
  220022. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  220023. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  220024. {
  220025. const char* const wildCardUTF8 = wildCard.toUTF8();
  220026. for (;;)
  220027. {
  220028. struct dirent* const de = readdir (dir);
  220029. if (de == 0)
  220030. break;
  220031. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  220032. {
  220033. result = String::fromUTF8 ((const uint8*) de->d_name);
  220034. const String path (parentDir + result);
  220035. if (isDir != 0 || fileSize != 0)
  220036. {
  220037. struct stat info;
  220038. const bool statOk = juce_stat (path, info);
  220039. if (isDir != 0)
  220040. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  220041. if (isHidden != 0)
  220042. *isHidden = (de->d_name[0] == '.')
  220043. || juce_isHiddenFile (path);
  220044. if (fileSize != 0)
  220045. *fileSize = statOk ? info.st_size : 0;
  220046. }
  220047. if (modTime != 0 || creationTime != 0)
  220048. {
  220049. int64 m, a, c;
  220050. juce_getFileTimes (path, m, a, c);
  220051. if (modTime != 0)
  220052. *modTime = m;
  220053. if (creationTime != 0)
  220054. *creationTime = c;
  220055. }
  220056. if (isReadOnly != 0)
  220057. *isReadOnly = ! juce_canWriteToFile (path);
  220058. return true;
  220059. }
  220060. }
  220061. return false;
  220062. }
  220063. };
  220064. // returns 0 on failure
  220065. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  220066. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  220067. Time* creationTime, bool* isReadOnly) throw()
  220068. {
  220069. DIR* const d = opendir (directory.toUTF8());
  220070. if (d != 0)
  220071. {
  220072. FindFileStruct* const ff = new FindFileStruct();
  220073. ff->parentDir = directory;
  220074. if (!ff->parentDir.endsWithChar (File::separator))
  220075. ff->parentDir += File::separator;
  220076. ff->wildCard = wildCard;
  220077. ff->dir = d;
  220078. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  220079. {
  220080. return ff;
  220081. }
  220082. else
  220083. {
  220084. firstResultFile = String::empty;
  220085. isDir = false;
  220086. closedir (d);
  220087. delete ff;
  220088. }
  220089. }
  220090. return 0;
  220091. }
  220092. bool juce_findFileNext (void* handle, String& resultFile,
  220093. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  220094. {
  220095. FindFileStruct* const ff = (FindFileStruct*) handle;
  220096. if (ff != 0)
  220097. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  220098. return false;
  220099. }
  220100. void juce_findFileClose (void* handle) throw()
  220101. {
  220102. FindFileStruct* const ff = (FindFileStruct*)handle;
  220103. if (ff != 0)
  220104. {
  220105. closedir (ff->dir);
  220106. delete ff;
  220107. }
  220108. }
  220109. bool juce_launchExecutable (const String& pathAndArguments) throw()
  220110. {
  220111. const char* const argv[4] = { "/bin/sh", "-c", (const char*) pathAndArguments, 0 };
  220112. const int cpid = fork();
  220113. if (cpid == 0)
  220114. {
  220115. // Child process
  220116. if (execve (argv[0], (char**) argv, 0) < 0)
  220117. exit (0);
  220118. }
  220119. else
  220120. {
  220121. if (cpid < 0)
  220122. return false;
  220123. }
  220124. return true;
  220125. }
  220126. bool juce_launchFile (const String& fileName,
  220127. const String& parameters) throw()
  220128. {
  220129. const ScopedAutoReleasePool pool;
  220130. if (parameters.isEmpty())
  220131. {
  220132. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  220133. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  220134. }
  220135. bool ok = false;
  220136. FSRef ref;
  220137. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  220138. {
  220139. if (PlatformUtilities::isBundle (fileName))
  220140. {
  220141. NSMutableArray* urls = [NSMutableArray array];
  220142. StringArray docs;
  220143. docs.addTokens (parameters, true);
  220144. for (int i = 0; i < docs.size(); ++i)
  220145. [urls addObject: juceStringToNS (docs[i])];
  220146. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  220147. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  220148. options: nil
  220149. additionalEventParamDescriptor: nil
  220150. launchIdentifiers: nil];
  220151. }
  220152. else
  220153. {
  220154. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  220155. }
  220156. }
  220157. return ok;
  220158. }
  220159. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  220160. {
  220161. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  220162. }
  220163. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  220164. {
  220165. uint8 path [2048];
  220166. zeromem (path, sizeof (path));
  220167. String result;
  220168. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  220169. result = String::fromUTF8 (path);
  220170. return PlatformUtilities::convertToPrecomposedUnicode (result);
  220171. }
  220172. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  220173. {
  220174. const ScopedAutoReleasePool pool;
  220175. return NSHFSTypeCodeFromFileType (NSHFSTypeOfFile (juceStringToNS (filename)));
  220176. }
  220177. bool PlatformUtilities::isBundle (const String& filename)
  220178. {
  220179. const ScopedAutoReleasePool pool;
  220180. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  220181. }
  220182. #endif
  220183. /********* End of inlined file: juce_mac_Files.mm *********/
  220184. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  220185. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220186. // compiled on its own).
  220187. #ifdef JUCE_INCLUDED_FILE
  220188. ScopedAutoReleasePool::ScopedAutoReleasePool()
  220189. {
  220190. pool = [[NSAutoreleasePool alloc] init];
  220191. }
  220192. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  220193. {
  220194. [((NSAutoreleasePool*) pool) release];
  220195. }
  220196. void PlatformUtilities::beep()
  220197. {
  220198. NSBeep();
  220199. }
  220200. void PlatformUtilities::addItemToDock (const File& file)
  220201. {
  220202. // check that it's not already there...
  220203. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  220204. .containsIgnoreCase (file.getFullPathName()))
  220205. {
  220206. 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>"
  220207. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  220208. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  220209. }
  220210. }
  220211. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220212. bool AlertWindow::showNativeDialogBox (const String& title,
  220213. const String& bodyText,
  220214. bool isOkCancel)
  220215. {
  220216. const ScopedAutoReleasePool pool;
  220217. return NSRunAlertPanel (juceStringToNS (title),
  220218. juceStringToNS (bodyText),
  220219. @"Ok",
  220220. isOkCancel ? @"Cancel" : nil,
  220221. nil) == NSAlertDefaultReturn;
  220222. }
  220223. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220224. {
  220225. if (files.size() == 0)
  220226. return false;
  220227. Component* sourceComp = Component::getComponentUnderMouse();
  220228. if (sourceComp == 0)
  220229. {
  220230. jassertfalse // this method must be called in response to a
  220231. // component's mouseDrag event!
  220232. return false;
  220233. }
  220234. const ScopedAutoReleasePool pool;
  220235. NSView* view = (NSView*) sourceComp->getWindowHandle();
  220236. if (view == 0)
  220237. return false;
  220238. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  220239. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  220240. owner: nil];
  220241. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  220242. for (int i = 0; i < files.size(); ++i)
  220243. [filesArray addObject: juceStringToNS (files[i])];
  220244. [pboard setPropertyList: filesArray
  220245. forType: NSFilenamesPboardType];
  220246. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  220247. fromView: nil];
  220248. dragPosition.x -= 16;
  220249. dragPosition.y -= 16;
  220250. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  220251. at: dragPosition
  220252. offset: NSMakeSize (0, 0)
  220253. event: [[view window] currentEvent]
  220254. pasteboard: pboard
  220255. source: view
  220256. slideBack: YES];
  220257. return true;
  220258. }
  220259. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220260. {
  220261. jassertfalse // not implemented!
  220262. return false;
  220263. }
  220264. bool Desktop::canUseSemiTransparentWindows() throw()
  220265. {
  220266. return true;
  220267. }
  220268. void Desktop::getMousePosition (int& x, int& y) throw()
  220269. {
  220270. const ScopedAutoReleasePool pool;
  220271. const NSPoint p ([NSEvent mouseLocation]);
  220272. x = roundFloatToInt (p.x);
  220273. y = roundFloatToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y);
  220274. }
  220275. void Desktop::setMousePosition (int x, int y) throw()
  220276. {
  220277. // this rubbish needs to be done around the warp call, to avoid causing a
  220278. // bizarre glitch..
  220279. CGAssociateMouseAndMouseCursorPosition (false);
  220280. #if (! defined (MAC_OS_X_VERSION_10_6)) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6
  220281. CGSetLocalEventsSuppressionInterval (0);
  220282. #endif
  220283. CGPoint pos = { x, y };
  220284. CGWarpMouseCursorPosition (pos);
  220285. CGAssociateMouseAndMouseCursorPosition (true);
  220286. }
  220287. #if MACOS_10_4_OR_EARLIER
  220288. class ScreenSaverDefeater : public Timer,
  220289. public DeletedAtShutdown
  220290. {
  220291. public:
  220292. ScreenSaverDefeater() throw()
  220293. {
  220294. startTimer (10000);
  220295. timerCallback();
  220296. }
  220297. ~ScreenSaverDefeater() {}
  220298. void timerCallback()
  220299. {
  220300. if (Process::isForegroundProcess())
  220301. UpdateSystemActivity (UsrActivity);
  220302. }
  220303. };
  220304. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220305. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220306. {
  220307. if (isEnabled)
  220308. {
  220309. deleteAndZero (screenSaverDefeater);
  220310. }
  220311. else if (screenSaverDefeater == 0)
  220312. {
  220313. screenSaverDefeater = new ScreenSaverDefeater();
  220314. }
  220315. }
  220316. bool Desktop::isScreenSaverEnabled() throw()
  220317. {
  220318. return screenSaverDefeater == 0;
  220319. }
  220320. #else
  220321. static IOPMAssertionID screenSaverDisablerID = 0;
  220322. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220323. {
  220324. if (isEnabled)
  220325. {
  220326. if (screenSaverDisablerID != 0)
  220327. {
  220328. IOPMAssertionRelease (screenSaverDisablerID);
  220329. screenSaverDisablerID = 0;
  220330. }
  220331. }
  220332. else
  220333. {
  220334. if (screenSaverDisablerID == 0)
  220335. {
  220336. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220337. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220338. CFSTR ("Juce"), &screenSaverDisablerID);
  220339. #else
  220340. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  220341. &screenSaverDisablerID);
  220342. #endif
  220343. }
  220344. }
  220345. }
  220346. bool Desktop::isScreenSaverEnabled() throw()
  220347. {
  220348. return screenSaverDisablerID == 0;
  220349. }
  220350. #endif
  220351. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220352. {
  220353. const ScopedAutoReleasePool pool;
  220354. monitorCoords.clear();
  220355. NSArray* screens = [NSScreen screens];
  220356. const float mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  220357. for (unsigned int i = 0; i < [screens count]; ++i)
  220358. {
  220359. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  220360. NSRect r = clipToWorkArea ? [s visibleFrame]
  220361. : [s frame];
  220362. monitorCoords.add (Rectangle ((int) r.origin.x,
  220363. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  220364. (int) r.size.width,
  220365. (int) r.size.height));
  220366. }
  220367. jassert (monitorCoords.size() > 0);
  220368. }
  220369. #endif
  220370. #endif
  220371. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  220372. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  220373. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220374. // compiled on its own).
  220375. #ifdef JUCE_INCLUDED_FILE
  220376. void Logger::outputDebugString (const String& text) throw()
  220377. {
  220378. fputs (text.toUTF8(), stderr);
  220379. fputs ("\n", stderr);
  220380. }
  220381. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  220382. {
  220383. String text;
  220384. va_list args;
  220385. va_start (args, format);
  220386. text.vprintf (format, args);
  220387. outputDebugString (text);
  220388. }
  220389. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  220390. {
  220391. static char testResult = 0;
  220392. if (testResult == 0)
  220393. {
  220394. struct kinfo_proc info;
  220395. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  220396. size_t sz = sizeof (info);
  220397. sysctl (m, 4, &info, &sz, 0, 0);
  220398. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  220399. }
  220400. return testResult > 0;
  220401. }
  220402. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  220403. {
  220404. return juce_isRunningUnderDebugger();
  220405. }
  220406. #endif
  220407. /********* End of inlined file: juce_mac_Debugging.mm *********/
  220408. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  220409. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  220410. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  220411. // compiled on its own).
  220412. #ifdef JUCE_INCLUDED_FILE
  220413. class NSViewComponentPeer;
  220414. END_JUCE_NAMESPACE
  220415. #define JuceNSView MakeObjCClassName(JuceNSView)
  220416. @interface JuceNSView : NSView
  220417. {
  220418. @public
  220419. NSViewComponentPeer* owner;
  220420. NSNotificationCenter* notificationCenter;
  220421. }
  220422. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  220423. - (void) dealloc;
  220424. - (BOOL) isOpaque;
  220425. - (void) drawRect: (NSRect) r;
  220426. - (void) mouseDown: (NSEvent*) ev;
  220427. - (void) asyncMouseDown: (NSEvent*) ev;
  220428. - (void) mouseUp: (NSEvent*) ev;
  220429. - (void) asyncMouseUp: (NSEvent*) ev;
  220430. - (void) mouseDragged: (NSEvent*) ev;
  220431. - (void) mouseMoved: (NSEvent*) ev;
  220432. - (void) mouseEntered: (NSEvent*) ev;
  220433. - (void) mouseExited: (NSEvent*) ev;
  220434. - (void) rightMouseDown: (NSEvent*) ev;
  220435. - (void) rightMouseDragged: (NSEvent*) ev;
  220436. - (void) rightMouseUp: (NSEvent*) ev;
  220437. - (void) otherMouseDown: (NSEvent*) ev;
  220438. - (void) otherMouseDragged: (NSEvent*) ev;
  220439. - (void) otherMouseUp: (NSEvent*) ev;
  220440. - (void) scrollWheel: (NSEvent*) ev;
  220441. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  220442. - (void) frameChanged: (NSNotification*) n;
  220443. - (void) keyDown: (NSEvent*) ev;
  220444. - (void) keyUp: (NSEvent*) ev;
  220445. - (void) flagsChanged: (NSEvent*) ev;
  220446. #if MACOS_10_4_OR_EARLIER
  220447. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  220448. #endif
  220449. - (BOOL) becomeFirstResponder;
  220450. - (BOOL) resignFirstResponder;
  220451. - (BOOL) acceptsFirstResponder;
  220452. - (NSArray*) getSupportedDragTypes;
  220453. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  220454. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  220455. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  220456. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  220457. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  220458. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  220459. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  220460. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  220461. @end
  220462. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  220463. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  220464. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  220465. #else
  220466. @interface JuceNSWindow : NSWindow
  220467. #endif
  220468. {
  220469. @private
  220470. NSViewComponentPeer* owner;
  220471. bool isZooming;
  220472. }
  220473. - (void) setOwner: (NSViewComponentPeer*) owner;
  220474. - (BOOL) canBecomeKeyWindow;
  220475. - (void) becomeKeyWindow;
  220476. - (BOOL) windowShouldClose: (id) window;
  220477. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  220478. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  220479. - (void) zoom: (id) sender;
  220480. @end
  220481. BEGIN_JUCE_NAMESPACE
  220482. class NSViewComponentPeer : public ComponentPeer
  220483. {
  220484. public:
  220485. NSViewComponentPeer (Component* const component,
  220486. const int windowStyleFlags,
  220487. NSView* viewToAttachTo);
  220488. ~NSViewComponentPeer();
  220489. void* getNativeHandle() const;
  220490. void setVisible (bool shouldBeVisible);
  220491. void setTitle (const String& title);
  220492. void setPosition (int x, int y);
  220493. void setSize (int w, int h);
  220494. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  220495. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  220496. void getBounds (int& x, int& y, int& w, int& h) const;
  220497. int getScreenX() const;
  220498. int getScreenY() const;
  220499. void relativePositionToGlobal (int& x, int& y);
  220500. void globalPositionToRelative (int& x, int& y);
  220501. void setMinimised (bool shouldBeMinimised);
  220502. bool isMinimised() const;
  220503. void setFullScreen (bool shouldBeFullScreen);
  220504. bool isFullScreen() const;
  220505. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  220506. const BorderSize getFrameSize() const;
  220507. bool setAlwaysOnTop (bool alwaysOnTop);
  220508. void toFront (bool makeActiveWindow);
  220509. void toBehind (ComponentPeer* other);
  220510. void setIcon (const Image& newIcon);
  220511. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  220512. for example having more than one juce plugin loaded into a host, then when a
  220513. method is called, the actual code that runs might actually be in a different module
  220514. than the one you expect... So any calls to library functions or statics that are
  220515. made inside obj-c methods will probably end up getting executed in a different DLL's
  220516. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  220517. To work around this insanity, I'm only allowing obj-c methods to make calls to
  220518. virtual methods of an object that's known to live inside the right module's space.
  220519. */
  220520. virtual void redirectMouseDown (NSEvent* ev);
  220521. virtual void redirectMouseUp (NSEvent* ev);
  220522. virtual void redirectMouseDrag (NSEvent* ev);
  220523. virtual void redirectMouseMove (NSEvent* ev);
  220524. virtual void redirectMouseEnter (NSEvent* ev);
  220525. virtual void redirectMouseExit (NSEvent* ev);
  220526. virtual void redirectMouseWheel (NSEvent* ev);
  220527. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  220528. virtual bool redirectKeyDown (NSEvent* ev);
  220529. virtual bool redirectKeyUp (NSEvent* ev);
  220530. virtual void redirectModKeyChange (NSEvent* ev);
  220531. #if MACOS_10_4_OR_EARLIER
  220532. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  220533. #endif
  220534. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  220535. virtual bool isOpaque();
  220536. virtual void drawRect (NSRect r);
  220537. virtual bool canBecomeKeyWindow();
  220538. virtual bool windowShouldClose();
  220539. virtual void redirectMovedOrResized();
  220540. virtual NSRect constrainRect (NSRect r);
  220541. static void showArrowCursorIfNeeded();
  220542. virtual void viewFocusGain();
  220543. virtual void viewFocusLoss();
  220544. bool isFocused() const;
  220545. void grabFocus();
  220546. void textInputRequired (int x, int y);
  220547. void repaint (int x, int y, int w, int h);
  220548. void performAnyPendingRepaintsNow();
  220549. juce_UseDebuggingNewOperator
  220550. NSWindow* window;
  220551. JuceNSView* view;
  220552. bool isSharedWindow, fullScreen;
  220553. };
  220554. END_JUCE_NAMESPACE
  220555. @implementation JuceNSView
  220556. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  220557. withFrame: (NSRect) frame
  220558. {
  220559. [super initWithFrame: frame];
  220560. owner = owner_;
  220561. notificationCenter = [NSNotificationCenter defaultCenter];
  220562. [notificationCenter addObserver: self
  220563. selector: @selector (frameChanged:)
  220564. name: NSViewFrameDidChangeNotification
  220565. object: self];
  220566. if (! owner_->isSharedWindow)
  220567. {
  220568. [notificationCenter addObserver: self
  220569. selector: @selector (frameChanged:)
  220570. name: NSWindowDidMoveNotification
  220571. object: owner_->window];
  220572. }
  220573. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  220574. return self;
  220575. }
  220576. - (void) dealloc
  220577. {
  220578. [notificationCenter removeObserver: self];
  220579. [super dealloc];
  220580. }
  220581. - (void) drawRect: (NSRect) r
  220582. {
  220583. if (owner != 0)
  220584. owner->drawRect (r);
  220585. }
  220586. - (BOOL) isOpaque
  220587. {
  220588. return owner == 0 || owner->isOpaque();
  220589. }
  220590. - (void) mouseDown: (NSEvent*) ev
  220591. {
  220592. // In some host situations, the host will stop modal loops from working
  220593. // correctly if they're called from a mouse event, so we'll trigger
  220594. // the event asynchronously..
  220595. if (JUCEApplication::getInstance() == 0)
  220596. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  220597. withObject: ev
  220598. waitUntilDone: NO];
  220599. else
  220600. [self asyncMouseDown: ev];
  220601. }
  220602. - (void) asyncMouseDown: (NSEvent*) ev
  220603. {
  220604. if (owner != 0)
  220605. owner->redirectMouseDown (ev);
  220606. }
  220607. - (void) mouseUp: (NSEvent*) ev
  220608. {
  220609. // In some host situations, the host will stop modal loops from working
  220610. // correctly if they're called from a mouse event, so we'll trigger
  220611. // the event asynchronously..
  220612. if (JUCEApplication::getInstance() == 0)
  220613. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  220614. withObject: ev
  220615. waitUntilDone: NO];
  220616. else
  220617. [self asyncMouseUp: ev];
  220618. }
  220619. - (void) asyncMouseUp: (NSEvent*) ev
  220620. {
  220621. if (owner != 0)
  220622. owner->redirectMouseUp (ev);
  220623. }
  220624. - (void) mouseDragged: (NSEvent*) ev
  220625. {
  220626. if (owner != 0)
  220627. owner->redirectMouseDrag (ev);
  220628. }
  220629. - (void) mouseMoved: (NSEvent*) ev
  220630. {
  220631. if (owner != 0)
  220632. owner->redirectMouseMove (ev);
  220633. }
  220634. - (void) mouseEntered: (NSEvent*) ev
  220635. {
  220636. if (owner != 0)
  220637. owner->redirectMouseEnter (ev);
  220638. }
  220639. - (void) mouseExited: (NSEvent*) ev
  220640. {
  220641. if (owner != 0)
  220642. owner->redirectMouseExit (ev);
  220643. }
  220644. - (void) rightMouseDown: (NSEvent*) ev
  220645. {
  220646. [self mouseDown: ev];
  220647. }
  220648. - (void) rightMouseDragged: (NSEvent*) ev
  220649. {
  220650. [self mouseDragged: ev];
  220651. }
  220652. - (void) rightMouseUp: (NSEvent*) ev
  220653. {
  220654. [self mouseUp: ev];
  220655. }
  220656. - (void) otherMouseDown: (NSEvent*) ev
  220657. {
  220658. [self mouseDown: ev];
  220659. }
  220660. - (void) otherMouseDragged: (NSEvent*) ev
  220661. {
  220662. [self mouseDragged: ev];
  220663. }
  220664. - (void) otherMouseUp: (NSEvent*) ev
  220665. {
  220666. [self mouseUp: ev];
  220667. }
  220668. - (void) scrollWheel: (NSEvent*) ev
  220669. {
  220670. if (owner != 0)
  220671. owner->redirectMouseWheel (ev);
  220672. }
  220673. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  220674. {
  220675. return YES;
  220676. }
  220677. - (void) frameChanged: (NSNotification*) n
  220678. {
  220679. if (owner != 0)
  220680. owner->redirectMovedOrResized();
  220681. }
  220682. - (void) keyDown: (NSEvent*) ev
  220683. {
  220684. if (owner == 0 || ! owner->redirectKeyDown (ev))
  220685. [super keyDown: ev];
  220686. }
  220687. - (void) keyUp: (NSEvent*) ev
  220688. {
  220689. if (owner == 0 || ! owner->redirectKeyUp (ev))
  220690. [super keyUp: ev];
  220691. }
  220692. - (void) flagsChanged: (NSEvent*) ev
  220693. {
  220694. if (owner != 0)
  220695. owner->redirectModKeyChange (ev);
  220696. }
  220697. #if MACOS_10_4_OR_EARLIER
  220698. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  220699. {
  220700. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  220701. return true;
  220702. return [super performKeyEquivalent: ev];
  220703. }
  220704. #endif
  220705. - (BOOL) becomeFirstResponder
  220706. {
  220707. if (owner != 0)
  220708. owner->viewFocusGain();
  220709. return true;
  220710. }
  220711. - (BOOL) resignFirstResponder
  220712. {
  220713. if (owner != 0)
  220714. owner->viewFocusLoss();
  220715. return true;
  220716. }
  220717. - (BOOL) acceptsFirstResponder
  220718. {
  220719. return owner != 0 && owner->canBecomeKeyWindow();
  220720. }
  220721. - (NSArray*) getSupportedDragTypes
  220722. {
  220723. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  220724. }
  220725. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  220726. {
  220727. return owner != 0 && owner->sendDragCallback (type, sender);
  220728. }
  220729. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  220730. {
  220731. if ([self sendDragCallback: 0 sender: sender])
  220732. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220733. else
  220734. return NSDragOperationNone;
  220735. }
  220736. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  220737. {
  220738. if ([self sendDragCallback: 0 sender: sender])
  220739. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  220740. else
  220741. return NSDragOperationNone;
  220742. }
  220743. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  220744. {
  220745. [self sendDragCallback: 1 sender: sender];
  220746. }
  220747. - (void) draggingExited: (id <NSDraggingInfo>) sender
  220748. {
  220749. [self sendDragCallback: 1 sender: sender];
  220750. }
  220751. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  220752. {
  220753. return YES;
  220754. }
  220755. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  220756. {
  220757. return [self sendDragCallback: 2 sender: sender];
  220758. }
  220759. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  220760. {
  220761. }
  220762. @end
  220763. @implementation JuceNSWindow
  220764. - (void) setOwner: (NSViewComponentPeer*) owner_
  220765. {
  220766. owner = owner_;
  220767. isZooming = false;
  220768. }
  220769. - (BOOL) canBecomeKeyWindow
  220770. {
  220771. return owner != 0 && owner->canBecomeKeyWindow();
  220772. }
  220773. - (void) becomeKeyWindow
  220774. {
  220775. [super becomeKeyWindow];
  220776. if (owner != 0)
  220777. owner->grabFocus();
  220778. }
  220779. - (BOOL) windowShouldClose: (id) window
  220780. {
  220781. return owner == 0 || owner->windowShouldClose();
  220782. }
  220783. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  220784. {
  220785. if (owner != 0)
  220786. frameRect = owner->constrainRect (frameRect);
  220787. return frameRect;
  220788. }
  220789. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  220790. {
  220791. if (isZooming)
  220792. return proposedFrameSize;
  220793. NSRect frameRect = [self frame];
  220794. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  220795. frameRect.size = proposedFrameSize;
  220796. if (owner != 0)
  220797. frameRect = owner->constrainRect (frameRect);
  220798. return frameRect.size;
  220799. }
  220800. - (void) zoom: (id) sender
  220801. {
  220802. isZooming = true;
  220803. [super zoom: sender];
  220804. isZooming = false;
  220805. }
  220806. - (void) windowWillMove: (NSNotification*) notification
  220807. {
  220808. if (juce::Component::getCurrentlyModalComponent() != 0
  220809. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  220810. && (owner->getStyleFlags() & juce::ComponentPeer::windowHasTitleBar) != 0)
  220811. juce::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  220812. }
  220813. @end
  220814. BEGIN_JUCE_NAMESPACE
  220815. class JuceNSImage
  220816. {
  220817. public:
  220818. JuceNSImage (const int width, const int height, const bool hasAlpha)
  220819. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  220820. width, height, hasAlpha)
  220821. {
  220822. lineStride = 0;
  220823. pixelStride = 0;
  220824. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  220825. lineStride, pixelStride);
  220826. imageRep = [[NSBitmapImageRep alloc]
  220827. initWithBitmapDataPlanes: &imageData
  220828. pixelsWide: width
  220829. pixelsHigh: height
  220830. bitsPerSample: 8
  220831. samplesPerPixel: pixelStride
  220832. hasAlpha: hasAlpha
  220833. isPlanar: NO
  220834. colorSpaceName: NSCalibratedRGBColorSpace
  220835. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  220836. bytesPerRow: lineStride
  220837. bitsPerPixel: 8 * pixelStride ];
  220838. juceImage.releasePixelDataReadWrite (imageData);
  220839. }
  220840. ~JuceNSImage()
  220841. {
  220842. [imageRep release];
  220843. }
  220844. Image& getJuceImage() throw() { return juceImage; }
  220845. void draw (const float x, const float y,
  220846. const RectangleList& clip,
  220847. const int originX, const int originY) const
  220848. {
  220849. // Our data is BGRA and the damned image rep only takes RGBA, so
  220850. // we need to byte-swap the active areas if there's an alpha channel...
  220851. if (juceImage.hasAlphaChannel())
  220852. {
  220853. RectangleList::Iterator iter (clip);
  220854. while (iter.next())
  220855. {
  220856. const Rectangle* const r = iter.getRectangle();
  220857. swapRGBOrder (r->getX() + originX,
  220858. r->getY() + originY,
  220859. r->getWidth(),
  220860. r->getHeight());
  220861. }
  220862. }
  220863. NSPoint p;
  220864. p.x = x;
  220865. p.y = y;
  220866. [imageRep drawAtPoint: p];
  220867. }
  220868. void drawNSImage (NSImage* imageToDraw)
  220869. {
  220870. const ScopedAutoReleasePool pool;
  220871. [NSGraphicsContext saveGraphicsState];
  220872. [NSGraphicsContext setCurrentContext:
  220873. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  220874. [imageToDraw drawAtPoint: NSZeroPoint
  220875. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  220876. operation: NSCompositeSourceOver
  220877. fraction: 1.0f];
  220878. [[NSGraphicsContext currentContext] flushGraphics];
  220879. [NSGraphicsContext restoreGraphicsState];
  220880. if (juceImage.hasAlphaChannel())
  220881. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  220882. }
  220883. private:
  220884. Image juceImage;
  220885. NSBitmapImageRep* imageRep;
  220886. uint8* imageData;
  220887. int pixelStride, lineStride;
  220888. void swapRGBOrder (const int x, const int y, const int w, int h) const
  220889. {
  220890. #if JUCE_BIG_ENDIAN
  220891. jassert (pixelStride == 4);
  220892. #endif
  220893. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  220894. .contains (Rectangle (x, y, w, h)));
  220895. uint8* start = imageData + x * pixelStride + y * lineStride;
  220896. while (--h >= 0)
  220897. {
  220898. uint8* p = start;
  220899. start += lineStride;
  220900. for (int i = w; --i >= 0;)
  220901. {
  220902. #if JUCE_BIG_ENDIAN
  220903. const uint8 oldp3 = p[3];
  220904. const uint8 oldp1 = p[1];
  220905. p[3] = p[0];
  220906. p[0] = oldp1;
  220907. p[1] = p[2];
  220908. p[2] = oldp3;
  220909. #else
  220910. const uint8 oldp0 = p[0];
  220911. p[0] = p[2];
  220912. p[2] = oldp0;
  220913. #endif
  220914. p += pixelStride;
  220915. }
  220916. }
  220917. }
  220918. };
  220919. static ComponentPeer* currentlyFocusedPeer = 0;
  220920. static VoidArray keysCurrentlyDown;
  220921. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220922. {
  220923. if (keysCurrentlyDown.contains ((void*) keyCode))
  220924. return true;
  220925. if (keyCode >= 'A' && keyCode <= 'Z'
  220926. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  220927. return true;
  220928. if (keyCode >= 'a' && keyCode <= 'z'
  220929. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  220930. return true;
  220931. return false;
  220932. }
  220933. static int getKeyCodeFromEvent (NSEvent* ev)
  220934. {
  220935. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  220936. int keyCode = unmodified[0];
  220937. if (keyCode == 0x19) // (backwards-tab)
  220938. keyCode = '\t';
  220939. else if (keyCode == 0x03) // (enter)
  220940. keyCode = '\r';
  220941. return keyCode;
  220942. }
  220943. static int currentModifiers = 0;
  220944. static void updateModifiers (NSEvent* e)
  220945. {
  220946. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  220947. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  220948. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  220949. m |= ModifierKeys::shiftModifier;
  220950. if (([e modifierFlags] & NSControlKeyMask) != 0)
  220951. m |= ModifierKeys::ctrlModifier;
  220952. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  220953. m |= ModifierKeys::altModifier;
  220954. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  220955. m |= ModifierKeys::commandModifier;
  220956. currentModifiers = m;
  220957. }
  220958. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  220959. {
  220960. updateModifiers (ev);
  220961. int keyCode = getKeyCodeFromEvent (ev);
  220962. if (keyCode != 0)
  220963. {
  220964. if (isKeyDown)
  220965. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  220966. else
  220967. keysCurrentlyDown.removeValue ((void*) keyCode);
  220968. }
  220969. }
  220970. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220971. {
  220972. return ModifierKeys (currentModifiers);
  220973. }
  220974. void ModifierKeys::updateCurrentModifiers() throw()
  220975. {
  220976. currentModifierFlags = currentModifiers;
  220977. }
  220978. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  220979. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  220980. {
  220981. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  220982. x = roundFloatToInt (p.x);
  220983. y = roundFloatToInt ([view frame].size.height - p.y);
  220984. }
  220985. static int getModifierForButtonNumber (const int num) throw()
  220986. {
  220987. return num == 0 ? ModifierKeys::leftButtonModifier
  220988. : (num == 1 ? ModifierKeys::rightButtonModifier
  220989. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  220990. }
  220991. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  220992. const int windowStyleFlags,
  220993. NSView* viewToAttachTo)
  220994. : ComponentPeer (component, windowStyleFlags),
  220995. window (0),
  220996. view (0)
  220997. {
  220998. NSRect r;
  220999. r.origin.x = 0;
  221000. r.origin.y = 0;
  221001. r.size.width = (float) component->getWidth();
  221002. r.size.height = (float) component->getHeight();
  221003. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  221004. [view setPostsFrameChangedNotifications: YES];
  221005. if (viewToAttachTo != 0)
  221006. {
  221007. window = [viewToAttachTo window];
  221008. [viewToAttachTo addSubview: view];
  221009. isSharedWindow = true;
  221010. setVisible (component->isVisible());
  221011. }
  221012. else
  221013. {
  221014. isSharedWindow = false;
  221015. r.origin.x = (float) component->getX();
  221016. r.origin.y = (float) component->getY();
  221017. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  221018. unsigned int style = 0;
  221019. if ((windowStyleFlags & windowHasTitleBar) == 0)
  221020. style = NSBorderlessWindowMask;
  221021. else
  221022. style = NSTitledWindowMask;
  221023. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  221024. style |= NSMiniaturizableWindowMask;
  221025. if ((windowStyleFlags & windowHasCloseButton) != 0)
  221026. style |= NSClosableWindowMask;
  221027. if ((windowStyleFlags & windowIsResizable) != 0)
  221028. style |= NSResizableWindowMask;
  221029. window = [[JuceNSWindow alloc] initWithContentRect: r
  221030. styleMask: style
  221031. backing: NSBackingStoreBuffered
  221032. defer: YES];
  221033. [((JuceNSWindow*) window) setOwner: this];
  221034. [window orderOut: nil];
  221035. [window setDelegate: (JuceNSWindow*) window];
  221036. [window setOpaque: component->isOpaque()];
  221037. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  221038. if (component->isAlwaysOnTop())
  221039. [window setLevel: NSFloatingWindowLevel];
  221040. [window setContentView: view];
  221041. [window setAutodisplay: YES];
  221042. [window setAcceptsMouseMovedEvents: YES];
  221043. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  221044. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  221045. [window setReleasedWhenClosed: YES];
  221046. [window retain];
  221047. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  221048. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  221049. }
  221050. setTitle (component->getName());
  221051. }
  221052. NSViewComponentPeer::~NSViewComponentPeer()
  221053. {
  221054. view->owner = 0;
  221055. [view removeFromSuperview];
  221056. [view release];
  221057. if (! isSharedWindow)
  221058. {
  221059. [((JuceNSWindow*) window) setOwner: 0];
  221060. [window close];
  221061. [window release];
  221062. }
  221063. }
  221064. void* NSViewComponentPeer::getNativeHandle() const
  221065. {
  221066. return view;
  221067. }
  221068. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  221069. {
  221070. if (isSharedWindow)
  221071. {
  221072. [view setHidden: ! shouldBeVisible];
  221073. }
  221074. else
  221075. {
  221076. if (shouldBeVisible)
  221077. [window orderFront: nil];
  221078. else
  221079. [window orderOut: nil];
  221080. }
  221081. }
  221082. void NSViewComponentPeer::setTitle (const String& title)
  221083. {
  221084. const ScopedAutoReleasePool pool;
  221085. if (! isSharedWindow)
  221086. [window setTitle: juceStringToNS (title)];
  221087. }
  221088. void NSViewComponentPeer::setPosition (int x, int y)
  221089. {
  221090. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  221091. }
  221092. void NSViewComponentPeer::setSize (int w, int h)
  221093. {
  221094. setBounds (component->getX(), component->getY(), w, h, false);
  221095. }
  221096. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  221097. {
  221098. fullScreen = isNowFullScreen;
  221099. w = jmax (0, w);
  221100. h = jmax (0, h);
  221101. NSRect r;
  221102. r.origin.x = (float) x;
  221103. r.origin.y = (float) y;
  221104. r.size.width = (float) w;
  221105. r.size.height = (float) h;
  221106. if (isSharedWindow)
  221107. {
  221108. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221109. if ([view frame].size.width != r.size.width
  221110. || [view frame].size.height != r.size.height)
  221111. [view setNeedsDisplay: true];
  221112. [view setFrame: r];
  221113. }
  221114. else
  221115. {
  221116. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  221117. [window setFrame: [window frameRectForContentRect: r]
  221118. display: true];
  221119. }
  221120. }
  221121. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  221122. {
  221123. NSRect r = [view frame];
  221124. if (global && [view window] != 0)
  221125. {
  221126. r = [view convertRect: r toView: nil];
  221127. NSRect wr = [[view window] frame];
  221128. r.origin.x += wr.origin.x;
  221129. r.origin.y += wr.origin.y;
  221130. y = (int) ([[[NSScreen screens] objectAtIndex:0] frame].size.height - r.origin.y - r.size.height);
  221131. }
  221132. else
  221133. {
  221134. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  221135. }
  221136. x = (int) r.origin.x;
  221137. w = (int) r.size.width;
  221138. h = (int) r.size.height;
  221139. }
  221140. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  221141. {
  221142. getBounds (x, y, w, h, ! isSharedWindow);
  221143. }
  221144. int NSViewComponentPeer::getScreenX() const
  221145. {
  221146. int x, y, w, h;
  221147. getBounds (x, y, w, h, true);
  221148. return x;
  221149. }
  221150. int NSViewComponentPeer::getScreenY() const
  221151. {
  221152. int x, y, w, h;
  221153. getBounds (x, y, w, h, true);
  221154. return y;
  221155. }
  221156. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  221157. {
  221158. int wx, wy, ww, wh;
  221159. getBounds (wx, wy, ww, wh, true);
  221160. x += wx;
  221161. y += wy;
  221162. }
  221163. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  221164. {
  221165. int wx, wy, ww, wh;
  221166. getBounds (wx, wy, ww, wh, true);
  221167. x -= wx;
  221168. y -= wy;
  221169. }
  221170. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  221171. {
  221172. if (constrainer != 0)
  221173. {
  221174. NSRect current = [window frame];
  221175. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  221176. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  221177. int x = (int) r.origin.x;
  221178. int y = (int) r.origin.y;
  221179. int w = (int) r.size.width;
  221180. int h = (int) r.size.height;
  221181. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  221182. (int) current.size.width, (int) current.size.height);
  221183. constrainer->checkBounds (x, y, w, h,
  221184. original,
  221185. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  221186. y != original.getY() && y + h == original.getBottom(),
  221187. x != original.getX() && x + w == original.getRight(),
  221188. y == original.getY() && y + h != original.getBottom(),
  221189. x == original.getX() && x + w != original.getRight());
  221190. r.origin.x = x;
  221191. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - y;
  221192. r.size.width = w;
  221193. r.size.height = h;
  221194. }
  221195. return r;
  221196. }
  221197. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  221198. {
  221199. if (! isSharedWindow)
  221200. {
  221201. if (shouldBeMinimised)
  221202. [window miniaturize: nil];
  221203. else
  221204. [window deminiaturize: nil];
  221205. }
  221206. }
  221207. bool NSViewComponentPeer::isMinimised() const
  221208. {
  221209. return window != 0 && [window isMiniaturized];
  221210. }
  221211. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  221212. {
  221213. if (! isSharedWindow)
  221214. {
  221215. Rectangle r (lastNonFullscreenBounds);
  221216. setMinimised (false);
  221217. if (fullScreen != shouldBeFullScreen)
  221218. {
  221219. if (shouldBeFullScreen)
  221220. r = Desktop::getInstance().getMainMonitorArea();
  221221. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  221222. if (r != getComponent()->getBounds() && ! r.isEmpty())
  221223. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  221224. }
  221225. }
  221226. }
  221227. bool NSViewComponentPeer::isFullScreen() const
  221228. {
  221229. return fullScreen;
  221230. }
  221231. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  221232. {
  221233. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  221234. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  221235. return false;
  221236. NSPoint p;
  221237. p.x = (float) x;
  221238. p.y = (float) y;
  221239. NSView* v = [view hitTest: p];
  221240. if (trueIfInAChildWindow)
  221241. return v != nil;
  221242. return v == view;
  221243. }
  221244. const BorderSize NSViewComponentPeer::getFrameSize() const
  221245. {
  221246. BorderSize b;
  221247. if (! isSharedWindow)
  221248. {
  221249. NSRect v = [view convertRect: [view frame] toView: nil];
  221250. NSRect w = [window frame];
  221251. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  221252. b.setBottom ((int) v.origin.y);
  221253. b.setLeft ((int) v.origin.x);
  221254. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  221255. }
  221256. return b;
  221257. }
  221258. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  221259. {
  221260. if (! isSharedWindow)
  221261. {
  221262. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  221263. : NSNormalWindowLevel];
  221264. }
  221265. return true;
  221266. }
  221267. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  221268. {
  221269. if (isSharedWindow)
  221270. {
  221271. [[view superview] addSubview: view
  221272. positioned: NSWindowAbove
  221273. relativeTo: nil];
  221274. }
  221275. if (window != 0 && component->isVisible())
  221276. {
  221277. if (makeActiveWindow)
  221278. [window makeKeyAndOrderFront: nil];
  221279. else
  221280. [window orderFront: nil];
  221281. }
  221282. }
  221283. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  221284. {
  221285. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  221286. if (isSharedWindow)
  221287. {
  221288. [[view superview] addSubview: view
  221289. positioned: NSWindowBelow
  221290. relativeTo: o->view];
  221291. }
  221292. else
  221293. {
  221294. [window orderWindow: NSWindowBelow
  221295. relativeTo: o->window != 0 ? [o->window windowNumber]
  221296. : nil ];
  221297. }
  221298. }
  221299. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  221300. {
  221301. // to do..
  221302. }
  221303. void NSViewComponentPeer::viewFocusGain()
  221304. {
  221305. if (currentlyFocusedPeer != this)
  221306. {
  221307. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  221308. currentlyFocusedPeer->handleFocusLoss();
  221309. currentlyFocusedPeer = this;
  221310. handleFocusGain();
  221311. }
  221312. }
  221313. void NSViewComponentPeer::viewFocusLoss()
  221314. {
  221315. if (currentlyFocusedPeer == this)
  221316. {
  221317. currentlyFocusedPeer = 0;
  221318. handleFocusLoss();
  221319. }
  221320. }
  221321. void juce_HandleProcessFocusChange()
  221322. {
  221323. keysCurrentlyDown.clear();
  221324. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  221325. {
  221326. if (Process::isForegroundProcess())
  221327. {
  221328. currentlyFocusedPeer->handleFocusGain();
  221329. ComponentPeer::bringModalComponentToFront();
  221330. }
  221331. else
  221332. {
  221333. currentlyFocusedPeer->handleFocusLoss();
  221334. // turn kiosk mode off if we lose focus..
  221335. Desktop::getInstance().setKioskModeComponent (0);
  221336. }
  221337. }
  221338. }
  221339. bool NSViewComponentPeer::isFocused() const
  221340. {
  221341. return isSharedWindow ? this == currentlyFocusedPeer
  221342. : (window != 0 && [window isKeyWindow]);
  221343. }
  221344. void NSViewComponentPeer::grabFocus()
  221345. {
  221346. if (window != 0)
  221347. {
  221348. [window makeKeyWindow];
  221349. [window makeFirstResponder: view];
  221350. viewFocusGain();
  221351. }
  221352. }
  221353. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  221354. {
  221355. }
  221356. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  221357. {
  221358. String unicode (nsStringToJuce ([ev characters]));
  221359. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  221360. int keyCode = getKeyCodeFromEvent (ev);
  221361. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  221362. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  221363. if (unicode.isNotEmpty() || keyCode != 0)
  221364. {
  221365. if (isKeyDown)
  221366. {
  221367. bool used = false;
  221368. while (unicode.length() > 0)
  221369. {
  221370. juce_wchar textCharacter = unicode[0];
  221371. unicode = unicode.substring (1);
  221372. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  221373. textCharacter = 0;
  221374. used = handleKeyUpOrDown (true) || used;
  221375. used = handleKeyPress (keyCode, textCharacter) || used;
  221376. }
  221377. return used;
  221378. }
  221379. else
  221380. {
  221381. if (handleKeyUpOrDown (false))
  221382. return true;
  221383. }
  221384. }
  221385. return false;
  221386. }
  221387. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  221388. {
  221389. updateKeysDown (ev, true);
  221390. bool used = handleKeyEvent (ev, true);
  221391. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  221392. {
  221393. // for command keys, the key-up event is thrown away, so simulate one..
  221394. updateKeysDown (ev, false);
  221395. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  221396. }
  221397. // (If we're running modally, don't allow unused keystrokes to be passed
  221398. // along to other blocked views..)
  221399. if (Component::getCurrentlyModalComponent() != 0)
  221400. used = true;
  221401. return used;
  221402. }
  221403. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  221404. {
  221405. updateKeysDown (ev, false);
  221406. return handleKeyEvent (ev, false)
  221407. || Component::getCurrentlyModalComponent() != 0;
  221408. }
  221409. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  221410. {
  221411. updateModifiers (ev);
  221412. handleModifierKeysChange();
  221413. }
  221414. #if MACOS_10_4_OR_EARLIER
  221415. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  221416. {
  221417. if ([ev type] == NSKeyDown)
  221418. return redirectKeyDown (ev);
  221419. else if ([ev type] == NSKeyUp)
  221420. return redirectKeyUp (ev);
  221421. return false;
  221422. }
  221423. #endif
  221424. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  221425. {
  221426. updateModifiers (ev);
  221427. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  221428. int x, y;
  221429. getMousePos (ev, view, x, y);
  221430. handleMouseDown (x, y, getMouseTime (ev));
  221431. }
  221432. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  221433. {
  221434. const int oldMods = currentModifiers;
  221435. updateModifiers (ev);
  221436. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  221437. int x, y;
  221438. getMousePos (ev, view, x, y);
  221439. handleMouseUp (oldMods, x, y, getMouseTime (ev));
  221440. showArrowCursorIfNeeded();
  221441. }
  221442. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  221443. {
  221444. updateModifiers (ev);
  221445. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  221446. int x, y;
  221447. getMousePos (ev, view, x, y);
  221448. handleMouseDrag (x, y, getMouseTime (ev));
  221449. }
  221450. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  221451. {
  221452. updateModifiers (ev);
  221453. int x, y;
  221454. getMousePos (ev, view, x, y);
  221455. handleMouseMove (x, y, getMouseTime (ev));
  221456. showArrowCursorIfNeeded();
  221457. }
  221458. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  221459. {
  221460. updateModifiers (ev);
  221461. int x, y;
  221462. getMousePos (ev, view, x, y);
  221463. handleMouseEnter (x, y, getMouseTime (ev));
  221464. }
  221465. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  221466. {
  221467. updateModifiers (ev);
  221468. int x, y;
  221469. getMousePos (ev, view, x, y);
  221470. handleMouseExit (x, y, getMouseTime (ev));
  221471. }
  221472. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  221473. {
  221474. updateModifiers (ev);
  221475. handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  221476. roundFloatToInt ([ev deltaY] * 10.0f),
  221477. getMouseTime (ev));
  221478. }
  221479. void NSViewComponentPeer::showArrowCursorIfNeeded()
  221480. {
  221481. if (Component::getComponentUnderMouse() == 0)
  221482. {
  221483. int mx, my;
  221484. Desktop::getInstance().getMousePosition (mx, my);
  221485. if (Desktop::getInstance().findComponentAt (mx, my) == 0)
  221486. [[NSCursor arrowCursor] set];
  221487. }
  221488. }
  221489. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  221490. {
  221491. NSString* bestType
  221492. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  221493. if (bestType == nil)
  221494. return false;
  221495. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  221496. int x = (int) p.x;
  221497. int y = (int) ([view frame].size.height - p.y);
  221498. StringArray files;
  221499. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  221500. if (list == nil)
  221501. return false;
  221502. if ([list isKindOfClass: [NSArray class]])
  221503. {
  221504. NSArray* items = (NSArray*) list;
  221505. for (unsigned int i = 0; i < [items count]; ++i)
  221506. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  221507. }
  221508. if (files.size() == 0)
  221509. return false;
  221510. if (type == 0)
  221511. handleFileDragMove (files, x, y);
  221512. else if (type == 1)
  221513. handleFileDragExit (files);
  221514. else if (type == 2)
  221515. handleFileDragDrop (files, x, y);
  221516. return true;
  221517. }
  221518. bool NSViewComponentPeer::isOpaque()
  221519. {
  221520. if (! getComponent()->isValidComponent())
  221521. return true;
  221522. return getComponent()->isOpaque();
  221523. }
  221524. void NSViewComponentPeer::drawRect (NSRect r)
  221525. {
  221526. if (r.size.width < 1.0f || r.size.height < 1.0f)
  221527. return;
  221528. const float y = [view frame].size.height - (r.origin.y + r.size.height);
  221529. JuceNSImage temp ((int) (r.size.width + 0.5f),
  221530. (int) (r.size.height + 0.5f),
  221531. ! getComponent()->isOpaque());
  221532. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  221533. const int originX = -roundFloatToInt (r.origin.x);
  221534. const int originY = -roundFloatToInt (y);
  221535. context.setOrigin (originX, originY);
  221536. const NSRect* rects = 0;
  221537. NSInteger numRects = 0;
  221538. [view getRectsBeingDrawn: &rects count: &numRects];
  221539. RectangleList clip;
  221540. for (int i = 0; i < numRects; ++i)
  221541. {
  221542. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  221543. roundFloatToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  221544. roundFloatToInt (rects[i].size.width),
  221545. roundFloatToInt (rects[i].size.height)));
  221546. }
  221547. if (context.reduceClipRegion (clip))
  221548. {
  221549. handlePaint (context);
  221550. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  221551. }
  221552. }
  221553. bool NSViewComponentPeer::canBecomeKeyWindow()
  221554. {
  221555. // If running as a plugin, let the component decide whether it's going to allow the window to get focused.
  221556. return ((getStyleFlags() & juce::ComponentPeer::windowIsTemporary) == 0)
  221557. && (JUCEApplication::getInstance() != 0
  221558. || (isValidPeer (this)
  221559. && ! getComponent()->getComponentPropertyBool ("juce_disallowFocus", false, false)));
  221560. }
  221561. bool NSViewComponentPeer::windowShouldClose()
  221562. {
  221563. if (! isValidPeer (this))
  221564. return YES;
  221565. handleUserClosingWindow();
  221566. return NO;
  221567. }
  221568. void NSViewComponentPeer::redirectMovedOrResized()
  221569. {
  221570. handleMovedOrResized();
  221571. }
  221572. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221573. {
  221574. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  221575. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  221576. // is apparently still available in 64-bit apps..
  221577. if (enableOrDisable)
  221578. {
  221579. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  221580. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221581. }
  221582. else
  221583. {
  221584. SetSystemUIMode (kUIModeNormal, 0);
  221585. }
  221586. }
  221587. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  221588. {
  221589. [view setNeedsDisplayInRect:
  221590. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  221591. (float) w, (float) h)];
  221592. }
  221593. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  221594. {
  221595. [view displayIfNeeded];
  221596. }
  221597. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  221598. {
  221599. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  221600. }
  221601. static Image* NSImageToJuceImage (NSImage* image)
  221602. {
  221603. JuceNSImage juceIm ((int) [image size].width,
  221604. (int) [image size].height,
  221605. true);
  221606. juceIm.drawNSImage (image);
  221607. return juceIm.getJuceImage().createCopy();
  221608. }
  221609. Image* juce_createIconForFile (const File& file)
  221610. {
  221611. const ScopedAutoReleasePool pool;
  221612. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  221613. return NSImageToJuceImage (im);
  221614. }
  221615. const int KeyPress::spaceKey = ' ';
  221616. const int KeyPress::returnKey = 0x0d;
  221617. const int KeyPress::escapeKey = 0x1b;
  221618. const int KeyPress::backspaceKey = 0x7f;
  221619. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  221620. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  221621. const int KeyPress::upKey = NSUpArrowFunctionKey;
  221622. const int KeyPress::downKey = NSDownArrowFunctionKey;
  221623. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  221624. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  221625. const int KeyPress::endKey = NSEndFunctionKey;
  221626. const int KeyPress::homeKey = NSHomeFunctionKey;
  221627. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  221628. const int KeyPress::insertKey = -1;
  221629. const int KeyPress::tabKey = 9;
  221630. const int KeyPress::F1Key = NSF1FunctionKey;
  221631. const int KeyPress::F2Key = NSF2FunctionKey;
  221632. const int KeyPress::F3Key = NSF3FunctionKey;
  221633. const int KeyPress::F4Key = NSF4FunctionKey;
  221634. const int KeyPress::F5Key = NSF5FunctionKey;
  221635. const int KeyPress::F6Key = NSF6FunctionKey;
  221636. const int KeyPress::F7Key = NSF7FunctionKey;
  221637. const int KeyPress::F8Key = NSF8FunctionKey;
  221638. const int KeyPress::F9Key = NSF9FunctionKey;
  221639. const int KeyPress::F10Key = NSF10FunctionKey;
  221640. const int KeyPress::F11Key = NSF1FunctionKey;
  221641. const int KeyPress::F12Key = NSF12FunctionKey;
  221642. const int KeyPress::F13Key = NSF13FunctionKey;
  221643. const int KeyPress::F14Key = NSF14FunctionKey;
  221644. const int KeyPress::F15Key = NSF15FunctionKey;
  221645. const int KeyPress::F16Key = NSF16FunctionKey;
  221646. const int KeyPress::numberPad0 = 0x30020;
  221647. const int KeyPress::numberPad1 = 0x30021;
  221648. const int KeyPress::numberPad2 = 0x30022;
  221649. const int KeyPress::numberPad3 = 0x30023;
  221650. const int KeyPress::numberPad4 = 0x30024;
  221651. const int KeyPress::numberPad5 = 0x30025;
  221652. const int KeyPress::numberPad6 = 0x30026;
  221653. const int KeyPress::numberPad7 = 0x30027;
  221654. const int KeyPress::numberPad8 = 0x30028;
  221655. const int KeyPress::numberPad9 = 0x30029;
  221656. const int KeyPress::numberPadAdd = 0x3002a;
  221657. const int KeyPress::numberPadSubtract = 0x3002b;
  221658. const int KeyPress::numberPadMultiply = 0x3002c;
  221659. const int KeyPress::numberPadDivide = 0x3002d;
  221660. const int KeyPress::numberPadSeparator = 0x3002e;
  221661. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221662. const int KeyPress::numberPadEquals = 0x30030;
  221663. const int KeyPress::numberPadDelete = 0x30031;
  221664. const int KeyPress::playKey = 0x30000;
  221665. const int KeyPress::stopKey = 0x30001;
  221666. const int KeyPress::fastForwardKey = 0x30002;
  221667. const int KeyPress::rewindKey = 0x30003;
  221668. #endif
  221669. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  221670. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  221671. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221672. // compiled on its own).
  221673. #ifdef JUCE_INCLUDED_FILE
  221674. static NSImage* juceImageToNSImage (const Image& image)
  221675. {
  221676. const ScopedAutoReleasePool pool;
  221677. int lineStride, pixelStride;
  221678. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  221679. lineStride, pixelStride);
  221680. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  221681. initWithBitmapDataPlanes: NULL
  221682. pixelsWide: image.getWidth()
  221683. pixelsHigh: image.getHeight()
  221684. bitsPerSample: 8
  221685. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  221686. hasAlpha: image.hasAlphaChannel()
  221687. isPlanar: NO
  221688. colorSpaceName: NSCalibratedRGBColorSpace
  221689. bitmapFormat: (NSBitmapFormat) 0
  221690. bytesPerRow: lineStride
  221691. bitsPerPixel: pixelStride * 8];
  221692. unsigned char* newData = [rep bitmapData];
  221693. memcpy (newData, pixels, lineStride * image.getHeight());
  221694. image.releasePixelDataReadOnly (pixels);
  221695. NSImage* im = [[NSImage alloc] init];
  221696. [im addRepresentation: rep];
  221697. [rep release];
  221698. return im;
  221699. }
  221700. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  221701. {
  221702. NSImage* im = juceImageToNSImage (image);
  221703. NSCursor* c = [[NSCursor alloc] initWithImage: im
  221704. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  221705. [im release];
  221706. return (void*) c;
  221707. }
  221708. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  221709. {
  221710. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  221711. jassert (im != 0);
  221712. if (im == 0)
  221713. return 0;
  221714. void* const curs = juce_createMouseCursorFromImage (*im,
  221715. (int) (hx * im->getWidth()),
  221716. (int) (hy * im->getHeight()));
  221717. delete im;
  221718. return curs;
  221719. }
  221720. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  221721. {
  221722. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  221723. MemoryBlock mb;
  221724. if (f.getChildFile (filename).loadFileAsData (mb))
  221725. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  221726. return 0;
  221727. }
  221728. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  221729. {
  221730. const ScopedAutoReleasePool pool;
  221731. NSCursor* c = 0;
  221732. switch (type)
  221733. {
  221734. case MouseCursor::NormalCursor:
  221735. c = [NSCursor arrowCursor];
  221736. break;
  221737. case MouseCursor::NoCursor:
  221738. {
  221739. Image blank (Image::ARGB, 8, 8, true);
  221740. return juce_createMouseCursorFromImage (blank, 0, 0);
  221741. }
  221742. case MouseCursor::DraggingHandCursor:
  221743. c = [NSCursor openHandCursor];
  221744. break;
  221745. case MouseCursor::CopyingCursor:
  221746. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  221747. case MouseCursor::WaitCursor:
  221748. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  221749. break;
  221750. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  221751. case MouseCursor::IBeamCursor:
  221752. c = [NSCursor IBeamCursor];
  221753. break;
  221754. case MouseCursor::PointingHandCursor:
  221755. c = [NSCursor pointingHandCursor];
  221756. break;
  221757. case MouseCursor::LeftRightResizeCursor:
  221758. c = [NSCursor resizeLeftRightCursor];
  221759. break;
  221760. case MouseCursor::LeftEdgeResizeCursor:
  221761. c = [NSCursor resizeLeftCursor];
  221762. break;
  221763. case MouseCursor::RightEdgeResizeCursor:
  221764. c = [NSCursor resizeRightCursor];
  221765. break;
  221766. case MouseCursor::UpDownResizeCursor:
  221767. case MouseCursor::TopEdgeResizeCursor:
  221768. case MouseCursor::BottomEdgeResizeCursor:
  221769. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  221770. case MouseCursor::TopLeftCornerResizeCursor:
  221771. case MouseCursor::BottomRightCornerResizeCursor:
  221772. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  221773. case MouseCursor::TopRightCornerResizeCursor:
  221774. case MouseCursor::BottomLeftCornerResizeCursor:
  221775. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  221776. case MouseCursor::UpDownLeftRightResizeCursor:
  221777. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  221778. case MouseCursor::CrosshairCursor:
  221779. c = [NSCursor crosshairCursor];
  221780. break;
  221781. }
  221782. [c retain];
  221783. return (void*) c;
  221784. }
  221785. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  221786. {
  221787. NSCursor* c = (NSCursor*) cursorHandle;
  221788. [c release];
  221789. }
  221790. void MouseCursor::showInAllWindows() const throw()
  221791. {
  221792. showInWindow (0);
  221793. }
  221794. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  221795. {
  221796. NSCursor* const c = (NSCursor*) getHandle();
  221797. [c set];
  221798. }
  221799. #endif
  221800. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  221801. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  221802. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221803. // compiled on its own).
  221804. #ifdef JUCE_INCLUDED_FILE
  221805. class NSViewComponentInternal : public ComponentMovementWatcher
  221806. {
  221807. Component* const owner;
  221808. NSViewComponentPeer* currentPeer;
  221809. bool wasShowing;
  221810. public:
  221811. NSView* const view;
  221812. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  221813. : ComponentMovementWatcher (owner_),
  221814. owner (owner_),
  221815. currentPeer (0),
  221816. wasShowing (false),
  221817. view (view_)
  221818. {
  221819. [view_ retain];
  221820. if (owner_->isShowing())
  221821. componentPeerChanged();
  221822. }
  221823. ~NSViewComponentInternal()
  221824. {
  221825. [view removeFromSuperview];
  221826. [view release];
  221827. }
  221828. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  221829. {
  221830. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  221831. // The ComponentMovementWatcher version of this method avoids calling
  221832. // us when the top-level comp is resized, but for an NSView we need to know this
  221833. // because with inverted co-ords, we need to update the position even if the
  221834. // top-left pos hasn't changed
  221835. if (comp.isOnDesktop() && wasResized)
  221836. componentMovedOrResized (wasMoved, wasResized);
  221837. }
  221838. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  221839. {
  221840. Component* const topComp = owner->getTopLevelComponent();
  221841. if (topComp->getPeer() != 0)
  221842. {
  221843. int x = 0, y = 0;
  221844. owner->relativePositionToOtherComponent (topComp, x, y);
  221845. NSRect r;
  221846. r.origin.x = (float) x;
  221847. r.origin.y = (float) y;
  221848. r.size.width = (float) owner->getWidth();
  221849. r.size.height = (float) owner->getHeight();
  221850. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  221851. [view setFrame: r];
  221852. }
  221853. }
  221854. void componentPeerChanged()
  221855. {
  221856. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  221857. if (currentPeer != peer)
  221858. {
  221859. [view removeFromSuperview];
  221860. currentPeer = peer;
  221861. if (peer != 0)
  221862. {
  221863. [peer->view addSubview: view];
  221864. componentMovedOrResized (false, false);
  221865. }
  221866. }
  221867. [view setHidden: ! owner->isShowing()];
  221868. }
  221869. void componentVisibilityChanged (Component&)
  221870. {
  221871. componentPeerChanged();
  221872. }
  221873. juce_UseDebuggingNewOperator
  221874. private:
  221875. NSViewComponentInternal (const NSViewComponentInternal&);
  221876. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  221877. };
  221878. NSViewComponent::NSViewComponent()
  221879. : info (0)
  221880. {
  221881. }
  221882. NSViewComponent::~NSViewComponent()
  221883. {
  221884. delete info;
  221885. }
  221886. void NSViewComponent::setView (void* view)
  221887. {
  221888. if (view != getView())
  221889. {
  221890. deleteAndZero (info);
  221891. if (view != 0)
  221892. info = new NSViewComponentInternal ((NSView*) view, this);
  221893. }
  221894. }
  221895. void* NSViewComponent::getView() const
  221896. {
  221897. return info == 0 ? 0 : info->view;
  221898. }
  221899. void NSViewComponent::paint (Graphics& g)
  221900. {
  221901. }
  221902. #endif
  221903. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  221904. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  221905. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  221906. // compiled on its own).
  221907. #ifdef JUCE_INCLUDED_FILE
  221908. AppleRemoteDevice::AppleRemoteDevice()
  221909. : device (0),
  221910. queue (0),
  221911. remoteId (0)
  221912. {
  221913. }
  221914. AppleRemoteDevice::~AppleRemoteDevice()
  221915. {
  221916. stop();
  221917. }
  221918. static io_object_t getAppleRemoteDevice() throw()
  221919. {
  221920. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  221921. io_iterator_t iter = 0;
  221922. io_object_t iod = 0;
  221923. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  221924. && iter != 0)
  221925. {
  221926. iod = IOIteratorNext (iter);
  221927. }
  221928. IOObjectRelease (iter);
  221929. return iod;
  221930. }
  221931. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  221932. {
  221933. jassert (*device == 0);
  221934. io_name_t classname;
  221935. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  221936. {
  221937. IOCFPlugInInterface** cfPlugInInterface = 0;
  221938. SInt32 score = 0;
  221939. if (IOCreatePlugInInterfaceForService (iod,
  221940. kIOHIDDeviceUserClientTypeID,
  221941. kIOCFPlugInInterfaceID,
  221942. &cfPlugInInterface,
  221943. &score) == kIOReturnSuccess)
  221944. {
  221945. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  221946. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  221947. device);
  221948. (void) hr;
  221949. (*cfPlugInInterface)->Release (cfPlugInInterface);
  221950. }
  221951. }
  221952. return *device != 0;
  221953. }
  221954. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  221955. {
  221956. if (queue != 0)
  221957. return true;
  221958. stop();
  221959. bool result = false;
  221960. io_object_t iod = getAppleRemoteDevice();
  221961. if (iod != 0)
  221962. {
  221963. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  221964. result = true;
  221965. else
  221966. stop();
  221967. IOObjectRelease (iod);
  221968. }
  221969. return result;
  221970. }
  221971. void AppleRemoteDevice::stop() throw()
  221972. {
  221973. if (queue != 0)
  221974. {
  221975. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  221976. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  221977. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  221978. queue = 0;
  221979. }
  221980. if (device != 0)
  221981. {
  221982. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  221983. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  221984. device = 0;
  221985. }
  221986. }
  221987. bool AppleRemoteDevice::isActive() const throw()
  221988. {
  221989. return queue != 0;
  221990. }
  221991. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  221992. {
  221993. if (result == kIOReturnSuccess)
  221994. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  221995. }
  221996. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  221997. {
  221998. Array <int> cookies;
  221999. CFArrayRef elements;
  222000. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  222001. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  222002. return false;
  222003. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  222004. {
  222005. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  222006. // get the cookie
  222007. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  222008. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  222009. continue;
  222010. long number;
  222011. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  222012. continue;
  222013. cookies.add ((int) number);
  222014. }
  222015. CFRelease (elements);
  222016. if ((*(IOHIDDeviceInterface**) device)
  222017. ->open ((IOHIDDeviceInterface**) device,
  222018. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  222019. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  222020. {
  222021. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  222022. if (queue != 0)
  222023. {
  222024. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  222025. for (int i = 0; i < cookies.size(); ++i)
  222026. {
  222027. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  222028. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  222029. }
  222030. CFRunLoopSourceRef eventSource;
  222031. if ((*(IOHIDQueueInterface**) queue)
  222032. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  222033. {
  222034. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  222035. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  222036. {
  222037. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  222038. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  222039. return true;
  222040. }
  222041. }
  222042. }
  222043. }
  222044. return false;
  222045. }
  222046. void AppleRemoteDevice::handleCallbackInternal()
  222047. {
  222048. int totalValues = 0;
  222049. AbsoluteTime nullTime = { 0, 0 };
  222050. char cookies [12];
  222051. int numCookies = 0;
  222052. while (numCookies < numElementsInArray (cookies))
  222053. {
  222054. IOHIDEventStruct e;
  222055. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  222056. break;
  222057. if ((int) e.elementCookie == 19)
  222058. {
  222059. remoteId = e.value;
  222060. buttonPressed (switched, false);
  222061. }
  222062. else
  222063. {
  222064. totalValues += e.value;
  222065. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  222066. }
  222067. }
  222068. cookies [numCookies++] = 0;
  222069. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  222070. static const char buttonPatterns[] =
  222071. {
  222072. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  222073. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  222074. 0x1f, 0x1d, 0x1c, 0x12, 0,
  222075. 0x1f, 0x1e, 0x1c, 0x12, 0,
  222076. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  222077. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  222078. 0x1f, 0x12, 0x04, 0x02, 0,
  222079. 0x1f, 0x12, 0x03, 0x02, 0,
  222080. 0x1f, 0x12, 0x1f, 0x12, 0,
  222081. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  222082. 19, 0
  222083. };
  222084. int buttonNum = (int) menuButton;
  222085. int i = 0;
  222086. while (i < numElementsInArray (buttonPatterns))
  222087. {
  222088. if (strcmp (cookies, buttonPatterns + i) == 0)
  222089. {
  222090. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  222091. break;
  222092. }
  222093. i += strlen (buttonPatterns + i) + 1;
  222094. ++buttonNum;
  222095. }
  222096. }
  222097. #endif
  222098. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  222099. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  222100. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222101. // compiled on its own).
  222102. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  222103. END_JUCE_NAMESPACE
  222104. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  222105. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  222106. {
  222107. CriticalSection* contextLock;
  222108. bool needsUpdate;
  222109. }
  222110. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  222111. - (bool) makeActive;
  222112. - (void) makeInactive;
  222113. - (void) reshape;
  222114. @end
  222115. @implementation ThreadSafeNSOpenGLView
  222116. - (id) initWithFrame: (NSRect) frameRect
  222117. pixelFormat: (NSOpenGLPixelFormat*) format
  222118. {
  222119. contextLock = new CriticalSection();
  222120. self = [super initWithFrame: frameRect pixelFormat: format];
  222121. if (self != nil)
  222122. [[NSNotificationCenter defaultCenter] addObserver: self
  222123. selector: @selector (_surfaceNeedsUpdate:)
  222124. name: NSViewGlobalFrameDidChangeNotification
  222125. object: self];
  222126. return self;
  222127. }
  222128. - (void) dealloc
  222129. {
  222130. [[NSNotificationCenter defaultCenter] removeObserver: self];
  222131. delete contextLock;
  222132. [super dealloc];
  222133. }
  222134. - (bool) makeActive
  222135. {
  222136. const ScopedLock sl (*contextLock);
  222137. if ([self openGLContext] == 0)
  222138. return false;
  222139. [[self openGLContext] makeCurrentContext];
  222140. if (needsUpdate)
  222141. {
  222142. [super update];
  222143. needsUpdate = false;
  222144. }
  222145. return true;
  222146. }
  222147. - (void) makeInactive
  222148. {
  222149. const ScopedLock sl (*contextLock);
  222150. [NSOpenGLContext clearCurrentContext];
  222151. }
  222152. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  222153. {
  222154. const ScopedLock sl (*contextLock);
  222155. needsUpdate = true;
  222156. }
  222157. - (void) update
  222158. {
  222159. const ScopedLock sl (*contextLock);
  222160. needsUpdate = true;
  222161. }
  222162. - (void) reshape
  222163. {
  222164. const ScopedLock sl (*contextLock);
  222165. needsUpdate = true;
  222166. }
  222167. @end
  222168. BEGIN_JUCE_NAMESPACE
  222169. class WindowedGLContext : public OpenGLContext
  222170. {
  222171. public:
  222172. WindowedGLContext (Component* const component,
  222173. const OpenGLPixelFormat& pixelFormat_,
  222174. NSOpenGLContext* sharedContext)
  222175. : renderContext (0),
  222176. pixelFormat (pixelFormat_)
  222177. {
  222178. jassert (component != 0);
  222179. NSOpenGLPixelFormatAttribute attribs [64];
  222180. int n = 0;
  222181. attribs[n++] = NSOpenGLPFADoubleBuffer;
  222182. attribs[n++] = NSOpenGLPFAAccelerated;
  222183. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  222184. attribs[n++] = NSOpenGLPFAColorSize;
  222185. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  222186. pixelFormat.greenBits,
  222187. pixelFormat.blueBits);
  222188. attribs[n++] = NSOpenGLPFAAlphaSize;
  222189. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  222190. attribs[n++] = NSOpenGLPFADepthSize;
  222191. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  222192. attribs[n++] = NSOpenGLPFAStencilSize;
  222193. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  222194. attribs[n++] = NSOpenGLPFAAccumSize;
  222195. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  222196. pixelFormat.accumulationBufferGreenBits,
  222197. pixelFormat.accumulationBufferBlueBits,
  222198. pixelFormat.accumulationBufferAlphaBits);
  222199. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  222200. attribs[n++] = NSOpenGLPFASampleBuffers;
  222201. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  222202. attribs[n++] = NSOpenGLPFAClosestPolicy;
  222203. attribs[n++] = NSOpenGLPFANoRecovery;
  222204. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  222205. NSOpenGLPixelFormat* format
  222206. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  222207. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  222208. pixelFormat: format];
  222209. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  222210. shareContext: sharedContext] autorelease];
  222211. const GLint swapInterval = 1;
  222212. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  222213. [view setOpenGLContext: renderContext];
  222214. [renderContext setView: view];
  222215. [format release];
  222216. viewHolder = new NSViewComponentInternal (view, component);
  222217. }
  222218. ~WindowedGLContext()
  222219. {
  222220. makeInactive();
  222221. [renderContext setView: nil];
  222222. delete viewHolder;
  222223. }
  222224. bool makeActive() const throw()
  222225. {
  222226. jassert (renderContext != 0);
  222227. [view makeActive];
  222228. return isActive();
  222229. }
  222230. bool makeInactive() const throw()
  222231. {
  222232. [view makeInactive];
  222233. return true;
  222234. }
  222235. bool isActive() const throw()
  222236. {
  222237. return [NSOpenGLContext currentContext] == renderContext;
  222238. }
  222239. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  222240. void* getRawContext() const throw() { return renderContext; }
  222241. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  222242. {
  222243. }
  222244. void swapBuffers()
  222245. {
  222246. [renderContext flushBuffer];
  222247. }
  222248. bool setSwapInterval (const int numFramesPerSwap)
  222249. {
  222250. [renderContext setValues: (const GLint*) &numFramesPerSwap
  222251. forParameter: NSOpenGLCPSwapInterval];
  222252. return true;
  222253. }
  222254. int getSwapInterval() const
  222255. {
  222256. GLint numFrames = 0;
  222257. [renderContext getValues: &numFrames
  222258. forParameter: NSOpenGLCPSwapInterval];
  222259. return numFrames;
  222260. }
  222261. void repaint()
  222262. {
  222263. // we need to invalidate the juce view that holds this gl view, to make it
  222264. // cause a repaint callback
  222265. NSView* v = (NSView*) viewHolder->view;
  222266. NSRect r = [v frame];
  222267. // bit of a bodge here.. if we only invalidate the area of the gl component,
  222268. // it's completely covered by the NSOpenGLView, so the OS throws away the
  222269. // repaint message, thus never causing our paint() callback, and never repainting
  222270. // the comp. So invalidating just a little bit around the edge helps..
  222271. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  222272. }
  222273. void* getNativeWindowHandle() const { return viewHolder->view; }
  222274. juce_UseDebuggingNewOperator
  222275. NSOpenGLContext* renderContext;
  222276. ThreadSafeNSOpenGLView* view;
  222277. private:
  222278. OpenGLPixelFormat pixelFormat;
  222279. NSViewComponentInternal* viewHolder;
  222280. WindowedGLContext (const WindowedGLContext&);
  222281. const WindowedGLContext& operator= (const WindowedGLContext&);
  222282. };
  222283. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  222284. const OpenGLPixelFormat& pixelFormat,
  222285. const OpenGLContext* const contextToShareWith)
  222286. {
  222287. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  222288. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  222289. if (c->renderContext == 0)
  222290. deleteAndZero (c);
  222291. return c;
  222292. }
  222293. void* OpenGLComponent::getNativeWindowHandle() const
  222294. {
  222295. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  222296. : 0;
  222297. }
  222298. void juce_glViewport (const int w, const int h)
  222299. {
  222300. glViewport (0, 0, w, h);
  222301. }
  222302. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  222303. OwnedArray <OpenGLPixelFormat>& results)
  222304. {
  222305. /* GLint attribs [64];
  222306. int n = 0;
  222307. attribs[n++] = AGL_RGBA;
  222308. attribs[n++] = AGL_DOUBLEBUFFER;
  222309. attribs[n++] = AGL_ACCELERATED;
  222310. attribs[n++] = AGL_NO_RECOVERY;
  222311. attribs[n++] = AGL_NONE;
  222312. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  222313. while (p != 0)
  222314. {
  222315. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  222316. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  222317. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  222318. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  222319. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  222320. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  222321. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  222322. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  222323. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  222324. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  222325. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  222326. results.add (pf);
  222327. p = aglNextPixelFormat (p);
  222328. }*/
  222329. //jassertfalse //xxx can't see how you do this in cocoa!
  222330. }
  222331. #endif
  222332. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  222333. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  222334. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222335. // compiled on its own).
  222336. #ifdef JUCE_INCLUDED_FILE
  222337. class JuceMainMenuHandler;
  222338. END_JUCE_NAMESPACE
  222339. using namespace JUCE_NAMESPACE;
  222340. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  222341. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222342. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  222343. #else
  222344. @interface JuceMenuCallback : NSObject
  222345. #endif
  222346. {
  222347. JuceMainMenuHandler* owner;
  222348. }
  222349. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  222350. - (void) dealloc;
  222351. - (void) menuItemInvoked: (id) menu;
  222352. - (void) menuNeedsUpdate: (NSMenu*) menu;
  222353. @end
  222354. BEGIN_JUCE_NAMESPACE
  222355. class JuceMainMenuHandler : private MenuBarModelListener,
  222356. private DeletedAtShutdown
  222357. {
  222358. public:
  222359. static JuceMainMenuHandler* instance;
  222360. JuceMainMenuHandler() throw()
  222361. : currentModel (0),
  222362. lastUpdateTime (0)
  222363. {
  222364. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  222365. }
  222366. ~JuceMainMenuHandler() throw()
  222367. {
  222368. setMenu (0);
  222369. jassert (instance == this);
  222370. instance = 0;
  222371. [callback release];
  222372. }
  222373. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  222374. {
  222375. if (currentModel != newMenuBarModel)
  222376. {
  222377. if (currentModel != 0)
  222378. currentModel->removeListener (this);
  222379. currentModel = newMenuBarModel;
  222380. if (currentModel != 0)
  222381. currentModel->addListener (this);
  222382. menuBarItemsChanged (0);
  222383. }
  222384. }
  222385. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  222386. const String& name, const int menuId, const int tag)
  222387. {
  222388. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  222389. action: nil
  222390. keyEquivalent: @""];
  222391. [item setTag: tag];
  222392. NSMenu* sub = createMenu (child, name, menuId, tag);
  222393. [parent setSubmenu: sub forItem: item];
  222394. [sub setAutoenablesItems: false];
  222395. [sub release];
  222396. }
  222397. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  222398. const String& name, const int menuId, const int tag)
  222399. {
  222400. [parentItem setTag: tag];
  222401. NSMenu* menu = [parentItem submenu];
  222402. [menu setTitle: juceStringToNS (name)];
  222403. while ([menu numberOfItems] > 0)
  222404. [menu removeItemAtIndex: 0];
  222405. PopupMenu::MenuItemIterator iter (menuToCopy);
  222406. while (iter.next())
  222407. addMenuItem (iter, menu, menuId, tag);
  222408. [menu setAutoenablesItems: false];
  222409. [menu update];
  222410. }
  222411. void menuBarItemsChanged (MenuBarModel*)
  222412. {
  222413. lastUpdateTime = Time::getMillisecondCounter();
  222414. StringArray menuNames;
  222415. if (currentModel != 0)
  222416. menuNames = currentModel->getMenuBarNames();
  222417. NSMenu* menuBar = [NSApp mainMenu];
  222418. while ([menuBar numberOfItems] > 1 + menuNames.size())
  222419. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  222420. int menuId = 1;
  222421. for (int i = 0; i < menuNames.size(); ++i)
  222422. {
  222423. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  222424. if (i >= [menuBar numberOfItems] - 1)
  222425. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  222426. else
  222427. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  222428. }
  222429. }
  222430. static void flashMenuBar (NSMenu* menu)
  222431. {
  222432. const unichar f35Key = NSF35FunctionKey;
  222433. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  222434. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  222435. action: nil
  222436. keyEquivalent: f35String];
  222437. [item setTarget: nil];
  222438. [menu insertItem: item atIndex: [menu numberOfItems]];
  222439. [item release];
  222440. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  222441. location: NSZeroPoint
  222442. modifierFlags: NSCommandKeyMask
  222443. timestamp: 0
  222444. windowNumber: 0
  222445. context: [NSGraphicsContext currentContext]
  222446. characters: f35String
  222447. charactersIgnoringModifiers: f35String
  222448. isARepeat: NO
  222449. keyCode: 0];
  222450. [menu performKeyEquivalent: f35Event];
  222451. [menu removeItem: item];
  222452. }
  222453. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  222454. {
  222455. for (int i = [menu numberOfItems]; --i >= 0;)
  222456. {
  222457. NSMenuItem* m = [menu itemAtIndex: i];
  222458. if ([m tag] == info.commandID)
  222459. return m;
  222460. if ([m submenu] != 0)
  222461. {
  222462. NSMenuItem* found = findMenuItem ([m submenu], info);
  222463. if (found != 0)
  222464. return found;
  222465. }
  222466. }
  222467. return 0;
  222468. }
  222469. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  222470. {
  222471. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  222472. if (item != 0)
  222473. flashMenuBar ([item menu]);
  222474. }
  222475. void updateMenus()
  222476. {
  222477. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  222478. menuBarItemsChanged (0);
  222479. }
  222480. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  222481. {
  222482. if (currentModel != 0)
  222483. {
  222484. if (commandManager != 0)
  222485. {
  222486. ApplicationCommandTarget::InvocationInfo info (commandId);
  222487. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  222488. commandManager->invoke (info, true);
  222489. }
  222490. currentModel->menuItemSelected (commandId, topLevelIndex);
  222491. }
  222492. }
  222493. MenuBarModel* currentModel;
  222494. uint32 lastUpdateTime;
  222495. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  222496. const int topLevelMenuId, const int topLevelIndex)
  222497. {
  222498. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  222499. if (text == 0)
  222500. text = @"";
  222501. if (iter.isSeparator)
  222502. {
  222503. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  222504. }
  222505. else if (iter.isSectionHeader)
  222506. {
  222507. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222508. action: nil
  222509. keyEquivalent: @""];
  222510. [item setEnabled: false];
  222511. }
  222512. else if (iter.subMenu != 0)
  222513. {
  222514. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222515. action: nil
  222516. keyEquivalent: @""];
  222517. [item setTag: iter.itemId];
  222518. [item setEnabled: iter.isEnabled];
  222519. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  222520. [sub setDelegate: nil];
  222521. [menuToAddTo setSubmenu: sub forItem: item];
  222522. }
  222523. else
  222524. {
  222525. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  222526. action: @selector (menuItemInvoked:)
  222527. keyEquivalent: @""];
  222528. [item setTag: iter.itemId];
  222529. [item setEnabled: iter.isEnabled];
  222530. [item setState: iter.isTicked ? NSOnState : NSOffState];
  222531. [item setTarget: (id) callback];
  222532. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  222533. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  222534. [item setRepresentedObject: info];
  222535. if (iter.commandManager != 0)
  222536. {
  222537. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  222538. ->getKeyPressesAssignedToCommand (iter.itemId));
  222539. if (keyPresses.size() > 0)
  222540. {
  222541. const KeyPress& kp = keyPresses.getReference(0);
  222542. juce_wchar key = kp.getTextCharacter();
  222543. if (kp.getKeyCode() == KeyPress::backspaceKey)
  222544. key = NSBackspaceCharacter;
  222545. else if (kp.getKeyCode() == KeyPress::deleteKey)
  222546. key = NSDeleteCharacter;
  222547. else if (key == 0)
  222548. key = (juce_wchar) kp.getKeyCode();
  222549. unsigned int mods = 0;
  222550. if (kp.getModifiers().isShiftDown())
  222551. mods |= NSShiftKeyMask;
  222552. if (kp.getModifiers().isCtrlDown())
  222553. mods |= NSControlKeyMask;
  222554. if (kp.getModifiers().isAltDown())
  222555. mods |= NSAlternateKeyMask;
  222556. if (kp.getModifiers().isCommandDown())
  222557. mods |= NSCommandKeyMask;
  222558. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  222559. [item setKeyEquivalentModifierMask: mods];
  222560. }
  222561. }
  222562. }
  222563. }
  222564. JuceMenuCallback* callback;
  222565. private:
  222566. NSMenu* createMenu (const PopupMenu menu,
  222567. const String& menuName,
  222568. const int topLevelMenuId,
  222569. const int topLevelIndex)
  222570. {
  222571. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  222572. [m setAutoenablesItems: false];
  222573. [m setDelegate: callback];
  222574. PopupMenu::MenuItemIterator iter (menu);
  222575. while (iter.next())
  222576. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  222577. [m update];
  222578. return m;
  222579. }
  222580. };
  222581. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  222582. END_JUCE_NAMESPACE
  222583. @implementation JuceMenuCallback
  222584. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  222585. {
  222586. [super init];
  222587. owner = owner_;
  222588. return self;
  222589. }
  222590. - (void) dealloc
  222591. {
  222592. [super dealloc];
  222593. }
  222594. - (void) menuItemInvoked: (id) menu
  222595. {
  222596. NSMenuItem* item = (NSMenuItem*) menu;
  222597. if ([[item representedObject] isKindOfClass: [NSArray class]])
  222598. {
  222599. NSArray* info = (NSArray*) [item representedObject];
  222600. owner->invoke ([item tag],
  222601. (ApplicationCommandManager*) (pointer_sized_int)
  222602. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  222603. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  222604. }
  222605. }
  222606. - (void) menuNeedsUpdate: (NSMenu*) menu;
  222607. {
  222608. if (JuceMainMenuHandler::instance != 0)
  222609. JuceMainMenuHandler::instance->updateMenus();
  222610. }
  222611. @end
  222612. BEGIN_JUCE_NAMESPACE
  222613. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  222614. const PopupMenu* extraItems)
  222615. {
  222616. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  222617. {
  222618. PopupMenu::MenuItemIterator iter (*extraItems);
  222619. while (iter.next())
  222620. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  222621. [menu addItem: [NSMenuItem separatorItem]];
  222622. }
  222623. NSMenuItem* item;
  222624. // Services...
  222625. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  222626. action: nil keyEquivalent: @""];
  222627. [menu addItem: item];
  222628. [item release];
  222629. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  222630. [menu setSubmenu: servicesMenu forItem: item];
  222631. [NSApp setServicesMenu: servicesMenu];
  222632. [servicesMenu release];
  222633. [menu addItem: [NSMenuItem separatorItem]];
  222634. // Hide + Show stuff...
  222635. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  222636. action: @selector (hide:) keyEquivalent: @"h"];
  222637. [item setTarget: NSApp];
  222638. [menu addItem: item];
  222639. [item release];
  222640. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  222641. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  222642. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  222643. [item setTarget: NSApp];
  222644. [menu addItem: item];
  222645. [item release];
  222646. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  222647. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  222648. [item setTarget: NSApp];
  222649. [menu addItem: item];
  222650. [item release];
  222651. [menu addItem: [NSMenuItem separatorItem]];
  222652. // Quit item....
  222653. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  222654. action: @selector (terminate:) keyEquivalent: @"q"];
  222655. [item setTarget: NSApp];
  222656. [menu addItem: item];
  222657. [item release];
  222658. return menu;
  222659. }
  222660. // Since our app has no NIB, this initialises a standard app menu...
  222661. static void rebuildMainMenu (const PopupMenu* extraItems)
  222662. {
  222663. // this can't be used in a plugin!
  222664. jassert (JUCEApplication::getInstance() != 0);
  222665. if (JUCEApplication::getInstance() != 0)
  222666. {
  222667. const ScopedAutoReleasePool pool;
  222668. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  222669. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  222670. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  222671. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  222672. [mainMenu setSubmenu: appMenu forItem: item];
  222673. [NSApp setMainMenu: mainMenu];
  222674. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  222675. [appMenu release];
  222676. [mainMenu release];
  222677. }
  222678. }
  222679. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  222680. const PopupMenu* extraAppleMenuItems) throw()
  222681. {
  222682. if (getMacMainMenu() != newMenuBarModel)
  222683. {
  222684. const ScopedAutoReleasePool pool;
  222685. if (newMenuBarModel == 0)
  222686. {
  222687. delete JuceMainMenuHandler::instance;
  222688. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  222689. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  222690. extraAppleMenuItems = 0;
  222691. }
  222692. else
  222693. {
  222694. if (JuceMainMenuHandler::instance == 0)
  222695. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  222696. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  222697. }
  222698. }
  222699. rebuildMainMenu (extraAppleMenuItems);
  222700. if (newMenuBarModel != 0)
  222701. newMenuBarModel->menuItemsChanged();
  222702. }
  222703. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  222704. {
  222705. return JuceMainMenuHandler::instance != 0
  222706. ? JuceMainMenuHandler::instance->currentModel : 0;
  222707. }
  222708. void initialiseMainMenu()
  222709. {
  222710. if (JUCEApplication::getInstance() != 0) // only needed in an app
  222711. rebuildMainMenu (0);
  222712. }
  222713. #endif
  222714. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  222715. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  222716. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222717. // compiled on its own).
  222718. #ifdef JUCE_INCLUDED_FILE
  222719. END_JUCE_NAMESPACE
  222720. using namespace JUCE_NAMESPACE;
  222721. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  222722. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  222723. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  222724. #else
  222725. @interface JuceFileChooserDelegate : NSObject
  222726. #endif
  222727. {
  222728. StringArray* filters;
  222729. }
  222730. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  222731. - (void) dealloc;
  222732. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  222733. @end
  222734. @implementation JuceFileChooserDelegate
  222735. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  222736. {
  222737. [super init];
  222738. filters = filters_;
  222739. return self;
  222740. }
  222741. - (void) dealloc
  222742. {
  222743. delete filters;
  222744. [super dealloc];
  222745. }
  222746. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  222747. {
  222748. const String fname (nsStringToJuce (filename));
  222749. for (int i = filters->size(); --i >= 0;)
  222750. if (fname.matchesWildcard ((*filters)[i], true))
  222751. return true;
  222752. return File (fname).isDirectory();
  222753. }
  222754. @end
  222755. BEGIN_JUCE_NAMESPACE
  222756. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  222757. const String& title,
  222758. const File& currentFileOrDirectory,
  222759. const String& filter,
  222760. bool selectsDirectory,
  222761. bool isSaveDialogue,
  222762. bool warnAboutOverwritingExistingFiles,
  222763. bool selectMultipleFiles,
  222764. FilePreviewComponent* extraInfoComponent)
  222765. {
  222766. const ScopedAutoReleasePool pool;
  222767. StringArray* filters = new StringArray();
  222768. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  222769. filters->trim();
  222770. filters->removeEmptyStrings();
  222771. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  222772. [delegate autorelease];
  222773. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  222774. : [NSOpenPanel openPanel];
  222775. [panel setTitle: juceStringToNS (title)];
  222776. if (! isSaveDialogue)
  222777. {
  222778. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222779. [openPanel setCanChooseDirectories: selectsDirectory];
  222780. [openPanel setCanChooseFiles: ! selectsDirectory];
  222781. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  222782. }
  222783. [panel setDelegate: delegate];
  222784. String directory, filename;
  222785. if (currentFileOrDirectory.isDirectory())
  222786. {
  222787. directory = currentFileOrDirectory.getFullPathName();
  222788. }
  222789. else
  222790. {
  222791. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  222792. filename = currentFileOrDirectory.getFileName();
  222793. }
  222794. if ([panel runModalForDirectory: juceStringToNS (directory)
  222795. file: juceStringToNS (filename)]
  222796. == NSOKButton)
  222797. {
  222798. if (isSaveDialogue)
  222799. {
  222800. results.add (new File (nsStringToJuce ([panel filename])));
  222801. }
  222802. else
  222803. {
  222804. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  222805. NSArray* urls = [openPanel filenames];
  222806. for (unsigned int i = 0; i < [urls count]; ++i)
  222807. {
  222808. NSString* f = [urls objectAtIndex: i];
  222809. results.add (new File (nsStringToJuce (f)));
  222810. }
  222811. }
  222812. }
  222813. [panel setDelegate: nil];
  222814. }
  222815. #endif
  222816. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  222817. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  222818. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  222819. // compiled on its own).
  222820. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  222821. #define theMovie ((QTMovie*) movie)
  222822. QuickTimeMovieComponent::QuickTimeMovieComponent()
  222823. : movie (0)
  222824. {
  222825. setOpaque (true);
  222826. setVisible (true);
  222827. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  222828. setView (view);
  222829. }
  222830. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  222831. {
  222832. closeMovie();
  222833. setView (0);
  222834. }
  222835. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  222836. {
  222837. return true;
  222838. }
  222839. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  222840. {
  222841. // unfortunately, QTMovie objects can only be created on the main thread..
  222842. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  222843. QTMovie* movie = 0;
  222844. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  222845. if (fin != 0)
  222846. {
  222847. movieFile = fin->getFile();
  222848. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  222849. error: nil];
  222850. }
  222851. else
  222852. {
  222853. MemoryBlock temp;
  222854. movieStream->readIntoMemoryBlock (temp);
  222855. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  222856. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  222857. {
  222858. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  222859. length: temp.getSize()]
  222860. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  222861. MIMEType: @""]
  222862. error: nil];
  222863. if (movie != 0)
  222864. break;
  222865. }
  222866. }
  222867. return movie;
  222868. }
  222869. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  222870. const bool controllerVisible)
  222871. {
  222872. closeMovie();
  222873. if (getPeer() == 0)
  222874. {
  222875. // To open a movie, this component must be visible inside a functioning window, so that
  222876. // the QT control can be assigned to the window.
  222877. jassertfalse
  222878. return false;
  222879. }
  222880. movie = openMovieFromStream (movieStream, movieFile);
  222881. [theMovie retain];
  222882. QTMovieView* view = (QTMovieView*) getView();
  222883. [view setMovie: theMovie];
  222884. [view setControllerVisible: controllerVisible];
  222885. setLooping (looping);
  222886. return movie != nil;
  222887. }
  222888. void QuickTimeMovieComponent::closeMovie()
  222889. {
  222890. stop();
  222891. QTMovieView* view = (QTMovieView*) getView();
  222892. [view setMovie: nil];
  222893. [theMovie release];
  222894. movie = 0;
  222895. movieFile = File::nonexistent;
  222896. }
  222897. bool QuickTimeMovieComponent::isMovieOpen() const
  222898. {
  222899. return movie != nil;
  222900. }
  222901. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  222902. {
  222903. return movieFile;
  222904. }
  222905. void QuickTimeMovieComponent::play()
  222906. {
  222907. [theMovie play];
  222908. }
  222909. void QuickTimeMovieComponent::stop()
  222910. {
  222911. [theMovie stop];
  222912. }
  222913. bool QuickTimeMovieComponent::isPlaying() const
  222914. {
  222915. return movie != 0 && [theMovie rate] != 0;
  222916. }
  222917. void QuickTimeMovieComponent::setPosition (const double seconds)
  222918. {
  222919. if (movie != 0)
  222920. {
  222921. QTTime t;
  222922. t.timeValue = (uint64) (100000.0 * seconds);
  222923. t.timeScale = 100000;
  222924. t.flags = 0;
  222925. [theMovie setCurrentTime: t];
  222926. }
  222927. }
  222928. double QuickTimeMovieComponent::getPosition() const
  222929. {
  222930. if (movie == 0)
  222931. return 0.0;
  222932. QTTime t = [theMovie currentTime];
  222933. return t.timeValue / (double) t.timeScale;
  222934. }
  222935. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  222936. {
  222937. [theMovie setRate: newSpeed];
  222938. }
  222939. double QuickTimeMovieComponent::getMovieDuration() const
  222940. {
  222941. if (movie == 0)
  222942. return 0.0;
  222943. QTTime t = [theMovie duration];
  222944. return t.timeValue / (double) t.timeScale;
  222945. }
  222946. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  222947. {
  222948. looping = shouldLoop;
  222949. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  222950. forKey: QTMovieLoopsAttribute];
  222951. }
  222952. bool QuickTimeMovieComponent::isLooping() const
  222953. {
  222954. return looping;
  222955. }
  222956. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  222957. {
  222958. [theMovie setVolume: newVolume];
  222959. }
  222960. float QuickTimeMovieComponent::getMovieVolume() const
  222961. {
  222962. return movie != 0 ? [theMovie volume] : 0.0f;
  222963. }
  222964. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  222965. {
  222966. width = 0;
  222967. height = 0;
  222968. if (movie != 0)
  222969. {
  222970. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  222971. width = s.width;
  222972. height = s.height;
  222973. }
  222974. }
  222975. void QuickTimeMovieComponent::paint (Graphics& g)
  222976. {
  222977. if (movie == 0)
  222978. g.fillAll (Colours::black);
  222979. }
  222980. bool QuickTimeMovieComponent::isControllerVisible() const
  222981. {
  222982. return controllerVisible;
  222983. }
  222984. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  222985. const bool isControllerVisible)
  222986. {
  222987. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  222988. movieFile = movieFile_;
  222989. return ok;
  222990. }
  222991. void QuickTimeMovieComponent::goToStart()
  222992. {
  222993. setPosition (0.0);
  222994. }
  222995. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  222996. const RectanglePlacement& placement)
  222997. {
  222998. int normalWidth, normalHeight;
  222999. getMovieNormalSize (normalWidth, normalHeight);
  223000. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  223001. {
  223002. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  223003. placement.applyTo (x, y, w, h,
  223004. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  223005. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  223006. if (w > 0 && h > 0)
  223007. {
  223008. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  223009. roundDoubleToInt (w), roundDoubleToInt (h));
  223010. }
  223011. }
  223012. else
  223013. {
  223014. setBounds (spaceToFitWithin);
  223015. }
  223016. }
  223017. #if ! (JUCE_MAC && JUCE_64BIT)
  223018. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  223019. {
  223020. if (movieStream == 0)
  223021. return false;
  223022. File file;
  223023. QTMovie* movie = openMovieFromStream (movieStream, file);
  223024. if (movie != nil)
  223025. result = [movie quickTimeMovie];
  223026. return movie != nil;
  223027. }
  223028. #endif
  223029. #endif
  223030. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  223031. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  223032. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223033. // compiled on its own).
  223034. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  223035. END_JUCE_NAMESPACE
  223036. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  223037. @interface OpenDiskDevice : NSObject
  223038. {
  223039. DRDevice* device;
  223040. NSMutableArray* tracks;
  223041. }
  223042. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  223043. - (void) dealloc;
  223044. - (bool) isDiskPresent;
  223045. - (int) getNumAvailableAudioBlocks;
  223046. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  223047. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  223048. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  223049. @end
  223050. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  223051. @interface AudioTrackProducer : NSObject
  223052. {
  223053. JUCE_NAMESPACE::AudioSource* source;
  223054. int readPosition, lengthInFrames;
  223055. }
  223056. - (AudioTrackProducer*) init: (int) lengthInFrames;
  223057. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  223058. - (void) dealloc;
  223059. - (void) setupTrackProperties: (DRTrack*) track;
  223060. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  223061. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  223062. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  223063. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  223064. toMedia:(NSDictionary*)mediaInfo;
  223065. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  223066. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  223067. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  223068. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  223069. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  223070. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  223071. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  223072. ioFlags:(uint32_t*)flags;
  223073. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  223074. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  223075. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  223076. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  223077. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  223078. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  223079. ioFlags:(uint32_t*)flags;
  223080. @end
  223081. @implementation OpenDiskDevice
  223082. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  223083. {
  223084. [super init];
  223085. device = device_;
  223086. tracks = [[NSMutableArray alloc] init];
  223087. return self;
  223088. }
  223089. - (void) dealloc
  223090. {
  223091. [tracks release];
  223092. [super dealloc];
  223093. }
  223094. - (bool) isDiskPresent
  223095. {
  223096. return [device isValid]
  223097. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  223098. isEqualTo: DRDeviceMediaStateMediaPresent];
  223099. }
  223100. - (int) getNumAvailableAudioBlocks
  223101. {
  223102. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  223103. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  223104. }
  223105. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  223106. {
  223107. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  223108. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  223109. [p setupTrackProperties: t];
  223110. [tracks addObject: t];
  223111. [t release];
  223112. [p release];
  223113. }
  223114. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  223115. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  223116. {
  223117. DRBurn* burn = [DRBurn burnForDevice: device];
  223118. if (! [device acquireExclusiveAccess])
  223119. {
  223120. *error = "Couldn't open or write to the CD device";
  223121. return;
  223122. }
  223123. [device acquireMediaReservation];
  223124. NSMutableDictionary* d = [[burn properties] mutableCopy];
  223125. [d autorelease];
  223126. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  223127. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  223128. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  223129. forKey: DRBurnCompletionActionKey];
  223130. [burn setProperties: d];
  223131. [burn writeLayout: tracks];
  223132. for (;;)
  223133. {
  223134. JUCE_NAMESPACE::Thread::sleep (300);
  223135. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  223136. if (listener != 0 && listener->audioCDBurnProgress (progress))
  223137. {
  223138. [burn abort];
  223139. *error = "User cancelled the write operation";
  223140. break;
  223141. }
  223142. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  223143. {
  223144. *error = "Write operation failed";
  223145. break;
  223146. }
  223147. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  223148. {
  223149. break;
  223150. }
  223151. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  223152. objectForKey: DRErrorStatusErrorStringKey];
  223153. if ([err length] > 0)
  223154. {
  223155. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  223156. break;
  223157. }
  223158. }
  223159. [device releaseMediaReservation];
  223160. [device releaseExclusiveAccess];
  223161. }
  223162. @end
  223163. @implementation AudioTrackProducer
  223164. - (AudioTrackProducer*) init: (int) lengthInFrames_
  223165. {
  223166. lengthInFrames = lengthInFrames_;
  223167. readPosition = 0;
  223168. return self;
  223169. }
  223170. - (void) setupTrackProperties: (DRTrack*) track
  223171. {
  223172. NSMutableDictionary* p = [[track properties] mutableCopy];
  223173. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  223174. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  223175. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  223176. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  223177. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  223178. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  223179. [track setProperties: p];
  223180. [p release];
  223181. }
  223182. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  223183. {
  223184. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  223185. if (s != nil)
  223186. s->source = source_;
  223187. return s;
  223188. }
  223189. - (void) dealloc
  223190. {
  223191. if (source != 0)
  223192. {
  223193. source->releaseResources();
  223194. delete source;
  223195. }
  223196. [super dealloc];
  223197. }
  223198. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  223199. {
  223200. }
  223201. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  223202. {
  223203. return true;
  223204. }
  223205. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  223206. {
  223207. return lengthInFrames;
  223208. }
  223209. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  223210. toMedia: (NSDictionary*) mediaInfo
  223211. {
  223212. if (source != 0)
  223213. source->prepareToPlay (44100 / 75, 44100);
  223214. readPosition = 0;
  223215. return true;
  223216. }
  223217. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  223218. {
  223219. if (source != 0)
  223220. source->prepareToPlay (44100 / 75, 44100);
  223221. return true;
  223222. }
  223223. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  223224. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  223225. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  223226. {
  223227. if (source != 0)
  223228. {
  223229. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  223230. if (numSamples > 0)
  223231. {
  223232. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  223233. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  223234. info.buffer = &tempBuffer;
  223235. info.startSample = 0;
  223236. info.numSamples = numSamples;
  223237. source->getNextAudioBlock (info);
  223238. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  223239. buffer, numSamples, 4);
  223240. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  223241. buffer + 2, numSamples, 4);
  223242. readPosition += numSamples;
  223243. }
  223244. return numSamples * 4;
  223245. }
  223246. return 0;
  223247. }
  223248. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  223249. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  223250. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  223251. ioFlags: (uint32_t*) flags
  223252. {
  223253. zeromem (buffer, bufferLength);
  223254. return bufferLength;
  223255. }
  223256. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  223257. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  223258. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  223259. {
  223260. return true;
  223261. }
  223262. @end
  223263. BEGIN_JUCE_NAMESPACE
  223264. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  223265. : internal (0)
  223266. {
  223267. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  223268. internal = (void*) dev;
  223269. }
  223270. AudioCDBurner::~AudioCDBurner()
  223271. {
  223272. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223273. if (dev != 0)
  223274. [dev release];
  223275. }
  223276. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  223277. {
  223278. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  223279. if (b->internal == 0)
  223280. deleteAndZero (b);
  223281. return b;
  223282. }
  223283. static NSArray* findDiskBurnerDevices()
  223284. {
  223285. NSMutableArray* results = [NSMutableArray array];
  223286. NSArray* devs = [DRDevice devices];
  223287. if (devs != 0)
  223288. {
  223289. int num = [devs count];
  223290. int i;
  223291. for (i = 0; i < num; ++i)
  223292. {
  223293. NSDictionary* dic = [[devs objectAtIndex: i] info];
  223294. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  223295. if (name != nil)
  223296. [results addObject: name];
  223297. }
  223298. }
  223299. return results;
  223300. }
  223301. const StringArray AudioCDBurner::findAvailableDevices()
  223302. {
  223303. NSArray* names = findDiskBurnerDevices();
  223304. StringArray s;
  223305. for (unsigned int i = 0; i < [names count]; ++i)
  223306. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  223307. return s;
  223308. }
  223309. bool AudioCDBurner::isDiskPresent() const
  223310. {
  223311. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223312. return dev != 0 && [dev isDiskPresent];
  223313. }
  223314. int AudioCDBurner::getNumAvailableAudioBlocks() const
  223315. {
  223316. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223317. return [dev getNumAvailableAudioBlocks];
  223318. }
  223319. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  223320. {
  223321. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223322. if (dev != 0)
  223323. {
  223324. [dev addSourceTrack: source numSamples: numSamps];
  223325. return true;
  223326. }
  223327. return false;
  223328. }
  223329. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  223330. const bool ejectDiscAfterwards,
  223331. const bool peformFakeBurnForTesting)
  223332. {
  223333. String error ("Couldn't open or write to the CD device");
  223334. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  223335. if (dev != 0)
  223336. {
  223337. error = String::empty;
  223338. [dev burn: listener
  223339. errorString: &error
  223340. ejectAfterwards: ejectDiscAfterwards
  223341. isFake: peformFakeBurnForTesting];
  223342. }
  223343. return error;
  223344. }
  223345. void AudioCDReader::ejectDisk()
  223346. {
  223347. const ScopedAutoReleasePool p;
  223348. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  223349. }
  223350. #endif
  223351. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  223352. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  223353. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223354. // compiled on its own).
  223355. #ifdef JUCE_INCLUDED_FILE
  223356. class FontHelper
  223357. {
  223358. NSFont* font;
  223359. public:
  223360. String name;
  223361. bool isBold, isItalic, needsItalicTransform;
  223362. float fontSize, totalSize, ascent;
  223363. int refCount;
  223364. NSMutableDictionary* attributes;
  223365. FontHelper (const String& name_,
  223366. const bool bold_,
  223367. const bool italic_,
  223368. const float size_)
  223369. : font (0),
  223370. name (name_),
  223371. isBold (bold_),
  223372. isItalic (italic_),
  223373. needsItalicTransform (false),
  223374. fontSize (size_),
  223375. refCount (1)
  223376. {
  223377. attributes = [[NSMutableDictionary dictionaryWithObject: [NSNumber numberWithInt: 0]
  223378. forKey: NSLigatureAttributeName] retain];
  223379. font = [NSFont fontWithName: juceStringToNS (name_) size: size_];
  223380. if (italic_)
  223381. {
  223382. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSItalicFontMask];
  223383. if (newFont == font)
  223384. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  223385. font = newFont;
  223386. }
  223387. if (bold_)
  223388. font = [[NSFontManager sharedFontManager] convertFont: font toHaveTrait: NSBoldFontMask];
  223389. [font retain];
  223390. ascent = fabsf ([font ascender]);
  223391. totalSize = ascent + fabsf ([font descender]);
  223392. }
  223393. ~FontHelper()
  223394. {
  223395. [font release];
  223396. [attributes release];
  223397. }
  223398. bool getPathAndKerning (const juce_wchar char1,
  223399. const juce_wchar char2,
  223400. Path* path,
  223401. float& kerning,
  223402. float* ascent,
  223403. float* descent)
  223404. {
  223405. const ScopedAutoReleasePool pool;
  223406. if (font == 0
  223407. || ! [[font coveredCharacterSet] longCharacterIsMember: (UTF32Char) char1])
  223408. return false;
  223409. String chars;
  223410. chars << ' ' << char1 << char2;
  223411. NSTextStorage* textStorage = [[[NSTextStorage alloc] initWithString: juceStringToNS (chars)
  223412. attributes: attributes] autorelease];
  223413. NSLayoutManager* layoutManager = [[[NSLayoutManager alloc] init] autorelease];
  223414. NSTextContainer* textContainer = [[[NSTextContainer alloc] init] autorelease];
  223415. [layoutManager addTextContainer: textContainer];
  223416. [textStorage addLayoutManager: layoutManager];
  223417. [textStorage setFont: font];
  223418. unsigned int glyphIndex = [layoutManager glyphRangeForCharacterRange: NSMakeRange (1, 1)
  223419. actualCharacterRange: 0].location;
  223420. NSPoint p1 = [layoutManager locationForGlyphAtIndex: glyphIndex];
  223421. NSPoint p2 = [layoutManager locationForGlyphAtIndex: glyphIndex + 1];
  223422. kerning = p2.x - p1.x;
  223423. if (ascent != 0)
  223424. *ascent = this->ascent;
  223425. if (descent != 0)
  223426. *descent = fabsf ([font descender]);
  223427. if (path != 0)
  223428. {
  223429. NSBezierPath* bez = [NSBezierPath bezierPath];
  223430. [bez moveToPoint: NSMakePoint (0, 0)];
  223431. [bez appendBezierPathWithGlyph: [layoutManager glyphAtIndex: glyphIndex]
  223432. inFont: font];
  223433. for (int i = 0; i < [bez elementCount]; ++i)
  223434. {
  223435. NSPoint p[3];
  223436. switch ([bez elementAtIndex: i associatedPoints: p])
  223437. {
  223438. case NSMoveToBezierPathElement:
  223439. path->startNewSubPath (p[0].x, -p[0].y);
  223440. break;
  223441. case NSLineToBezierPathElement:
  223442. path->lineTo (p[0].x, -p[0].y);
  223443. break;
  223444. case NSCurveToBezierPathElement:
  223445. path->cubicTo (p[0].x, -p[0].y, p[1].x, -p[1].y, p[2].x, -p[2].y);
  223446. break;
  223447. case NSClosePathBezierPathElement:
  223448. path->closeSubPath();
  223449. break;
  223450. default:
  223451. jassertfalse
  223452. break;
  223453. }
  223454. }
  223455. if (needsItalicTransform)
  223456. path->applyTransform (AffineTransform::identity.sheared (-0.15, 0));
  223457. }
  223458. return kerning != 0;
  223459. }
  223460. juce_wchar getDefaultChar()
  223461. {
  223462. return 0;
  223463. }
  223464. };
  223465. class FontHelperCache : public Timer,
  223466. public DeletedAtShutdown
  223467. {
  223468. VoidArray cache;
  223469. public:
  223470. FontHelperCache()
  223471. {
  223472. }
  223473. ~FontHelperCache()
  223474. {
  223475. for (int i = cache.size(); --i >= 0;)
  223476. {
  223477. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223478. delete f;
  223479. }
  223480. clearSingletonInstance();
  223481. }
  223482. FontHelper* getFont (const String& name,
  223483. const bool bold,
  223484. const bool italic,
  223485. const float size = 1024)
  223486. {
  223487. for (int i = cache.size(); --i >= 0;)
  223488. {
  223489. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223490. if (f->name == name
  223491. && f->isBold == bold
  223492. && f->isItalic == italic
  223493. && f->fontSize == size)
  223494. {
  223495. f->refCount++;
  223496. return f;
  223497. }
  223498. }
  223499. FontHelper* const f = new FontHelper (name, bold, italic, size);
  223500. cache.add (f);
  223501. return f;
  223502. }
  223503. void releaseFont (FontHelper* f)
  223504. {
  223505. for (int i = cache.size(); --i >= 0;)
  223506. {
  223507. FontHelper* const f2 = (FontHelper*) cache.getUnchecked(i);
  223508. if (f == f2)
  223509. {
  223510. f->refCount--;
  223511. if (f->refCount == 0)
  223512. startTimer (5000);
  223513. break;
  223514. }
  223515. }
  223516. }
  223517. void timerCallback()
  223518. {
  223519. stopTimer();
  223520. for (int i = cache.size(); --i >= 0;)
  223521. {
  223522. FontHelper* const f = (FontHelper*) cache.getUnchecked(i);
  223523. if (f->refCount == 0)
  223524. {
  223525. cache.remove (i);
  223526. delete f;
  223527. }
  223528. }
  223529. if (cache.size() == 0)
  223530. delete this;
  223531. }
  223532. juce_DeclareSingleton_SingleThreaded_Minimal (FontHelperCache)
  223533. };
  223534. juce_ImplementSingleton_SingleThreaded (FontHelperCache)
  223535. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  223536. bool bold,
  223537. bool italic,
  223538. bool addAllGlyphsToFont) throw()
  223539. {
  223540. // This method is only safe to be called from the normal UI thread..
  223541. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223542. FontHelper* const helper = FontHelperCache::getInstance()
  223543. ->getFont (fontName, bold, italic);
  223544. clear();
  223545. setAscent (helper->ascent / helper->totalSize);
  223546. setName (fontName);
  223547. setDefaultCharacter (helper->getDefaultChar());
  223548. setBold (bold);
  223549. setItalic (italic);
  223550. if (addAllGlyphsToFont)
  223551. {
  223552. //xxx
  223553. jassertfalse
  223554. }
  223555. FontHelperCache::getInstance()->releaseFont (helper);
  223556. }
  223557. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  223558. {
  223559. // This method is only safe to be called from the normal UI thread..
  223560. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  223561. if (character == 0)
  223562. return false;
  223563. FontHelper* const helper = FontHelperCache::getInstance()
  223564. ->getFont (getName(), isBold(), isItalic());
  223565. Path path;
  223566. float width;
  223567. bool foundOne = false;
  223568. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  223569. {
  223570. path.applyTransform (AffineTransform::scale (1.0f / helper->totalSize,
  223571. 1.0f / helper->totalSize));
  223572. addGlyph (character, path, width / helper->totalSize);
  223573. for (int i = 0; i < glyphs.size(); ++i)
  223574. {
  223575. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  223576. float kerning;
  223577. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  223578. {
  223579. kerning = (kerning - width) / helper->totalSize;
  223580. if (kerning != 0)
  223581. addKerningPair (character, g->getCharacter(), kerning);
  223582. }
  223583. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  223584. {
  223585. kerning = kerning / helper->totalSize - g->width;
  223586. if (kerning != 0)
  223587. addKerningPair (g->getCharacter(), character, kerning);
  223588. }
  223589. }
  223590. foundOne = true;
  223591. }
  223592. FontHelperCache::getInstance()->releaseFont (helper);
  223593. return foundOne;
  223594. }
  223595. const StringArray Font::findAllTypefaceNames() throw()
  223596. {
  223597. StringArray names;
  223598. const ScopedAutoReleasePool pool;
  223599. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  223600. for (unsigned int i = 0; i < [fonts count]; ++i)
  223601. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  223602. names.sort (true);
  223603. return names;
  223604. }
  223605. void Typeface::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  223606. {
  223607. defaultSans = "Lucida Grande";
  223608. defaultSerif = "Times New Roman";
  223609. defaultFixed = "Monaco";
  223610. }
  223611. #endif
  223612. /********* End of inlined file: juce_mac_Fonts.mm *********/
  223613. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  223614. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223615. // compiled on its own).
  223616. #ifdef JUCE_INCLUDED_FILE
  223617. struct CallbackMessagePayload
  223618. {
  223619. MessageCallbackFunction* function;
  223620. void* parameter;
  223621. void* volatile result;
  223622. bool volatile hasBeenExecuted;
  223623. };
  223624. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  223625. for example having more than one juce plugin loaded into a host, then when a
  223626. method is called, the actual code that runs might actually be in a different module
  223627. than the one you expect... So any calls to library functions or statics that are
  223628. made inside obj-c methods will probably end up getting executed in a different DLL's
  223629. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  223630. To work around this insanity, I'm only allowing obj-c methods to make calls to
  223631. virtual methods of an object that's known to live inside the right module's space.
  223632. */
  223633. class AppDelegateRedirector
  223634. {
  223635. public:
  223636. AppDelegateRedirector() {}
  223637. virtual ~AppDelegateRedirector() {}
  223638. virtual NSApplicationTerminateReply shouldTerminate()
  223639. {
  223640. if (JUCEApplication::getInstance() != 0)
  223641. {
  223642. JUCEApplication::getInstance()->systemRequestedQuit();
  223643. return NSTerminateCancel;
  223644. }
  223645. return NSTerminateNow;
  223646. }
  223647. virtual BOOL openFile (const NSString* filename)
  223648. {
  223649. if (JUCEApplication::getInstance() != 0)
  223650. {
  223651. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  223652. return YES;
  223653. }
  223654. return NO;
  223655. }
  223656. virtual void openFiles (NSArray* filenames)
  223657. {
  223658. StringArray files;
  223659. for (unsigned int i = 0; i < [filenames count]; ++i)
  223660. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  223661. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  223662. {
  223663. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  223664. }
  223665. }
  223666. virtual void focusChanged()
  223667. {
  223668. juce_HandleProcessFocusChange();
  223669. }
  223670. virtual void deliverMessage (void* message)
  223671. {
  223672. // no need for an mm lock here - deliverMessage locks it
  223673. MessageManager::getInstance()->deliverMessage (message);
  223674. }
  223675. virtual void performCallback (CallbackMessagePayload* pl)
  223676. {
  223677. pl->result = (*pl->function) (pl->parameter);
  223678. pl->hasBeenExecuted = true;
  223679. }
  223680. virtual void deleteSelf()
  223681. {
  223682. delete this;
  223683. }
  223684. };
  223685. END_JUCE_NAMESPACE
  223686. using namespace JUCE_NAMESPACE;
  223687. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  223688. static int numPendingMessages = 0;
  223689. @interface JuceAppDelegate : NSObject
  223690. {
  223691. @private
  223692. id oldDelegate;
  223693. AppDelegateRedirector* redirector;
  223694. @public
  223695. bool flushingMessages;
  223696. }
  223697. - (JuceAppDelegate*) init;
  223698. - (void) dealloc;
  223699. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  223700. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  223701. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  223702. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  223703. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  223704. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  223705. - (void) customEvent: (id) data;
  223706. - (void) performCallback: (id) info;
  223707. - (void) dummyMethod;
  223708. @end
  223709. @implementation JuceAppDelegate
  223710. - (JuceAppDelegate*) init
  223711. {
  223712. [super init];
  223713. redirector = new AppDelegateRedirector();
  223714. numPendingMessages = 0;
  223715. flushingMessages = false;
  223716. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  223717. if (JUCEApplication::getInstance() != 0)
  223718. {
  223719. oldDelegate = [NSApp delegate];
  223720. [NSApp setDelegate: self];
  223721. }
  223722. else
  223723. {
  223724. oldDelegate = 0;
  223725. [center addObserver: self selector: @selector (applicationDidResignActive:)
  223726. name: NSApplicationDidResignActiveNotification object: NSApp];
  223727. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  223728. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  223729. [center addObserver: self selector: @selector (applicationWillUnhide:)
  223730. name: NSApplicationWillUnhideNotification object: NSApp];
  223731. }
  223732. return self;
  223733. }
  223734. - (void) dealloc
  223735. {
  223736. if (oldDelegate != 0)
  223737. [NSApp setDelegate: oldDelegate];
  223738. redirector->deleteSelf();
  223739. [super dealloc];
  223740. }
  223741. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  223742. {
  223743. return redirector->shouldTerminate();
  223744. }
  223745. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  223746. {
  223747. return redirector->openFile (filename);
  223748. }
  223749. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  223750. {
  223751. return redirector->openFiles (filenames);
  223752. }
  223753. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  223754. {
  223755. redirector->focusChanged();
  223756. }
  223757. - (void) applicationDidResignActive: (NSNotification*) aNotification
  223758. {
  223759. redirector->focusChanged();
  223760. }
  223761. - (void) applicationWillUnhide: (NSNotification*) aNotification
  223762. {
  223763. redirector->focusChanged();
  223764. }
  223765. - (void) customEvent: (id) n
  223766. {
  223767. atomicDecrement (numPendingMessages);
  223768. NSData* data = (NSData*) n;
  223769. void* message = 0;
  223770. [data getBytes: &message length: sizeof (message)];
  223771. [data release];
  223772. if (message != 0 && ! flushingMessages)
  223773. redirector->deliverMessage (message);
  223774. }
  223775. - (void) performCallback: (id) info
  223776. {
  223777. if ([info isKindOfClass: [NSData class]])
  223778. {
  223779. CallbackMessagePayload* pl = (CallbackMessagePayload*) [((NSData*) info) bytes];
  223780. if (pl != 0)
  223781. redirector->performCallback (pl);
  223782. }
  223783. else
  223784. {
  223785. jassertfalse // should never get here!
  223786. }
  223787. }
  223788. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  223789. @end
  223790. BEGIN_JUCE_NAMESPACE
  223791. static JuceAppDelegate* juceAppDelegate = 0;
  223792. void MessageManager::runDispatchLoop()
  223793. {
  223794. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  223795. {
  223796. const ScopedAutoReleasePool pool;
  223797. // must only be called by the message thread!
  223798. jassert (isThisTheMessageThread());
  223799. [NSApp run];
  223800. }
  223801. }
  223802. void MessageManager::stopDispatchLoop()
  223803. {
  223804. quitMessagePosted = true;
  223805. [NSApp stop: nil];
  223806. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  223807. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  223808. }
  223809. static bool isEventBlockedByModalComps (NSEvent* e)
  223810. {
  223811. if (Component::getNumCurrentlyModalComponents() == 0)
  223812. return false;
  223813. NSWindow* const w = [e window];
  223814. if (w == 0 || [w worksWhenModal])
  223815. return false;
  223816. bool isKey = false, isInputAttempt = false;
  223817. switch ([e type])
  223818. {
  223819. case NSKeyDown:
  223820. case NSKeyUp:
  223821. isKey = isInputAttempt = true;
  223822. break;
  223823. case NSLeftMouseDown:
  223824. case NSRightMouseDown:
  223825. case NSOtherMouseDown:
  223826. isInputAttempt = true;
  223827. break;
  223828. case NSLeftMouseDragged:
  223829. case NSRightMouseDragged:
  223830. case NSLeftMouseUp:
  223831. case NSRightMouseUp:
  223832. case NSOtherMouseUp:
  223833. case NSOtherMouseDragged:
  223834. if (Component::getComponentUnderMouse() != 0)
  223835. return false;
  223836. break;
  223837. case NSMouseMoved:
  223838. case NSMouseEntered:
  223839. case NSMouseExited:
  223840. case NSCursorUpdate:
  223841. case NSScrollWheel:
  223842. case NSTabletPoint:
  223843. case NSTabletProximity:
  223844. break;
  223845. default:
  223846. return false;
  223847. }
  223848. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  223849. {
  223850. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  223851. NSView* const compView = (NSView*) peer->getNativeHandle();
  223852. if ([compView window] == w)
  223853. {
  223854. if (isKey)
  223855. {
  223856. if (compView == [w firstResponder])
  223857. return false;
  223858. }
  223859. else
  223860. {
  223861. if (NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil],
  223862. [compView bounds]))
  223863. return false;
  223864. }
  223865. }
  223866. }
  223867. if (isInputAttempt)
  223868. {
  223869. if (! [NSApp isActive])
  223870. [NSApp activateIgnoringOtherApps: YES];
  223871. Component* const modal = Component::getCurrentlyModalComponent (0);
  223872. if (modal != 0)
  223873. modal->inputAttemptWhenModal();
  223874. }
  223875. return true;
  223876. }
  223877. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  223878. {
  223879. const ScopedAutoReleasePool pool;
  223880. jassert (isThisTheMessageThread()); // must only be called by the message thread
  223881. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  223882. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  223883. while (! quitMessagePosted)
  223884. {
  223885. const ScopedAutoReleasePool pool;
  223886. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223887. beforeDate: endDate];
  223888. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  223889. untilDate: endDate
  223890. inMode: NSDefaultRunLoopMode
  223891. dequeue: YES];
  223892. if (e != 0 && ! isEventBlockedByModalComps (e))
  223893. [NSApp sendEvent: e];
  223894. if (Time::getMillisecondCounter() >= endTime)
  223895. break;
  223896. }
  223897. return ! quitMessagePosted;
  223898. }
  223899. void MessageManager::doPlatformSpecificInitialisation()
  223900. {
  223901. if (juceAppDelegate == 0)
  223902. juceAppDelegate = [[JuceAppDelegate alloc] init];
  223903. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  223904. // correctly (needed prior to 10.5)
  223905. if (! [NSThread isMultiThreaded])
  223906. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  223907. toTarget: juceAppDelegate
  223908. withObject: nil];
  223909. initialiseMainMenu();
  223910. }
  223911. void MessageManager::doPlatformSpecificShutdown()
  223912. {
  223913. if (juceAppDelegate != 0)
  223914. {
  223915. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  223916. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  223917. // Annoyingly, cancelPerformSelectorsWithTarget can't actually cancel the messages
  223918. // sent by performSelectorOnMainThread, so need to manually flush these before quitting..
  223919. juceAppDelegate->flushingMessages = true;
  223920. for (int i = 100; --i >= 0 && numPendingMessages > 0;)
  223921. {
  223922. const ScopedAutoReleasePool pool;
  223923. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  223924. beforeDate: [NSDate dateWithTimeIntervalSinceNow: 5 * 0.001]];
  223925. }
  223926. [juceAppDelegate release];
  223927. juceAppDelegate = 0;
  223928. }
  223929. }
  223930. bool juce_postMessageToSystemQueue (void* message)
  223931. {
  223932. atomicIncrement (numPendingMessages);
  223933. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  223934. withObject: (id) [[NSData alloc] initWithBytes: &message length: (int) sizeof (message)]
  223935. waitUntilDone: NO];
  223936. return true;
  223937. }
  223938. void MessageManager::broadcastMessage (const String& value) throw()
  223939. {
  223940. }
  223941. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  223942. void* data)
  223943. {
  223944. if (isThisTheMessageThread())
  223945. {
  223946. return (*callback) (data);
  223947. }
  223948. else
  223949. {
  223950. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  223951. // deadlock because the message manager is blocked from running, so can never
  223952. // call your function..
  223953. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  223954. const ScopedAutoReleasePool pool;
  223955. CallbackMessagePayload cmp;
  223956. cmp.function = callback;
  223957. cmp.parameter = data;
  223958. cmp.result = 0;
  223959. cmp.hasBeenExecuted = false;
  223960. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  223961. withObject: [NSData dataWithBytesNoCopy: &cmp
  223962. length: sizeof (cmp)
  223963. freeWhenDone: NO]
  223964. waitUntilDone: YES];
  223965. return cmp.result;
  223966. }
  223967. }
  223968. #endif
  223969. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  223970. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  223971. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223972. // compiled on its own).
  223973. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  223974. END_JUCE_NAMESPACE
  223975. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  223976. @interface DownloadClickDetector : NSObject
  223977. {
  223978. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  223979. }
  223980. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  223981. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  223982. request: (NSURLRequest*) request
  223983. frame: (WebFrame*) frame
  223984. decisionListener: (id<WebPolicyDecisionListener>) listener;
  223985. @end
  223986. @implementation DownloadClickDetector
  223987. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  223988. {
  223989. [super init];
  223990. ownerComponent = ownerComponent_;
  223991. return self;
  223992. }
  223993. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  223994. request: (NSURLRequest*) request
  223995. frame: (WebFrame*) frame
  223996. decisionListener: (id <WebPolicyDecisionListener>) listener
  223997. {
  223998. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  223999. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  224000. [listener use];
  224001. else
  224002. [listener ignore];
  224003. }
  224004. @end
  224005. BEGIN_JUCE_NAMESPACE
  224006. class WebBrowserComponentInternal : public NSViewComponent
  224007. {
  224008. public:
  224009. WebBrowserComponentInternal (WebBrowserComponent* owner)
  224010. {
  224011. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  224012. frameName: @""
  224013. groupName: @""];
  224014. setView (webView);
  224015. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  224016. [webView setPolicyDelegate: clickListener];
  224017. }
  224018. ~WebBrowserComponentInternal()
  224019. {
  224020. [webView setPolicyDelegate: nil];
  224021. [clickListener release];
  224022. setView (0);
  224023. }
  224024. void goToURL (const String& url,
  224025. const StringArray* headers,
  224026. const MemoryBlock* postData)
  224027. {
  224028. NSMutableURLRequest* r
  224029. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224030. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224031. timeoutInterval: 30.0];
  224032. if (postData != 0 && postData->getSize() > 0)
  224033. {
  224034. [r setHTTPMethod: @"POST"];
  224035. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  224036. length: postData->getSize()]];
  224037. }
  224038. if (headers != 0)
  224039. {
  224040. for (int i = 0; i < headers->size(); ++i)
  224041. {
  224042. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  224043. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  224044. [r setValue: juceStringToNS (headerValue)
  224045. forHTTPHeaderField: juceStringToNS (headerName)];
  224046. }
  224047. }
  224048. stop();
  224049. [[webView mainFrame] loadRequest: r];
  224050. }
  224051. void goBack()
  224052. {
  224053. [webView goBack];
  224054. }
  224055. void goForward()
  224056. {
  224057. [webView goForward];
  224058. }
  224059. void stop()
  224060. {
  224061. [webView stopLoading: nil];
  224062. }
  224063. void refresh()
  224064. {
  224065. [webView reload: nil];
  224066. }
  224067. private:
  224068. WebView* webView;
  224069. DownloadClickDetector* clickListener;
  224070. };
  224071. WebBrowserComponent::WebBrowserComponent()
  224072. : browser (0),
  224073. blankPageShown (false)
  224074. {
  224075. setOpaque (true);
  224076. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  224077. }
  224078. WebBrowserComponent::~WebBrowserComponent()
  224079. {
  224080. deleteAndZero (browser);
  224081. }
  224082. void WebBrowserComponent::goToURL (const String& url,
  224083. const StringArray* headers,
  224084. const MemoryBlock* postData)
  224085. {
  224086. lastURL = url;
  224087. lastHeaders.clear();
  224088. if (headers != 0)
  224089. lastHeaders = *headers;
  224090. lastPostData.setSize (0);
  224091. if (postData != 0)
  224092. lastPostData = *postData;
  224093. blankPageShown = false;
  224094. browser->goToURL (url, headers, postData);
  224095. }
  224096. void WebBrowserComponent::stop()
  224097. {
  224098. browser->stop();
  224099. }
  224100. void WebBrowserComponent::goBack()
  224101. {
  224102. lastURL = String::empty;
  224103. blankPageShown = false;
  224104. browser->goBack();
  224105. }
  224106. void WebBrowserComponent::goForward()
  224107. {
  224108. lastURL = String::empty;
  224109. browser->goForward();
  224110. }
  224111. void WebBrowserComponent::refresh()
  224112. {
  224113. browser->refresh();
  224114. }
  224115. void WebBrowserComponent::paint (Graphics& g)
  224116. {
  224117. }
  224118. void WebBrowserComponent::checkWindowAssociation()
  224119. {
  224120. // when the component becomes invisible, some stuff like flash
  224121. // carries on playing audio, so we need to force it onto a blank
  224122. // page to avoid this, (and send it back when it's made visible again).
  224123. if (isShowing())
  224124. {
  224125. if (blankPageShown)
  224126. goBack();
  224127. }
  224128. else
  224129. {
  224130. if (! blankPageShown)
  224131. {
  224132. blankPageShown = true;
  224133. browser->goToURL ("about:blank", 0, 0);
  224134. }
  224135. }
  224136. }
  224137. void WebBrowserComponent::reloadLastURL()
  224138. {
  224139. if (lastURL.isNotEmpty())
  224140. {
  224141. goToURL (lastURL, &lastHeaders, &lastPostData);
  224142. lastURL = String::empty;
  224143. }
  224144. }
  224145. void WebBrowserComponent::parentHierarchyChanged()
  224146. {
  224147. checkWindowAssociation();
  224148. }
  224149. void WebBrowserComponent::resized()
  224150. {
  224151. browser->setSize (getWidth(), getHeight());
  224152. }
  224153. void WebBrowserComponent::visibilityChanged()
  224154. {
  224155. checkWindowAssociation();
  224156. }
  224157. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224158. {
  224159. return true;
  224160. }
  224161. #endif
  224162. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  224163. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  224164. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224165. // compiled on its own).
  224166. #ifdef JUCE_INCLUDED_FILE
  224167. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  224168. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  224169. #endif
  224170. #undef log
  224171. #if JUCE_COREAUDIO_LOGGING_ENABLED
  224172. #define log(a) Logger::writeToLog (a)
  224173. #else
  224174. #define log(a)
  224175. #endif
  224176. #undef OK
  224177. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  224178. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  224179. {
  224180. if (err == noErr)
  224181. return true;
  224182. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  224183. jassertfalse
  224184. return false;
  224185. }
  224186. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  224187. #else
  224188. #define OK(a) (a == noErr)
  224189. #endif
  224190. class CoreAudioInternal : public Timer
  224191. {
  224192. public:
  224193. CoreAudioInternal (AudioDeviceID id)
  224194. : inputLatency (0),
  224195. outputLatency (0),
  224196. callback (0),
  224197. #if ! MACOS_10_4_OR_EARLIER
  224198. audioProcID (0),
  224199. #endif
  224200. inputDevice (0),
  224201. isSlaveDevice (false),
  224202. deviceID (id),
  224203. started (false),
  224204. audioBuffer (0),
  224205. numInputChans (0),
  224206. numOutputChans (0),
  224207. callbacksAllowed (true),
  224208. numInputChannelInfos (0),
  224209. numOutputChannelInfos (0),
  224210. tempInputBuffers (0),
  224211. tempOutputBuffers (0),
  224212. inputChannelInfo (0),
  224213. outputChannelInfo (0)
  224214. {
  224215. sampleRate = 0;
  224216. bufferSize = 512;
  224217. if (deviceID == 0)
  224218. {
  224219. error = TRANS("can't open device");
  224220. }
  224221. else
  224222. {
  224223. updateDetailsFromDevice();
  224224. AudioDeviceAddPropertyListener (deviceID,
  224225. kAudioPropertyWildcardChannel,
  224226. kAudioPropertyWildcardSection,
  224227. kAudioPropertyWildcardPropertyID,
  224228. deviceListenerProc, this);
  224229. }
  224230. }
  224231. ~CoreAudioInternal()
  224232. {
  224233. AudioDeviceRemovePropertyListener (deviceID,
  224234. kAudioPropertyWildcardChannel,
  224235. kAudioPropertyWildcardSection,
  224236. kAudioPropertyWildcardPropertyID,
  224237. deviceListenerProc);
  224238. stop (false);
  224239. juce_free (audioBuffer);
  224240. juce_free (tempInputBuffers);
  224241. juce_free (tempOutputBuffers);
  224242. juce_free (inputChannelInfo);
  224243. juce_free (outputChannelInfo);
  224244. delete inputDevice;
  224245. }
  224246. void allocateTempBuffers()
  224247. {
  224248. const int tempBufSize = bufferSize + 4;
  224249. juce_free (audioBuffer);
  224250. audioBuffer = (float*) juce_calloc ((numInputChans + numOutputChans) * tempBufSize * sizeof (float));
  224251. juce_free (tempInputBuffers);
  224252. tempInputBuffers = (float**) juce_calloc (sizeof (float*) * (numInputChans + 2));
  224253. juce_free (tempOutputBuffers);
  224254. tempOutputBuffers = (float**) juce_calloc (sizeof (float*) * (numOutputChans + 2));
  224255. int i, count = 0;
  224256. for (i = 0; i < numInputChans; ++i)
  224257. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  224258. for (i = 0; i < numOutputChans; ++i)
  224259. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  224260. }
  224261. // returns the number of actual available channels
  224262. void fillInChannelInfo (const bool input)
  224263. {
  224264. int chanNum = 0;
  224265. UInt32 size;
  224266. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  224267. {
  224268. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  224269. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  224270. {
  224271. const int numStreams = bufList->mNumberBuffers;
  224272. for (int i = 0; i < numStreams; ++i)
  224273. {
  224274. const AudioBuffer& b = bufList->mBuffers[i];
  224275. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  224276. {
  224277. String name;
  224278. {
  224279. uint8 channelName [256];
  224280. zerostruct (channelName);
  224281. UInt32 nameSize = sizeof (channelName);
  224282. if (AudioDeviceGetProperty (deviceID, chanNum + 1, input, kAudioDevicePropertyChannelName,
  224283. &nameSize, &channelName) == noErr)
  224284. name = String::fromUTF8 (channelName, nameSize);
  224285. }
  224286. if (input)
  224287. {
  224288. if (activeInputChans[chanNum])
  224289. {
  224290. inputChannelInfo [numInputChannelInfos].streamNum = i;
  224291. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  224292. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  224293. ++numInputChannelInfos;
  224294. }
  224295. if (name.isEmpty())
  224296. name << "Input " << (chanNum + 1);
  224297. inChanNames.add (name);
  224298. }
  224299. else
  224300. {
  224301. if (activeOutputChans[chanNum])
  224302. {
  224303. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  224304. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  224305. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  224306. ++numOutputChannelInfos;
  224307. }
  224308. if (name.isEmpty())
  224309. name << "Output " << (chanNum + 1);
  224310. outChanNames.add (name);
  224311. }
  224312. ++chanNum;
  224313. }
  224314. }
  224315. }
  224316. juce_free (bufList);
  224317. }
  224318. }
  224319. void updateDetailsFromDevice()
  224320. {
  224321. stopTimer();
  224322. if (deviceID == 0)
  224323. return;
  224324. const ScopedLock sl (callbackLock);
  224325. Float64 sr;
  224326. UInt32 size = sizeof (Float64);
  224327. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  224328. sampleRate = sr;
  224329. UInt32 framesPerBuf;
  224330. size = sizeof (framesPerBuf);
  224331. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  224332. {
  224333. bufferSize = framesPerBuf;
  224334. allocateTempBuffers();
  224335. }
  224336. bufferSizes.clear();
  224337. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  224338. {
  224339. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  224340. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  224341. {
  224342. bufferSizes.add ((int) ranges[0].mMinimum);
  224343. for (int i = 32; i < 8192; i += 32)
  224344. {
  224345. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  224346. {
  224347. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  224348. {
  224349. bufferSizes.addIfNotAlreadyThere (i);
  224350. break;
  224351. }
  224352. }
  224353. }
  224354. if (bufferSize > 0)
  224355. bufferSizes.addIfNotAlreadyThere (bufferSize);
  224356. }
  224357. juce_free (ranges);
  224358. }
  224359. if (bufferSizes.size() == 0 && bufferSize > 0)
  224360. bufferSizes.add (bufferSize);
  224361. sampleRates.clear();
  224362. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  224363. String rates;
  224364. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  224365. {
  224366. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  224367. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  224368. {
  224369. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  224370. {
  224371. bool ok = false;
  224372. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  224373. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  224374. ok = true;
  224375. if (ok)
  224376. {
  224377. sampleRates.add (possibleRates[i]);
  224378. rates << possibleRates[i] << T(" ");
  224379. }
  224380. }
  224381. }
  224382. juce_free (ranges);
  224383. }
  224384. if (sampleRates.size() == 0 && sampleRate > 0)
  224385. {
  224386. sampleRates.add (sampleRate);
  224387. rates << sampleRate;
  224388. }
  224389. log (T("sr: ") + rates);
  224390. inputLatency = 0;
  224391. outputLatency = 0;
  224392. UInt32 lat;
  224393. size = sizeof (UInt32);
  224394. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  224395. inputLatency = (int) lat;
  224396. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  224397. outputLatency = (int) lat;
  224398. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  224399. inChanNames.clear();
  224400. outChanNames.clear();
  224401. juce_free (inputChannelInfo);
  224402. inputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numInputChans + 2));
  224403. numInputChannelInfos = 0;
  224404. juce_free (outputChannelInfo);
  224405. outputChannelInfo = (CallbackDetailsForChannel*) juce_calloc (sizeof (CallbackDetailsForChannel) * (numOutputChans + 2));
  224406. numOutputChannelInfos = 0;
  224407. fillInChannelInfo (true);
  224408. fillInChannelInfo (false);
  224409. }
  224410. const StringArray getSources (bool input)
  224411. {
  224412. StringArray s;
  224413. int num = 0;
  224414. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  224415. if (types != 0)
  224416. {
  224417. for (int i = 0; i < num; ++i)
  224418. {
  224419. AudioValueTranslation avt;
  224420. char buffer[256];
  224421. avt.mInputData = (void*) &(types[i]);
  224422. avt.mInputDataSize = sizeof (UInt32);
  224423. avt.mOutputData = buffer;
  224424. avt.mOutputDataSize = 256;
  224425. UInt32 transSize = sizeof (avt);
  224426. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  224427. {
  224428. DBG (buffer);
  224429. s.add (buffer);
  224430. }
  224431. }
  224432. juce_free (types);
  224433. }
  224434. return s;
  224435. }
  224436. int getCurrentSourceIndex (bool input) const
  224437. {
  224438. OSType currentSourceID = 0;
  224439. UInt32 size = 0;
  224440. int result = -1;
  224441. if (deviceID != 0
  224442. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  224443. {
  224444. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  224445. {
  224446. int num = 0;
  224447. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  224448. if (types != 0)
  224449. {
  224450. for (int i = 0; i < num; ++i)
  224451. {
  224452. if (types[num] == currentSourceID)
  224453. {
  224454. result = i;
  224455. break;
  224456. }
  224457. }
  224458. juce_free (types);
  224459. }
  224460. }
  224461. }
  224462. return result;
  224463. }
  224464. void setCurrentSourceIndex (int index, bool input)
  224465. {
  224466. if (deviceID != 0)
  224467. {
  224468. int num = 0;
  224469. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  224470. if (types != 0)
  224471. {
  224472. if (((unsigned int) index) < (unsigned int) num)
  224473. {
  224474. OSType typeId = types[index];
  224475. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  224476. }
  224477. juce_free (types);
  224478. }
  224479. }
  224480. }
  224481. const String reopen (const BitArray& inputChannels,
  224482. const BitArray& outputChannels,
  224483. double newSampleRate,
  224484. int bufferSizeSamples)
  224485. {
  224486. error = String::empty;
  224487. log ("CoreAudio reopen");
  224488. callbacksAllowed = false;
  224489. stopTimer();
  224490. stop (false);
  224491. activeInputChans = inputChannels;
  224492. activeOutputChans = outputChannels;
  224493. activeInputChans.setRange (inChanNames.size(),
  224494. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  224495. false);
  224496. activeOutputChans.setRange (outChanNames.size(),
  224497. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  224498. false);
  224499. numInputChans = activeInputChans.countNumberOfSetBits();
  224500. numOutputChans = activeOutputChans.countNumberOfSetBits();
  224501. // set sample rate
  224502. Float64 sr = newSampleRate;
  224503. UInt32 size = sizeof (sr);
  224504. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  224505. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  224506. // change buffer size
  224507. UInt32 framesPerBuf = bufferSizeSamples;
  224508. size = sizeof (framesPerBuf);
  224509. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  224510. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  224511. // wait for the changes to happen (on some devices)
  224512. int i = 30;
  224513. while (--i >= 0)
  224514. {
  224515. updateDetailsFromDevice();
  224516. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  224517. break;
  224518. Thread::sleep (100);
  224519. }
  224520. if (i < 0)
  224521. error = "Couldn't change sample rate/buffer size";
  224522. if (sampleRates.size() == 0)
  224523. error = "Device has no available sample-rates";
  224524. if (bufferSizes.size() == 0)
  224525. error = "Device has no available buffer-sizes";
  224526. if (inputDevice != 0 && error.isEmpty())
  224527. error = inputDevice->reopen (inputChannels,
  224528. outputChannels,
  224529. newSampleRate,
  224530. bufferSizeSamples);
  224531. callbacksAllowed = true;
  224532. return error;
  224533. }
  224534. bool start (AudioIODeviceCallback* cb)
  224535. {
  224536. if (! started)
  224537. {
  224538. callback = 0;
  224539. if (deviceID != 0)
  224540. {
  224541. #if MACOS_10_4_OR_EARLIER
  224542. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  224543. #else
  224544. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  224545. #endif
  224546. {
  224547. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  224548. {
  224549. started = true;
  224550. }
  224551. else
  224552. {
  224553. #if MACOS_10_4_OR_EARLIER
  224554. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224555. #else
  224556. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224557. audioProcID = 0;
  224558. #endif
  224559. }
  224560. }
  224561. }
  224562. }
  224563. if (started)
  224564. {
  224565. const ScopedLock sl (callbackLock);
  224566. callback = cb;
  224567. }
  224568. if (inputDevice != 0)
  224569. return started && inputDevice->start (cb);
  224570. else
  224571. return started;
  224572. }
  224573. void stop (bool leaveInterruptRunning)
  224574. {
  224575. callbackLock.enter();
  224576. callback = 0;
  224577. callbackLock.exit();
  224578. if (started
  224579. && (deviceID != 0)
  224580. && ! leaveInterruptRunning)
  224581. {
  224582. OK (AudioDeviceStop (deviceID, audioIOProc));
  224583. #if MACOS_10_4_OR_EARLIER
  224584. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  224585. #else
  224586. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  224587. audioProcID = 0;
  224588. #endif
  224589. started = false;
  224590. callbackLock.enter();
  224591. callbackLock.exit();
  224592. // wait until it's definately stopped calling back..
  224593. for (int i = 40; --i >= 0;)
  224594. {
  224595. Thread::sleep (50);
  224596. UInt32 running = 0;
  224597. UInt32 size = sizeof (running);
  224598. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  224599. if (running == 0)
  224600. break;
  224601. }
  224602. callbackLock.enter();
  224603. callbackLock.exit();
  224604. }
  224605. if (inputDevice != 0)
  224606. inputDevice->stop (leaveInterruptRunning);
  224607. }
  224608. double getSampleRate() const
  224609. {
  224610. return sampleRate;
  224611. }
  224612. int getBufferSize() const
  224613. {
  224614. return bufferSize;
  224615. }
  224616. void audioCallback (const AudioBufferList* inInputData,
  224617. AudioBufferList* outOutputData)
  224618. {
  224619. int i;
  224620. const ScopedLock sl (callbackLock);
  224621. if (callback != 0)
  224622. {
  224623. if (inputDevice == 0)
  224624. {
  224625. for (i = numInputChans; --i >= 0;)
  224626. {
  224627. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  224628. float* dest = tempInputBuffers [i];
  224629. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  224630. + info.dataOffsetSamples;
  224631. const int stride = info.dataStrideSamples;
  224632. if (stride != 0) // if this is zero, info is invalid
  224633. {
  224634. for (int j = bufferSize; --j >= 0;)
  224635. {
  224636. *dest++ = *src;
  224637. src += stride;
  224638. }
  224639. }
  224640. }
  224641. }
  224642. if (! isSlaveDevice)
  224643. {
  224644. if (inputDevice == 0)
  224645. {
  224646. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  224647. numInputChans,
  224648. tempOutputBuffers,
  224649. numOutputChans,
  224650. bufferSize);
  224651. }
  224652. else
  224653. {
  224654. jassert (inputDevice->bufferSize == bufferSize);
  224655. // Sometimes the two linked devices seem to get their callbacks in
  224656. // parallel, so we need to lock both devices to stop the input data being
  224657. // changed while inside our callback..
  224658. const ScopedLock sl (inputDevice->callbackLock);
  224659. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  224660. inputDevice->numInputChans,
  224661. tempOutputBuffers,
  224662. numOutputChans,
  224663. bufferSize);
  224664. }
  224665. for (i = numOutputChans; --i >= 0;)
  224666. {
  224667. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224668. const float* src = tempOutputBuffers [i];
  224669. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224670. + info.dataOffsetSamples;
  224671. const int stride = info.dataStrideSamples;
  224672. if (stride != 0) // if this is zero, info is invalid
  224673. {
  224674. for (int j = bufferSize; --j >= 0;)
  224675. {
  224676. *dest = *src++;
  224677. dest += stride;
  224678. }
  224679. }
  224680. }
  224681. }
  224682. }
  224683. else
  224684. {
  224685. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  224686. {
  224687. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  224688. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  224689. + info.dataOffsetSamples;
  224690. const int stride = info.dataStrideSamples;
  224691. if (stride != 0) // if this is zero, info is invalid
  224692. {
  224693. for (int j = bufferSize; --j >= 0;)
  224694. {
  224695. *dest = 0.0f;
  224696. dest += stride;
  224697. }
  224698. }
  224699. }
  224700. }
  224701. }
  224702. // called by callbacks
  224703. void deviceDetailsChanged()
  224704. {
  224705. if (callbacksAllowed)
  224706. startTimer (100);
  224707. }
  224708. void timerCallback()
  224709. {
  224710. stopTimer();
  224711. log ("CoreAudio device changed callback");
  224712. const double oldSampleRate = sampleRate;
  224713. const int oldBufferSize = bufferSize;
  224714. updateDetailsFromDevice();
  224715. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  224716. {
  224717. callbacksAllowed = false;
  224718. stop (false);
  224719. updateDetailsFromDevice();
  224720. callbacksAllowed = true;
  224721. }
  224722. }
  224723. CoreAudioInternal* getRelatedDevice() const
  224724. {
  224725. UInt32 size = 0;
  224726. CoreAudioInternal* result = 0;
  224727. if (deviceID != 0
  224728. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  224729. && size > 0)
  224730. {
  224731. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  224732. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  224733. {
  224734. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  224735. {
  224736. if (devs[i] != deviceID && devs[i] != 0)
  224737. {
  224738. result = new CoreAudioInternal (devs[i]);
  224739. if (result->error.isEmpty())
  224740. {
  224741. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  224742. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  224743. if (thisIsInput != otherIsInput
  224744. || (inChanNames.size() + outChanNames.size() == 0)
  224745. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  224746. break;
  224747. }
  224748. deleteAndZero (result);
  224749. }
  224750. }
  224751. }
  224752. juce_free (devs);
  224753. }
  224754. return result;
  224755. }
  224756. juce_UseDebuggingNewOperator
  224757. String error;
  224758. int inputLatency, outputLatency;
  224759. BitArray activeInputChans, activeOutputChans;
  224760. StringArray inChanNames, outChanNames;
  224761. Array <double> sampleRates;
  224762. Array <int> bufferSizes;
  224763. AudioIODeviceCallback* callback;
  224764. #if ! MACOS_10_4_OR_EARLIER
  224765. AudioDeviceIOProcID audioProcID;
  224766. #endif
  224767. CoreAudioInternal* inputDevice;
  224768. bool isSlaveDevice;
  224769. private:
  224770. CriticalSection callbackLock;
  224771. AudioDeviceID deviceID;
  224772. bool started;
  224773. double sampleRate;
  224774. int bufferSize;
  224775. float* audioBuffer;
  224776. int numInputChans, numOutputChans;
  224777. bool callbacksAllowed;
  224778. struct CallbackDetailsForChannel
  224779. {
  224780. int streamNum;
  224781. int dataOffsetSamples;
  224782. int dataStrideSamples;
  224783. };
  224784. int numInputChannelInfos, numOutputChannelInfos;
  224785. CallbackDetailsForChannel* inputChannelInfo;
  224786. CallbackDetailsForChannel* outputChannelInfo;
  224787. float** tempInputBuffers;
  224788. float** tempOutputBuffers;
  224789. CoreAudioInternal (const CoreAudioInternal&);
  224790. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  224791. static OSStatus audioIOProc (AudioDeviceID inDevice,
  224792. const AudioTimeStamp* inNow,
  224793. const AudioBufferList* inInputData,
  224794. const AudioTimeStamp* inInputTime,
  224795. AudioBufferList* outOutputData,
  224796. const AudioTimeStamp* inOutputTime,
  224797. void* device)
  224798. {
  224799. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  224800. return noErr;
  224801. }
  224802. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  224803. UInt32 inLine,
  224804. Boolean isInput,
  224805. AudioDevicePropertyID inPropertyID,
  224806. void* inClientData)
  224807. {
  224808. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  224809. switch (inPropertyID)
  224810. {
  224811. case kAudioDevicePropertyBufferSize:
  224812. case kAudioDevicePropertyBufferFrameSize:
  224813. case kAudioDevicePropertyNominalSampleRate:
  224814. case kAudioDevicePropertyStreamFormat:
  224815. case kAudioDevicePropertyDeviceIsAlive:
  224816. intern->deviceDetailsChanged();
  224817. break;
  224818. case kAudioDevicePropertyBufferSizeRange:
  224819. case kAudioDevicePropertyVolumeScalar:
  224820. case kAudioDevicePropertyMute:
  224821. case kAudioDevicePropertyPlayThru:
  224822. case kAudioDevicePropertyDataSource:
  224823. case kAudioDevicePropertyDeviceIsRunning:
  224824. break;
  224825. }
  224826. return noErr;
  224827. }
  224828. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  224829. {
  224830. OSType* types = 0;
  224831. UInt32 size = 0;
  224832. num = 0;
  224833. if (deviceID != 0
  224834. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  224835. {
  224836. types = (OSType*) juce_calloc (size);
  224837. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  224838. {
  224839. num = size / sizeof (OSType);
  224840. }
  224841. else
  224842. {
  224843. juce_free (types);
  224844. types = 0;
  224845. }
  224846. }
  224847. return types;
  224848. }
  224849. };
  224850. class CoreAudioIODevice : public AudioIODevice
  224851. {
  224852. public:
  224853. CoreAudioIODevice (const String& deviceName,
  224854. AudioDeviceID inputDeviceId,
  224855. const int inputIndex_,
  224856. AudioDeviceID outputDeviceId,
  224857. const int outputIndex_)
  224858. : AudioIODevice (deviceName, "CoreAudio"),
  224859. inputIndex (inputIndex_),
  224860. outputIndex (outputIndex_),
  224861. isOpen_ (false),
  224862. isStarted (false)
  224863. {
  224864. internal = 0;
  224865. CoreAudioInternal* device = 0;
  224866. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  224867. {
  224868. jassert (inputDeviceId != 0);
  224869. device = new CoreAudioInternal (inputDeviceId);
  224870. lastError = device->error;
  224871. if (lastError.isNotEmpty())
  224872. deleteAndZero (device);
  224873. }
  224874. else
  224875. {
  224876. device = new CoreAudioInternal (outputDeviceId);
  224877. lastError = device->error;
  224878. if (lastError.isNotEmpty())
  224879. {
  224880. deleteAndZero (device);
  224881. }
  224882. else if (inputDeviceId != 0)
  224883. {
  224884. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  224885. lastError = device->error;
  224886. if (lastError.isNotEmpty())
  224887. {
  224888. delete secondDevice;
  224889. }
  224890. else
  224891. {
  224892. device->inputDevice = secondDevice;
  224893. secondDevice->isSlaveDevice = true;
  224894. }
  224895. }
  224896. }
  224897. internal = device;
  224898. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  224899. hardwareListenerProc, internal);
  224900. }
  224901. ~CoreAudioIODevice()
  224902. {
  224903. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  224904. hardwareListenerProc);
  224905. delete internal;
  224906. }
  224907. const StringArray getOutputChannelNames()
  224908. {
  224909. return internal->outChanNames;
  224910. }
  224911. const StringArray getInputChannelNames()
  224912. {
  224913. if (internal->inputDevice != 0)
  224914. return internal->inputDevice->inChanNames;
  224915. else
  224916. return internal->inChanNames;
  224917. }
  224918. int getNumSampleRates()
  224919. {
  224920. return internal->sampleRates.size();
  224921. }
  224922. double getSampleRate (int index)
  224923. {
  224924. return internal->sampleRates [index];
  224925. }
  224926. int getNumBufferSizesAvailable()
  224927. {
  224928. return internal->bufferSizes.size();
  224929. }
  224930. int getBufferSizeSamples (int index)
  224931. {
  224932. return internal->bufferSizes [index];
  224933. }
  224934. int getDefaultBufferSize()
  224935. {
  224936. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  224937. if (getBufferSizeSamples(i) >= 512)
  224938. return getBufferSizeSamples(i);
  224939. return 512;
  224940. }
  224941. const String open (const BitArray& inputChannels,
  224942. const BitArray& outputChannels,
  224943. double sampleRate,
  224944. int bufferSizeSamples)
  224945. {
  224946. isOpen_ = true;
  224947. if (bufferSizeSamples <= 0)
  224948. bufferSizeSamples = getDefaultBufferSize();
  224949. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  224950. lastError = internal->error;
  224951. return lastError;
  224952. }
  224953. void close()
  224954. {
  224955. isOpen_ = false;
  224956. }
  224957. bool isOpen()
  224958. {
  224959. return isOpen_;
  224960. }
  224961. int getCurrentBufferSizeSamples()
  224962. {
  224963. return internal != 0 ? internal->getBufferSize() : 512;
  224964. }
  224965. double getCurrentSampleRate()
  224966. {
  224967. return internal != 0 ? internal->getSampleRate() : 0;
  224968. }
  224969. int getCurrentBitDepth()
  224970. {
  224971. return 32; // no way to find out, so just assume it's high..
  224972. }
  224973. const BitArray getActiveOutputChannels() const
  224974. {
  224975. return internal != 0 ? internal->activeOutputChans : BitArray();
  224976. }
  224977. const BitArray getActiveInputChannels() const
  224978. {
  224979. BitArray chans;
  224980. if (internal != 0)
  224981. {
  224982. chans = internal->activeInputChans;
  224983. if (internal->inputDevice != 0)
  224984. chans.orWith (internal->inputDevice->activeInputChans);
  224985. }
  224986. return chans;
  224987. }
  224988. int getOutputLatencyInSamples()
  224989. {
  224990. if (internal == 0)
  224991. return 0;
  224992. // this seems like a good guess at getting the latency right - comparing
  224993. // this with a round-trip measurement, it gets it to within a few millisecs
  224994. // for the built-in mac soundcard
  224995. return internal->outputLatency + internal->getBufferSize() * 2;
  224996. }
  224997. int getInputLatencyInSamples()
  224998. {
  224999. if (internal == 0)
  225000. return 0;
  225001. return internal->inputLatency + internal->getBufferSize() * 2;
  225002. }
  225003. void start (AudioIODeviceCallback* callback)
  225004. {
  225005. if (internal != 0 && ! isStarted)
  225006. {
  225007. if (callback != 0)
  225008. callback->audioDeviceAboutToStart (this);
  225009. isStarted = true;
  225010. internal->start (callback);
  225011. }
  225012. }
  225013. void stop()
  225014. {
  225015. if (isStarted && internal != 0)
  225016. {
  225017. AudioIODeviceCallback* const lastCallback = internal->callback;
  225018. isStarted = false;
  225019. internal->stop (true);
  225020. if (lastCallback != 0)
  225021. lastCallback->audioDeviceStopped();
  225022. }
  225023. }
  225024. bool isPlaying()
  225025. {
  225026. if (internal->callback == 0)
  225027. isStarted = false;
  225028. return isStarted;
  225029. }
  225030. const String getLastError()
  225031. {
  225032. return lastError;
  225033. }
  225034. int inputIndex, outputIndex;
  225035. juce_UseDebuggingNewOperator
  225036. private:
  225037. CoreAudioInternal* internal;
  225038. bool isOpen_, isStarted;
  225039. String lastError;
  225040. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  225041. {
  225042. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  225043. switch (inPropertyID)
  225044. {
  225045. case kAudioHardwarePropertyDevices:
  225046. intern->deviceDetailsChanged();
  225047. break;
  225048. case kAudioHardwarePropertyDefaultOutputDevice:
  225049. case kAudioHardwarePropertyDefaultInputDevice:
  225050. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  225051. break;
  225052. }
  225053. return noErr;
  225054. }
  225055. CoreAudioIODevice (const CoreAudioIODevice&);
  225056. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  225057. };
  225058. class CoreAudioIODeviceType : public AudioIODeviceType
  225059. {
  225060. public:
  225061. CoreAudioIODeviceType()
  225062. : AudioIODeviceType (T("CoreAudio")),
  225063. hasScanned (false)
  225064. {
  225065. }
  225066. ~CoreAudioIODeviceType()
  225067. {
  225068. }
  225069. void scanForDevices()
  225070. {
  225071. hasScanned = true;
  225072. inputDeviceNames.clear();
  225073. outputDeviceNames.clear();
  225074. inputIds.clear();
  225075. outputIds.clear();
  225076. UInt32 size;
  225077. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  225078. {
  225079. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  225080. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  225081. {
  225082. static bool alreadyLogged = false;
  225083. const int num = size / sizeof (AudioDeviceID);
  225084. for (int i = 0; i < num; ++i)
  225085. {
  225086. char name[1024];
  225087. size = sizeof (name);
  225088. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  225089. {
  225090. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  225091. if (! alreadyLogged)
  225092. log (T("CoreAudio device: ") + nameString);
  225093. const int numIns = getNumChannels (devs[i], true);
  225094. const int numOuts = getNumChannels (devs[i], false);
  225095. if (numIns > 0)
  225096. {
  225097. inputDeviceNames.add (nameString);
  225098. inputIds.add (devs[i]);
  225099. }
  225100. if (numOuts > 0)
  225101. {
  225102. outputDeviceNames.add (nameString);
  225103. outputIds.add (devs[i]);
  225104. }
  225105. }
  225106. }
  225107. alreadyLogged = true;
  225108. }
  225109. juce_free (devs);
  225110. }
  225111. inputDeviceNames.appendNumbersToDuplicates (false, true);
  225112. outputDeviceNames.appendNumbersToDuplicates (false, true);
  225113. }
  225114. const StringArray getDeviceNames (const bool wantInputNames) const
  225115. {
  225116. jassert (hasScanned); // need to call scanForDevices() before doing this
  225117. if (wantInputNames)
  225118. return inputDeviceNames;
  225119. else
  225120. return outputDeviceNames;
  225121. }
  225122. int getDefaultDeviceIndex (const bool forInput) const
  225123. {
  225124. jassert (hasScanned); // need to call scanForDevices() before doing this
  225125. AudioDeviceID deviceID;
  225126. UInt32 size = sizeof (deviceID);
  225127. // if they're asking for any input channels at all, use the default input, so we
  225128. // get the built-in mic rather than the built-in output with no inputs..
  225129. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  225130. : kAudioHardwarePropertyDefaultOutputDevice,
  225131. &size, &deviceID) == noErr)
  225132. {
  225133. if (forInput)
  225134. {
  225135. for (int i = inputIds.size(); --i >= 0;)
  225136. if (inputIds[i] == deviceID)
  225137. return i;
  225138. }
  225139. else
  225140. {
  225141. for (int i = outputIds.size(); --i >= 0;)
  225142. if (outputIds[i] == deviceID)
  225143. return i;
  225144. }
  225145. }
  225146. return 0;
  225147. }
  225148. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  225149. {
  225150. jassert (hasScanned); // need to call scanForDevices() before doing this
  225151. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  225152. if (d == 0)
  225153. return -1;
  225154. return asInput ? d->inputIndex
  225155. : d->outputIndex;
  225156. }
  225157. bool hasSeparateInputsAndOutputs() const { return true; }
  225158. AudioIODevice* createDevice (const String& outputDeviceName,
  225159. const String& inputDeviceName)
  225160. {
  225161. jassert (hasScanned); // need to call scanForDevices() before doing this
  225162. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  225163. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  225164. String deviceName (outputDeviceName);
  225165. if (deviceName.isEmpty())
  225166. deviceName = inputDeviceName;
  225167. if (index >= 0)
  225168. return new CoreAudioIODevice (deviceName,
  225169. inputIds [inputIndex],
  225170. inputIndex,
  225171. outputIds [outputIndex],
  225172. outputIndex);
  225173. return 0;
  225174. }
  225175. juce_UseDebuggingNewOperator
  225176. private:
  225177. StringArray inputDeviceNames, outputDeviceNames;
  225178. Array <AudioDeviceID> inputIds, outputIds;
  225179. bool hasScanned;
  225180. static int getNumChannels (AudioDeviceID deviceID, bool input)
  225181. {
  225182. int total = 0;
  225183. UInt32 size;
  225184. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  225185. {
  225186. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  225187. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  225188. {
  225189. const int numStreams = bufList->mNumberBuffers;
  225190. for (int i = 0; i < numStreams; ++i)
  225191. {
  225192. const AudioBuffer& b = bufList->mBuffers[i];
  225193. total += b.mNumberChannels;
  225194. }
  225195. }
  225196. juce_free (bufList);
  225197. }
  225198. return total;
  225199. }
  225200. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  225201. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  225202. };
  225203. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  225204. {
  225205. return new CoreAudioIODeviceType();
  225206. }
  225207. #undef log
  225208. #endif
  225209. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  225210. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  225211. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225212. // compiled on its own).
  225213. #ifdef JUCE_INCLUDED_FILE
  225214. #undef log
  225215. #define log(a) Logger::writeToLog(a)
  225216. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  225217. {
  225218. if (err == noErr)
  225219. return true;
  225220. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  225221. jassertfalse
  225222. return false;
  225223. }
  225224. #undef OK
  225225. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  225226. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  225227. {
  225228. String result;
  225229. CFStringRef str = 0;
  225230. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  225231. if (str != 0)
  225232. {
  225233. result = PlatformUtilities::cfStringToJuceString (str);
  225234. CFRelease (str);
  225235. str = 0;
  225236. }
  225237. MIDIEntityRef entity = 0;
  225238. MIDIEndpointGetEntity (endpoint, &entity);
  225239. if (entity == 0)
  225240. return result; // probably virtual
  225241. if (result.isEmpty())
  225242. {
  225243. // endpoint name has zero length - try the entity
  225244. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  225245. if (str != 0)
  225246. {
  225247. result += PlatformUtilities::cfStringToJuceString (str);
  225248. CFRelease (str);
  225249. str = 0;
  225250. }
  225251. }
  225252. // now consider the device's name
  225253. MIDIDeviceRef device = 0;
  225254. MIDIEntityGetDevice (entity, &device);
  225255. if (device == 0)
  225256. return result;
  225257. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  225258. if (str != 0)
  225259. {
  225260. const String s (PlatformUtilities::cfStringToJuceString (str));
  225261. CFRelease (str);
  225262. // if an external device has only one entity, throw away
  225263. // the endpoint name and just use the device name
  225264. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  225265. {
  225266. result = s;
  225267. }
  225268. else if (! result.startsWithIgnoreCase (s))
  225269. {
  225270. // prepend the device name to the entity name
  225271. result = (s + T(" ") + result).trimEnd();
  225272. }
  225273. }
  225274. return result;
  225275. }
  225276. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  225277. {
  225278. String result;
  225279. // Does the endpoint have connections?
  225280. CFDataRef connections = 0;
  225281. int numConnections = 0;
  225282. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  225283. if (connections != 0)
  225284. {
  225285. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  225286. if (numConnections > 0)
  225287. {
  225288. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  225289. for (int i = 0; i < numConnections; ++i, ++pid)
  225290. {
  225291. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  225292. MIDIObjectRef connObject;
  225293. MIDIObjectType connObjectType;
  225294. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  225295. if (err == noErr)
  225296. {
  225297. String s;
  225298. if (connObjectType == kMIDIObjectType_ExternalSource
  225299. || connObjectType == kMIDIObjectType_ExternalDestination)
  225300. {
  225301. // Connected to an external device's endpoint (10.3 and later).
  225302. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  225303. }
  225304. else
  225305. {
  225306. // Connected to an external device (10.2) (or something else, catch-all)
  225307. CFStringRef str = 0;
  225308. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  225309. if (str != 0)
  225310. {
  225311. s = PlatformUtilities::cfStringToJuceString (str);
  225312. CFRelease (str);
  225313. }
  225314. }
  225315. if (s.isNotEmpty())
  225316. {
  225317. if (result.isNotEmpty())
  225318. result += (", ");
  225319. result += s;
  225320. }
  225321. }
  225322. }
  225323. }
  225324. CFRelease (connections);
  225325. }
  225326. if (result.isNotEmpty())
  225327. return result;
  225328. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  225329. return getEndpointName (endpoint, false);
  225330. }
  225331. const StringArray MidiOutput::getDevices()
  225332. {
  225333. StringArray s;
  225334. const ItemCount num = MIDIGetNumberOfDestinations();
  225335. for (ItemCount i = 0; i < num; ++i)
  225336. {
  225337. MIDIEndpointRef dest = MIDIGetDestination (i);
  225338. if (dest != 0)
  225339. {
  225340. String name (getConnectedEndpointName (dest));
  225341. if (name.isEmpty())
  225342. name = "<error>";
  225343. s.add (name);
  225344. }
  225345. else
  225346. {
  225347. s.add ("<error>");
  225348. }
  225349. }
  225350. return s;
  225351. }
  225352. int MidiOutput::getDefaultDeviceIndex()
  225353. {
  225354. return 0;
  225355. }
  225356. static MIDIClientRef globalMidiClient;
  225357. static bool hasGlobalClientBeenCreated = false;
  225358. static bool makeSureClientExists()
  225359. {
  225360. if (! hasGlobalClientBeenCreated)
  225361. {
  225362. String name (T("JUCE"));
  225363. if (JUCEApplication::getInstance() != 0)
  225364. name = JUCEApplication::getInstance()->getApplicationName();
  225365. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  225366. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  225367. CFRelease (appName);
  225368. }
  225369. return hasGlobalClientBeenCreated;
  225370. }
  225371. struct MidiPortAndEndpoint
  225372. {
  225373. MIDIPortRef port;
  225374. MIDIEndpointRef endPoint;
  225375. };
  225376. MidiOutput* MidiOutput::openDevice (int index)
  225377. {
  225378. MidiOutput* mo = 0;
  225379. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  225380. {
  225381. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  225382. CFStringRef pname;
  225383. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225384. {
  225385. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  225386. if (makeSureClientExists())
  225387. {
  225388. MIDIPortRef port;
  225389. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  225390. {
  225391. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  225392. mpe->port = port;
  225393. mpe->endPoint = endPoint;
  225394. mo = new MidiOutput();
  225395. mo->internal = (void*)mpe;
  225396. }
  225397. }
  225398. CFRelease (pname);
  225399. }
  225400. }
  225401. return mo;
  225402. }
  225403. MidiOutput::~MidiOutput()
  225404. {
  225405. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  225406. MIDIPortDispose (mpe->port);
  225407. delete mpe;
  225408. }
  225409. void MidiOutput::reset()
  225410. {
  225411. }
  225412. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  225413. {
  225414. return false;
  225415. }
  225416. void MidiOutput::setVolume (float leftVol, float rightVol)
  225417. {
  225418. }
  225419. void MidiOutput::sendMessageNow (const MidiMessage& message)
  225420. {
  225421. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  225422. if (message.isSysEx())
  225423. {
  225424. const int maxPacketSize = 256;
  225425. int pos = 0, bytesLeft = message.getRawDataSize();
  225426. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  225427. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 * numPackets + message.getRawDataSize());
  225428. packets->numPackets = numPackets;
  225429. MIDIPacket* p = packets->packet;
  225430. for (int i = 0; i < numPackets; ++i)
  225431. {
  225432. p->timeStamp = 0;
  225433. p->length = jmin (maxPacketSize, bytesLeft);
  225434. memcpy (p->data, message.getRawData() + pos, p->length);
  225435. pos += p->length;
  225436. bytesLeft -= p->length;
  225437. p = MIDIPacketNext (p);
  225438. }
  225439. MIDISend (mpe->port, mpe->endPoint, packets);
  225440. juce_free (packets);
  225441. }
  225442. else
  225443. {
  225444. MIDIPacketList packets;
  225445. packets.numPackets = 1;
  225446. packets.packet[0].timeStamp = 0;
  225447. packets.packet[0].length = message.getRawDataSize();
  225448. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  225449. MIDISend (mpe->port, mpe->endPoint, &packets);
  225450. }
  225451. }
  225452. const StringArray MidiInput::getDevices()
  225453. {
  225454. StringArray s;
  225455. const ItemCount num = MIDIGetNumberOfSources();
  225456. for (ItemCount i = 0; i < num; ++i)
  225457. {
  225458. MIDIEndpointRef source = MIDIGetSource (i);
  225459. if (source != 0)
  225460. {
  225461. String name (getConnectedEndpointName (source));
  225462. if (name.isEmpty())
  225463. name = "<error>";
  225464. s.add (name);
  225465. }
  225466. else
  225467. {
  225468. s.add ("<error>");
  225469. }
  225470. }
  225471. return s;
  225472. }
  225473. int MidiInput::getDefaultDeviceIndex()
  225474. {
  225475. return 0;
  225476. }
  225477. struct MidiPortAndCallback
  225478. {
  225479. MidiInput* input;
  225480. MIDIPortRef port;
  225481. MIDIEndpointRef endPoint;
  225482. MidiInputCallback* callback;
  225483. MemoryBlock pendingData;
  225484. int pendingBytes;
  225485. double pendingDataTime;
  225486. bool active;
  225487. };
  225488. static CriticalSection callbackLock;
  225489. static VoidArray activeCallbacks;
  225490. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  225491. {
  225492. if (*d == 0xf0)
  225493. {
  225494. mpe->pendingBytes = 0;
  225495. mpe->pendingDataTime = time;
  225496. }
  225497. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  225498. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  225499. uint8* dest = totalMessage + mpe->pendingBytes;
  225500. while (size > 0)
  225501. {
  225502. if (mpe->pendingBytes > 0 && *d >= 0x80)
  225503. {
  225504. if (*d >= 0xfa || *d == 0xf8)
  225505. {
  225506. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  225507. ++d;
  225508. --size;
  225509. }
  225510. else
  225511. {
  225512. if (*d == 0xf7)
  225513. {
  225514. *dest++ = *d++;
  225515. mpe->pendingBytes++;
  225516. --size;
  225517. }
  225518. break;
  225519. }
  225520. }
  225521. else
  225522. {
  225523. *dest++ = *d++;
  225524. mpe->pendingBytes++;
  225525. --size;
  225526. }
  225527. }
  225528. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  225529. {
  225530. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  225531. mpe->pendingBytes,
  225532. mpe->pendingDataTime));
  225533. mpe->pendingBytes = 0;
  225534. }
  225535. else
  225536. {
  225537. mpe->callback->handlePartialSysexMessage (mpe->input,
  225538. totalMessage,
  225539. mpe->pendingBytes,
  225540. mpe->pendingDataTime);
  225541. }
  225542. }
  225543. static void midiInputProc (const MIDIPacketList* pktlist,
  225544. void* readProcRefCon,
  225545. void* srcConnRefCon)
  225546. {
  225547. double time = Time::getMillisecondCounterHiRes() * 0.001;
  225548. const double originalTime = time;
  225549. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  225550. const ScopedLock sl (callbackLock);
  225551. if (activeCallbacks.contains (mpe) && mpe->active)
  225552. {
  225553. const MIDIPacket* packet = &pktlist->packet[0];
  225554. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  225555. {
  225556. const uint8* d = (const uint8*) (packet->data);
  225557. int size = packet->length;
  225558. while (size > 0)
  225559. {
  225560. time = originalTime;
  225561. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  225562. {
  225563. processSysex (mpe, d, size, time);
  225564. }
  225565. else
  225566. {
  225567. int used = 0;
  225568. const MidiMessage m (d, size, used, 0, time);
  225569. if (used <= 0)
  225570. {
  225571. jassertfalse // malformed midi message
  225572. break;
  225573. }
  225574. else
  225575. {
  225576. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  225577. }
  225578. size -= used;
  225579. d += used;
  225580. }
  225581. }
  225582. packet = MIDIPacketNext (packet);
  225583. }
  225584. }
  225585. }
  225586. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  225587. {
  225588. MidiInput* mi = 0;
  225589. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  225590. {
  225591. MIDIEndpointRef endPoint = MIDIGetSource (index);
  225592. if (endPoint != 0)
  225593. {
  225594. CFStringRef pname;
  225595. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  225596. {
  225597. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  225598. if (makeSureClientExists())
  225599. {
  225600. MIDIPortRef port;
  225601. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  225602. mpe->active = false;
  225603. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  225604. {
  225605. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  225606. {
  225607. mpe->port = port;
  225608. mpe->endPoint = endPoint;
  225609. mpe->callback = callback;
  225610. mpe->pendingBytes = 0;
  225611. mpe->pendingData.ensureSize (128);
  225612. mi = new MidiInput (getDevices() [index]);
  225613. mpe->input = mi;
  225614. mi->internal = (void*) mpe;
  225615. const ScopedLock sl (callbackLock);
  225616. activeCallbacks.add (mpe);
  225617. }
  225618. else
  225619. {
  225620. OK (MIDIPortDispose (port));
  225621. delete mpe;
  225622. }
  225623. }
  225624. else
  225625. {
  225626. delete mpe;
  225627. }
  225628. }
  225629. }
  225630. CFRelease (pname);
  225631. }
  225632. }
  225633. return mi;
  225634. }
  225635. MidiInput::MidiInput (const String& name_)
  225636. : name (name_)
  225637. {
  225638. }
  225639. MidiInput::~MidiInput()
  225640. {
  225641. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225642. mpe->active = false;
  225643. callbackLock.enter();
  225644. activeCallbacks.removeValue (mpe);
  225645. callbackLock.exit();
  225646. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  225647. OK (MIDIPortDispose (mpe->port));
  225648. delete mpe;
  225649. }
  225650. void MidiInput::start()
  225651. {
  225652. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225653. const ScopedLock sl (callbackLock);
  225654. mpe->active = true;
  225655. }
  225656. void MidiInput::stop()
  225657. {
  225658. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  225659. const ScopedLock sl (callbackLock);
  225660. mpe->active = false;
  225661. }
  225662. #undef log
  225663. #endif
  225664. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  225665. /********* Start of inlined file: juce_mac_CameraDevice.mm *********/
  225666. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225667. // compiled on its own).
  225668. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME && JUCE_USE_CAMERA
  225669. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  225670. class QTCameraDeviceInteral;
  225671. END_JUCE_NAMESPACE
  225672. @interface QTCaptureCallbackDelegate : NSObject
  225673. {
  225674. @public
  225675. CameraDevice* owner;
  225676. QTCameraDeviceInteral* internal;
  225677. Time* firstRecordedTime;
  225678. }
  225679. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  225680. - (void) dealloc;
  225681. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225682. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225683. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225684. fromConnection: (QTCaptureConnection*) connection;
  225685. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225686. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225687. fromConnection: (QTCaptureConnection*) connection;
  225688. @end
  225689. BEGIN_JUCE_NAMESPACE
  225690. class QTCameraDeviceInteral
  225691. {
  225692. public:
  225693. QTCameraDeviceInteral (CameraDevice* owner, int index)
  225694. {
  225695. const ScopedAutoReleasePool pool;
  225696. session = [[QTCaptureSession alloc] init];
  225697. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  225698. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  225699. input = 0;
  225700. fileOutput = 0;
  225701. imageOutput = 0;
  225702. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  225703. internalDev: this];
  225704. NSError* err = 0;
  225705. [device retain];
  225706. [device open: &err];
  225707. if (err == 0)
  225708. {
  225709. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  225710. [session addInput: input error: &err];
  225711. if (err == 0)
  225712. {
  225713. resetFile();
  225714. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  225715. [imageOutput setDelegate: callbackDelegate];
  225716. if (err == 0)
  225717. {
  225718. [session startRunning];
  225719. return;
  225720. }
  225721. }
  225722. }
  225723. openingError = nsStringToJuce ([err description]);
  225724. DBG (openingError);
  225725. }
  225726. ~QTCameraDeviceInteral()
  225727. {
  225728. [session stopRunning];
  225729. [session removeOutput: imageOutput];
  225730. [session release];
  225731. [input release];
  225732. [device release];
  225733. [fileOutput release];
  225734. [imageOutput release];
  225735. [callbackDelegate release];
  225736. }
  225737. void resetFile()
  225738. {
  225739. [session removeOutput: fileOutput];
  225740. [fileOutput release];
  225741. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  225742. [fileOutput setDelegate: callbackDelegate];
  225743. }
  225744. void addListener (CameraImageListener* listenerToAdd)
  225745. {
  225746. const ScopedLock sl (listenerLock);
  225747. if (listeners.size() == 0)
  225748. [session addOutput: imageOutput error: nil];
  225749. listeners.addIfNotAlreadyThere (listenerToAdd);
  225750. }
  225751. void removeListener (CameraImageListener* listenerToRemove)
  225752. {
  225753. const ScopedLock sl (listenerLock);
  225754. listeners.removeValue (listenerToRemove);
  225755. if (listeners.size() == 0)
  225756. [session removeOutput: imageOutput];
  225757. }
  225758. static void drawNSBitmapIntoJuceImage (Image& dest, NSBitmapImageRep* source)
  225759. {
  225760. const ScopedAutoReleasePool pool;
  225761. int lineStride, pixelStride;
  225762. uint8* pixels = dest.lockPixelDataReadWrite (0, 0, dest.getWidth(), dest.getHeight(),
  225763. lineStride, pixelStride);
  225764. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  225765. initWithBitmapDataPlanes: &pixels
  225766. pixelsWide: dest.getWidth()
  225767. pixelsHigh: dest.getHeight()
  225768. bitsPerSample: 8
  225769. samplesPerPixel: pixelStride
  225770. hasAlpha: dest.hasAlphaChannel()
  225771. isPlanar: NO
  225772. colorSpaceName: NSCalibratedRGBColorSpace
  225773. bitmapFormat: (NSBitmapFormat) 0
  225774. bytesPerRow: lineStride
  225775. bitsPerPixel: pixelStride * 8];
  225776. [NSGraphicsContext saveGraphicsState];
  225777. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithBitmapImageRep: rep]];
  225778. [source drawAtPoint: NSZeroPoint];
  225779. [[NSGraphicsContext currentContext] flushGraphics];
  225780. [NSGraphicsContext restoreGraphicsState];
  225781. uint8* start = pixels;
  225782. for (int h = dest.getHeight(); --h >= 0;)
  225783. {
  225784. uint8* p = start;
  225785. start += lineStride;
  225786. for (int i = dest.getWidth(); --i >= 0;)
  225787. {
  225788. #if JUCE_BIG_ENDIAN
  225789. const uint8 oldp3 = p[3];
  225790. const uint8 oldp1 = p[1];
  225791. p[3] = p[0];
  225792. p[0] = oldp1;
  225793. p[1] = p[2];
  225794. p[2] = oldp3;
  225795. #else
  225796. const uint8 oldp0 = p[0];
  225797. p[0] = p[2];
  225798. p[2] = oldp0;
  225799. #endif
  225800. p += pixelStride;
  225801. }
  225802. }
  225803. dest.releasePixelDataReadWrite (pixels);
  225804. }
  225805. void callListeners (NSBitmapImageRep* bitmap)
  225806. {
  225807. Image image (Image::ARGB, [bitmap size].width, [bitmap size].height, false);
  225808. drawNSBitmapIntoJuceImage (image, bitmap);
  225809. const ScopedLock sl (listenerLock);
  225810. for (int i = listeners.size(); --i >= 0;)
  225811. {
  225812. CameraImageListener* l = (CameraImageListener*) listeners[i];
  225813. if (l != 0)
  225814. l->imageReceived (image);
  225815. }
  225816. }
  225817. QTCaptureDevice* device;
  225818. QTCaptureDeviceInput* input;
  225819. QTCaptureSession* session;
  225820. QTCaptureMovieFileOutput* fileOutput;
  225821. QTCaptureDecompressedVideoOutput* imageOutput;
  225822. QTCaptureCallbackDelegate* callbackDelegate;
  225823. String openingError;
  225824. VoidArray listeners;
  225825. CriticalSection listenerLock;
  225826. };
  225827. END_JUCE_NAMESPACE
  225828. @implementation QTCaptureCallbackDelegate
  225829. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  225830. internalDev: (QTCameraDeviceInteral*) d
  225831. {
  225832. [super init];
  225833. owner = owner_;
  225834. internal = d;
  225835. firstRecordedTime = 0;
  225836. return self;
  225837. }
  225838. - (void) dealloc
  225839. {
  225840. delete firstRecordedTime;
  225841. [super dealloc];
  225842. }
  225843. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  225844. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  225845. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225846. fromConnection: (QTCaptureConnection*) connection
  225847. {
  225848. const ScopedAutoReleasePool pool;
  225849. CIImage* image = [CIImage imageWithCVImageBuffer: videoFrame];
  225850. NSBitmapImageRep* bitmap = [[[NSBitmapImageRep alloc] initWithCIImage: image] autorelease];
  225851. internal->callListeners (bitmap);
  225852. }
  225853. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  225854. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  225855. fromConnection: (QTCaptureConnection*) connection
  225856. {
  225857. if (firstRecordedTime == 0)
  225858. firstRecordedTime = new Time (Time::getCurrentTime());
  225859. }
  225860. @end
  225861. BEGIN_JUCE_NAMESPACE
  225862. class QTCaptureViewerComp : public NSViewComponent
  225863. {
  225864. public:
  225865. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  225866. {
  225867. const ScopedAutoReleasePool pool;
  225868. captureView = [[QTCaptureView alloc] init];
  225869. [captureView setCaptureSession: internal->session];
  225870. setSize (640, 480); // xxx need to somehow get the movie size - how?
  225871. setView (captureView);
  225872. }
  225873. ~QTCaptureViewerComp()
  225874. {
  225875. setView (0);
  225876. [captureView setCaptureSession: nil];
  225877. [captureView release];
  225878. }
  225879. QTCaptureView* captureView;
  225880. };
  225881. CameraDevice::CameraDevice (const String& name_, int index)
  225882. : name (name_)
  225883. {
  225884. isRecording = false;
  225885. QTCameraDeviceInteral* d = new QTCameraDeviceInteral (this, index);
  225886. internal = d;
  225887. }
  225888. CameraDevice::~CameraDevice()
  225889. {
  225890. stopRecording();
  225891. delete (QTCameraDeviceInteral*) internal;
  225892. internal = 0;
  225893. }
  225894. Component* CameraDevice::createViewerComponent()
  225895. {
  225896. return new QTCaptureViewerComp (this, (QTCameraDeviceInteral*) internal);
  225897. }
  225898. const String CameraDevice::getFileExtension()
  225899. {
  225900. return ".mov";
  225901. }
  225902. void CameraDevice::startRecordingToFile (const File& file)
  225903. {
  225904. stopRecording();
  225905. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225906. deleteAndZero (d->callbackDelegate->firstRecordedTime);
  225907. file.deleteFile();
  225908. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  225909. [d->session addOutput: d->fileOutput error: nil];
  225910. isRecording = true;
  225911. }
  225912. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  225913. {
  225914. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225915. if (d->callbackDelegate->firstRecordedTime != 0)
  225916. return *d->callbackDelegate->firstRecordedTime;
  225917. return Time();
  225918. }
  225919. void CameraDevice::stopRecording()
  225920. {
  225921. if (isRecording)
  225922. {
  225923. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225924. d->resetFile();
  225925. isRecording = false;
  225926. }
  225927. }
  225928. void CameraDevice::addListener (CameraImageListener* listenerToAdd)
  225929. {
  225930. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225931. if (listenerToAdd != 0)
  225932. d->addListener (listenerToAdd);
  225933. }
  225934. void CameraDevice::removeListener (CameraImageListener* listenerToRemove)
  225935. {
  225936. QTCameraDeviceInteral* const d = (QTCameraDeviceInteral*) internal;
  225937. if (listenerToRemove != 0)
  225938. d->removeListener (listenerToRemove);
  225939. }
  225940. const StringArray CameraDevice::getAvailableDevices()
  225941. {
  225942. const ScopedAutoReleasePool pool;
  225943. StringArray results;
  225944. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  225945. for (int i = 0; i < [devs count]; ++i)
  225946. {
  225947. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  225948. results.add (nsStringToJuce ([dev localizedDisplayName]));
  225949. }
  225950. return results;
  225951. }
  225952. CameraDevice* CameraDevice::openDevice (int index,
  225953. int minWidth, int minHeight,
  225954. int maxWidth, int maxHeight)
  225955. {
  225956. CameraDevice* d = new CameraDevice (getAvailableDevices() [index], index);
  225957. if (((QTCameraDeviceInteral*) (d->internal))->openingError.isEmpty())
  225958. return d;
  225959. delete d;
  225960. return 0;
  225961. }
  225962. #endif
  225963. /********* End of inlined file: juce_mac_CameraDevice.mm *********/
  225964. #endif
  225965. END_JUCE_NAMESPACE
  225966. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  225967. #endif